text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
public static boolean isLocked(int roomId) {
if(keyRequired[roomId-1] != 0) {
return true;
} else {
return false;
}
} | 1 |
@Override
public int getMask(int plane, int localX, int localY) {
int currentChunkX = localX / 8;
int currentChunkY = localY / 8;
int rotation = regionCoords[plane][currentChunkX][currentChunkY][3];
int realChunkX = regionCoords[plane][currentChunkX][currentChunkY][0];
int realChunkY = regionCoords[plane][currentChunkX][currentChunkY][1];
if (realChunkX == 0 || realChunkY == 0)
return -1;
int realRegionId = (((realChunkX / 8) << 8) + (realChunkY / 8));
Region region = World.getRegion(realRegionId, true);
if (region instanceof DynamicRegion) {
if (Settings.DEBUG)
Logger.log(this,
"YOU CANT MAKE A REAL MAP AREA INTO A DYNAMIC REGION!, IT MAY DEADLOCK!");
return -1; // no information so that data not loaded
}
int realRegionOffsetX = (realChunkX - ((realChunkX / 8) * 8));
int realRegionOffsetY = (realChunkY - ((realChunkY / 8) * 8));
int posInChunkX = (localX - (currentChunkX * 8));
int posInChunkY = (localY - (currentChunkY * 8));
if (rotation != 0) {
for (int rotate = 0; rotate < (4 - rotation); rotate++) {
int fakeChunckX = posInChunkX;
int fakeChunckY = posInChunkY;
posInChunkX = fakeChunckY;
posInChunkY = 7 - fakeChunckX;
}
}
int realLocalX = (realRegionOffsetX * 8) + posInChunkX;
int realLocalY = (realRegionOffsetY * 8) + posInChunkY;
int mask = region.getMask(
regionCoords[plane][currentChunkX][currentChunkY][2],
realLocalX, realLocalY);
if(removedMap != null)
mask = mask & (~removedMap.getMasks()[plane][localX][localY]);
return mask;
} | 7 |
@Override
public void spring(MOB target)
{
if(target.location()!=null)
{
if((!invoker().mayIFight(target))
||(isLocalExempt(target))
||(invoker().getGroupMembers(new HashSet<MOB>()).contains(target))
||(target==invoker())
||(doesSaveVsTraps(target)))
target.location().show(target,null,null,CMMsg.MASK_ALWAYS|CMMsg.MSG_NOISE,L("<S-NAME> avoid(s) the acid burst!"));
else
if(target.location().show(invoker(),target,this,CMMsg.MASK_ALWAYS|CMMsg.MSG_NOISE,L("@x1 sprays acid all over <T-NAME>!",affected.name())))
{
super.spring(target);
CMLib.combat().postDamage(invoker(),target,null,CMLib.dice().roll(trapLevel()+abilityCode(),24,1),CMMsg.MASK_ALWAYS|CMMsg.TYP_ACID,Weapon.TYPE_MELTING,L("The acid <DAMAGE> <T-NAME>!"));
}
}
} | 7 |
private static List<Class<?>> classListFromJar(final String name, List<String> classpath) {
final List<Class<?>> results = new ArrayList<Class<?>>();
try (final JarFile jf = new JarFile(name)) {
final File jFile = new File(name);
ClassLoader cl =
new URLClassLoader(new URL[]{makeFileURL(jFile.getAbsolutePath())});
final Enumeration<JarEntry> entries = jf.entries();
while (entries.hasMoreElements()) {
final JarEntry jarEntry = entries.nextElement();
String entName = jarEntry.getName();
if (entName.endsWith(".class")) {
int n = entName.length();
try {
results.add(
cl.loadClass(
entName.substring(0, n - 6).replace('/','.')));
} catch (ClassNotFoundException e) {
System.err.println(e);
// Caught here so we go on to next one.
}
}
}
} catch (Exception e) {
throw new IllegalArgumentException(name, e);
}
return results;
} | 7 |
public static void asm_addwf(Integer akt_Befehl, Prozessor cpu) {
// Komponenten auslesen
Integer f = getOpcodeFromToBit(akt_Befehl, 0, 6);
Integer w = cpu.getW();
Integer result = cpu.getSpeicherzellenWert(f) + w;
// Speicherort abfragen
if(getOpcodeFromToBit(akt_Befehl, 7, 7) == 1) {
// in f Register speichern
cpu.setSpeicherzellenWert(f, result, true);
}
else {
// in w Register speichern
cpu.setW(result, true);
}
// PC ++
cpu.incPC();
} | 1 |
public Image getImage(String key) {
if(loadedImages.containsKey(key))
return loadedImages.get(key);
else
return null;
} | 1 |
private void visitObjectLiteral(Node node, Node child)
{
Object[] properties = (Object[])node.getProp(Node.OBJECT_IDS_PROP);
int count = properties.length;
// load array with property ids
addNewObjectArray(count);
for (int i = 0; i != count; ++i) {
cfw.add(ByteCode.DUP);
cfw.addPush(i);
Object id = properties[i];
if (id instanceof String) {
cfw.addPush((String)id);
} else {
cfw.addPush(((Integer)id).intValue());
addScriptRuntimeInvoke("wrapInt", "(I)Ljava/lang/Integer;");
}
cfw.add(ByteCode.AASTORE);
}
// load array with property values
addNewObjectArray(count);
Node child2 = child;
for (int i = 0; i != count; ++i) {
cfw.add(ByteCode.DUP);
cfw.addPush(i);
int childType = child.getType();
if (childType == Token.GET) {
generateExpression(child.getFirstChild(), node);
} else if (childType == Token.SET) {
generateExpression(child.getFirstChild(), node);
} else {
generateExpression(child, node);
}
cfw.add(ByteCode.AASTORE);
child = child.getNext();
}
// load array with getterSetter values
cfw.addPush(count);
cfw.add(ByteCode.NEWARRAY, ByteCode.T_INT);
for (int i = 0; i != count; ++i) {
cfw.add(ByteCode.DUP);
cfw.addPush(i);
int childType = child2.getType();
if (childType == Token.GET) {
cfw.add(ByteCode.ICONST_M1);
} else if (childType == Token.SET) {
cfw.add(ByteCode.ICONST_1);
} else {
cfw.add(ByteCode.ICONST_0);
}
cfw.add(ByteCode.IASTORE);
child2 = child2.getNext();
}
cfw.addALoad(contextLocal);
cfw.addALoad(variableObjectLocal);
addScriptRuntimeInvoke("newObjectLiteral",
"([Ljava/lang/Object;"
+"[Ljava/lang/Object;"
+"[I"
+"Lorg/mozilla/javascript/Context;"
+"Lorg/mozilla/javascript/Scriptable;"
+")Lorg/mozilla/javascript/Scriptable;");
} | 8 |
private String[][] parseText(String textFile){
FileReader input = null;
try {
input = new FileReader(textFile);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedReader bufRead = new BufferedReader(input);
String myLine = null;
String[][] array = new String[Map.ARRAYSIZE][Map.ARRAYSIZE];
int row = 0;
try {
while ( (myLine = bufRead.readLine()) != null)
{
array[row++] = myLine.split(" ");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
bufRead.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return array;
} | 4 |
public void run()
{
FileInputStream fis = null;
ZipInputStream zis = null;
try
{
try
{
File directory = new File(this.outputParentDirectory + File.separatorChar + this.zipFilePath.substring(this.zipFilePath.lastIndexOf(File.separatorChar)));
if(directory.exists())directory.delete();
directory.mkdir();
fis = new FileInputStream(zipFilePath);
zis = new ZipInputStream(fis);
ZipEntry entry;
while((entry = zis.getNextEntry())!=null)
{
extractToFile(zis, directory.getAbsolutePath(), entry);
}
fis.close();
zis.close();
}
catch(EOFException exception)
{
fis.close();
zis.close();
new Thread(new Cleanup(System.getProperties().getProperty("user.home") + File.separator + "Droid Drow")).start();
}
catch(FileNotFoundException exception)
{
fis.close();
zis.close();
}
}
catch(NullPointerException excepion)
{
throw new NullPointerException();
}
catch(IOException ex)
{
ex.printStackTrace();
}
} | 6 |
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// BufferedReader br = new BufferedReader(new FileReader("input.in"));
StringBuilder sb = new StringBuilder();
String line = "";
d: do {
line = br.readLine();
if (line == null)
break;
if(line.length()>0)
if(Character.isDigit(line.charAt(0)))
sb.append(num((new StringBuilder(line)).reverse().toString()));
else
sb.append(let(line));
else
sb.append("\n");
} while (line != null);
System.out.print(sb);
} | 4 |
static Object[][] subtract(Object[][] x, Object[][] y) {
Object[][] ret = new Object[x.length][];
for (int i = 0; i < x.length; i++) {
ret[i] = new Object[x[i].length];
for (int j = 0; j < x[i].length; j++) {
Object a = x[i][j];
Object b = y[i][j];
if (a == null || b == null) {
ret[i][j] = null;
} else if (a instanceof Integer) {
ret[i][j] = (Integer) a - (Integer) b;
} else if (a instanceof Double) {
ret[i][j] = (Double) a - (Double) b;
} else {
ret[i][j] = ((BigInteger) a).subtract((BigInteger) b);
}
}
}
return ret;
} | 6 |
public Value execute(Interpreter machine) throws MyException {
if (_operands != null && _operands.size() >= 3
&& _operands.get(0).isSymbol()
&& _operands.get(1).execute(machine).isNumber()
&& _operands.get(2).execute(machine).isNumber()) {
Symbol I = (Symbol) _operands.get(0);
double L = _operands.get(1).execute(machine).doubleValue();
double U = _operands.get(2).execute(machine).doubleValue();
machine.put(I.getString(), new Numeral(L).execute(machine));
if (_operands.size() == 3) {
if (L > U) {
machine.put(I.getString(), new Numeral(L).execute(machine));
return null;
} else {
machine.put(I.getString(), new Numeral(U).execute(machine));
return null;
}
}
while (L <= U) {
machine.put(I.getString(), new Numeral(L).execute(machine));
int counter = 3;
while (counter < _operands.size()) {
_operands.get(counter).execute(machine);
counter += 1;
}
L += 1;
}
} else {
throw new MyException("Error: incorrect args for");
}
return null;
} | 9 |
public boolean canShoot(Placeable currentObj) {
for (GameAction currentGameAction : getGameActions()) {
if (currentGameAction.canShoot(currentObj)) {
return true;
}
}
return false;
} | 2 |
private Point getTargetBlock(Point cur){
int cnt = 0;
if (this.maze[cur.x][cur.y + 1] == false) {cnt++;}
if (this.maze[cur.x][cur.y - 1] == false) {cnt++;}
if (this.maze[cur.x + 1][cur.y] == false) {cnt++;}
if (this.maze[cur.x - 1][cur.y] == false) {cnt++;}
if (cnt == 1) {
if (this.maze[cur.x][cur.y + 1] == false) {return new Point(cur.x, cur.y - 1);}
if (this.maze[cur.x][cur.y - 1] == false) {return new Point(cur.x, cur.y + 1);}
if (this.maze[cur.x + 1][cur.y] == false) {return new Point(cur.x - 1, cur.y);}
if (this.maze[cur.x - 1][cur.y] == false) {return new Point(cur.x + 1, cur.y);}
}
return null;
} | 9 |
public void checkingDataBasedOnDateSelected() {
String datafromDisplay = dataFromLabel;
System.out.println("datafromDisplay: " + dataFromLabel);
try {
file_Grouping = new File(SelectingLogFileToReadXml.PathOfFileUsedInDateBasedGrouping,
"FileWithBlockDate.txt");
fwSeek = new FileWriter(file_Grouping);
brSeek = new BufferedReader(new FileReader(WritingXmlFromLogFileToTxtFile.fileCreatedAfterXmlIsExtractedFromLogFile));
bwSeek = new BufferedWriter(fwSeek);
while ((sCurrentLineForQuery = brSeek.readLine()) != null) {
if (datafromDisplay.substring(0, 1).equalsIgnoreCase(
sCurrentLineForQuery.substring(0, 1))) {
if (datafromDisplay.substring(4, 5).equalsIgnoreCase(
sCurrentLineForQuery.substring(4, 5))) {
if (datafromDisplay.substring(8, 10).equalsIgnoreCase(
sCurrentLineForQuery.substring(8, 10))) {
if (datafromDisplay.substring(11, 12)
.equalsIgnoreCase(
sCurrentLineForQuery.substring(11,
12))) {
if (datafromDisplay.substring(12, 13)
.equalsIgnoreCase(
sCurrentLineForQuery.substring(
12, 13))) {
bwSeek.write(sCurrentLineForQuery);
bwSeek.newLine();
bwSeek.flush();
}
}
//else {
// FLAG_FOR_TIME = 1;
// }
}
}
} else {
FLAG_FOR_DATE = 1;
}
}
} catch (Exception e) {
e.printStackTrace();
}
} | 7 |
public static Rectangle transform(Rectangle rectangle,
Direction direction,
boolean horizontalFlip,
boolean verticalFlip,
int width,
int height) {
int x = horizontalFlip ? (direction.isHorizontal() ? width : height) - rectangle.width - rectangle.x : rectangle.x;
int y = verticalFlip ? (direction.isHorizontal() ? height : width) - rectangle.height - rectangle.y : rectangle.y;
return direction == Direction.DOWN ? new Rectangle(width - y - rectangle.height,
x,
rectangle.height,
rectangle.width) :
direction == Direction.LEFT ? new Rectangle(width - x - rectangle.width,
height - y - rectangle.height,
rectangle.width,
rectangle.height) :
direction == Direction.UP ? new Rectangle(y,
height - x - rectangle.width,
rectangle.height,
rectangle.width) :
new Rectangle(x, y, rectangle.width, rectangle.height);
} | 7 |
public void update(long elapsedTime) {
// select the correct Animation
Animation newAnim = anim;
if (getVelocityX() < 0) {
newAnim = left;
}
else if (getVelocityX() > 0) {
newAnim = right;
}
if (state == STATE_DYING && newAnim == left) {
newAnim = deadLeft;
}
else if (state == STATE_DYING && newAnim == right) {
newAnim = deadRight;
}
// update the Animation
if (anim != newAnim) {
anim = newAnim;
anim.start();
}
else {
anim.update(elapsedTime);
}
// update to "dead" state
stateTime += elapsedTime;
if (state == STATE_DYING && stateTime >= DIE_TIME) {
setState(STATE_DEAD);
}
} | 9 |
@Override
public boolean equals(Object object){
if(this.x == ((Coordinate)object).x && this.y == ((Coordinate)object).y)
return true;
else
return false;
} | 2 |
public boolean type(char key, java.awt.event.KeyEvent ev) {
if (key == 27) {
if (justclose)
ui.destroy(this);
else
wdgmsg("close");
return (true);
}
return (super.type(key, ev));
} | 2 |
public void useSurf()
{
surfing=true;
messageBox=new ErrorWindow();
messageBox.addMessage("You ride on your Pokemon!","Hidden Move: Surf");
messageBox.repaint();
while(messageBox.isVisible())
{
try
{
repaint();
Thread.sleep(10);
}
catch(Exception ignored){}
}
bgm.stop();
bikeSong.stop();
bicycling=false;
surfSong.loop();
jf.toFront();
moving=false;
performingAction=false;
} | 2 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TimeSheetPK other = (TimeSheetPK) obj;
if (emp_ID != other.emp_ID)
return false;
if (week_end_day == null) {
if (other.week_end_day != null)
return false;
} else if (!week_end_day.equals(other.week_end_day))
return false;
return true;
} | 7 |
private void addLeavesToList(ArrayList<AreaObject> list) {
for (int i = 0; i < mStorageCount; i++) {
if (mLeafNode) {
list.add(mStorage[i]);
} else {
((AreaNode) mStorage[i]).addLeavesToList(list);
}
mStorage[i] = null;
}
mStorageCount = 0;
mLeafNode = true;
} | 2 |
public void paint(GC gc, int width, int height) {
if (!example.checkAdvancedGraphics()) return;
Device device = gc.getDevice();
// top triangle
Path path = new Path(device);
path.moveTo(width/2, 0);
path.lineTo(width/2+100, 173);
path.lineTo(width/2-100, 173);
path.lineTo(width/2, 0);
// bottom triangle
Path path2 = new Path(device);
path2.moveTo(width/2, height);
path2.lineTo(width/2+100, height-173);
path2.lineTo(width/2-100, height-173);
path2.lineTo(width/2, height);
// left triangle
Path path3 = new Path(device);
path3.moveTo(0, height/2);
path3.lineTo(173, height/2-100);
path3.lineTo(173, height/2+100);
path3.lineTo(0, height/2);
// right triangle
Path path4 = new Path(device);
path4.moveTo(width, height/2);
path4.lineTo(width-173, height/2-100);
path4.lineTo(width-173, height/2+100);
path4.lineTo(width, height/2);
// circle
Path path5 = new Path(device);
path5.moveTo((width-200)/2, (height-200)/2);
path5.addArc((width-200)/2, (height-200)/2, 200, 200, 0, 360);
// top rectangle
Path path6 = new Path(device);
path6.addRectangle((width-40)/2, 175, 40, ((height-200)/2)-177);
// bottom rectangle
Path path7 = new Path(device);
path7.addRectangle((width-40)/2, ((height-200)/2)+202, 40, (height-175)-(((height-200)/2)+202));
// left rectangle
Path path8 = new Path(device);
path8.addRectangle(175, (height-40)/2, ((width-200)/2)-177, 40);
// right rectangle
Path path9 = new Path(device);
path9.addRectangle((width-200)/2+202, (height-40)/2, (width-175)-((width-200)/2+202), 40);
path.addPath(path2);
path.addPath(path3);
path.addPath(path4);
path.addPath(path5);
path.addPath(path6);
path.addPath(path7);
path.addPath(path8);
path.addPath(path9);
gc.setClipping(path);
Pattern pattern = null;
if (background.getBgColor1() != null) {
gc.setBackground(background.getBgColor1());
} else if (background.getBgImage() != null) {
pattern = new Pattern(device, background.getBgImage());
gc.setBackgroundPattern(pattern);
}
gc.setLineWidth(2);
gc.fillRectangle((width-rectWidth)/2, (height-rectHeight)/2, rectWidth, rectHeight);
gc.drawPath(path);
if (pattern != null)
pattern.dispose();
path9.dispose();
path8.dispose();
path7.dispose();
path6.dispose();
path5.dispose();
path4.dispose();
path3.dispose();
path2.dispose();
path.dispose();
} | 4 |
@Around(" call(void de.codecentric.performance.Demo.method* (..)) ")
public void aroundDemoMethodCall(final ProceedingJoinPoint thisJoinPoint) throws Throwable {
long cpuStart = threadMXBean.getCurrentThreadCpuTime();
long start = System.nanoTime();
thisJoinPoint.proceed();
long end = System.nanoTime();
long cpuEnd = threadMXBean.getCurrentThreadCpuTime();
String currentMethod = thisJoinPoint.getSignature().toString();
if (executionPath.size() < MAX_EXECUTION_PATH) {
executionPath.add(currentMethod);
}
MethodStatistics statistics = methodStatistics.get(currentMethod);
if (statistics == null) {
statistics = new MoreMethodStatistics(currentMethod);
methodStatistics.put(currentMethod, statistics);
}
statistics.addTime(end - start);
statistics.addCPUTime(cpuEnd - cpuStart);
overhead += System.nanoTime() - end;
} | 2 |
* @return Returns the parsed response. Index 0 is response, Index 1 is confidence score
*/
private void parseResponse(String rawResponse, GoogleResponse googleResponse) {
if (!rawResponse.contains("utterance"))
return;
String array = substringBetween(rawResponse, "[", "]");
String[] parts = array.split("}");
boolean first = true;
for( String s : parts ) {
if( first ) {
first = false;
String utterancePart = s.split(",")[0];
String confidencePart = s.split(",")[1];
String utterance = utterancePart.split(":")[1];
String confidence = confidencePart.split(":")[1];
utterance = stripQuotes(utterance);
confidence = stripQuotes(confidence);
if( utterance.equals("null") ) {
utterance = null;
}
if( confidence.equals("null") ) {
confidence = null;
}
googleResponse.setResponse(utterance);
googleResponse.setConfidence(confidence);
} else {
String utterance = s.split(":")[1];
utterance = stripQuotes(utterance);
if( utterance.equals("null") ) {
utterance = null;
}
googleResponse.getOtherPossibleResponses().add(utterance);
}
} | 6 |
public void wiggleSort(int[] nums) {
int[] sorted=Arrays.copyOfRange(nums,0,nums.length);
Arrays.sort(sorted);
int minEnd=(nums.length-1)/2 , maxEnd=nums.length-1;
for(int i=0;i<nums.length;++i){
if(i%2==0){
nums[i]=sorted[minEnd--];
}else{
nums[i]=sorted[maxEnd--];
}
}
} | 2 |
public static void testStdIO(){
//Reading standard input
InputStreamReader cin=null;
try{
cin = new InputStreamReader(System.in);
println("Enter characters. 'q' to quit");
char c;
do{
c = (char) cin.read();
println(c);
}while(c!='q');
}
catch(IOException ioe){
println("IOException caught reading in");
}
try{
if(cin!=null){ cin.close(); }
}
catch(IOException ioe){
println("IOException caught in close");
}
} | 4 |
public List<Integer> getRWinfo() {
if(type.equals(Type.READ) || type.equals(Type.WRITE)) {
return getNumericList(operation);
}
return null;
} | 2 |
public int getSubsampleFrequency() {
String freq = (String)subsampleFreqBox.getSelectedItem();
if (freq.equals(ALL)) {
return 1;
}
if (freq.equals(HALF)) {
return 2;
}
if (freq.equals(THIRD)) {
return 3;
}
if (freq.equals(QUARTER)) {
return 4;
}
if (freq.equals(TENTH)) {
return 10;
}
if (freq.equals(TWENTIETH)) {
return 20;
}
if (freq.equals(HUNDRETH)) {
return 100;
}
return 10;
} | 7 |
private int readRemaining( ByteBuffer dst ) throws SSLException {
if( inData.hasRemaining() ) {
return transfereTo( inData, dst );
}
if( !inData.hasRemaining() )
inData.clear();
// test if some bytes left from last read (e.g. BUFFER_UNDERFLOW)
if( inCrypt.hasRemaining() ) {
unwrap();
int amount = transfereTo( inData, dst );
if( amount > 0 )
return amount;
}
return 0;
} | 4 |
private String translateIndexToQuery(String ruleSymbol, boolean translatedFlag) {
if (ruleSymbol.equals("Default") || translatedFlag)
return ruleSymbol;
String ruleString;
if (ruleSymbol.equals("."))
ruleString = "intersect";
else if (ruleSymbol.equals("+"))
ruleString = "union";
else if (domconfBundle.containsKey("Auth["+ruleSymbol+"]"))
ruleString = domconfBundle.getString("Auth["+ruleSymbol+"]");
else
ruleString = "miss";
return ruleString;
} | 5 |
public static Arena getArena(int id) {
for (Arena a : SuperBaseBattle.arenaList)
if (a.getArenaId() == id)
return a;
return null;
} | 2 |
public void showSplash() {
setBackground(Color.white);
JLabel label = new JLabel(createImageIcon(image1));
add(label, BorderLayout.CENTER);
pack();
centerScreen();
setVisible(true);
} | 0 |
@Override
protected void paintComponent(Graphics gc) {
Insets insets = getInsets();
int x = insets.left;
int y = insets.top;
int width = getWidth() - (insets.left + insets.right);
int height = getHeight() - (insets.top + insets.bottom);
if (mInMouseDown && mPressed) {
gc.setColor(Colors.adjustBrightness(getBackground(), -0.2f));
gc.fillRect(x, y, width, height);
}
if (mShowBorder || mInMouseDown) {
gc.setColor(Colors.adjustBrightness(getBackground(), -0.4f));
gc.drawRect(x, y, width - 1, height - 1);
}
gc.setFont(getFont());
gc.setColor(Color.BLACK);
String text = getText();
Rectangle bounds = getBounds();
bounds.x = insets.left;
bounds.y = insets.top;
bounds.width -= insets.left + insets.right;
bounds.height -= insets.top + insets.bottom;
TextDrawing.draw(gc, bounds, text, SwingConstants.CENTER, SwingConstants.CENTER);
} | 4 |
@Override
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
if(action.equals("Exit")){
ui.exit();
}
else if(action.equals("New grid..")){
ui.kaynnista();
}
else if(action.equals("About")){
ui.naytaAbout();
}
else if(action.equals("Change dictionary..")){
try {
ui.vaihdaSanakirjaa();
} catch (Exception ex) {
}
}
else if (action.equals("Help")){
try {ui.naytaHelp();}
catch (Exception ex) {
ui.helpVirhe();
}
}
else if(action.equals("About")){
ui.naytaAbout();
}
} | 8 |
private Tuple<Float, HeuristicData> min(LongBoard state, HeuristicData data, float alpha,
float beta, int action, int depth) {
statesChecked++;
Tuple<Float, HeuristicData> y = new Tuple<>((float) Integer.MAX_VALUE, data);
Winner win = gameFinished(state);
Float cached = cacheGet(state);
if(null != cached) {
return new Tuple<>(cached,null);
}
// If the state is a finished state
if (win != Winner.NOT_FINISHED) {
float value = utility(win, depth);
cache(state, value);
return new Tuple<>(value, null);
}
if (depth == 0) {
hasReachedMaxDepth = true;
HeuristicData newData = H.moveHeuristic(data, action, playerID);
Tuple<Float, HeuristicData> value = h(state, newData);
cache(state, value._1);
return value;
}
for (int newaction : generateActions(state)) {
// Stop if time's up
if (isTimeUp()) break;
HeuristicData newData = H.moveHeuristic(data, action, playerID);
Tuple<Float, HeuristicData> max = max(
result(state, newaction), newData, alpha, beta, newaction, depth - 1
);
if (max._1 < y._1) {
y = max;
}
// tests for possible alpha cut
if (y._1 <= alpha) {
cutoffs++;
cache(state, y._1);
return y;
}
beta = Math.min(beta, y._1);
}
cache(state, y._1);
return y;
} | 7 |
public boolean setStartPosition(int length) {
if (length < 5 || length > 50)
return false;
int row = 0;
int col = 0;
Color c = null;
do {
row = 0 + (int) (Math.random() * length);
col = 0 + (int) (Math.random() * length);
c = map.grid[row][col];
} while (c != Color.GREEN);
start_pos = new Position(row, col);
position = new Position(row, col);
visited = new boolean[length][length];
for (int i = 0; i < length; i++) {
for (int j = 0; j < length; j++)
visited[i][j] = false;
}
return true;
} | 5 |
public String getLetters(String str)
{
int breakPos = 0;
for(int i = 0; i < str.length(); i++) //get the first letters in the string
{
char ch = str.charAt(i);
if(!Character.isLetter(ch))
{
breakPos = i;
break;
}
if(i == str.length()-1)
breakPos = i+1;
}
return str.substring(0, breakPos); //return the letters found
} | 3 |
@Override
public void run() {
if (file == null)
return;
try {
BufferedReader br = new BufferedReader(new FileReader(file));
br.readLine();
String line;
ItemCatDao icDao = new ItemCatDao();
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
ItemCat ic = new ItemCat();
ic.setCid(Long.parseLong(values[0].split("\"")[1]));
ic.setParentCid(Long.parseLong(values[1].split("\"")[1]));
ic.setName(values[2].split("\"")[1]);
if(Boolean.parseBoolean(values[3].split("\"")[1])){
ic.setIsLeaf(ItemCat.ISLEAF_TRUE);
}else{
ic.setIsLeaf(ItemCat.ISLEAF_FALSE);
}
System.out.println(ic.toJSONObject());
icDao.insert(ic);
// break;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
} | 6 |
private void loadSector(File sectorFile) {
try {
Scanner scanner = new Scanner(sectorFile);
Sector sector = new Sector();
while (scanner.hasNext()) {
String line = scanner.nextLine();
if (line.startsWith("TRIANGLE")) {
String[] split = line.split(": ");
String coords = split[1];
String[] seperated = coords.split("|");
Vertex[] vertices = new Vertex[3];
// Step Through Each Vertex In Triangle
for (int vertloop = 0; vertloop < 3; vertloop++) // Loop Through All The Vertices
{
String[] values = seperated[vertloop].split(",");
float x = Float.parseFloat(values[0]);
float y = Float.parseFloat(values[1]);
float z = Float.parseFloat(values[2]);
float u = Float.parseFloat(values[3]);
float v = Float.parseFloat(values[4]);
// Store Values Into Respective Vertices
Vertex vertex = new Vertex(x, y, z, u, v);
vertices[vertloop] = vertex;
}
Triangle triangle = new Triangle(vertices);
sector.addShape(triangle);
} else if (line.startsWith("TILE")) {
String[] split = line.split(": ");
String coords = split[1];
String[] seperated = coords.split(";");
Vertex[] vertices = new Vertex[4];
// Step Through Each Vertex In Triangle
for (int vertloop = 0; vertloop < 4; vertloop++) // Loop Through All The Vertices
{
String[] values = seperated[vertloop].split(",");
float x = Float.parseFloat(values[0]);
float y = Float.parseFloat(values[1]);
float z = Float.parseFloat(values[2]);
float u = Float.parseFloat(values[3]);
float v = Float.parseFloat(values[4]);
// Store Values Into Respective Vertices
Vertex vertex = new Vertex(x, y, z, u, v);
vertices[vertloop] = vertex;
}
Tile tile = new Tile(vertices);
sector.addShape(tile);
}
}
sectors.add(sector);
} catch (FileNotFoundException ex) {
Logger.getLogger(MapLoader.class.getName()).log(Level.SEVERE, null, ex);
}
} | 6 |
public void method293(int z, int x, int y) {
GroundTile groundTile = groundTiles[z][x][y];
if (groundTile == null) {
return;
}
for (int j1 = 0; j1 < groundTile.anInt1317; j1++) {
InteractiveObject interactiveObject = groundTile.interactiveObjects[j1];
if ((interactiveObject.uid >> 29 & 3) == 2 && interactiveObject.x == x && interactiveObject.y == y) {
method289(interactiveObject);
return;
}
}
} | 5 |
@Override
public boolean test(String value) {
// TODO Auto-generated method stub
if (value == null || value.length() == 0) {
return false;
}
int len = value.length();
if (!Character.isUpperCase(value.charAt(0))) {
return false;
}
for (int i = 1; i < len; i++) {
char c = value.charAt(i);
if (!Character.isLowerCase(c) && c != ',' && c != '.') {
return false;
}
}
return true;
} | 7 |
public void handleInteraction(Automaton automaton,
AutomatonSimulator simulator, Configuration[] configurations,
Object initialInput) {
SimulatorPane simpane = new SimulatorPane(automaton, simulator,
configurations, environment, false);
if (initialInput instanceof String[])
initialInput = java.util.Arrays.asList((String[]) initialInput);
environment.add(simpane, "Simulate: " + initialInput,
new CriticalTag() {
});
environment.setActive(simpane);
} | 1 |
@EventHandler(priority = EventPriority.HIGH)
public void EntityTargetEvent (final Entity entity, final Entity target,
final TargetReason reason) {
if (entity instanceof Bat) {
Bat wisp = (Bat) entity;
if (MMWisp.isWisp(wisp)) {
plugin.getServer().getScheduler()
.scheduleSyncDelayedTask(plugin, new Runnable() {
public void run () {
entity.getWorld().playEffect(
entity.getLocation(),
Effect.MOBSPAWNER_FLAMES, 0);
entity.getWorld().playEffect(
entity.getLocation(),
Effect.POTION_BREAK, 0);
entity.getWorld().playEffect(
entity.getLocation(), Effect.SMOKE, 0);
entity.getWorld().playEffect(
entity.getLocation(),
Effect.ENDER_SIGNAL, 0);
entity.getWorld().playEffect(
entity.getLocation(),
Effect.POTION_BREAK, 1);
}
}, 20L);
}
}
} | 2 |
String getValue(int i, int j) {
if (j >= columns.size()) return null;
ArrayList<String> col = columns.get(j);
if (i >= col.size()) return null;
return col.get(i);
} | 2 |
public static Complex[] fft(Complex[] x) {
int N = x.length;
// base case
if (N == 1) return new Complex[] { x[0] };
// radix 2 Cooley-Tukey FFT
if (N % 2 != 0) { throw new RuntimeException("N is not a power of 2"); }
// fft of even terms
Complex[] even = new Complex[N/2];
for (int k = 0; k < N/2; k++) {
even[k] = x[2*k];
}
Complex[] q = fft(even);
// fft of odd terms
Complex[] odd = even; // reuse the array
for (int k = 0; k < N/2; k++) {
odd[k] = x[2*k + 1];
}
Complex[] r = fft(odd);
// combine
Complex[] y = new Complex[N];
for (int k = 0; k < N/2; k++) {
double kth = -2 * k * Math.PI / N;
Complex wk = new Complex(Math.cos(kth), Math.sin(kth));
if (r[k] != null) {
y[k] = q[k].plus(wk.times(r[k]));
y[k + N/2] = q[k].minus(wk.times(r[k]));
}
}
// System.out.println("Done with this FFT");
return y;
} | 6 |
public static void main(String[] args) {
// Using Sieve of Eratosthenes to mark all non-primes as false
boolean[] nums = new boolean[200000];
for (int i = 2; i < nums.length; i++)
nums[i] = true;
int nextPrime = 2;
while (nextPrime < nums.length / 2) {
int i = nextPrime;
for (; i < nums.length; i += nextPrime)
nums[i] = false;
nums[nextPrime] = true;
for (int j = nextPrime + 1; j < nums.length; j++) {
if (nums[j] == true) {
nextPrime = j;
break;
}
}
}
int count = 0, i = 0;
for (; count < 10001; i++) {
if (nums[i] == true)
count++;
}
System.out.println(i - 1);
// Solution: 104743
} | 7 |
private SortedSet<Schema> readSchemas() throws IOException,
CubeXmlFileNotExistsException, DocumentException,
CorrespondingDimensionNotExistsException {
Configuration conf = CubeConfiguration.getConfiguration();
FileSystem hdfs = FileSystem.get(conf);
Path schemaXmlFile = new Path(PathConf.getSchemaXmlFilePath());
if (!hdfs.exists(schemaXmlFile)) {
throw new CubeXmlFileNotExistsException();
}
FSDataInputStream in = hdfs.open(schemaXmlFile);
SAXReader reader = new SAXReader();
Document document = reader.read(in);
List<?> schemaList = document.selectNodes("//schemas/schema");
Node schemaNode;
String schemaName;
String dimensionName;
Dimension correspondingDimension;
SortedSet<Dimension> correspondingDimensions = new TreeSet<Dimension>();
SortedSet<Schema> schemas = new TreeSet<Schema>();
Node dimensionNameNode;
for (Iterator<?> iteratorForSchema = schemaList.iterator(); iteratorForSchema
.hasNext(); ) {
schemaNode = (Node) iteratorForSchema.next();
schemaName = schemaNode.selectSingleNode("name").getText();
List<?> dimensionNameNodeList = schemaNode
.selectNodes("dimensionName");
for (Iterator<?> iteratorForDimensionName = dimensionNameNodeList
.iterator(); iteratorForDimensionName.hasNext(); ) {
dimensionNameNode = (Node) iteratorForDimensionName.next();
dimensionName = dimensionNameNode.getText();
correspondingDimension = findCorrespondingDimension(
dimensionName, dimensions);
correspondingDimensions.add(correspondingDimension);
}
schemas.add(Schema.getSchema(schemaName, correspondingDimensions));
}
return schemas;
} | 7 |
public int getScore() {
return score;
} | 0 |
private RequestType parseRequest(BufferedReader input, StringBuilder arg) {
String query;
try {
query = input.readLine();
} catch (IOException e) {
System.out.println("\t\tMaster.parseRequest():\tError! I/O exception happened in readLine().");
return RequestType.EXCEPTION;
}
if (query == null || query.length() < 1) {
return RequestType.UNIMPLEMENTED;
}
String[] comp = query.split("\t");
if (comp.length < 2) {
return RequestType.UNIMPLEMENTED;
}
if (comp[0].equals("register")) {
arg.append(comp[1]);
return RequestType.REGISTER;
} else if (comp[0].equals("query")) {
arg.append(comp[1]);
return RequestType.QUERY;
} else if (comp[0].equals("deregister")) {
arg.append(comp[1]);
return RequestType.DEREGISTER;
} else {
return RequestType.UNIMPLEMENTED;
}
} | 7 |
@Override
public void doSharpen() {
if (imageManager.getBufferedImage() == null) return;
WritableRaster raster = imageManager.getBufferedImage().getRaster();
double[][] newPixels = new double[raster.getWidth()][raster.getHeight()];
for (int x = 1; x < raster.getWidth() - 1; x++) {
for (int y = 1; y < raster.getHeight() - 1; y++) {
double weighted = 0;
weighted += raster.getPixel(x, y+1, new double[3])[0];
weighted += raster.getPixel(x, y-1, new double[3])[0];
weighted += raster.getPixel(x+1, y, new double[3])[0];
weighted += raster.getPixel(x-1, y, new double[3])[0];
weighted *= -1;
weighted += 6*raster.getPixel(x, y, new double[3])[0];
weighted /= 2;
if (weighted > 255)
weighted = 255;
else if (weighted < 0)
weighted = 0;
newPixels[x][y] = weighted;
}
}
for (int x = 1; x < raster.getWidth() - 1; x++) {
for (int y = 1; y < raster.getHeight() - 1; y++) {
double[] pixel = new double[3];
pixel[0] = pixel[1] = pixel[2] = newPixels[x][y];
raster.setPixel(x, y, pixel);
}
}
GUIFunctions.refresh();
} | 7 |
private void updateMovement(double time) {
if (atDestinationNode()) {
location = getLocFromMapLoc(currentDestinationX, currentDestinationY);
if (isFinalDestination()) {
updateFinalLoc();
} else {
updateNextLoc();
}
} else {
gunAngle = bodyAngle = getLocFromMapLoc(currentDestinationX, currentDestinationY)
.getAngleFromPoint(location);
location = new Vector2d(location, bodyAngle, SPEED * time);
}
} | 2 |
public setNow() {
this.info = "adjust the server time";
this.addParamConstraint("timestamp", ApiHandler.ParamCons.INTEGER,"the new timestamp of 'now', in ms");
} | 0 |
public static Item[] getSortedInventoryList() {
Item[] inventoryList
= Survivalist.getCurrentGame().getInventory();
Item tempItem;
for (int i = 0; i < inventoryList.length - 1; i++) {
for (int j = 0; j < inventoryList.length - 1 - i; j++) {
if (inventoryList[j].getDescription().
compareToIgnoreCase(inventoryList[j + 1].getDescription()) > 0) {
tempItem = inventoryList[j];
inventoryList[j] = inventoryList[j + 1];
inventoryList[j + 1] = tempItem;
}
}
}
return inventoryList;
} | 3 |
@EventHandler
public void MagmaCubeWeakness(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getMagmaCubeConfig().getDouble("MagmaCube.Weakness.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getMagmaCubeConfig().getBoolean("MagmaCube.Weakness.Enabled", true) && damager instanceof MagmaCube && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.WEAKNESS, plugin.getMagmaCubeConfig().getInt("MagmaCube.Weakness.Time"), plugin.getMagmaCubeConfig().getInt("MagmaCube.Weakness.Power")));
}
} | 6 |
public void bufferMap(){
// Pre-buffer map image
// System.out.println("Buffering map");
int xLoc, yLoc;
mapImage = new BufferedImage(maxX, maxY, BufferedImage.TYPE_4BYTE_ABGR);
Graphics g = mapImage.getGraphics();
for (int y = 0; y < maxY/TILEWIDTH; y++) {
for (int x = 0; x < maxX/TILEWIDTH; x++) {
try {
xLoc = (x * TILEWIDTH);
yLoc = (y * TILEWIDTH);
floor[x][y].draw(g, xLoc, yLoc, TILEWIDTH, TILEWIDTH);
if (environment[x][y] != null) {
environment[x][y].draw(g, xLoc, yLoc, TILEWIDTH, TILEWIDTH);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
} | 4 |
public static Transmission parse (DataInputStream dis) {
Transmission trans = null;
try {
while (dis.available() <= 0)
Thread.sleep(10); // spin waiting for data
trans = new Transmission();
trans.role = PlayerRole.lookupRole(dis.readInt());
ignore(dis);
trans.startingCorner = StartCorner.lookupCorner(dis.readInt());
for(int i = 0; i < trans.greenZone.length; i++) {
ignore(dis);
trans.greenZone[i] = dis.readInt();
}
for(int i = 0; i < trans.redZone.length; i++) {
ignore(dis);
trans.redZone[i] = dis.readInt();
}
return trans;
} catch (IOException e) {
// failed to read transmitted data
LCD.drawString("IO Ex", 0, 7);
return trans;
} catch (InterruptedException e) {
return trans;
}
} | 5 |
public static void GAMING() throws IOException{
int timeblock = 1;
BufferedReader r = new BufferedReader (new InputStreamReader(System.in));
while (timeblock > 0){
System.out.println("What would Damon like to play right now?");
{
System.out.println("1. League of Legends");
System.out.println("2. Starcraft 1 or 2");
System.out.println("3. Osu");
System.out.println("4. CounterStrike");
System.out.println("5. Some Random game with Edward");
System.out.println("Damon would like to choose option: ");
int choice = DamonTools.validInput(Integer.parseInt(r.readLine()), 5, 1);
if (choice == 1)
{
System.out.println("Damon fed on team quite badly and ragequit. However, he did learn from his mistakes.");
DamonStats.LeagueSkills += 1;
}
else if (choice == 2)
{
System.out.println("Damon played 1vs1 with Nan in Starcraft. Needless to say he lost badly.");
DamonStats.StarCraftSkills += 1;
}
else if (choice == 3)
{
System.out.println("Damon played Osu for hours. However, his rank is still below Nan's.");
DamonStats.OsuSkills += 1;
}
else if (choice == 4)
{
System.out.println("Damon played CounterStrike, the only game he is good at.");
DamonStats.CounterStrikeSkills += 1;
}
else
{
System.out.println("Edward invited Damon to play a new game. Damon did not particularly like it, so Edward flipped him.");
DamonStats.RandomGameSkills += 1;
}
timeblock -= 1;
}
}
} | 5 |
public void paintComponent(Graphics g)
{
mxGraph graph = graphComponent.getGraph();
Rectangle clip = g.getClipBounds();
updateIncrementAndUnits();
// Fills clipping area with background.
if (activelength > 0 && inactiveBackground != null)
{
g.setColor(inactiveBackground);
}
else
{
g.setColor(getBackground());
}
g.fillRect(clip.x, clip.y, clip.width, clip.height);
// Draws the active region.
g.setColor(getBackground());
Point2D p = new Point2D.Double(activeoffset, activelength);
if (orientation == ORIENTATION_HORIZONTAL)
{
g.fillRect((int) p.getX(), clip.y, (int) p.getY(), clip.height);
}
else
{
g.fillRect(clip.x, (int) p.getX(), clip.width, (int) p.getY());
}
double left = clip.getX();
double top = clip.getY();
double right = left + clip.getWidth();
double bottom = top + clip.getHeight();
// Fetches some global display state information
mxPoint trans = graph.getView().getTranslate();
double scale = graph.getView().getScale();
double tx = trans.getX() * scale;
double ty = trans.getY() * scale;
// Sets the distance of the grid lines in pixels
double stepping = increment;
if (stepping < tickDistance)
{
int count = (int) Math
.round(Math.ceil(tickDistance / stepping) / 2) * 2;
stepping = count * stepping;
}
// Creates a set of strokes with individual dash offsets
// for each direction
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.setFont(labelFont);
g.setColor(Color.black);
int smallTick = rulerSize - rulerSize / 3;
int middleTick = rulerSize / 2;
// TODO: Merge into a single drawing loop for both orientations
if (orientation == ORIENTATION_HORIZONTAL)
{
double xs = Math.floor((left - tx) / stepping) * stepping + tx;
double xe = Math.ceil(right / stepping) * stepping;
xe += (int) Math.ceil(stepping);
for (double x = xs; x <= xe; x += stepping)
{
// FIXME: Workaround for rounding errors when adding stepping to
// xs or ys multiple times (leads to double grid lines when zoom
// is set to eg. 121%)
double xx = Math.round((x - tx) / stepping) * stepping + tx;
int ix = (int) Math.round(xx);
g.drawLine(ix, rulerSize, ix, 0);
String text = format((x - tx) / increment);
g.drawString(text, ix + 2, labelFont.getSize());
ix += (int) Math.round(stepping / 4);
g.drawLine(ix, rulerSize, ix, smallTick);
ix += (int) Math.round(stepping / 4);
g.drawLine(ix, rulerSize, ix, middleTick);
ix += (int) Math.round(stepping / 4);
g.drawLine(ix, rulerSize, ix, smallTick);
}
}
else
{
double ys = Math.floor((top - ty) / stepping) * stepping + ty;
double ye = Math.ceil(bottom / stepping) * stepping;
ye += (int) Math.ceil(stepping);
for (double y = ys; y <= ye; y += stepping)
{
// FIXME: Workaround for rounding errors when adding stepping to
// xs or ys multiple times (leads to double grid lines when zoom
// is set to eg. 121%)
y = Math.round((y - ty) / stepping) * stepping + ty;
int iy = (int) Math.round(y);
g.drawLine(rulerSize, iy, 0, iy);
String text = format((y - ty) / increment);
// Rotates the labels in the vertical ruler
AffineTransform at = ((Graphics2D) g).getTransform();
((Graphics2D) g).rotate(-Math.PI / 2, 0, iy);
g.drawString(text, 1, iy + labelFont.getSize());
((Graphics2D) g).setTransform(at);
iy += (int) Math.round(stepping / 4);
g.drawLine(rulerSize, iy, smallTick, iy);
iy += (int) Math.round(stepping / 4);
g.drawLine(rulerSize, iy, middleTick, iy);
iy += (int) Math.round(stepping / 4);
g.drawLine(rulerSize, iy, smallTick, iy);
}
}
// Draw Mouseposition
g.setColor(Color.green);
if (orientation == ORIENTATION_HORIZONTAL)
{
g.drawLine(mouse.x, rulerSize, mouse.x, 0);
}
else
{
g.drawLine(rulerSize, mouse.y, 0, mouse.y);
}
} | 8 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
StudentAttendance other = (StudentAttendance) obj;
if (internalID == null) {
if (other.internalID != null)
return false;
} else if (!internalID.equals(other.internalID))
return false;
return true;
} | 6 |
public String getQuery() {
return query;
} | 0 |
public String getWrong() {
return wrong;
} | 0 |
private void listaVariaveis(boolean varLocal) {
// <lista_variaveis> ::= <variavel> <lista_variaveis> | “}”
// <variavel>::= <tipo_primitivo> <id> <compl_declaracao_var>| <id><id> “;”
// <compl_declaracao_var> ::= “=” <valor> “;” | <definição_matriz>
// <definição_matriz> ::= “[” <inteiro> “]” <definição_matriz> | “;”
if (varLocal == true) {
varLocal2 = 1;
if (!acabouListaTokens()) {
nextToken();
if (tipoDoToken[1].equals(" {")) {
if (!acabouListaTokens()) {
nextToken();
this.listaDeCamposVariaveis();
} else {
System.out.println("FIM DE ARQUIVO!");
}
}
} else {
System.out.println("FIM DE ARQUIVO!");
}
} else if (varLocal == false) {
System.out.println("ENTREI EM FALSE");
if (!acabouListaTokens()) {
nextToken();
if (tipoDoToken[1].equals(" {")) {
if (!acabouListaTokens()) {
nextToken();
this.listaDeCamposVariaveis();
} else {
System.out.println("FIM DE ARQUIVO!");
}
}
} else {
System.out.println("FIM DE ARQUIVO!");
}
}
} | 8 |
public void Download10KbyCIK(String symbol, boolean isCurrent) {
GetURL gURL = new GetURL();
ArrayList<String> URLs = gURL.Get10kURLwithCIK(symbol, isCurrent);
Iterator<String> it = URLs.iterator();
while(it.hasNext()) {
String str = it.next();
int index0 = str.indexOf("data");
int index1 = str.indexOf("/", index0+5);
String CIK = str.substring(index0+5, index1);
int index2 = str.lastIndexOf('.');
if(index2 <= 14) continue;
String year, url;
if(isCurrent == false) {
url = str.substring(0, str.length() - 2);
year = str.substring(str.length() - 2);
if(Integer.parseInt(year) < 60) {
year = "20" + year;
}
else {
year = "19" + year;
}
}
else {
// this part need to improve if used later
// we don't use this now
year = "2014"; //this year is 2014, will be false next year.
url = str;
}
String ext = url.substring(index2);
// 10K folder should exist
String fileName = "./10K/" + CIK + "_" + year + ".txt";// + "_" + index + ext;
//DownLoad10K(url, fileName);
StringBuffer sb_10K = Get10kContent(url);
String s_10K = null;
if(ext.equals(".txt")) {
s_10K = sb_10K.toString();
}
else if(sb_10K != null) {
s_10K = extractAllText(sb_10K.toString());
}
try {
if(s_10K != null && s_10K.length() > 0) {
FileWriter fw = new FileWriter(fileName);
fw.write(s_10K);
fw.close();
System.out.println(fileName);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} | 9 |
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (this.record != null) {
if (qName.equals(this.className)) {
// окончание чтения записи
this.records.put(this.record.getUnique(), this.record);
this.record = null;
} else if (this.record.getUniqueFields().contains(qName)) {
// Задание значения уникального поля
ReflectionHelper.setFieldValue(this.record,
"String", qName, this.fieldValue.toString());
} else {
// Задание значения обычного поля (type м.б. null)
ReflectionHelper.setFieldValue(this.record,
this.type, qName, this.fieldValue.toString());
}
}
} | 3 |
public void setSizeField() {
boolean fault = true;
while (fault) {
System.out.print("Введите размерность игрового поля: ");
Scanner scanner = new Scanner(System.in);
try {
this.field.sizeField = scanner.nextInt();
fault = false;
}catch(Exception er){
System.out.println("Неверный ввод, попробуйте снова!!");
}
}
} | 2 |
@Override
public Set<AndroidMethod> parse() throws IOException {
Set<AndroidMethod> methodList = new HashSet<AndroidMethod>(INITIAL_SET_SIZE);
BufferedReader rdr = readFile();
String line = null;
Pattern p = Pattern.compile(regex);
String currentPermission = null;
while ((line = rdr.readLine()) != null) {
if(line.startsWith("Permission:"))
currentPermission = line.substring(11);
else{
Matcher m = p.matcher(line);
if(m.find()) {
AndroidMethod singleMethod = parseMethod(m, currentPermission);
if (singleMethod != null) {
if(!methodList.add(singleMethod)){
for (AndroidMethod am : methodList)
if (am.equals(singleMethod)) {
am.addPermission(currentPermission);
break;
}
}
}
}
}
}
try {
if (rdr != null)
rdr.close();
} catch (IOException e) {
e.printStackTrace();
}
return methodList;
} | 9 |
public void setExtractMode(String extractMode) {
if( !extractMode.equals(EXTRACT_MODE_TRUST) && !extractMode.equals(EXTRACT_MODE_INFER) )
{
throw new RuntimeException("Invalid setting " + extractMode + " for parameter extractMode");
}
this.extractMode = extractMode;
} | 2 |
public double findMedianSortedArrays(int A[], int B[]) {
int m = A.length, n = B.length;
assert (m + n > 0);
if (m == 0) {
return n % 2 == 1 ? B[n / 2] : (double) (B[n / 2 - 1] + B[n / 2]) / 2.;
}
if (n == 0) {
return m % 2 == 1 ? A[m / 2] : (double) (A[m / 2 - 1] + A[m / 2]) / 2.;
}
int temp = findKthPosition(A, B, (m + n) / 2 + 1);
if (temp < 0) {
temp = findKthPosition(B, A, (m + n) / 2 + 1);
temp = B[temp];
} else {
temp = A[temp];
}
int temp1 = temp;
if ((m + n) % 2 == 0) {
temp1 = findKthPosition(A, B, (m + n) / 2);
if (temp1 < 0) {
temp1 = findKthPosition(B, A, (m + n) / 2);
temp1 = B[temp1];
} else {
temp1 = A[temp1];
}
}
return (double) (temp + temp1) / 2.;
} | 7 |
private static void calcNoOfNodes(Node node) {
if (node instanceof Parent) {
if (((Parent) node).getChildrenUnmodifiable().size() != 0) {
ObservableList<Node> tempChildren = ((Parent) node).getChildrenUnmodifiable();
noOfNodes += tempChildren.size();
for (Node n : tempChildren) {
calcNoOfNodes(n);
//System.out.println(n.getStyleClass().toString());
}
}
}
} | 3 |
private HttpHandler createContext() {
return new HttpHandler() {
@Override
public void handle(HttpExchange he) throws IOException {
he.getResponseHeaders().add("Access-Control-Allow-Origin", "*");
String path = he.getRequestURI().getPath();
int lastIndexOf = path.lastIndexOf("/");
if("GET".equalsIgnoreCase(he.getRequestMethod())){
if (lastIndexOf > 0){
try {
int id = Integer.parseInt(path.substring(lastIndexOf + 1));
he.sendResponseHeaders(200, 0);
OutputStream responseBody = he.getResponseBody();
String json = new Gson().toJson(facade.getPersonAsJSON(id));
System.out.println(json);
responseBody.write(json.getBytes());
System.out.println("done");
} catch (NotFoundException ex) {
Logger.getLogger(webServer.class.getName()).log(Level.SEVERE, null, ex);
}
}else{
he.sendResponseHeaders(200, 0);
try (OutputStream responseBody = he.getResponseBody())
{
String json = new Gson().toJson(facade.getPersonsAsJSON());
System.out.println(json);
responseBody.write(json.getBytes());
}
}
}
if("DELETE".equalsIgnoreCase(he.getRequestMethod())){
if (lastIndexOf > 0){
he.sendResponseHeaders(200, 0);
try (OutputStream responseBody = he.getResponseBody()){
int id = Integer.parseInt(path.substring(lastIndexOf + 1));
String json = new Gson().toJson(facade.delete(id));
System.out.println(json);
responseBody.write(("Deleted: " + json).getBytes());
} catch (NotFoundException ex) {
Logger.getLogger(webServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
if("POST".equalsIgnoreCase(he.getRequestMethod())){
String message = "";
Scanner scanner = new Scanner(he.getRequestBody());
while (scanner.hasNextLine())
{
message += scanner.nextLine();
}
he.sendResponseHeaders(200, 0);
try (OutputStream responseBody = he.getResponseBody()){
String json = new Gson().toJson(facade.addPersonFromGson(message));
System.out.println(json);
responseBody.write(("Added: " + json).getBytes());
}
}
}
};
} | 8 |
private void disp(int[] bowl) {
String str = "|";
for (int i = 0; i < bowl.length; i++) {
str += " " + bowl[i] + " |";
}
str += "\n";
System.out.println(str);
} | 1 |
public void printReport(ArrayList<Diff> aDiffL) throws Exception {
ArrayList<Diff> firstL, secondL;
String report;
String newL = System.getProperty("line.separator");
//separating the diffs depending on their schema
firstL = new ArrayList();
secondL = new ArrayList();
for (Diff d : aDiffL) {
if (d.getSchema() == 1) {
firstL.add(d);
} else if (d.getSchema() == 2) {
secondL.add(d);
} else {
throw new Exception("Invalid Schema number detected");
}
}
//title of the report
report = "SchemaDiffer Report" + newL + newL;
//first list results
if (!firstL.isEmpty()) {
report += "Elements existing in the first schema ONLY: " + newL + newL;
for (Diff d : firstL) {
report += d.toString() + newL;
}
report += newL + "--------" + newL + newL;
} else {
report += "No Elements" + newL;
}
//second list results
if (!secondL.isEmpty()) {
DifferUtils.writeFile(report, "report.txt");
report += "Elements existing in the second schema ONLY: " + newL + newL;
for (Diff d : secondL) {
report += d.toString() + newL;
}
report += newL + "--------" + newL + newL;
} else {
report += "No Elements" + newL + newL;
}
report += "End of Report" + newL;
report += "Brought to you by Alex Hughes <[email protected]> || github.com/ahughes117/schema_differ" + newL;
//finally writing the file
DifferUtils.writeFile(report, "report.txt");
} | 7 |
@SuppressWarnings("unchecked")
private void thursdayCheckActionPerformed(java.awt.event.ActionEvent evt) {
if(this.dayChecks[4].isSelected()) {
this.numSelected++;
if(this.firstSelection) {
stretch();
}
this.models[4] = new DefaultListModel<Object>();
this.thursdayJobList.setModel(this.models[4]);
this.thursdayScrollPane.setViewportView(this.thursdayJobList);
this.thursdayJobName.setColumns(20);
this.thursdayLabel.setText("Job Name:");
this.thursdayAddJob.setText("Add Job");
this.thursdayAddJob.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
if(!Config.this.thursdayJobName.getText().isEmpty()) {
Config.this.models[4].addElement(Config.this.thursdayJobName.getText());
Config.this.thursdayJobList.setModel(Config.this.models[4]);
Config.this.thursdayJobName.setText("");
}
}
});
this.thursdayDeleteJob.setText("Delete Job");
this.thursdayDeleteJob.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
while(!Config.this.thursdayJobList.isSelectionEmpty()) {
int n = Config.this.thursdayJobList.getSelectedIndex();
Config.this.models[4].remove(n);
}
}
});
javax.swing.GroupLayout thursdayTabLayout = new javax.swing.GroupLayout(this.thursdayTab);
this.thursdayTab.setLayout(thursdayTabLayout);
thursdayTabLayout.setHorizontalGroup(
thursdayTabLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(thursdayTabLayout.createSequentialGroup()
.addContainerGap()
.addComponent(this.thursdayScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 182, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(thursdayTabLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(thursdayTabLayout.createSequentialGroup()
.addComponent(this.thursdayLabel)
.addGroup(thursdayTabLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(thursdayTabLayout.createSequentialGroup()
.addGap(14, 14, 14)
.addComponent(this.thursdayAddJob))
.addGroup(thursdayTabLayout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(this.thursdayJobName, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addComponent(this.thursdayDeleteJob))
.addContainerGap(431, Short.MAX_VALUE))
);
thursdayTabLayout.setVerticalGroup(
thursdayTabLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(thursdayTabLayout.createSequentialGroup()
.addContainerGap()
.addGroup(thursdayTabLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(thursdayTabLayout.createSequentialGroup()
.addGroup(thursdayTabLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(this.thursdayJobName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(this.thursdayLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(this.thursdayAddJob)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(this.thursdayDeleteJob))
.addComponent(this.thursdayScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(25, Short.MAX_VALUE))
);
this.dayTabs.addTab("Thursday", this.thursdayTab);
} else {
this.numSelected--;
stretch();
this.dayTabs.remove(this.thursdayTab);
}
} | 4 |
public static boolean resizeVideo(Rectangle newVideoBounds)
{
try
{
Player player = null;
ServiceContext serviceContext = ServiceContextFactory.getInstance().getServiceContexts()[0];
if (serviceContext != null && serviceContext.getService() != null && serviceContext.getServiceContentHandlers() != null)
{
ServiceContentHandler[] handlers = serviceContext.getServiceContentHandlers();
for (int i = 0; i < handlers.length; i++)
{
if (handlers[i] instanceof Player)
{
player = (Player) handlers[i];
break;
}
}
}
if (null == player)
{
System.out.println("Player is null...");
return false;
}
Control playerControl = player.getControl("javax.tv.media.AWTVideoSizeControl");
if (playerControl instanceof AWTVideoSizeControl)
{
AWTVideoSizeControl videoSizeControl = (AWTVideoSizeControl) playerControl;
Rectangle videoSizeSource = videoSizeControl.getSize().getSource();
Rectangle destination = getResolutionResolvedRect(newVideoBounds);
AWTVideoSize newVideoSize = new AWTVideoSize(videoSizeSource, destination);
return videoSizeControl.setSize(newVideoSize);
}
}
catch (Exception e)
{
System.out.println("Exception caught in video resize code. This is "
+ "expected in PC, but in STB, investigate the rootcause");
}
return false;
} | 8 |
public V valAt(K key) {
if (key == null) return getNullVal();
V val = map.get(key);
if (val != null) return val;
val = lookup.valAt(key);
if (val != null) map.putIfAbsent(key, val);
return val;
} | 3 |
public static Vector<Caddie> getContenuCaddie () throws BDException {
Vector<Caddie> res = new Vector<Caddie>();
String requete = "select idr, nomS, TO_CHAR(DATEREP, 'DD/MM/YYYY HH24:MI') AS DATEREP, lecaddie.numS, lecaddie.numZ, nomC, qt from lesspectacles, lecaddie, leszones where lesspectacles.numS=lecaddie.nums and lecaddie.numz = leszones.numz order by idr asc";
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
try {
conn = BDConnexion.getConnexion();
stmt = conn.createStatement();
rs = stmt.executeQuery(requete);
while (rs.next()) {
res.addElement(new Caddie(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getInt(4), rs.getInt(5), rs.getString(6) , rs.getInt(7)));
}
} catch (SQLException e) {
throw new BDException("Problème dans l'interrogation du caddie (Code Oracle : "+e.getErrorCode()+")");
}
finally {
BDConnexion.FermerTout(conn, stmt, rs);
}
return res;
} | 2 |
public int uniquePaths(int m, int n) {
// Note: The Solution object is instantiated only once and is reused by
// each test case.
int[][] grid = new int[m][n];
for (int i = m - 1; i >= 0; --i) {
grid[i][n - 1] = 1;
}
for (int j = n - 1; j >= 0; --j) {
grid[m - 1][j] = 1;
}
for (int i = m - 2; i >= 0; --i) {
for (int j = n - 2; j >= 0; --j) {
grid[i][j] = grid[i][j + 1] + grid[i + 1][j];
}
}
return grid[0][0];
} | 4 |
public static int countPageHtmlCode(final String filePath) throws IOException{
File file = new File(filePath);
FileReader leavesFileReader = new FileReader(file);
BufferedReader br = new BufferedReader(leavesFileReader);
int count = 0;
String line;
while((line = br.readLine()) != null){
if(line.contains("page_html_code")){
count++;
}
}
br.close();
return count;
} | 2 |
private boolean processConjunction(List<Boolean> values,
Conjunction conjuntion) {
boolean retVal = true;
if (conjuntion.equals(Conjunction.Or)) {
retVal = false;
}
for (Boolean bool : values) {
if (conjuntion.equals(Conjunction.And)) {
retVal = retVal && bool;
}
if (conjuntion.equals(Conjunction.Or)) {
retVal = retVal || bool;
}
}
return retVal;
} | 6 |
private int scoreBowl(int[] bowl) {
int score = 0;
for (int i = 0; i < preferences.length; i++) {
score += bowl[i] * preferences[i];
}
return score;
} | 1 |
private void refreshClassList() {
selectClassContainer.clear();
// first show all classes
for (Image img : selectClassImageList) {
selectClassContainer.add(img);
}
// then set visibility of classbuttons depending on classes taken
int i = 1;
if (DDOCharacter.getTakenClasses().size() >= 3) {
selectClassContainer.clear();
for (Image img : selectClassImageList) {
if(DDOCharacter.classTaken(i)){
selectClassContainer.add(img);
}
else{
//making this a new image also gets rid of the handler for adding classes
selectClassContainer.add(new Image("images/general/forbidden50x50black.png"));
}
++i;
}
}
} | 4 |
public void testBuild00(){
TrieBuilder builder = DoubleArrayTrieImpl.createBuilder();
try {
builder.build(null);
fail("");
} catch (IllegalArgumentException e){
assertEquals("The list of keys is null.", e.getMessage());
} catch (Exception e){
fail("");
}
try {
List<String> keys = new ArrayList<String>();
keys.add("abac");
keys.add("bab");
keys.add("ab");
keys.add("cc");
builder.build(keys);
fail("");
} catch (IllegalArgumentException e){
assertEquals("The list of keys has not been sorted yet, some duplications have been found, or some keys are empty.", e.getMessage());
} catch (Exception e){
fail("");
}
try {
List<String> keys = new ArrayList<String>();
keys.add("abac");
keys.add("bab");
keys.add("bab");
keys.add("cc");
builder.build(keys);
builder.build(null);
fail("");
} catch (IllegalArgumentException e){
assertEquals("The list of keys has not been sorted yet, some duplications have been found, or some keys are empty.", e.getMessage());
} catch (Exception e){
fail("");
}
try {
List<String> keys = new ArrayList<String>();
keys.add("");
keys.add("abc");
keys.add("abcd");
keys.add("cc");
builder.build(keys);
builder.build(null);
fail("");
} catch (IllegalArgumentException e){
assertEquals("The list of keys has not been sorted yet, some duplications have been found, or some keys are empty.", e.getMessage());
} catch (Exception e){
fail("");
}
} | 8 |
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (super.equals(o)) {
return true;
}
orgataxe.entity.Vehicle vehicle = (orgataxe.entity.Vehicle) o;
if (licencePlate != null ? !licencePlate.equals(vehicle.licencePlate) : vehicle.licencePlate != null) {
return false;
}
return true;
} | 6 |
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded,
boolean leaf, int row, boolean hasFocus)
{
JLabel result = (JLabel) super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row,
hasFocus);
if (Prefs.getInstance().getPrefs().getBoolean(Integer.toString(result.getText().hashCode()), false))
result.setForeground(Color.LIGHT_GRAY);
return result;
} | 1 |
public TestLinkUriResolverTest(URI expectedUri, final TestLinkId<?> testLinkId) {
this.testLinkId = testLinkId;
this.expectedUri = expectedUri;
} | 1 |
private static void printDeck(String[] bestDeck) {
for (String s : bestDeck) {
System.out.print(s + ", ");
}
} | 1 |
public Point toGate(Point current){
double ox = 0, oy = 0;
Point gate = new Point(dimension/2, dimension/2);
// if both the x and y of the piper are farther than 1 from the gate, change both
// !finishround signifies that the piper is not ready to move towards the target yet
if(Math.abs(gate.x - current.x) > 1 && Math.abs(gate.y - current.y) > 1 && !finishround){
double dist = distance(current, gate);
assert dist > 0;
ox = (gate.x - current.x) / dist * mpspeed;
oy = (gate.y - current.y) / dist * mpspeed;
}
// if the x of the piper is farther than 1 from the gate, change x
else if(Math.abs(gate.x - current.x) > 1 && !finishround){
double dist = distance(current, gate);
assert dist > 0;
ox = (gate.x - current.x) / dist * mpspeed;
}
// if the y of the piper is farther than 1 from the gate, change y
else if(Math.abs(gate.y - current.y) > 1 && !finishround){
double dist = distance(current, gate);
assert dist > 0;
oy = (gate.y - current.y) / dist * mpspeed;
}
// now the piper is close to the gate, so it can move towards the target
else if(Math.abs(target.x - current.x) > 1){
finishround = true; // change finishround to false to show that the piper has finished sweeping its region and can move to the left side
double dist = distance(current, target);
assert dist > 0;
ox = (target.x - current.x) / dist * mpspeed;
}
Point next = new Point(current.x + ox, current.y + oy);
return next;
} | 8 |
public static String[] removeSlashStrings(String[] data)
{
ArrayList<String> result = new ArrayList<String>();
for (int i = 0; i < data.length; i++)
{
if (!data[i].equals("/"))
{
result.add(data[i]);
}
}
String[] res = new String[result.size()];
result.toArray(res);
return res;
} | 2 |
public void keyReleased(KeyEvent e)
{
int keycode = e.getKeyCode();
System.out.println("key released: ");
switch(keycode)
{
case KeyEvent.VK_UP:
System.out.println("up");
this.upPress = false;
break;
case KeyEvent.VK_DOWN:
System.out.println("down");
this.downPress = false;
break;
case KeyEvent.VK_LEFT:
System.out.println("left");
this.leftPress = false;
break;
case KeyEvent.VK_RIGHT:
System.out.println("right");
this.rightPress = false;
break;
case KeyEvent.VK_SPACE:
System.out.println("space");
this.spacePress = false;
break;
}
} | 5 |
private CommandResponse doGet(String commandName, List<Pair<String,String>> headers, Object commandParameters, Class<?> responseCastClass) //throws ClientException may need to add this in later
{
CommandResponse result = null;
int clientVersion = 0;
if(commandName.contains("game/model")) {
int modelIndex = commandName.indexOf("=") + 1;
if(modelIndex > -1) {
clientVersion = Integer.parseInt(commandName.substring(modelIndex));
}
commandName = "game/model";
}
switch(commandName) {
case "game/listAI":
result = new CommandResponse(null, 200, MOCK_AIS, null);
break;
case "game/commands":
LogEntry[] messages = new LogEntry[getCommandsLog().getLogMessages().size()];
messages = getCommandsLog().getLogMessages().toArray(messages);
result = new CommandResponse(null, 200, messages, null);
break;
case "game/model":
if(VALID_JOINED_GAME_COOKIE.equals(headers.get(0).getValue())) {
if(clientVersion != getServerModel().getVersion()) {
result = new CommandResponse(null, 200, getServerModel(), null);
}
else {
result = new CommandResponse(null, 200, null, null);
}
}
else {
result = new CommandResponse(null, 404, null, null);
}
break;
case "games/list":
result = new CommandResponse(null, 200, GAMES_ARRAY, null);
break;
default:
result = new CommandResponse(null, 400, "default case", "Error: Unhandled Get Case Reached!");
}
return result;
} | 9 |
private InetAddress findMatch(String dest) {
InetAddress realDstIP = null;
int prefixLength = 0;
/* Finds the best matching prefix for the destination IP */
for (String prefix : prefixes.keySet()) {
String[] prefixArr = prefix.split("\\.");
String[] destArr = dest.split("\\.");
String p = "";
dest = "";
for (int i = 0; i < prefixArr.length; i++) {
p += String.format("%3s", prefixArr[i]).replace(' ', '0');
}
for (int i = 0; i < destArr.length; i++) {
dest += String.format("%3s", destArr[i]).replace(' ', '0');
}
if (dest.startsWith(p) && p.length() > prefixLength) {
realDstIP = prefixes.get(prefix);
prefixLength = prefix.length();
}
}
return realDstIP;
} | 5 |
public boolean isPrime(long num) {
if (num % 2 == 0) {return false;}
else {
for (long x = 3l; x*x < num; x += 2) {
if(num % x == 0) {
return false;
}
}
}
return true;
} | 3 |
static RunnerConfig parseCommandLine( Options opts, String[] args ) throws ParseException, UnknownHostException {
final CommandLine cl = new GnuParser().parse( opts, args );
if( cl.hasOption( OPT_h ) ) {
// Jnetcat -l
new HelpFormatter().printHelp( "Jnetcat [ -h ] [ -l listenPort [ listenAddr ] ] ", opts );
return null;
} else if( cl.hasOption( OPT_l ) ) {
// Jnetcat -l listenPort [ bindAddr ]
if( 2 <= cl.getArgs().length ) throw new IllegalArgumentException( "too much parameters for '-l'" );
// Check listen port
final int listenPort = Integer.parseInt( cl.getOptionValue( OPT_l ).trim() );
if( listenPort < 1 || 65535 < listenPort ) throw new IllegalArgumentException( "listenPort range ( 1-65535 ): listenPort=" + listenPort );
// Check bind address (optional)
if( cl.getArgs().length == 1 ) {
final InetAddress bindAddr = parseInetAddress( cl.getArgs()[0].trim(), "bindAddr" );
log.debug( "bindAddr=[{}]", bindAddr );
return DataReceiverConfig.getInstance( listenPort, bindAddr );
}
return DataReceiverConfig.getInstance( listenPort );
} else if( cl.getArgs().length == 2 ) {
// Jnetcat targetAddr targetPort
final InetAddress targetAddr = parseInetAddress( cl.getArgs()[0].trim(), "targetAddr" );
final int targetPort = Integer.parseInt( cl.getArgs()[1].trim() );
if( targetPort < 1 || 65535 < targetPort ) throw new IllegalArgumentException( "targetPort range ( 1-65535 ): listenPort=" + targetPort );
return DataSenderConfig.getInstance( targetAddr, targetPort );
}
throw new IllegalArgumentException( "invalid parameter." + cl.getArgList() );
} | 9 |
public boolean delBannedWord(String badWord) {
if (badWord.indexOf(":") > 0) {
String thisSplut[] = badWord.split(":",2);
badWord = thisSplut[0];
}
if (wordList.containsKey(badWord)) {
wordList.remove(badWord);
saveWordList();
return true;
} else {
return false;
}
} | 2 |
public static DatabaseClosure createClosure(String name, File target) {
if (closures.containsKey(name))
throw new RuntimeException("Closure with that name already exists.");
DatabaseClosure closure = new DatabaseClosure(name, target);
return closures.put(name, closure);
} | 1 |
private static Map<? extends Attribute, ?> fixattrs(Map<? extends Attribute, ?> attrs) {
Map<Attribute, Object> ret = new HashMap<Attribute, Object>();
for(Map.Entry<? extends Attribute, ?> e : attrs.entrySet()) {
if(e.getKey() == TextAttribute.SIZE) {
ret.put(e.getKey(), ((Number)e.getValue()).floatValue());
} else {
ret.put(e.getKey(), e.getValue());
}
}
return(ret);
} | 8 |
private boolean pushPrimitiveArg(Class<?> argclass, Object arg) {
if (argclass.equals(Float.class)) {
pushFloatArg((float) arg);
} else if (argclass.equals(Integer.class)) {
pushIntArg((int) arg);
} else if (argclass.equals(Long.class)) {
pushLongArg((long) arg);
} else if (argclass.equals(Double.class)) {
pushDoubleArg((double) arg);
} else if (argclass.equals(Boolean.class)) {
pushBooleanArg((boolean) arg);
} else if (argclass.equals(Byte.class)) {
pushByteArg((byte) arg);
} else {
return false;
}
// if we took one of the push paths, return true
return true;
} | 7 |
public double getDuration() {
// Return nothing if we don't have sufficient information.
if(this.dateRoundStarted == null || this.dateRoundEnded == null)
return -1;
// Get our round duration
long diffMilliseconds = (this.dateRoundEnded.getTime() - this.dateRoundStarted.getTime());
double seconds = (double)diffMilliseconds / 1000;
return seconds;
} | 2 |
public static void main(String[] args) {
if(true && true){
System.out.println(1);
}
if(true && false){
System.out.println(2);
}
if(false && true){
System.out.println(3);
}
if(false && false){
System.out.println(4);
}
} | 8 |