method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
55cc1877-c4e7-48e9-ad4c-b5c60c78babb
3
public int checkReactionID(int IDCheck){ int index=-1; for(int i=0; i<graphNodes.size(); i++){ if( (graphNodes.get(i).getID()==IDCheck) && (graphNodes.get(i).getType() == _REACTION_) ){ index=i; } } return index; }
7dc72bf2-66ba-483a-b179-9012ba207028
5
public String getSchedule() { ByteArrayOutputStream outputString = new ByteArrayOutputStream(); PrintWriter output = new PrintWriter(outputString, true); if (timePoints.size() == 0) return ""; BusStop[] tp = new BusStop[timePoints.size()]; output.println("SCHEDULE FOR LINE " + name); for(int i=0, j=0; i < route.size(); i++) { BusStop bs = route.get(i); if (bs instanceof TimePoint) { tp[j++] = bs; output.printf("%20s",bs.getName()); } } output.println(); Time next = first; while (next.compareTo(last) != 1) { Time nextTimePoint = next.clone(); for(int i=0; i < tp.length; i++) { nextTimePoint = nextTimePoint.advanceMinutes(timePoints.get(i)); output.printf("%20s",nextTimePoint); } output.println(); next = next.advanceMinutes(period); } output.println(); return outputString.toString(); }
04e38a1d-47fc-4c3a-a7a5-9acb26471331
7
@Override public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException { Input input = gc.getInput(); Character.update(input, delta); for (Iterator<Enemy> iterator = mobs.iterator(); iterator.hasNext(); ) { Enemy e = iterator.next(); e.update(delta); } // check collisions checkCollisions(); if(input.isKeyPressed(Input.KEY_F5)){ init(gc, sbg); } if(level != -1) timer -= delta; // timer runs out if(timer < -2){ Sounds.die.play(); level--; initLevel(); } if(gameOver && theendTimer < 9000){ theendTimer += delta; } particles.update(delta); if(input.isKeyPressed(Input.KEY_ENTER)){ initLevel(); } }
f9f5e9be-7f91-48c2-aa27-ef53f9d35c31
2
public ContainmentProblem(Query query, Query view, String shouldMatch) { this.query = query; this.view = view; if (shouldMatch.equals("true")) { this.shouldMatch = 0; } else if (shouldMatch.equals("false")) { this.shouldMatch = 1; } //System.out.println(query); //System.out.println(view); //calcViewPositions(); //System.out.println(); }
1ddfd4d8-cfb2-411d-91e0-ab6650e1169a
2
public static List<Integer> parseNumericStringArrayObject(Object object) throws InvalidRpcDataException { if (object == null) { return null; } if (object instanceof String[]) { return parseNumericStringArray((String[]) object); } else { throw new InvalidRpcDataException("Expected an array of numeric Strings, but got: " + object.getClass().getName()); } }
41e1d1e3-9d33-437a-877d-015dccdca92e
9
private void readToken() { while (true) { prompt(); String token = _input.findWithinHorizon(TOKEN_PATN, 0); if (token == null) { token = "*EOF*"; } else if (token.startsWith("'")) { if (token.length() == 1 || !token.endsWith("'")) { throw error("unterminated literal constant"); } } else if (token.startsWith("/*")) { if (token.length() < 4 || !token.endsWith("*/")) { throw error("unterminated comment"); } continue; } else if (token.endsWith("\n")) { _shouldPrompt = true; continue; } _buffer.add(token); _continued = !token.equals(";"); return; } }
52c4a36a-32aa-42bc-b0de-613fc97cba9b
8
static final int method2064(int i, int i_0_, int i_1_, int i_2_) { anInt3549++; if (aa_Sub1.aSArray5191 == null) return 0; int i_3_ = i >> 937361225; int i_4_ = i_2_ >> -1589419447; if ((i_3_ ^ 0xffffffff) > -1 || (i_4_ ^ 0xffffffff) > -1 || i_3_ > -1 + Class367_Sub4.mapSizeX || ((Class348_Sub40_Sub3.mapSizeY + -1 ^ 0xffffffff) > (i_4_ ^ 0xffffffff))) return 0; int i_5_ = i_0_; if ((i_5_ ^ 0xffffffff) > -4 && (Class348_Sub33.settingFlags[1][i_3_][i_4_] & 0x2 ^ 0xffffffff) != -1) i_5_++; if (i_1_ != 11219) nativeLibraries = null; return aa_Sub1.aSArray5191[i_5_].method3986(i, i_2_, (byte) -113); }
027d1174-face-41d5-8a48-e60c1c2cff05
1
@Override public void destroy() { super.destroy(); if (gameTimer != null) { gameTimer.cancel(); } }
1f4736e9-9406-47a5-a49d-5a7b09bd02de
6
public static final String getName(final byte level) { switch (level) { case 0: return "Rookie"; case 1: return "Genin"; case 2: return "Chunin"; case 3: return "Jounin"; case 4: return "Sannin"; case 5: return "Hokage"; default: return "SystemError"; } }
68639edc-fbf4-40d5-8d56-5eb402b20ddf
3
@Override public void update(final int delta) { if (Controls.getInstance().wasEnter()) isStarted = true; if (!isStarted) return; if (currentLevel.isFinished()) { System.out.println("Level comlete..."); System.out.println("New Level"); } currentLevel.update(delta); }
3cedcdbc-78fa-4ff9-8241-4b7ab173d87c
8
private void jButton21ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton21ActionPerformed // TODO add your handling code here: String str=""; int l; str = this.jTextField23.getText().toUpperCase(); if(Biblio.containsKey(str)){ j = (Juego) Biblio.get(str); this.jPanel7.setVisible(true); this.jTextField20.setText(j.getNombre()); this.jTextField21.setText(j.getEmpresa()); for(int q=0;q<j.getPlataformas().size();q++){ rr.addElement(j.getPlataformas().get(q)); } this.jList5.setModel(rr); str = j.getGenero(); for(l=0;l<14;l++){ if(this.jComboBox7.getItemAt(l).equals(str)){ this.jComboBox7.setSelectedIndex(l); } } Integer w; w = j.getAño(); for(l=0;l<62;l++){ if(this.jComboBox6.getItemAt(l).equals(w)){ this.jComboBox6.setSelectedIndex(l); } } str = j.getClasificacion(); for(l=0;l<7;l++){ if(this.jComboBox8.getItemAt(l).equals(str)){ this.jComboBox8.setSelectedIndex(l); } } this.jTextField23.setVisible(false); this.jLabel31.setVisible(false); this.jButton21.setVisible(false); this.jButton22.setVisible(false); }else{ JOptionPane.showMessageDialog(null,"El Juego No Esta En La Base De Datos / Verifique Escritura"); return; } }//GEN-LAST:event_jButton21ActionPerformed
d058a616-6c2f-47b8-bc9e-84f9f327caf5
3
public List<String> logInUser() { List<String> serviceList = null; // Get user's service list if (user.getUserType().equals(UserTypes.buyer)) { serviceList = med .logInBuyer(user.getUsername(), user.getPassword()); } else { if (user.getUserType().equals(UserTypes.seller)) { serviceList = med.logInSeller(user.getUsername(), user.getPassword()); } else { System.err.println("User type undefined"); System.exit(1); } } if (serviceList != null) user.setUserServiceList(serviceList); return serviceList; }
09b4ee94-a008-4d0d-956a-4bcbe6f252c6
5
private ArrayList<members> searchForMembers(ArrayList<members> memberList, String input){ ArrayList<members> updated_memberList = new ArrayList<members>(); for(members current: memberList){ try { if (current.getId().toString().contains((input))){ updated_memberList.add(current); } } catch( Exception e ) { if (current.getFirstName().toUpperCase().contains(input.toUpperCase())){ updated_memberList.add(current); } else if (current.getFirstName().toUpperCase().contains(input.toUpperCase())){ updated_memberList.add(current); } } } return updated_memberList; }
6361bf72-7156-4413-b9ac-1e7b361c76d6
2
@Override public void epoch(Player p) { if (TRAIN_score && score_file != null) score_net.export(score_file); }
aa33caa0-841f-42bb-8fc0-790fc58e47ff
6
private static float calculatePriceMain(int[] seriesCounts) { Arrays.sort(seriesCounts); int numBooks = 0; int numUniqueBooks = 0; for(int series = 0; series < seriesSize; series++) { numBooks += seriesCounts[series]; if(seriesCounts[series] > 0) { numUniqueBooks++; } } if(numBooks == numUniqueBooks) { return prices[numBooks]; } float minPrice = numBooks * unitPrice; int numCombinations = (int) (Math.pow(2, numUniqueBooks)); for(int combination = 1; combination < numCombinations; combination++) { int[] seriesCountsCopy = seriesCounts.clone(); int[] decrementals = new int[seriesSize]; int combinationCopy = combination; for(int i = seriesSize - 1; i >= 0; i--) { int decremental = combinationCopy & 1; decrementals[i] = decremental; combinationCopy = combinationCopy >> 1; } for(int i = 0; i < seriesSize; i++) { seriesCountsCopy[i] = seriesCountsCopy[i] - decrementals[i]; } minPrice = Math.min(minPrice, calculatePriceMain(seriesCountsCopy) + calculatePriceMain(decrementals)); } return minPrice; }
fa58bfca-dd2b-4ae9-a358-28526ed56e17
8
public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; for (int id = 0; id < shapes.size(); id++) { GradientPaint p = null; if (select + 1 == id) p = new GradientPaint(300, 0, new Color(0xff, 0x5f, 0), 600, 0, new Color(0, 0x5f, 0xff)); else p = new GradientPaint(200, 0, Color.LIGHT_GRAY, 700, 0, Color.DARK_GRAY); g2.setPaint(p); g2.fill(shapes.get(id)); if (id > 0) { g2.setColor(Color.BLACK); g2.draw(shapes.get(id)); } } Font font = new Font("Serif", Font.BOLD, 30); Font font2 = new Font("Serif", Font.BOLD, 20); g2.setFont(font); FontRenderContext frc = g2.getFontRenderContext(); GlyphVector gv = font.createGlyphVector(frc, s[0]); Shape glyph = gv.getOutline(350, 130); g2.draw(glyph); String[] str = getKeyStrings(); for (int i = 0; i < 4; i++) { gv = font.createGlyphVector(frc, s[i + 2]); GlyphVector gv2 = font.createGlyphVector(frc, str[i]); glyph = gv.getOutline(250, 230 + i * 70); Shape glyph2 = gv2.getOutline(500, 230 + i * 70); g2.draw(glyph); g2.draw(glyph2); g2.setFont(font2); if (select == i) { if (frame.isKeybinding()) gv = font2.createGlyphVector(frc, "please select a key"); else gv = font2.createGlyphVector(frc, "to change press " + getKeyString(frame.getEnterKey())); glyph = gv.getOutline(230, 257 + i * 70); g2.draw(glyph); } if (select == 2) { gv = font2.createGlyphVector(frc, s[1]); glyph = gv.getOutline(555, 397); g2.draw(glyph); } if (select == 3) { gv = font2.createGlyphVector(frc, s[7]); glyph = gv.getOutline(585, 467); g2.draw(glyph); } g2.setFont(font); } gv = font.createGlyphVector(frc, s[6]); glyph = gv.getOutline(400, 510); g2.draw(glyph); }
1ffde62e-f988-4280-9737-e6b7acee2845
0
public String getManufacturer() { return manufacturer; }
3bc77ca0-4f5e-49ee-ab9f-9cacbcaf3459
8
public TypeBinding postConversionType(Scope scope) { TypeBinding convertedType = this.resolvedType; // if (this.valueCast != null) // convertedType = this.valueCast; int runtimeType = (this.implicitConversion & IMPLICIT_CONVERSION_MASK) >> 4; switch (runtimeType) { case T_boolean : convertedType = TypeBinding.BOOLEAN; break; case T_short : convertedType = TypeBinding.SHORT; break; case T_char : convertedType = TypeBinding.CHAR; break; case T_int : convertedType = TypeBinding.INT; break; case T_float : convertedType = TypeBinding.FLOAT; break; case T_long : convertedType = TypeBinding.LONG; break; case T_double : convertedType = TypeBinding.DOUBLE; break; default : } if ((this.implicitConversion & BOXING) != 0) { convertedType = scope.environment().computeBoxingType(convertedType); } return convertedType; }
c71f5b24-49d2-489a-a3eb-5cb5655bb48c
4
private static Image drawBorder(Frontier frontier, Image image) { if (image.isRgb()) { // for (Point p : frontier.getInnerBorder()) { // image.setPixel(p.x, p.y, RED, 255); // image.setPixel(p.x, p.y, GREEN, 0); // image.setPixel(p.x, p.y, BLUE, 0); // } for (Point p : frontier.getOuterBorder()) { image.setPixel(p.x, p.y, RED, 0); image.setPixel(p.x, p.y, GREEN, 255); image.setPixel(p.x, p.y, BLUE, 0); } } else if (image.isHsv()) { for (Point p : frontier.getInnerBorder()) { image.setPixel(p.x, p.y, HUE, 35); image.setPixel(p.x, p.y, SATURATION, 1); image.setPixel(p.x, p.y, VALUE, 255); } } return image; }
c74c02cd-43ca-432a-a155-71e96c659a44
9
protected void FillBuff() throws java.io.IOException { if (maxNextCharInd == available) { if (available == bufsize) { if (tokenBegin > 2048) { bufpos = maxNextCharInd = 0; available = tokenBegin; } else if (tokenBegin < 0) bufpos = maxNextCharInd = 0; else ExpandBuff(false); } else if (available > tokenBegin) available = bufsize; else if ((tokenBegin - available) < 2048) ExpandBuff(true); else available = tokenBegin; } int i; try { if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1) { inputStream.close(); throw new java.io.IOException(); } else maxNextCharInd += i; return; } catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; } }
4ad07077-bccf-44be-ab1b-19d28e8d8b9f
5
@Override public boolean onCommand(CommandSender sender, Command cmd, String cmdLabel, String[] args) { try { if(args.length == 4) { int checkradius; int allowednumberofblocks; Material matchmaterial = Material.matchMaterial(args[1]); if(matchmaterial == null) { throw new IllegalArgumentException("Material not found."); } String material = matchmaterial.toString(); try { checkradius = Integer.parseInt(args[2]); }catch(NumberFormatException e) { throw new IllegalArgumentException("Radius must be a Number."); } try { allowednumberofblocks = Integer.parseInt(args[3]); }catch(NumberFormatException e) { throw new IllegalArgumentException("The Amount of blocks must be a Number."); } FileConfiguration config = plugin.getConfig(); config.options().configuration().set("searchfor." + material + ".activate", true); config.options().configuration().set("searchfor." + material + ".checkradius", checkradius); config.options().configuration().set("searchfor." + material + ".allowednumberofblocks", allowednumberofblocks); plugin.saveConfig(); sender.sendMessage(ChatColor.GOLD + "[" + plugin.getName().toString() + "] " + material + " has been added."); } else { throw new IllegalArgumentException("Wrong number of arguments."); } }catch(IllegalArgumentException e) { sender.sendMessage(ChatColor.RED + "[" + plugin.getName().toString() + "] " + e.getMessage()); PluginDescriptionFile description = plugin.getDescription(); sender.sendMessage(ChatColor.GOLD + " " + description.getCommands().get("rub " + args[0].toLowerCase()).get("description")); sender.sendMessage(ChatColor.GOLD + " - usage: " + ChatColor.WHITE + description.getCommands().get("rub " + args[0].toLowerCase()).get("usage")); } return true; }
75472070-f828-4e25-8e82-4f7ccbb7e9e0
0
public AutomatonDirectedGraph(Automaton automaton) { super(automaton); }
3fd8b6a3-8aa7-4a81-bf01-548e5fecc68a
9
void closeNoMsgPlayer() { // Disabled this check... if this is called, the player needs to be closed. // if (blnIsClosing) // { // /* // ** Already closing elsewhere // */ // return; // } blnIsClosing = true; blnWorking = false; removeFromGroup(); if (vctConditions.size() != 0) { engGame.vctCheckConditions.removeElement(this); } engGame.removeDuskObject(this); engGame.vctSockets.removeElement(this); try { sckConnection.shutdownInput(); }catch(Exception e){} try { sckConnection.shutdownOutput(); }catch(Exception e){} try { bfrSocketIn.close(); }catch(Exception e){} savePlayer(); try { rafFile.close(); rafBackup.close(); }catch(Exception e){} if (thnFollowing != null && thnFollowing.isPet()) { thnFollowing.close(); } try { stmOut.close(); }catch(Exception e) {} blnStopThread = true; engGame.log.printMessage(Log.INFO, sckConnection.getInetAddress().toString()+":"+strName+" has logged out"); engGame.chatMessage(strName+" has logged out.",strName); try { sckConnection.close(); }catch(Exception e){} strName = null; }
7ebec2d3-5f46-4eea-8bc3-2b0901657c56
9
@Override public boolean tick(Tickable ticking, int tickID) { Item I=null; if(affected instanceof Item) I=(Item)affected; if((canBeUninvoked())&&(I!=null)&&(I.owner() instanceof MOB) &&(I.amWearingAt(Wearable.WORN_LEGS)||I.amWearingAt(Wearable.WORN_ARMS))) { final MOB mob=(MOB)I.owner(); if((!mob.amDead()) &&(mob.isMonster()) &&(CMLib.flags().isInTheGame(mob,false))) CMLib.commands().postRemove(mob,I,false); } return super.tick(ticking,tickID); }
9c20f449-213f-46b7-8043-c5731c1b276c
4
@SuppressWarnings("unchecked") private T createExtension(String name) { Class<?> clazz = getExtensionClasses().get(name); if (clazz == null) { throw new IllegalStateException("Error when load extension class(interface: " + iFaceType); } try { T instance = (T) EXTENSION_INSTANCES.get(clazz); if (instance == null) { EXTENSION_INSTANCES.putIfAbsent(clazz, (T) clazz.newInstance()); instance = (T) EXTENSION_INSTANCES.get(clazz); } injectExtension(instance); /*Set<Class<?>> wrapperClasses = cachedWrapperClasses; if (wrapperClasses != null && wrapperClasses.size() > 0) { for (Class<?> wrapperClass : wrapperClasses) { instance = injectExtension((T) wrapperClass.getConstructor(iFaceType).newInstance(instance)); } }*/ return instance; } catch (Throwable t) { throw new IllegalStateException("Extension instance(name: " + name + ", class: " + iFaceType + ") could not be instantiated: " + t.getMessage(), t); } }
30057615-e243-4580-ac2c-37ae1dbdf87d
9
@Override public void update(final int delta) { super.update(delta); if (controls.isRIGHT()) { direction.add(SPEED * delta, 0); left = false; } if (controls.isLEFT()) { direction.add(-SPEED * delta, 0); left = true; } // if (controls.isUP()) { // direction.add(0, -SPEED * delta); // } // if (controls.isDOWN()) { // direction.add(0, SPEED * delta); // } if (controls.isCTRL() && isShotEnable && lastShot > SHOOT_COOLDOWN) { World.getInstance().addEntity(new ShootEntity(pos.copy().add(0, -5), left)); lastShot = 0; } if (controls.wasSpace() && isJumpEnable && lastJump > JUMP_COOLDOWN && gravity.length() < 1.9) { SoundEffect.JUMP.play(); direction.add(0, -SPEED * 50 * 13); lastJump = 0; } lastJump += delta; lastShot += delta; move(delta); }
0728a11e-a82b-4319-b4d3-dad286d5c02d
8
private void drawTooltip() { if(menuActionRow < 2 && itemSelected == 0 && spellSelected == 0) return; String s; if(itemSelected == 1 && menuActionRow < 2) s = "Use " + selectedItemName + " with..."; else if(spellSelected == 1 && menuActionRow < 2) s = spellTooltip + "..."; else s = menuActionName[menuActionRow - 1]; if(menuActionRow > 2) s = s + "@whi@ / " + (menuActionRow - 2) + " more options"; chatTextDrawingArea.method390(4, 0xffffff, s, loopCycle / 1000, 15); }
8e862994-455d-4005-b2a4-7951ecdeccb1
5
public int find(int[] sequence) { int n = sequence.length; int a[] = new int[48]; int ans = 0; int f = 0; for(int i = 0;i < n - 1;i++){ for(int j = i + 1;j < n;j++){ if(sequence[i] != sequence[j]){ ans++; }else{ if(a[sequence[i]] == 0&&f == 0){ ans++; a[sequence[i]]++; f++; } } } } return ans; }
f9229a06-e804-47f3-b5aa-1b6cba657b9f
3
@Override public SpecialTile getSpecialTile(Location loc) { if(!isValidLocation(loc)) return null; for(Location l : specialTiles){ if(l.sameCoord(loc)){ return (SpecialTile) l.getTile(); } } return null; }
a890ba42-21d1-4bc8-8dae-c1b0ada42978
8
public ImagePlus applyWithMask() { final int width = input.getWidth(); final int height = input.getHeight(); final int depth = input.getStackSize(); //final ImagePlus imageOutput = input.duplicate(); //final ImageStack imageStackOutput = imageOutput.getStack(); final ImageStack inputStack = input.getStack(); final ImagePlus binaryOutput = input.duplicate(); final ImageStack binaryStackOutput = binaryOutput.getStack(); // Initialize binary output image // Binarize output image for (int k = 0; k < depth; ++k) for (int i = 0; i < width; ++i) for (int j = 0; j < height; ++j) binaryStackOutput.setVoxel(i, j, k, 1); // Apply 3x3x3 minimum filter IJ.log(" Minimum filtering..."); final long t0 = System.currentTimeMillis(); final double[][][] localMinValues = filterMin3D( input ); if( null == localMinValues ) return null; final long t1 = System.currentTimeMillis(); IJ.log(" Filtering took " + (t1-t0) + " ms."); // find regional minima IJ.showStatus( "Finding regional minima..." ); final AtomicInteger ai = new AtomicInteger(0); final int n_cpus = Prefs.getThreads(); final int dec = (int) Math.ceil((double) depth / (double) n_cpus); Thread[] threads = ThreadUtil.createThreadArray(n_cpus); for (int ithread = 0; ithread < threads.length; ithread++) { threads[ithread] = new Thread() { public void run() { for (int k = ai.getAndIncrement(); k < n_cpus; k = ai.getAndIncrement()) { int zmin = dec * k; int zmax = dec * ( k + 1 ); if (zmin<0) zmin = 0; if (zmax > depth) zmax = depth; findMinimaRange( zmin, zmax, inputStack, binaryStackOutput, localMinValues, tabMask ); } } }; } ThreadUtil.startAndJoin(threads); IJ.showProgress(1.0); //(new ImagePlus("valued minima", imageStackOutput)).show(); ImagePlus output = new ImagePlus("regional-minima-" + input.getTitle(), binaryStackOutput); output.setCalibration( input.getCalibration() ); return output; } //apply
6c91760a-dc48-4b55-907b-cfdefbc8076e
6
private void processMouse() { while (Mouse.next()) { boolean handled = false; for (MouseEventHandler handler: mouseEventHandlers) { if (Mouse.getEventButton()!=-1) { if (Mouse.getEventButtonState()) { handled = handler.onMouseDown(Mouse.getEventX(), Mouse.getEventY(), Mouse.getEventButton()); } else { handled = handler.onMouseUp(Mouse.getEventX(), Mouse.getEventY(), Mouse.getEventButton()); } } else if (Mouse.getEventDWheel()!=0) { handled = handler.onMouseScroll(Mouse.getEventX(), Mouse.getEventY(), Mouse.getEventDWheel()); } else { handled = handler.onMouseMove(Mouse.getEventX(), Mouse.getEventY(), Mouse.getEventDX(), Mouse.getEventDY()); } if (handled) break; } } }
8e4f30a4-7076-4fa2-80a8-00a71c75f9ee
0
@Test public void test_addPawn() { assertNotNull(board); assertEquals(numberOfPawns, board.numberOfPawns()); Pawn pawn1 = new Pawn('l', 3, 4, board); board.addPawn(pawn1); assertEquals(numberOfPawns + 1, board.numberOfPawns()); }
0bbf771d-7cc5-46d3-8719-6fc79a1cc42d
8
protected void drawItemLabel(Graphics2D g2, XYDataset dataset, int series, int item, XYPlot plot, XYItemLabelGenerator generator, Rectangle2D bar, boolean negative) { String label = generator.generateLabel(dataset, series, item); if (label == null) { return; // nothing to do } Font labelFont = getItemLabelFont(series, item); g2.setFont(labelFont); Paint paint = getItemLabelPaint(series, item); g2.setPaint(paint); // find out where to place the label... ItemLabelPosition position = null; if (!negative) { position = getPositiveItemLabelPosition(series, item); } else { position = getNegativeItemLabelPosition(series, item); } // work out the label anchor point... Point2D anchorPoint = calculateLabelAnchorPoint( position.getItemLabelAnchor(), bar, plot.getOrientation()); if (isInternalAnchor(position.getItemLabelAnchor())) { Shape bounds = TextUtilities.calculateRotatedStringBounds(label, g2, (float) anchorPoint.getX(), (float) anchorPoint.getY(), position.getTextAnchor(), position.getAngle(), position.getRotationAnchor()); if (bounds != null) { if (!bar.contains(bounds.getBounds2D())) { if (!negative) { position = getPositiveItemLabelPositionFallback(); } else { position = getNegativeItemLabelPositionFallback(); } if (position != null) { anchorPoint = calculateLabelAnchorPoint( position.getItemLabelAnchor(), bar, plot.getOrientation()); } } } } if (position != null) { TextUtilities.drawRotatedString(label, g2, (float) anchorPoint.getX(), (float) anchorPoint.getY(), position.getTextAnchor(), position.getAngle(), position.getRotationAnchor()); } }
97c64cb5-1780-4e32-8ff1-c9fd625382a6
8
@SuppressWarnings("unchecked") public void load(File modelDirectory, String modelPrefix) throws JChunkerException { ObjectInputStream featDictClassInputStream = null; try { featDictClassInputStream = new ObjectInputStream(new FileInputStream(new File(modelDirectory, modelPrefix + FEAT_DICTIONARY_CLASS_FILE_EXTENSION))); // Get the feature dictionary's class name. String featDictClassName = featDictClassInputStream.readUTF(); // Load the feature dictionary's class. Class<? extends FeatDictionary> featDictionaryClass = (Class<? extends FeatDictionary>) Class.forName(featDictClassName); featDictionary = featDictionaryClass.newInstance(); // Load the feature dictionary. featDictionary.load(modelDirectory, modelPrefix); } catch (FileNotFoundException e) { throw new JChunkerException("The feature dictionary settings file was not found.", e); } catch (IOException e) { throw new JChunkerException("An error occurred when loading the feature dictionary settings.", e); } catch (ClassNotFoundException e) { throw new JChunkerException("The feature dictionary's class could not be found.", e); } catch (InstantiationException e) { throw new JChunkerException("The feature dictionary's class could not be instantiated.", e); } catch (IllegalAccessException e) { throw new JChunkerException("The feature dictionary's class was not accessed properly.", e); } finally { try { featDictClassInputStream.close(); } catch (IOException e) { throw new JChunkerException("An error occurred when closing the feature dictionary's settings file.", e); } } }
4a698d0f-cf2a-4037-91bf-8fc751962559
0
public Counter() {}
1605083e-358c-489c-9dda-c5e62b312356
1
public void paint(Graphics g) { g.setColor(mouseHovering ? HOVER_BACKGROUND_COLOR : BASE_BACKGROUND_COLOR); g.fillRect(bounds.x, bounds.y, bounds.width, bounds.height); g.setColor(BORDER_COLOR); g.drawRect(bounds.x, bounds.y, bounds.width, bounds.height); g.setColor(TEXT_COLOR); int textX = bounds.x + ((bounds.width - g.getFontMetrics().stringWidth(text)) / 2); // Button's text is horizontally centered int textY = bounds.y + bounds.height / 2; // The text is already vertically centered g.drawString(text, textX, textY); }
9e2516a6-9202-4561-a753-18e79cc87db4
7
public static boolean computeCell(long world,int col,int row) { // liveCell is true if the cell at position (col,row) in world is live boolean liveCell = getCell(world, col, row); // neighbours is the number of live neighbours to cell (col,row) int neighbours = countNeighbours(world, col, row); // we will return this value at the end of the method to indicate whether // cell (col,row) should be live in the next generation boolean nextCell = false; //A live cell with less than two neighbours dies (underpopulation) if (neighbours < 2) { nextCell = false; } //A live cell with two or three neighbours lives (a balanced population) //TODO: write a if statement to check neighbours and update nextCell if (liveCell && (neighbours == 2 || neighbours == 3)) { nextCell = true; } //A live cell with with more than three neighbours dies (overcrowding) //TODO: write a if statement to check neighbours and update nextCell if (neighbours > 3) { nextCell = false; } //A dead cell with exactly three live neighbours comes alive //TODO: write a if statement to check neighbours and update nextCell if (!liveCell && (neighbours == 3)) { nextCell = true; } return nextCell; }
cef63341-5d4c-4993-9313-da62da1dd68c
3
@Override public List<Funcionario> listAll() { Connection conn = null; PreparedStatement pstm = null; ResultSet rs = null; List<Funcionario> funcionarios = new ArrayList<>(); try{ conn = ConnectionFactory.getConnection(); pstm = conn.prepareStatement(LIST); rs = pstm.executeQuery(); while (rs.next()){ Funcionario f = new Funcionario(); f.setId_funcionario(rs.getInt("id_funcionario")); f.setNome(rs.getString("nome_fn")); f.setTelefone(rs.getString("telefone_fn")); f.setBairro(rs.getString("bairro_fn")); f.setRg(rs.getString("rg_fn")); f.setFuncao(rs.getString("funcao_fn")); f.setCidade(rs.getString("cidade_fn")); f.setEndereco(rs.getString("endereco_fn")); f.setCpf(rs.getString("cpf_fn")); f.setSalario(rs.getDouble("salario_fn")); f.setLOJA_id_loja(rs.getInt("LOJA_id_loja")); f.setUSUARIO_id_usuario(rs.getInt("USUARIO_id_usuario")); funcionarios.add(f); } }catch(Exception e){ JOptionPane.showMessageDialog(null,"Erro ao listar funcionarios " + e); }finally{ try{ ConnectionFactory.closeConnection(conn, pstm, rs); }catch(Exception e){ JOptionPane.showMessageDialog(null,"Erro ao desconectar com o banco " + e); } } return funcionarios; }
eda4ebe4-645b-4e47-9872-200a49f6b063
2
public void testGetValue() { Partial test = createHourMinPartial(COPTIC_PARIS); assertEquals(10, test.getValue(0)); assertEquals(20, test.getValue(1)); try { test.getValue(-1); } catch (IndexOutOfBoundsException ex) {} try { test.getValue(2); } catch (IndexOutOfBoundsException ex) {} }
61ee8ad2-fdb9-4816-855a-1c7233b08f33
4
public static int itemAmount(int itemID, int itemX, int itemY) { for (int i = 0; i <= 5000; i++) { // Phate: Loop through all item spots if(globalItemID[i] == itemID && globalItemX[i] == itemX && globalItemY[i] == itemY) // Phate: Found item return globalItemAmount[i]; } return 0; // Phate: Item doesnt exist }
7e37c510-578b-46fc-85db-91e8e268a2be
0
public JuliaMandelbrotFrame() { setDefaultCloseOperation(EXIT_ON_CLOSE); setLayout(new GridLayout(1,2)); setSize(700,300); mand = new MandelbrotPanelDouble(); mand.addMouseMotionListener(new MouseMotionListener(){ @Override public void mouseDragged(MouseEvent e) { } @Override public void mouseMoved(MouseEvent e) { double[] cpx = mand.pixelToCoord(e.getX(), e.getY()); julia.setC(cpx[0], cpx[1]); } }); julia = new JuliaPanelDouble(0,0); add(mand); add(julia); setUpMenuBar(); setVisible(true); zoomControls.doClick(); }
faea6165-dadb-46f7-a492-fda0842bc9e2
9
public static String getTriadChordName(ArrayList<Key> chord){ String name = ""; //add the root note name += chord.get(0).getStringNote(); //check if the third is major or minor String third = (NotesUtils.getIntervalBetweenTwoKeys(chord.get(1).getMidiKey(), chord.get(0).getMidiKey()) == 4) ? "major" : "minor"; //check if the fifth is diminished or augmented String fifth = null; if (NotesUtils.getIntervalBetweenTwoKeys(chord.get(2).getMidiKey(), chord.get(0).getMidiKey()) == 6) fifth = "dim"; else if (NotesUtils.getIntervalBetweenTwoKeys(chord.get(2).getMidiKey(), chord.get(0).getMidiKey()) == 7) fifth = "perfect"; else if (NotesUtils.getIntervalBetweenTwoKeys(chord.get(2).getMidiKey(), chord.get(0).getMidiKey()) == 8) fifth = "aug"; if (third == "minor" && fifth == "dim") name += "dim"; else if (third == "major" && fifth == "aug") name += "aug"; else name += (third=="major") ? "": "m"; return name; }
9bee30fa-51bc-444f-903d-116e787a80a4
0
public static GameMaster fromGenerator(TargetGenerator targetGenerator) { return new GameMaster(targetGenerator.generate()); }
c95b29e8-f002-4c25-9add-ea7c780a4916
8
public void addCalendars(List<EventCalendar> calendars) { Connection connection = null; PreparedStatement statement = null; PreparedStatement selectStatement = null; try { // Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); // Open a connection System.out.println("Connecting to database..."); connection = DriverManager.getConnection(DB_URL,USER,PASS); System.out.println("Creating statement..."); String sqlInsert = "INSERT INTO calendar VALUES(?)"; statement = connection.prepareStatement(sqlInsert); // Inserts all the possible calendars that an event can have into the calendar table for (EventCalendar calendar : calendars) { //check if the calendar already exists in the database String sqlSelect = "SELECT name FROM calendar WHERE name = \"" + calendar.getNameOfCalendar() + "\""; selectStatement = connection.prepareStatement(sqlSelect); ResultSet executeQuery = selectStatement.executeQuery(); if(!executeQuery.next()){ System.out.println("Inserting calendar: " + calendar.getNameOfCalendar()); statement.setString(1, calendar.getNameOfCalendar()); statement.executeUpdate(); } } statement.close(); connection.close(); } catch(SQLException se) { se.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } finally { try{ if (statement != null) { statement.close(); } } catch(SQLException se2) { } try { if (connection != null) { connection.close(); } } catch (SQLException se) { se.printStackTrace(); } } }
bc720513-eb48-4393-b1ac-51b12bca57cd
9
protected void notifyReceivedMsg(MqttWireMessage message) throws MqttException { final String methodName = "notifyReceivedMsg"; this.lastInboundActivity = System.currentTimeMillis(); // @TRACE 651=received key={0} message={1} log.fine(className, methodName, "651", new Object[] { new Integer(message.getMessageId()), message }); if (!quiescing) { if (message instanceof MqttPublish) { MqttPublish send = (MqttPublish) message; switch (send.getMessage().getQos()) { case 0: case 1: if (callback != null) { callback.messageArrived(send); } break; case 2: persistence.put(getReceivedPersistenceKey(message), (MqttPublish) message); inboundQoS2.put(new Integer(send.getMessageId()), send); this.send(new MqttPubRec(send), null); } } else if (message instanceof MqttPubRel) { MqttPublish sendMsg = (MqttPublish) inboundQoS2 .get(new Integer(message.getMessageId())); if (sendMsg != null) { if (callback != null) { callback.messageArrived(sendMsg); } } else { // Original publish has already been delivered. MqttPubComp pubComp = new MqttPubComp(message .getMessageId()); this.send(pubComp, null); } } } }
f0f968b5-c60c-49bb-a5a3-086206f2fec8
4
private void openButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openButtonActionPerformed int result = openChooser.showOpenDialog(this); if (result == JFileChooser.APPROVE_OPTION) { File[] selected = openChooser.getSelectedFiles(); if (selected.length > 0) { for (File file : selected) { loadFile(file); } } else { loadFile(openChooser.getSelectedFile()); } try { saveProjectConf(getWork()); } catch (IOException ex) { Main.logger.log(Level.SEVERE, "Error", ex); ex.printStackTrace(System.err); } } }//GEN-LAST:event_openButtonActionPerformed
ecbc68d9-a3f3-425d-b1d5-7da77eae46db
8
private void updateStateWaiting(List<Keyword> keywords, List<String> terms) { if (keywords!= null && !keywords.isEmpty()) { for (Keyword kw : keywords) { if (kw.getWord().equals("ingredient") || kw.getWord().equals("ingredients")) { newObjectClass = Ingredient.class; } if (kw.getWord().equals("tool") || kw.getWord().equals("tools")) { newObjectClass = Tool.class; } } if (newObjectClass != null) { getCurrentDialogState().setCurrentState(KitchenAssistance.KA_WAITING_FOR_LOCATION); } } else { DialogManager.giveDialogManager().setInErrorState(true); } }
fe7e1fe1-9be5-4f48-85c0-8ecc7ffc94dd
7
public static void main(String[] args){ // Socket which will connect to the engine. Socket socket = null; // Reader to read packets from engine BufferedReader inStream = null; // Convenience wrapper to write back to engine PrintWriter outStream = null; // port number specified by engine to connect to. int port = Integer.parseInt(args[0]); try { socket = new Socket("localhost", port); outStream = new PrintWriter(socket.getOutputStream(), true); inStream = new BufferedReader(new InputStreamReader( socket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Don't know about host - can't connect."); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for the connection."); System.exit(1); } String input; while (true) { try { // block until engine sends us a packet, then read it into input input = inStream.readLine(); } catch (IOException e) { System.out.println("Connection reset while waiting to read."); e.printStackTrace(); break; } if (input == null) { System.out.println("Gameover, engine disconnected"); break; } // Here is where you should implement code to parse the packets from // the engine and act on it. System.out.println(input); if (input.split(" ")[0].compareToIgnoreCase("GETACTION") == 0) { // When appropriate, reply to the engine with a legal action. // The engine will ignore all spurious packets you send. // The engine will also check/fold for you if you return an // illegal action. outStream.println("CHECK"); } } // Once the server disconnects from us, close our streams and sockets. try { outStream.close(); inStream.close(); socket.close(); } catch (IOException e) { System.out.println("Encounterd problem shutting down connections"); e.printStackTrace(); } }
36cee418-252b-4a14-8cad-9cf678501216
1
@Override public <E extends IElement> E create(Class<E> ElementClass, WebElement element) { try{ return ElementClass.getConstructor(WebElement.class).newInstance(element); } catch(Exception e){ throw new RuntimeException(e); } }
d362a197-8c4a-4d91-80af-d4818aa64ebb
5
public static int findWordEnd(String line, int pos, String noWordSep) { char ch = line.charAt(pos); if(noWordSep == null) noWordSep = ""; boolean selectNoLetter = (!Character.isLetterOrDigit(ch) && noWordSep.indexOf(ch) == -1); int wordEnd = line.length(); for(int i = pos; i < line.length(); i++) { ch = line.charAt(i); if(selectNoLetter ^ (!Character.isLetterOrDigit(ch) && noWordSep.indexOf(ch) == -1)) { wordEnd = i; break; } } return wordEnd; }
8c23aea2-02f1-4730-8166-f86d6beebce8
9
@Override public void run(){ try{ while(true){ move(); for(int i = 0; i < shots.length; i++){ if(shots[i] != null){ shots[i].moveShot(id); shots[i] = GameFrame.checkShots(shots[i], id); } if(shots[i] != null){ if(shots[i].getX() > 1200 || shots[i].getX() < 0 || shots[i].getY() > 800 || shots[i].getY() < 0){ shots[i] = null; } } } Thread.sleep(5); } }catch(Exception e){System.err.println(e.getMessage());} }
2c689acf-9b86-4114-9466-d444b2d9cf25
4
public void drawOptions(SpriteBatch sb) { int x, y, px = font[0].getRegionWidth()-1, py = font[0].getRegionHeight() + 2; for (int j = 0; j <= menuMaxY; j++) for (int i = 0; i <= menuMaxX; i++) { x = (Game.width/2 - menuOptions[i][j].length() * px - px/2)/2 ; y = (Game.height/4 - j * py - 28); if (i == cursor.x && j == cursor.y){ sb.draw(btnHighlight.getFrame(), 0, y - 1); // draw menu button highlight sb.draw(btnHighlight.getFrame(), (Game.width/4 - PERIODX + 1), y-1); } drawString(sb, font, px, menuOptions[i][j], x, y); // draw menu buttons } }
cf1abc4d-82ed-440c-8bed-96f50ebccd8c
5
public Writer write(Writer writer) throws JSONException { try { boolean b = false; int len = this.length(); writer.write('['); for (int i = 0; i < len; i += 1) { if (b) { writer.write(','); } Object v = this.myArrayList.get(i); if (v instanceof JSONObject) { ((JSONObject)v).write(writer); } else if (v instanceof JSONArray) { ((JSONArray)v).write(writer); } else { writer.write(JSONObject.valueToString(v)); } b = true; } writer.write(']'); return writer; } catch (IOException e) { throw new JSONException(e); } }
9f29cb1b-81f8-4517-9a7b-543129ab7794
1
public Boolean close() { try { this.con.close(); return true; } catch (SQLException e) { log.severe("Couldn't close Connection: "); LogHandler.writeStackTrace(log, e, Level.SEVERE); return false; } }
4f0107bf-47c5-4113-9d41-c1ce09c0c87f
1
@FXML private void handleTxtPriceAction(ActionEvent event) { if (txtPrice.getText().isEmpty()) { return; } cobSuppliers.requestFocus(); }
1c05d998-d626-426d-85e0-1de3acf9c05e
6
public List<AlumnoDTO> getAlumnosPorGrupo(int idGrupo){ List<AlumnoDTO> alumnos = new ArrayList<AlumnoDTO>(); Connection con = null; PreparedStatement pst = null; ResultSet rs = null; try { con = EscolarConnectionFactory .getInstance().getConnection(); String sql = "select a.matricula, a.apellidos, a.nombres from alumnos a, alumnos_x_grupo b where a.matricula=b.matricula and a.id_situacion=1 and b.id_grupo=? order by a.apellidos"; pst = con.prepareStatement(sql); pst.setInt(1, idGrupo); rs = pst.executeQuery(); while (rs.next()) { AlumnoDTO alumno = new AlumnoDTO(); alumno.setMatricula(rs.getString("matricula")); alumno.setApellidos(rs.getString("apellidos")); alumno.setNombres(rs.getString("nombres")); alumnos.add(alumno); } } catch (SQLException e) { e.printStackTrace(); } finally { try { if (con != null) con.close(); if (pst != null) pst.close(); if (rs != null) rs.close(); } catch (SQLException e) { e.printStackTrace(); } } return alumnos; }
06b961f3-72c4-4a59-849a-4cc7422e5632
7
private final boolean cvc(int i) { if (i < 2 || !cons(i) || cons(i-1) || !cons(i-2)) return false; { int ch = b[i]; if (ch == 'w' || ch == 'x' || ch == 'y') return false; } return true; }
d58c698b-be58-4db6-b682-117269735861
9
public CircleTile(int rank) { super(rank); setToolTipText(toString()); switch(rank){ case 1: circles[0] = new Pancake( 49, 29, Color.RED); break; case 2: circles[0] = new Circle(45 + 3, 35 - 21, MYGREEN); circles[1] = new Circle(45 + 3, 35 + 9, Color.RED); break; case 3: circles[0] = new Circle(25, 5, Color.BLUE); circles[1] = new Circle(49, 29, Color.RED); circles[2] = new Circle(72, 52, MYGREEN); break; case 4: circles[0] = new Circle(45 - 12, 35 - 21, Color.BLUE); circles[1] = new Circle(45 - 12, 35 + 9, MYGREEN); circles[2] = new Circle(45 + 18, 35 - 21, MYGREEN); circles[3] = new Circle(45 + 18, 35 + 9, Color.BLUE); break; case 5: circles[0] = new Circle(25, 5, Color.BLUE); circles[1] = new Circle(49, 29, Color.RED); circles[2] = new Circle(72, 52, Color.BLUE); circles[3] = new Circle(72, 5, MYGREEN); circles[4] = new Circle(25, 52, MYGREEN); break; case 6: circles[0] = new Circle(45 - 12, 5, MYGREEN); circles[1] = new Circle(45 + 18, 5, MYGREEN); circles[2] = new Circle(45 - 12, 29, Color.RED); circles[3] = new Circle(45 + 18, 29, Color.RED); circles[4] = new Circle(45 - 12, 52, Color.RED); circles[5] = new Circle(45 + 18, 52, Color.RED); break; case 7: circles[0] = new Circle(25, 5, MYGREEN); circles[1] = new Circle(49, 15, MYGREEN); circles[2] = new Circle(72, 27, MYGREEN); circles[3] = new Circle(45 - 12, 38, Color.RED); circles[4] = new Circle(45 + 18, 38, Color.RED); circles[5] = new Circle(45 - 12, 52, Color.RED); circles[6] = new Circle(45 + 18, 52, Color.RED); break; case 8: circles[0] = new Circle(45 - 12, 2, Color.BLUE); circles[1] = new Circle(45 + 18, 2, Color.BLUE); circles[2] = new Circle(45 - 12, 20, Color.BLUE); circles[3] = new Circle(45 + 18, 20, Color.BLUE); circles[4] = new Circle(45 - 12, 38, Color.BLUE); circles[5] = new Circle(45 + 18, 38, Color.BLUE); circles[6] = new Circle(45 + 18, 55, Color.BLUE); circles[7] = new Circle(45 - 12, 55, Color.BLUE); break; case 9: circles[0] = new Circle(25, 5, MYGREEN); circles[1] = new Circle(49, 5, MYGREEN); circles[2] = new Circle(72, 5, MYGREEN); circles[3] = new Circle(25, 29, Color.RED); circles[4] = new Circle(49, 29, Color.RED); circles[5] = new Circle(72, 29, Color.RED); circles[6] = new Circle(25, 52, Color.BLUE); circles[7] = new Circle(49, 52, Color.BLUE); circles[8] = new Circle(72, 52, Color.BLUE); break; } }
c5bdd3ce-aa8b-48a6-b45e-2180d6d4108f
0
@AfterClass public static void tearDownClass() { }
2a3999bb-73ad-46ed-80d3-a6c489a98e4a
8
void designateTask(int i, int i0, TaskEnum type) { if(this.getTile(i, i0).getDesignate()==type) { this.getTile(i, i0).setDesignate(null); this.getTaskmanager().undesignateTask(this.getMap().getTile(i, i0).getActualTask(), this.getBeastcollection()); return; } switch(type) { case digging: this.getTile(i, i0).designateMine(); break; case walling: this.getTile(i, i0).designateWall(); } if(this.getTile(i, i0).getDesignate()==type)//if successfully designated { if(this.getTile(i, i0).getDesignate()==TaskEnum.digging && this.getTile(i, i0).isWalkable()) return; if(this.getTile(i, i0).getDesignate()==TaskEnum.walling && this.getTile(i, i0).isExplored()==false) return; Task ntask = TaskFactory.newCompositeTask(-1, i, i0, type); this.getMap().getTile(i, i0).setActualTask(ntask.getTaskid()); this.getTaskmanager().addTask(ntask); } }
d99cc484-93cb-4c4c-98e2-7630f4989a60
5
@Override public void ParseIn(Connection Main, Server Environment) { Room Room = Environment.RoomManager.GetRoom(Main.Data.CurrentRoom); if (Room == null) { return; } if (!Room.CheckRights(Main.Data, true)) { return; } int junk = Main.DecodeInt(); RoomItem Item = Room.GetItem(Main.DecodeInt()); if (Item == null) { return; } if(Item.BaseItem.Interaction == Environment.Furniture.POSTIT) { return; // not allowed to pick up post.its } Room.RemoveFurniture(Main, Item); Main.AddItem(Item.Id, Item.ExtraData, Item.BaseItem, true); if(Item.BaseItem.Interaction == Environment.Furniture.TELEPORT) { Environment.Teleports.DelRoom(Item.Id); } // Update Inventory Environment.InitPacket(101, Main.ClientMessage); Environment.EndPacket(Main.Socket, Main.ClientMessage); }
14ab0803-3c37-4012-bf0c-8b69ddec738b
4
public static void main(String[] args) { LinearProbingHashST<String, Integer> st = new LinearProbingHashST<String, Integer>(); for (int i = 0; !StdIn.isEmpty(); i++) { String key = StdIn.readString(); st.put(key, i); } // print keys for (String s : st.keys()) StdOut.println(s + " " + st.get(s)); for (String s : st.keys()) st.delete(s); if (st.isEmpty()) System.out.println("Successfully deleted all items"); else System.out.println("Unsuccessful in deleting all items"); }
fed54f02-1ae4-4cd9-b273-24c546e8c11c
4
public boolean equals(Wall wall){ if (wall.getX() == x && wall.getY() == y && wall.width == width && wall.height == height){ return true; } return false; }
c107379e-2b84-4032-834b-41fb17111634
1
private void addDatabaseLoadPanel(JScrollPanelledPane stepScroll) { JPanel dbLoad = JComponentFactory .makePanel(JComponentFactory.HORIZONTAL); CustomButton loadDB = JComponentFactory.makeLoadDatabaseButton( "Load Database", confirmLoad); if (programSettings.autoLoadDatabase) { autoLoad.setSelected(true); confirmLoad.setSelected(true); confirmLoad.setEnabled(false); loadDB.setEnabled(false); JComponentFactory.startLoadingDataBase(); // JComponentFactory.addReportsTab(); } else { autoLoad.setSelected(false); } dbLoad.add(autoLoad); dbLoad.add(confirmLoad); dbLoad.add(loadDB); dbLoad.add(showFFT); stepScroll.addComp(dbLoad); }
a64b8189-0440-4930-aef8-56af2be40b72
6
public boolean growCrops(Player player, String[] args, int radius) { Block playerCenter = player.getLocation().getBlock(); // Get Centrepoint (Player) int crops = 0; for (int x = -radius; x < radius; x++) { for (int y = -radius; y < radius; y++) { for (int z = -radius; z < radius; z++) { Block b = playerCenter.getRelative(x,y,z); if (playerCenter.getRelative(x,y,z).getType() == Material.CROPS) { int dataValue = b.getData(); if (dataValue != 7) { b.setData((byte) 7); crops++; } else if (dataValue == (byte) 7) { // DO NOTHING } } } } } player.sendMessage(ChatColor.GREEN+"Grown "+crops+" crops"); return true; }
5b27e106-b323-4a27-8826-eed5bbd9a150
2
public static void caught(int index) { if(index>=151) { System.out.println("MISSINGNO caught; system crash"); System.exit(-1); } if(caught[index] == false) { caught[index] = true; totalCaught++; } }
0e8105d4-fbdd-49b6-af1e-9dc58fb77a21
6
protected void padTabRun(int tabPlacement, int start, int end, int max) { Rectangle lastRect = rects[end]; if (tabPlacement == TOP || tabPlacement == BOTTOM) { int runWidth = (lastRect.x + lastRect.width) - rects[start].x; int deltaWidth = max - (lastRect.x + lastRect.width); float factor = (float) deltaWidth / (float) runWidth; for (int j = start; j <= end; j++) { Rectangle pastRect = rects[j]; if (j > start) { pastRect.x = rects[j - 1].x + rects[j - 1].width; } pastRect.width += Math.round((float) pastRect.width * factor); } lastRect.width = max - lastRect.x; } else { int runHeight = (lastRect.y + lastRect.height) - rects[start].y; int deltaHeight = max - (lastRect.y + lastRect.height); float factor = (float) deltaHeight / (float) runHeight; for (int j = start; j <= end; j++) { Rectangle pastRect = rects[j]; if (j > start) { pastRect.y = rects[j - 1].y + rects[j - 1].height; } pastRect.height += Math.round((float) pastRect.height * factor); } lastRect.height = max - lastRect.y; } }
eabb5c13-83b7-4c21-9f10-96a8303c596d
7
private JPanel buildTop() { JPanel panel = new JPanel(); panel.setLayout(gl); JLabel reportLabel = new JLabel("Duplicate Report Folder:"); gc.gridx = 0; gc.gridy = 0; gl.setConstraints(reportLabel, gc); panel.add(reportLabel); reportFolder = new JTextField("C:\\report\\",60); gc.gridx = 1; gc.gridy = 0; gl.setConstraints(reportFolder,gc); panel.add(reportFolder); reportButton = new JButton("Browse"); reportChooser.setFileHidingEnabled(true); reportChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); reportButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (!reportFolder.getText().isEmpty()) { File dir = new File(reportFolder.getText()); if (dir.exists() && dir.isDirectory() && dir.canRead() && dir.canWrite() && dir.canExecute()) { reportChooser.setCurrentDirectory(dir); } } int retVal = reportChooser.showDialog(getSelfRef(), "Choose a Report Directory"); if (retVal == JFileChooser.APPROVE_OPTION) { File file = reportChooser.getSelectedFile(); reportFolder.setText(file.getAbsolutePath()); } } }); gc.gridx = 2; gc.gridy = 0; gl.setConstraints(reportButton,gc); panel.add(reportButton); /* * Build the types of reports they can generate */ JPanel reportPanel = buildReportPanel(); gc.gridx = 1; gc.gridy = 1; gl.setConstraints(reportPanel,gc); panel.add(reportPanel); return panel; }
7d4894c1-c84c-4b1d-a95a-a62878d90cb4
5
public boolean equals(Object obj) { if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pessoa other = (Pessoa) obj; if (matricula == null) { if (other.matricula != null) return false; } else if (!matricula.equals(other.matricula)) return false; return true; }
1bf09bd6-ad22-4f3a-ab3b-15275a21f193
7
public Deck(Graphics g) { String cardName = ""; for (int i = 0; i < suitArray.length; i++) { for (int j = 0; j < valueArray.length; j++) { Card card = new Card(valueArray[j],suitArray[i]); if (valueArray[j] == 1) { cardName = "A" + suitArray[i]; } else if (valueArray[j] == 11) { cardName = "J" + suitArray[i]; } else if (valueArray[j] == 12) { cardName = "Q" + suitArray[i]; } else if(valueArray[j] == 13) { cardName = "K" + suitArray[i]; } else { cardName = valueArray[j] + suitArray[i]; } //too lazy to change the name from movie poster poster = new MoviePoster(cardName); if(x > 1000) { x = 0; y += 75; } Rectangle a = new Rectangle(x,y,50,75); poster.draw(g,a); x += 50; //what was I trying to do here I don't remember deck[count] = card; count++; } } }
9c823476-b2e9-43f2-b437-e63ff7e880eb
4
@Override public boolean doMove() { int curIndex = curGb.readMemory(curGb.pokemon.fightCurMoveNumAddress); //System.out.println("current move index "+curIndex+", goal position is "+goalIndex); int stepsDown = (goalIndex + numOwnMoves - curIndex) % numOwnMoves; int stepsUp = (curIndex + numOwnMoves - goalIndex) % numOwnMoves; if(stepsDown < stepsUp) { //System.out.println("taking "+stepsDown+" steps down"); while(stepsDown-->0) new EflPressButton(Move.DOWN, PressMetric.PRESSED).execute(); } else if(stepsUp > 0) { //System.out.println("taking "+stepsUp+" steps up"); while(stepsUp-->0) new EflPressButton(Move.UP, PressMetric.PRESSED).execute(); } //Thread.sleep(1000); return true; }
2a2e66e8-025b-4d03-bf0b-77eff782f965
4
protected static double convertDist( double value, DistType from, DistType to ) { //first convert to nautical miles if( from == DistType.KILO ) value *= 0.539957; else if( from == DistType.MILES ) value *= 0.868976; //now convert to the to type if( to == DistType.KILO ) value *= 1.852; else if( to == DistType.MILES ) value *= 1.15078; return value; }
f9c619a9-6815-464c-b513-b514a3db375b
0
public static ScoreManagerSingleton getInstance() { return ourInstance; }
3f87b840-1957-4901-b921-9eddb5d02f15
3
@Override public String execute(SessionRequestContent request) throws ServletLogicException { String page = ConfigurationManager.getProperty("path.page.order"); try { Criteria criteria = new Criteria(); Order order = (Order) request.getSessionAttribute(JSP_CURRENT_ORDER); if (order == null) { throw new TechnicalException("message.errorNullEntity"); } criteria.addParam(DAO_ID_ORDER, order.getIdOrder()); criteria.addParam(DAO_ID_USER, order.getUser().getIdUser()); criteria.addParam(DAO_ORDER_TOURIST_LIST, order.getTouristCollection()); User user = (User) request.getSessionAttribute(JSP_USER); if (user != null) { criteria.addParam(DAO_USER_LOGIN, user.getLogin()); ClientType type = ClientTypeManager.clientTypeOf(user.getRole().getRoleName()); criteria.addParam(DAO_ROLE_NAME, type); } else { criteria.addParam(DAO_ROLE_NAME, request.getSessionAttribute(JSP_ROLE_TYPE)); } AbstractLogic orderLogic = LogicFactory.getInctance(LogicType.ORDERLOGIC); Integer resIdOrder = orderLogic.doDeleteEntity(criteria); request.setParameter(JSP_SELECT_ID, resIdOrder.toString()); order.setStatus(DELETED); page = new ShowOrder().execute(request); } catch (TechnicalException ex) { request.setAttribute("errorDeleteReason", ex.getMessage()); request.setAttribute("errorDelete", "message.errorDeleteData"); request.setSessionAttribute(JSP_PAGE, page); } return page; }
0267b759-266c-4056-8daa-7a75d73d36c0
8
public Collection<AbstractClassPathLocation> findBelow(URI toplevel) { final Collection<AbstractClassPathLocation> rval = new ArrayList<AbstractClassPathLocation>(); final File startPoint = new File(toplevel); // First, check if the entry represents a multi-plugin (in that case we don't add // anything else) /* if ($(startPoint).filter(".*\\.plugin?$").get(0) != null) { rval.add(AbstractClassPathLocation.newClasspathLocation(this.cache, toplevel.toString(), toplevel)); return rval; }*/ // Check if this is a directory or a file if (startPoint.isDirectory()) { final File[] listFiles = startPoint.listFiles(); boolean hasJARs = false; for (File file : listFiles) { if (file.getAbsolutePath().endsWith(".jar")) { rval.add(AbstractClassPathLocation.newClasspathLocation(this.cache, file.toURI().toString(), file.toURI())); hasJARs = true; } /* if ($(file).filter(".*\\.plugin?$").get(0) != null) { rval.add(AbstractClassPathLocation.newClasspathLocation(this.cache, file.toURI().toString(), file.toURI())); hasJARs = true; }*/ } // If we have JARs, we already added them if (hasJARs) return rval; // If we have no JARs, this is probably a classpath, in this case warn that // the method is not recommended if (toplevel.toString().contains("/bin/") || toplevel.toString().contains("class")) { this.logger.warning("Adding plugins in 'raw' classpaths, such as 'bin/' or 'classes/' is not recommended. Please use classpath://* instead (the video is a bit outdated in this respect)."); } rval.add(AbstractClassPathLocation.newClasspathLocation(this.cache, toplevel.toString(), toplevel)); return rval; } // If this is directly a JAR, add this if (startPoint.isFile() && startPoint.getAbsolutePath().endsWith(".jar")) { rval.add(AbstractClassPathLocation.newClasspathLocation(this.cache, toplevel.toString(), toplevel)); return rval; } return rval; }
a1a70fa0-c329-448e-ac71-ca8b054dc5a7
2
public void newInput() { if (!running) { running = true; if (moveInput()) { YSPL.world.getWorldFrame().getGUI().step(); } running = false; } }
76cae6d5-31d9-4e6d-aaec-cb58a04d545f
0
public EnvParams(){ //nothing }
2a1c5c85-e9f3-4075-990f-1bd19976b7be
7
private int pushDownMax(int i) { int iBound = queue.size(); E v = queue.get(i); while (true) { int iDown = (i << 1) + 1; E vDown; if (iBound < iDown) { break; } if (iDown == iBound) { iDown = iBound - 1; vDown = queue.get(iDown); } else { vDown = queue.get(iDown); int iRight = iDown + 2; if (iRight <= iBound) { if (iRight == iBound) { iRight = iBound - 1; } E vRight = queue.get(iRight); if (less(vDown, vRight)) { vDown = vRight; iDown = iRight; } } } if (!less(v, vDown)) { break; } queue.set(i, vDown); i = iDown; } queue.set(i, v); return i; }
8b966f1a-deae-4ce0-a258-0e6388b35e94
9
private boolean IsPermutation(int n1, int n2) { char[] n1Chars = Integer.toString(n1).toCharArray(); char[] n2Chars = Integer.toString(n2).toCharArray(); if (n1Chars.length != n2Chars.length) { return false; } for (int i = 0; i < n1Chars.length; i++) { boolean wasFound = false; for (int j = 0; j < n2Chars.length; j++) { if (n1Chars[i] == n2Chars[j]) { wasFound = true; break; } } if (!wasFound) { return false; } } for (int i = 0; i < n2Chars.length; i++) { boolean wasFound = false; for (int j = 0; j < n1Chars.length; j++) { if (n1Chars[j] == n2Chars[i]) { wasFound = true; break; } } if (!wasFound) { return false; } } return true; }
cfc080aa-f5bb-4320-acb7-45d0365d99be
1
private static int[] generate(int size) { int[] ints = new int[size]; for (int i = 0; i < size; i++) { ints[i] = RANDOM.nextInt(); } return ints; }
c85b4fe7-0ab0-4c15-b16d-e533bc90bcd2
9
public void auxEliminar( T pElemento, Retorno retorno ) throws ElementoNoExisteException { // Compara el elemento con el valor almacenado en el nodo int resultado = elem.compareTo( pElemento ); if( resultado == 0 ) { // Caso 1: El elemento est� en el nodo actual if( izqNodo == null & derNodo == null ) { // No tiene hijos, simplemente debe eliminarlo retorno.diferenciaAltura = true; retorno.respuesta = null; } else if( izqNodo == null ) { retorno.respuesta = derNodo; retorno.diferenciaAltura = true; } else { // Reemplaza el nodo con la mayor elemento del nodo izquierdo NodoAVL<T> reemplazo = izqNodo.mayorElemento( ); elem = reemplazo.elem; izqNodo.auxEliminar( reemplazo.elem, retorno ); izqNodo = retorno.respuesta; // Balancea si es necesario if( retorno.diferenciaAltura ) { balanElimDer( retorno ); } else { retorno.respuesta = this; } } } else if( resultado > 0 ) { // Caso 2: El elemento debe estar por la izquierda if( izqNodo == null ) { //throw new ElementoNoExisteException( "El elemento no se encuentra en el �rbol" ); } else{ izqNodo.auxEliminar( pElemento, retorno ); izqNodo = retorno.respuesta; // Balancea si es necesario if( retorno.diferenciaAltura ) { balanElimDer( retorno ); } else { retorno.respuesta = this; }} } else { // Caso 3: El elemento debe estar por la derecha if( derNodo == null ) { //throw new ElementoNoExisteException( "El elemento no se encuentra en el �rbol" ); } else{ derNodo.auxEliminar( pElemento, retorno ); derNodo = retorno.respuesta; } // Balancea si es necesario if( retorno.diferenciaAltura ) { balanElimIzq( retorno ); } else { retorno.respuesta = this; } } }
886d3696-14cf-41e5-b5de-9467f5cc0277
3
@Override public void report() { final List<String> busiestActors = new ArrayList<>(); int highestCount = 0; for (final Map.Entry<String, Integer> actorYearToMovieCountEntry : actorYearToMovieCount.entrySet()) if (actorYearToMovieCountEntry.getValue() > highestCount) { busiestActors.clear(); busiestActors.add(actorYearToMovieCountEntry.getKey()); highestCount = actorYearToMovieCountEntry.getValue(); } else if (actorYearToMovieCountEntry.getValue() == highestCount) busiestActors.add(actorYearToMovieCountEntry.getKey()); System.out.println(String.format("Most prolific actor(s) in one year: %s with %d movies.", busiestActors, highestCount)); }
87da3768-c023-4b41-a5c8-2f12df26041e
2
public boolean hasItem(Point p) { if(inventory.size()==0) return false; System.out.println("Clicked on (" + p.getX() + ", " + p.getY()+ ")"); Point topLeft = new Point(IMG_XOFFSET, IMG_YOFFSET); int totalHeight = IMG_YOFFSET + ITEM_HEIGHT * inventory.size(); if(withinBounds(p, topLeft, ITEM_WIDTH, totalHeight)) { return true; } else { return false; } }
1539b419-a523-4f55-8728-64f79ae9f4e7
9
@Override public double evaluate(int[][] board) { int max = 0; for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { max = Math.max(max, board[i][j]); cnt[board[i][j]]++; } } int target = -1; for (int i = max; i >= 2; i >>= 1) { if (cnt[i] >= 2) { target = i; break; } } int fx = -1, fy = -1, sx = -1, sy = -1; for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { if (board[i][j] == target) { if (fx == -1) { fx = i; fy = j; } else { sx = i; sy = j; } } } } if(sx == -1) { return 0; } return dist(fx, fy, sx, sy); }
8162d6d0-a9b7-4dd7-a7da-322e3a81b6e2
9
int insertKeyRehash(byte val, int index, int hash, byte state) { // compute the double hash final int length = _set.length; int probe = 1 + (hash % (length - 2)); final int loopIndex = index; int firstRemoved = -1; /** * Look until FREE slot or we start to loop */ do { // Identify first removed slot if (state == REMOVED && firstRemoved == -1) firstRemoved = index; index -= probe; if (index < 0) { index += length; } state = _states[index]; // A FREE slot stops the search if (state == FREE) { if (firstRemoved != -1) { insertKeyAt(firstRemoved, val); return firstRemoved; } else { consumeFreeSlot = true; insertKeyAt(index, val); return index; } } if (state == FULL && _set[index] == val) { return -index - 1; } // Detect loop } while (index != loopIndex); // We inspected all reachable slots and did not find a FREE one // If we found a REMOVED slot we return the first one found if (firstRemoved != -1) { insertKeyAt(firstRemoved, val); return firstRemoved; } // Can a resizing strategy be found that resizes the set? throw new IllegalStateException("No free or removed slots available. Key set full?!!"); }
bb6747bf-0505-4be4-bb6d-10119a40201a
7
@Override public String execute(HttpServletRequest request) throws SQLException, ClassNotFoundException { String tableName = request.getParameter("TableName"); System.out.println(tableName); if (tableName != null && tableName != "") { try { Class.forName("org.h2.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } Connection connection = DriverManager.getConnection("jdbc:h2:tcp://localhost/F:/Видео Epam/db/FPDB", "Rody", "1"); //"jdbc:h2:tcp://localhost/F:/Видео Epam/db/FPDB", "Rody", "1" Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("SELECT * FROM " + tableName); ResultSetMetaData resultSetMD = resultSet.getMetaData(); List<Element> namesOfColumns = new ArrayList<>(); int i = 2; while(i <= resultSetMD.getColumnCount()){ if (resultSetMD.getColumnName(i) != "ID") namesOfColumns.add(new Element(FirsUpperSymbol(resultSetMD.getColumnName(i).toLowerCase()))); i++; } String valuesString = "("; String colsNamesString = "("; String[] parameters = request.getParameterValues("ValuesForInsertToDB"); for (String parameter : parameters) { valuesString = valuesString + "'" + parameter + "'" +","; } valuesString = valuesString.substring(0,valuesString.length()-1) + ")"; System.out.println(valuesString); for (Element nameOfColumn : namesOfColumns) { colsNamesString = colsNamesString + nameOfColumn.getElement() + ","; } colsNamesString = colsNamesString.substring(0,colsNamesString.length()-1) + ")"; System.out.println(colsNamesString); statement.execute("insert into " + tableName + " " + colsNamesString + " values " + valuesString); connection.close(); } return "index.jsp"; }
153de60f-c2bd-4dde-83bf-917f1224970a
3
public static void removeCols(JTable paymentTable) { TableColumnModel tcm = paymentTable.getColumnModel(); System.out.println("getColumnCount:" + tcm.getColumnCount()); if (tcm.getColumnCount() == 7) { paymentTable.removeColumn(tcm.getColumn(6)); } if (tcm.getColumnCount() == 6) { paymentTable.removeColumn(tcm.getColumn(5)); } if (tcm.getColumnCount() == 5) { paymentTable.removeColumn(tcm.getColumn(4)); } }
fa8da385-412b-4d46-a8bb-1b11180ba748
6
private boolean updateAfterPlace(TPoint [] coordPts) { boolean rowFilled = false; for (int j = 0; j < coordPts.length; j++) { int checkX = coordPts[j].x; int checkY = coordPts[j].y; widths[checkY] += 1; if (widths[checkY] == width) rowFilled = true; if (heights[checkX] < checkY + 1) { heights[checkX] = checkY + 1; } } // update MaxHeight after piece has been added maxHeight = heights[0]; for (int i = 0; i < width; i++) { int possMax = heights[i]; if (possMax > maxHeight) maxHeight = possMax; } // update grid to include piece for (int i = 0; i < coordPts.length; i++) { grid[coordPts[i].x][coordPts[i].y] = true; } return rowFilled; }
62da5b6c-0b4f-4158-b915-a9444c181d2c
2
public void setAbsoluteVolume(float volume) { for(int i = 0; i < playList.size(); i++) { GameSong gs = playList.get(i); if(gs != null) { gs.setVolume(volume); } } }
017d7a8c-4319-4539-a267-3f00473d95d1
5
@Override public void retirada(BigDecimal valor) { switch(status) { case Platinum: saldo = saldo.subtract(valor); if(saldo.compareTo(new BigDecimal("100000.0")) == -1) { status = Categorias.Gold; } break; case Gold: saldo = saldo.subtract(valor); if(saldo.compareTo(new BigDecimal("25000.0")) == -1) { status = Categorias.Silver; } break; case Silver: saldo = saldo.subtract(valor); } }
ca2f532f-757c-4038-acce-1e962d245946
4
private void bubbleDown(int pos) { int c1Pos = 2*pos + 1; int c2Pos = 2*pos + 2; int maxPos = c1Pos; if(c1Pos <= len - 1) { if(c2Pos <= len - 1) { if(heap[c1Pos] < heap[c2Pos]) maxPos = c2Pos; } if(heap[maxPos] > heap[pos]) { swap(maxPos, pos); bubbleDown(maxPos); } } }
bc28acab-48a8-4f23-a611-e50f7cf0c2c2
7
protected void drawDays() { Calendar tmpCalendar = (Calendar) calendar.clone(); int firstDayOfWeek = tmpCalendar.getFirstDayOfWeek(); tmpCalendar.set(Calendar.DAY_OF_MONTH, 1); int firstDay = tmpCalendar.get(Calendar.DAY_OF_WEEK) - firstDayOfWeek; if (firstDay < 0) { firstDay += 7; } int i; for (i = 0; i < firstDay; i++) { days[i + 7].setVisible(false); days[i + 7].setText(""); } tmpCalendar.add(Calendar.MONTH, 1); Date firstDayInNextMonth = tmpCalendar.getTime(); tmpCalendar.add(Calendar.MONTH, -1); Date day = tmpCalendar.getTime(); int n = 0; Color foregroundColor = getForeground(); while (day.before(firstDayInNextMonth)) { days[i + n + 7].setText(Integer.toString(n + 1)); days[i + n + 7].setVisible(true); if (tmpCalendar.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR) && tmpCalendar.get(Calendar.YEAR) == today.get(Calendar.YEAR)) { days[i + n + 7].setForeground(colorRed); } else { days[i + n + 7].setForeground(foregroundColor); } if (n + 1 == this.day) { days[i + n + 7].setBackground(selectedColor); selectedDay = days[i + n + 7]; } else { days[i + n + 7].setBackground(oldDayBackgroundColor); } n++; tmpCalendar.add(Calendar.DATE, 1); day = tmpCalendar.getTime(); } for (int k = n + i + 7; k < 49; k++) { days[k].setVisible(false); days[k].setText(""); } }
ed313f60-a79f-4604-90e2-395148ac59f9
2
private String getMD5Hash(String password){ try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] messageDigest = md.digest(password.getBytes()); BigInteger number = new BigInteger(1, messageDigest); String hashtext = number.toString(16); while (hashtext.length() < 32) { hashtext = "0" + hashtext; } return hashtext; } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } }
52bcb07e-283c-4b9d-8926-fc80bed867ed
8
public Controller(Grid lagrille,List<Integer[]> lesPersonnes, ChartLine chartline) { /* * STEP 1 : Definition de la grille */ drawArea = new DrawAreaUI(); this.grid = lagrille; drawArea.setGridUi(new GridUI(grid)); drawArea.paintGrid(); /* * STEP 2 : Definition des personnes */ this.personnes = new ArrayList<Person>(); int i = 0; for(Integer[] p: lesPersonnes) { addPerson(new Person(i, p[0], p[1], this)); i++; } /* * STEP 3 : Definition des charts */ this.chartExit = chartline; nbIterations = 0; chartDistance = new Chart("Distance parcourue"); /* * STEP 4 : Definition du timer (toute les 1 secondes) */ timer = new Timer( 1000, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ArrayList<Person> clonePersonnes = new ArrayList<Person>(); for (Person p : personnes ) { clonePersonnes.add((Person) p.clone()); } Iterator<Person> it = clonePersonnes.iterator(); Iterator<Person> it2 = personnes.iterator(); ArrayList<Person> personToRemove = new ArrayList<Person>(); Person p; Person p2; while(it.hasNext()) { p = it.next(); p2 = it2.next(); // Dans le cas ou la personne n'est plus dans le systeme if(!p.updatePosition()) { personToRemove.add(p2); it.remove(); chartDistance.addPoint(p.getDistance(), "Distances", Integer.toString(p.getId())); drawArea.removePersonUi(p.getUi()); } } Iterator<Person> it3 = personnes.iterator(); while(it3.hasNext()) { p2 = it3.next(); if(personToRemove.contains(p2)){ it3.remove(); } } personToRemove.clear(); resolveConflicts(clonePersonnes); for(int i = 0; i < clonePersonnes.size(); i++) { personnes.get(i).update(clonePersonnes.get(i)); } if(personnes.isEmpty()) { // en 1 iteration, l'indivitdu se deplace de 0.4m a 1m/s // il s'ecoule donc 0.4 seconde par iteration System.out.println("Temps d'evacuation:" +nbIterations * temps + " s"); chartExit.addPoint(nbIterations * temps, "Dates de sortie", Integer.toString(grid.getNbExit())); stopSimulation(); } drawArea.updateItems(); nbIterations++; } } ); timer.setInitialDelay(1000); }
ddce45e6-e466-435e-a30a-6162824966b6
8
public static void getPathHeuristics(int[] start,int[] goal,int obj[]){ //System.out.println("Score goal :"+score[goal[0]][goal[1]][0]+" "+score[goal[0]][goal[1]][1]); if(finiteStateMachine.value==null){ finiteStateMachine.value = new int[10][10]; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { finiteStateMachine.value[i][j] = 60; } } } //System.out.println("goal :"+goal[0]+" "+goal[1]); //System.out.println("start :"+start[0]+" "+start[1]); int currentX = goal[0], currentY = goal[1],weight = score[goal[0]][goal[1]][0],yhold =goal[1],xhold =goal[0]; while(true){ if(currentX==start[0] && currentY==start[1] || weight>obj[2]/1000){ break; }else{ //System.out.print("("+currentX+","+currentY+")"); if(finiteStateMachine.value[currentX][currentY]>weight) finiteStateMachine.value[currentX][currentY] = weight; yhold = currentY; xhold = currentX; currentX = camefrom[xhold][yhold][0]; currentY = camefrom[xhold][yhold][1]; } } //System.out.println(""); }
9919ebd4-87b0-4e3c-b64f-0ee32e219e4c
3
private int findNoneZero(int n, int k) { int[] arr = new int[10]; int index = 0; for (int i = 0; i < 10; i++) { if (i == k) continue; arr[index] = i; index++; } ArrayList<Integer> nineBase = getNineInvertedDigits(n); int result = 0; for (int i = nineBase.size() -1 ; i > -1; i--) { index = nineBase.get(i); result = result * 10 + arr[index]; } return result; }
e1ae430a-b00b-4ae5-844c-70b5021773ac
9
@Override public void endElement(String uri, String localName, String qName) throws SAXException{ switch (qName){ case "plane": planes.add(plane); break; case "model": plane.setModel(Model.getModel(content)); break; case "origin": plane.setOrigin(Country.getCountry(content)); break; case "type": plane.setType(PlaneType.getType(content)); break; case "crew": plane.setCrew(Integer.parseInt(content)); break; case "length": plane.getParameters().setLength(Double.parseDouble(content)); break; case "wingspan": plane.getParameters().setWingspan(Double.parseDouble(content)); break; case "weight": plane.getParameters().setWeight(Double.parseDouble(content)); break; case "price": plane.setPrice(Double.parseDouble(content)); break; } }
75da85dc-6b21-4c5a-8369-688ecea73f5f
1
public Bear(boolean randomAge, Field field, Location location) { super(field, location); if(randomAge) { setAge(getRandom().nextInt(MAX_AGE)); setFoodLevel(getRandom().nextInt(RABBIT_FOOD_VALUE + FOX_FOOD_VALUE)); } else{ setAge(0); setFoodLevel(RABBIT_FOOD_VALUE + FOX_FOOD_VALUE); } }
f73fd06b-90a2-4e46-b909-5f03be0e7373
3
public boolean isEmpty() { for (ItemStack item : this.items) { if (item != null && item.getType() != Material.AIR) { return false; } } return true; }
af6ea480-bfda-4ef1-802b-8f19f777446e
2
public static int gMin(ArrayList<node> list){ int min = (list.get(0)).frequency; int index = 0; for(int i=1; i<list.size(); i++){ if((list.get(i)).frequency < min){ min = (list.get(i)).frequency; index=i; } } return index; }