method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
ab8c33ee-cced-4c67-bbce-fde5bef20b81
7
public void timechk() { for (World w : plugin.gmtWorlds) { if (plugin.getConfig().getBoolean("worlds." + w.getName() + ".keep_night") && plugin.gmtPlayerCount.containsKey(w.getName()) && plugin.gmtHasSwitched.contains(w.getName())) { if (plugin.gmtPlayerCount.get(w.getName()) > 0) { Long now = w.getTime(); Long dusk = 21500L; Long dawn = plugin.getConfig().getLong("worlds." + w.getName() + ".time") + 1000; if (now < dawn || now > dusk) { // set the time to dawn w.setTime(dawn); } } } } }
6f6568bd-1fbf-453e-b800-5b22e3af2b85
6
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Agregar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Agregar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Agregar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Agregar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Agregar().setVisible(true); } }); }
ea12b7ab-0bf5-467e-9ad0-dc4551de6cca
0
public void mouseReleased(MouseEvent e) {}
143b3b83-a718-428c-a472-84c9f67eb777
1
public ImagePreview(String src) { super(); try { image = ImageIO.read(new File(src)); } catch (IOException ex) { } setPreferredSize(new Dimension(image.getWidth(), image.getHeight())); }
3f0d72ef-767b-4e4a-898f-d50e94140a4c
9
public void scrollCellToView(JTable table, int rowIndex, int vColIndex) { if (!(table.getParent() instanceof JViewport)) { return; } JViewport viewport = (JViewport) table.getParent(); Rectangle rect = table.getCellRect(rowIndex, vColIndex, true); Rectangle viewRect = viewport.getViewRect(); int x = viewRect.x; int y = viewRect.y; if (rect.x >= viewRect.x && rect.x <= (viewRect.x + viewRect.width - rect.width)){ } else if (rect.x < viewRect.x){ x = rect.x; } else if (rect.x > (viewRect.x + viewRect.width - rect.width)) { x = rect.x - viewRect.width + rect.width; } if (rect.y >= viewRect.y && rect.y <= (viewRect.y + viewRect.height - rect.height)){ } else if (rect.y < viewRect.y){ y = rect.y; } else if (rect.y > (viewRect.y + viewRect.height - rect.height)){ y = rect.y - viewRect.height + rect.height; } viewport.setViewPosition(new Point(x,y)); }
1b311b91-8969-4dcc-997a-2f2ad3f84a92
4
public final void grabMouse() { if(!this.hasMouse) { this.hasMouse = true; if(this.levelLoaded) { try { Mouse.setNativeCursor(this.cursor); Mouse.setCursorPosition(this.width / 2, this.height / 2); } catch (LWJGLException var2) { var2.printStackTrace(); } if(this.canvas == null) { this.canvas.requestFocus(); } } else { Mouse.setGrabbed(true); } this.setCurrentScreen((GuiScreen)null); this.lastClick = this.ticks + 10000; } }
15366b96-572a-49a1-a036-3ff2ceaccfd3
3
public boolean isViable(Field field) { // How many counts are non-zero. int nonZero = 0; if(!countsValid) { generateCounts(field); } for(Class key : counters.keySet()) { Counter info = counters.get(key); if(info.getCount() > 0) { nonZero++; } } return nonZero > 1; }
d9f25996-fa47-454b-871d-b0a0edb4bc2f
9
@Override public void copySources( HashMap<String, Source> srcMap ) { if( srcMap == null ) return; Set<String> keys = srcMap.keySet(); Iterator<String> iter = keys.iterator(); String sourcename; Source source; // Make sure the buffer map exists: if( bufferMap == null ) { bufferMap = new HashMap<String, SoundBuffer>(); importantMessage( "Buffer Map was null in method 'copySources'" ); } // remove any existing sources before starting: sourceMap.clear(); SoundBuffer buffer; // loop through and copy all the sources: while( iter.hasNext() ) { sourcename = iter.next(); source = srcMap.get( sourcename ); if( source != null ) { buffer = null; if( !source.toStream ) { loadSound( source.filenameURL ); buffer = bufferMap.get( source.filenameURL.getFilename() ); } if( !source.toStream && buffer != null ) { buffer.trimData( maxClipSize ); } if( source.toStream || buffer != null ) { sourceMap.put( sourcename, new SourceJavaSound( listener, source, buffer ) ); } } } }
fed1d520-dee6-4cd2-ae73-00c2e5cf8ee1
3
public boolean add(Pet pet) { for (int i = 0; i < list.length; i++) { if (list[i] == null) { list[i] = pet; return true; } } Pet[] tempList = new Pet[list.length + 1]; for (int j = 0; j < list.length; j++) { tempList[j] = list[j]; } tempList[list.length] = pet; this.list = tempList; return true; }
72bd3a39-51c2-4c13-b4f1-86cb6b3f42c2
3
protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(map, 0, 0, this); if (players != null) { for (Player p: players) { g.setColor(Color.RED); g.fillOval(p.getX(), p.getY(), 10, 10); g.setColor(Color.BLACK); g.drawOval(p.getX(), p.getY(), 10, 10); } } if (user != null) { g.setColor(Color.GREEN); g.fillOval(user.getX(), user.getY(), 10, 10); g.setColor(Color.BLACK); g.drawOval(user.getX(), user.getY(), 10, 10); } }
316ab950-e832-4314-8737-0a58b7224ee2
5
public void load() throws IOException, InvalidConfigurationException { if (!file.exists()) { BufferedWriter writer = null; BufferedReader reader = null; try { InputStream in = CommandBoat.getInstance().getResource("commands.yml"); reader = new BufferedReader(new InputStreamReader(in)); writer = new BufferedWriter(new FileWriter(file)); String line; while ((line = reader.readLine()) != null) { writer.write(line); writer.write(System.lineSeparator()); } } catch (IOException ex) { CommandBoat.getInstance().getLogger().log(Level.SEVERE, null, ex); } finally { try { writer.close(); } catch (IOException ex) { CommandBoat.getInstance().getLogger().log(Level.SEVERE, null, ex); } try { reader.close(); } catch (IOException ex) { CommandBoat.getInstance().getLogger().log(Level.SEVERE, null, ex); } } } config.load(file); }
1dbe1026-bd95-40e5-8442-10f123aacec0
4
public static void UpperStreet(){ try { if(conn == null || conn.isClosed()){ conn = DatabaseConnection.getConnection(); } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try{ conn.setAutoCommit(false); PreparedStatement stmnt = conn.prepareStatement("UPDATE Addresses set street = CONCAT( UPPER( LEFT( street, 1 ) ) , SUBSTRING( street, 2 ))"); stmnt.execute(); conn.commit(); conn.setAutoCommit(true); }catch(SQLException e){ e.printStackTrace(); } }
d332c8ca-2c8a-4a0e-9c32-d9d16fe49126
3
public void actionPerformed(ActionEvent e) { ConfigurationButton button = null; try { button = (ConfigurationButton) e.getSource(); } catch (ClassCastException ex) { return; // Then, we don't care. } Configuration config = button.getConfiguration(); if (!configurationToButtonMap.containsKey(config)) return; if (button.isSelected()) selected.add(config); else selected.remove(config); distributeSelectionEvent(new ConfigurationSelectionEvent(this)); }
21fc2d98-9a0e-4e60-b51d-c573d7e01ba9
9
public void allMove() { // 물고기들을 이동시키고 충돌확인하고 이벤트를 처리하는 메소드 // 컴퓨터 물고기와 플레이어 물고기를 모두 논리이동시킨다 for (int i = 0; i < curFishNumber; i++) { fishList.elementAt(i).move(); } this.playerFish1.move(); if (this.gameMode == FishEater.GAME_RUN_2P) { this.playerFish2.move(); } // 컴퓨터 물고기가 화면 밖으로 나갔을 경우 remove한다. for (int i = 0; i < curFishNumber; i++) { if (fishList.elementAt(i).isOutOfbound()) { fishList.removeElementAt(i); curFishNumber--; } } // 플레이어 물고기와 컴퓨터 물고기가 충돌했는지 확인하고 충돌 할 경우 // 먹을 수 있다면, 먹고, 먹을 수 없다면 먹지 않고, 먹혀야 한다면 먹힌다. allCollisionTest(playerFish1); if (gameMode == FishEater.GAME_RUN_2P) { allCollisionTest(playerFish2); } // 플레이어 물고기 끼리 충돌했는지 검사한뒤 적당한 이벤트를 발생한다 // curLevel를 설정하여 리스폰 되는 컴퓨터 물고기의 레벨을 조정한다 // 게임 진행 모드의 플레이어의 수에 따라 정해진다 if (gameMode == FishEater.GAME_RUN_2P) { if (playerFish1.isCollition(playerFish2.getFish())) { if (playerFish1.isEatable(playerFish2)) { playerFish1.eat(playerFish2.getFish()); playerFish2.eaten(); } else if (playerFish2.isEatable(playerFish1)) { playerFish2.eat(playerFish1.getFish()); playerFish1.eaten(); } } curLevel = (playerFish1.getLevel() + playerFish2.getLevel()) / 2; } else { curLevel = playerFish1.getLevel(); } }
4746ccbb-51e2-44c4-8270-ace1a856e8d1
3
protected void toString2(StringBuffer sbuf) { sbuf.append("pos=").append(position).append(", len=") .append(length).append(", in=").append(incoming) .append(", exit{"); if (exit != null) { for (int i = 0; i < exit.length; i++) sbuf.append(exit[i].position).append(", "); } sbuf.append("}, {"); Catch th = toCatch; while (th != null) { sbuf.append("(").append(th.body.position).append(", ") .append(th.typeIndex).append("), "); th = th.next; } sbuf.append("}"); }
ebfb1655-3571-4f3f-8c43-843a9ab44f8e
9
protected void submitData(){ if (isComplete()){ String name = nameField.getText(); float magneticHeading = Float.parseFloat(magneticHeadingField.getText()); //float altitude = Float.parseFloat(altitudeField.getText()) / UnitConversionRate.convertDistanceUnitIndexToFactor(runwayAltitudeUnitsID); String parentAirfield = ""; String parentId = ""; try{ parentAirfield = objectSet.getCurrentAirfield().getDesignator(); parentId = objectSet.getCurrentAirfield().getId(); }catch (Exception e){ } Runway newRunway = new Runway(name, magneticHeading, parentAirfield, 0, ""); newRunway.setId(currentRunway.getId()); newRunway.setParentId(parentId); try{ objectSet.setCurrentRunway(newRunway); Object[] options = {"One-time Launch", "Save to Database"}; int choice = JOptionPane.showOptionDialog(rootPane, "Do you want to use this Runway for a one-time launch or save it to the database?", "", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); System.out.println(choice); if (choice == 0){ parent.update("2"); this.dispose(); } else { if (isEditEntry){ DatabaseEntryEdit.UpdateEntry(newRunway); } else{ Random randomId = new Random(); newRunway.setId(String.valueOf(randomId.nextInt(100000000))); while (DatabaseEntryIdCheck.IdCheck(newRunway)){ newRunway.setId(String.valueOf(randomId.nextInt(100000000))); } DatabaseUtilities.DatabaseDataObjectUtilities.addRunwayToDB(newRunway); } parent.update("2"); this.dispose(); } }catch(SQLException e1) { if(e1.getErrorCode() == 30000){ System.out.println(e1.getMessage()); JOptionPane.showMessageDialog(rootPane, "Sorry, but the runway " + newRunway.toString() + " already exists in the database", "Error", JOptionPane.INFORMATION_MESSAGE); } }catch (ClassNotFoundException e2) { JOptionPane.showMessageDialog(rootPane, "Error: No access to database currently. Please try again later.", "Error", JOptionPane.INFORMATION_MESSAGE); } catch (Exception e3) { } } }
9688fbfe-7111-4d7c-becc-b1f7d6846182
2
public Player(Vector3f position) { if(mesh == null) { Vertex[] vertices = new Vertex[]{new Vertex(new Vector3f(-SIZEX,START,START), new Vector2f(0.1f,0.1f)), new Vertex(new Vector3f(-SIZEX,SIZEY,START), new Vector2f(0.1f,0.1f)), new Vertex(new Vector3f(SIZEX,SIZEY,START), new Vector2f(0.1f,0.1f)), new Vertex(new Vector3f(SIZEX,START,START), new Vector2f(0.1f,0.1f))}; int[] indices = new int[]{0,1,2, 0,2,3}; mesh = new Mesh(vertices, indices); } if(gunMaterial == null) { gunMaterial = new Material(new Texture("PISGB0.png")); } camera = new Camera(position, new Vector3f(0, 0, 1), new Vector3f(0, 1, 0)); this.random = new Random(); gunTransform = new Transform(); gunTransform.setTranslation(new Vector3f(8,0,9)); movementVector = zeroVector; this.health = MAX_HEALTH; }
8df16a1a-a8c8-4d05-abcc-6c77b46d9ce9
0
@Test public void testCreateServices() throws Exception { //Test TestTicketPoolManager can be initialized without throwing any exception. ServiceManager.getServices().initializeServices(new Object[] {new TestRailwayRepository(), new TestTicketPoolManager()}); //IRailwayRepository repo = ServiceManager.getServices().getRequiredService(IRailwayRepository.class); ITicketPoolManager tpm = ServiceManager.getServices().getRequiredService(ITicketPoolManager.class); Assert.assertNotNull(tpm); }
de774258-abef-43f4-9314-5250009ecfaf
0
public ConnectionHandler(Socket sock) throws IOException { this.socket = sock; out = new PrintWriter(socket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); }
067a4042-059d-48e7-9832-aa2a10044c2f
6
public static boolean transform(LoopBlock forBlock, StructuredBlock last) { if (!(last.outer instanceof SequentialBlock)) return false; SequentialBlock sequBlock = (SequentialBlock) last.outer; if (!(sequBlock.subBlocks[0] instanceof InstructionBlock)) return false; InstructionBlock init = (InstructionBlock) sequBlock.subBlocks[0]; if (!init.getInstruction().isVoid() || !(init.getInstruction() instanceof CombineableOperator) || !forBlock.conditionMatches((CombineableOperator) init .getInstruction())) return false; if (GlobalOptions.verboseLevel > 0) GlobalOptions.err.print('f'); forBlock.setInit((InstructionBlock) sequBlock.subBlocks[0]); return true; }
46728f62-b838-41d6-9bd1-5a636003c240
8
@Override public double getFMeasure(String classValue) throws IllegalArgumentException { if( classValue == null) throw new IllegalArgumentException("Error: null class value"); if( this.valueToIndex.get(classValue) == null) throw new IllegalArgumentException("Error: state = " + classValue + " didn't found"); if( this.performances.size() == 0) return Double.NaN; if( this.fmeasure == null) { this.fmeasure = new double[this.indexToValue.size()]; for(int i = 0; i < this.fmeasure.length; ++i) this.fmeasure[i] = 0.0; Iterator<PType> iterPerf = this.performances.iterator(); while(iterPerf.hasNext()) { PType perf = iterPerf.next(); for(int i = 0; i < this.fmeasure.length; ++i) this.fmeasure[i] += perf.getFMeasure(this.indexToValue(i)); } for(int i = 0; i < this.fmeasure.length; ++i) this.fmeasure[i] /= this.performances.size(); } return this.fmeasure[this.valueToIndex.get(classValue)]; }
1478595a-a1d1-46dc-918e-0022a2fc16c5
3
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (!sender.hasPermission("under50.broadcast")) { sender.sendMessage(ChatColor.RED + "No permission"); return true; } if (args.length == 0) { sender.sendMessage("Try /bcast <message>"); return true; } StringBuilder message = new StringBuilder(); for (String part : args) { message.append(" ").append(part); } Bukkit.getServer().broadcastMessage(ChatColor.AQUA + "[BROADCAST]" + message.toString()); return true; }
9de1740f-e21a-4e4c-8b1e-77f9e6ef192e
1
public boolean useTeleport() { if (teleports > 0) { teleports--; return true; } else { return false; } }
a37e3536-ef90-4812-9648-e57656e62ff9
4
private OSCMessage convertMessage() { OSCMessage message = new OSCMessage(); message.setAddress(readString()); char[] types = readTypes(); if (null == types) { // we are done return message; } moveToFourByteBoundry(); for (int i = 0; i < types.length; i++) { if ('[' == types[i]) { // we're looking at an array -- read it in message.addArgument(readArray(types, i)); // then increment i to the end of the array while (']' != types[i]) i++; } else message.addArgument(readArgument(types[i])); } return message; }
aff6dec0-447f-4178-9374-cd5942049f0e
7
boolean canMoveTo(int inLocX, int inLocY,LivingThing thnStore) { int i; LivingThing thnStore2; DuskObject objStore=null; Script scrStore; boolean blnStore; try { objStore = objEntities[inLocX][inLocY]; }catch(Exception e) {} if (scrCanMoveThroughLivingThing != null) { while (objStore != null) { if (objStore.isLivingThing()) { thnStore2 = (LivingThing)objStore; synchronized(scrCanMoveThroughLivingThing) { scrCanMoveThroughLivingThing.varVariables.clearVariables(); scrCanMoveThroughLivingThing.varVariables.addVariable("moving",thnStore); scrCanMoveThroughLivingThing.varVariables.addVariable("blocking",thnStore2); if (!scrCanMoveThroughLivingThing.rewindAndParseScript()) return false; } } objStore = objStore.objNext; } } try { scrStore = new Script("defCanMoveScripts/"+inLocX+"_"+inLocY,this,false); scrStore.varVariables.addVariable("trigger",thnStore); blnStore = scrStore.rewindAndParseScript(); scrStore.close(); return blnStore; }catch (Exception e){} try { scrStore = (Script)vctTiles.elementAt(shrMap[inLocX][inLocY]); synchronized(scrStore) { scrStore.varVariables.clearVariables(); scrStore.varVariables.addVariable("trigger",thnStore); blnStore = scrStore.rewindAndParseScript(); } return blnStore; }catch (Exception e){} return false; }
9564d077-66f2-4282-a5b2-47a1688732df
2
public boolean kickFromChannel(String chan, String msg) { boolean success = true; msg = addNewLines(msg); String[] msgArr = msg.split("\n"); char ch; for(int j=0;j<msgArr.length;j++) { /* * Meaning if one call to sendln returns false * This entire function will return false */ if( !sendln("kick " + chan + " " + msgArr[j]) ) { success = false; } } return success; }
b32acd18-b009-4b42-acef-7fa2f172c927
4
private static int idchf(palString string) { int ivec, ictab; char c = ' '; int nptr = string.getPos(); int digit = 0; int l_string = string.length(); /* Character/vector tables */ TRACE("idchf"); final int NCREC = 20; final char kctab[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ' ', '\t', 'D', 'd', 'E', 'e', '.', '+', '-', ','}; final int kvtab[] = {NUMBER, NUMBER, NUMBER, NUMBER, NUMBER, NUMBER, NUMBER, NUMBER, NUMBER, NUMBER, SPACE, SPACE, EXPSYM, EXPSYM, EXPSYM, EXPSYM, PERIOD, PLUS, MINUS, COMMA}; /* Initialize returned value */ ivec = OTHER; /* Pointer outside field? */ if (nptr < 0 || nptr >= l_string) { /* Yes: prepare returned value */ ivec = END; } else { /* Not end of field: identify character */ c = string.getNextChar(); for (ictab = 0; ictab < NCREC; ictab++) { if (kctab[ictab] == c) { /* Recognized */ ivec = kvtab[ictab]; /* Allow for numerals */ digit = ictab; /* Quit the loop */ break; } } /* Increment pointer */ nptr++; } string.setDigit(digit); ENDTRACE("idchf"); /* Return the value identifying the character */ return ivec; }
d8e7370f-ff83-4909-bed6-36d1424697db
1
public World() { try { map = new TiledMap("res/map/map.tmx"); } catch (SlickException e) { // TODO Auto-generated catch block e.printStackTrace(); } layerMap = new CustomLayerBasedMap(map, map.getLayerIndex("objects"), map.getLayerIndex("npc")); }
d54f251d-5052-43a9-84ef-9634cc3feed8
4
@Override public String execute() { ContactListHandler contactListHandler = new ContactListHandler(); contactListHandler.setContactDao(new ContactDao()); try { contactListHandler.executeSearch(); int currentPage = getCurrentPage(commandParameter.getRequestParameter(COMMAND_PARAM), commandParameter.getRequestParameter(CURRENT_PAGE_PARAM)); List<Contact> contacts = null; for (int i = 0; i < currentPage; i++) { contacts = contactListHandler.getNextElements(RECORDS_PER_PAGE); } ContactsDto contactsDto = new ContactsDto(); contactsDto.setContacts(new ContactToContactDtoConverter().convert(contacts)); contactsDto.setPath(commandParameter.getRequestURI()); int numOfPages = getNumberOfPages(contactListHandler.getSize()); contactsDto.setNumOfPages(numOfPages); contactsDto.setCurrentPage(currentPage); String xml = new ContactsDtoToXmlConverter().convertToXml(contactsDto); ApplictionResources applictionResources = ApplictionResources.getInstance(); InputStream xsltInputStream = applictionResources.getResourceAsStream(XSLT_SCRIPT_PATH); XSLTTransformer transformer = new XSLTTransformer(); transformer.transform(IOUtils.toInputStream(xml), xsltInputStream, commandParameter.getOutputStream()); } catch (IOException e) { e.printStackTrace(); } catch (ListHandlerException e) { e.printStackTrace(); } catch (IteratorException e) { e.printStackTrace(); } return UrlUtil.getPage(commandParameter); }
f8f17717-7343-42e6-86f7-9ef22e9f0790
4
@EventHandler public void onEntityShootBow(EntityShootBowEvent event) { if (event.getEntity() instanceof Player) { ItemStack item = event.getBow(); if (item == null || !Config.isItemEnabled(plugin, item.getTypeId())) { return; } Weapon weapon = new Weapon(plugin, item); int levelState = weapon.getLevel(); if (weapon.getLevel() > levelState) { Util.dropExperience(event.getEntity().getLocation(), Config.EXP_ON_LEVEL, 3); } arrows.put(event.getProjectile(), weapon); } }
d8c1db5a-e38e-4fb4-918c-17701ddcd24b
7
private void start(String props, String cluster_name, long rpc_timeout, long caching_time, boolean migrate_data, boolean use_l1_cache, int l1_max_entries, long l1_reaping_interval, int l2_max_entries, long l2_reaping_interval) throws Exception { MBeanServer server=ManagementFactory.getPlatformMBeanServer(); cache=new ReplCache<>(props, cluster_name); cache.setCallTimeout(rpc_timeout); cache.setCachingTime(caching_time); cache.setMigrateData(migrate_data); JmxConfigurator.register(cache, server, BASENAME + ":name=cache"); JmxConfigurator.register(cache.getL2Cache(), server, BASENAME + ":name=l2-cache"); if(use_l1_cache) { Cache<String,String> l1_cache=new Cache<>(); cache.setL1Cache(l1_cache); if(l1_reaping_interval > 0) l1_cache.enableReaping(l1_reaping_interval); if(l1_max_entries > 0) l1_cache.setMaxNumberOfEntries(l1_max_entries); JmxConfigurator.register(cache.getL1Cache(), server, BASENAME + ":name=l1-cache"); } if(l2_max_entries > 0 || l2_reaping_interval > 0) { Cache<String, ReplCache.Value<String>> l2_cache=cache.getL2Cache(); if(l2_max_entries > 0) l2_cache.setMaxNumberOfEntries(l2_max_entries); if(l2_reaping_interval > 0) l2_cache.enableReaping(l2_reaping_interval); } Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { cache.stop(); } }); cache.start(); model=new MyTableModel<String,String>(); model.setMap(cache.getL2Cache().getInternalMap()); cache.addChangeListener(model); frame=new JFrame("ReplCacheDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); table=new MyTable(model); table.setPreferredScrollableViewportSize(new Dimension(500, 200)); // table.setFillsViewportHeight(true); // JDK 6 specific table.setShowGrid(false); table.setFont(table.getFont().deriveFont(Font.BOLD)); add(new JScrollPane(table)); JPanel key=new JPanel(new FlowLayout(FlowLayout.LEFT)); key.add(new JLabel("Key ")); key.add(key_field); add(key); JPanel value=new JPanel(new FlowLayout(FlowLayout.LEFT)); value.add(new JLabel("Value")); value.add(value_field); add(value); JPanel repl_count=new JPanel(new FlowLayout(FlowLayout.LEFT)); repl_count.add(new JLabel("Replication count")); repl_count.add(repl_count_field); add(repl_count); JPanel timeout=new JPanel(new FlowLayout(FlowLayout.LEFT)); timeout.add(new JLabel("Timeout")); timeout.add(timeout_field); add(timeout); JPanel buttons=new JPanel(); JButton put_button=createButton("Put"); buttons.add(createButton("Put")); buttons.add(createButton("Remove")); buttons.add(createButton("Clear")); buttons.add(createButton("Rebalance")); buttons.add(createButton("Exit")); buttons.add(num_elements); add(buttons); setOpaque(true); root_pane.addTab("Data", this); JPanel perf_panel=new JPanel(); perf_panel.setLayout(new BoxLayout(perf_panel, BoxLayout.Y_AXIS)); perf_panel.setOpaque(true); root_pane.addTab("Perf test", perf_panel); perf_panel.add(status); status.setForeground(Color.BLUE); JPanel prefix=new JPanel(new FlowLayout(FlowLayout.LEFT)); prefix.add(new JLabel("Key prefix")); prefix.add(perf_key_prefix); perf_panel.add(prefix); JPanel keys=new JPanel(new FlowLayout(FlowLayout.LEFT)); keys.add(new JLabel("Number of keys to insert")); keys.add(perf_num_keys); perf_panel.add(keys); JPanel size=new JPanel(new FlowLayout(FlowLayout.LEFT)); size.add(new JLabel("Size of each key (bytes)")); size.add(perf_size); size.add(new JLabel(" (ignored for now)")); perf_panel.add(size); JPanel perf_repl_count=new JPanel(new FlowLayout(FlowLayout.LEFT)); perf_repl_count.add(new JLabel("Replication count")); perf_repl_count.add(perf_repl_count_field); perf_panel.add(perf_repl_count); JPanel perf_timeout=new JPanel(new FlowLayout(FlowLayout.LEFT)); perf_timeout.add(new JLabel("Timeout")); perf_timeout.add(perf_timeout_field); perf_panel.add(perf_timeout); JPanel perf_buttons=new JPanel(new FlowLayout(FlowLayout.LEFT)); perf_buttons.add(createButton("Start")); perf_buttons.add(createButton("Stop")); perf_buttons.add(createButton("Reset")); perf_buttons.add(createButton("Exit")); perf_panel.add(perf_buttons); frame.setContentPane(root_pane); frame.pack(); frame.getRootPane().setDefaultButton(put_button); frame.setVisible(true); setTitle("ReplCacheDemo"); cache.addMembershipListener(new MembershipListener() { public void viewAccepted(View new_view) { setTitle("ReplCacheDemo"); } public void suspect(Address suspected_mbr) { } public void block() { } public void unblock() { } }); }
fce2c9f3-3c2a-4715-8772-7c62c1fa0a23
3
protected CasavaFastqParser(String id) { Matcher m = Pattern.compile(REGEX).matcher(id); // Last guard block if (!m.matches()) return; setAttribute(IdAttributes.FASTQ_TYPE, NAME); for (IdAttributes a : regexAttributeMap.keySet()) { String value = m.group(regexAttributeMap.get(a)); if (value != null) setAttribute(a, m.group(regexAttributeMap.get(a))); } }
993ab8b1-1623-422c-9e7a-374a07612750
5
@Override public int authorized(String email, String password) { int ret = -1; /* SELECT id, password, group_id FROM b_user AS bu RIGHT JOIN b_user_group AS bug ON bu.id = bug.user_id WHERE login = ? AND group_id = 1 AND active = 'Y' */ String q = "SELECT id, password, group_id\n" + "FROM b_user AS bu\n" + "RIGHT JOIN b_user_group AS bug ON bu.id = bug.user_id\n" + "WHERE login = ? AND group_id = 1 AND active = 'Y'"; Object[] params = {email}; if(email != null && password != null) try ( Connection con = Db.ds.getConnection(); PreparedStatement ps = Helpers.createStatement(con, q, params); ResultSet rs = ps.executeQuery() ) { if(rs.next()) { String saltnhash = rs.getString("password"); String salt = saltnhash.substring(0, 8); String hash_string = saltnhash.substring(8); byte[] hash = Hex.decodeHex(hash_string.toCharArray()); boolean match = Arrays.equals(hash, (md.digest((salt + password).getBytes(StandardCharsets.UTF_8)))); if(match) ret = rs.getInt("id"); } else log.info("No such user {}", email); } catch(Exception e) { log.error(e.toString(), e); } else log.info("Not enough credentials to check authorization"); return ret; }
3a2cbcd7-304b-4f5d-8e58-742fd05d676f
4
public void test_constructor() { try { new ScaledDurationField(null, DurationFieldType.minutes(), 10); fail(); } catch (IllegalArgumentException ex) {} try { new ScaledDurationField(MillisDurationField.INSTANCE, null, 10); fail(); } catch (IllegalArgumentException ex) {} try { new ScaledDurationField(MillisDurationField.INSTANCE, DurationFieldType.minutes(), 0); fail(); } catch (IllegalArgumentException ex) {} try { new ScaledDurationField(MillisDurationField.INSTANCE, DurationFieldType.minutes(), 1); fail(); } catch (IllegalArgumentException ex) {} }
5ef7af64-b60e-4c00-ba05-a2c50f51756b
4
@Override public String display() { //Displays assembly language program with line numbers String displayString = " <Label>: <Instruction/Operand> <#Comment>\n\n"; if (leadingComments.size() > 0) { //Display leading comments, if there are any for (int i = 0; i < leadingComments.size(); i++) { displayString += leadingComments.get(i) + "\n"; } displayString += "\n"; //Add extra space for clarity } int lineReference = 0; //For display of line numbers, including blank lines for (int i = 0; i < displayProgram.size(); i++) { if (lineReference < 10) { //Line number formatting displayString += "0" + lineReference + "| " + displayProgram.get(i) + "\n"; lineReference++; } else { displayString += lineReference + "| " + displayProgram.get(i) + "\n"; lineReference++; } } return displayString; }
9514d750-3130-4b9c-bd33-3dfa15bdb4fd
2
private static BitSet fromByteArray(byte[] bytes) { BitSet bits = new BitSet(); for (int i=0; i<bytes.length*8; i++) { if ((bytes[bytes.length-i/8-1]&(1<<(i%8))) > 0) { bits.set(i); } } return bits; }
ba30529b-18e0-4b22-9fbf-0259ed1df675
0
public AlphaMerger(int[] alpha) { this.alpha = alpha; }
0961612d-a3e8-4f46-a05e-53c562d2e1e6
8
public String setMidiOut(int id) { if(_synthesizer != null) { _synthesizer.close(); _synthesizer = null; _midiDevices.setSynthesizer(_synthesizer); } if(id > _midiDevices.getNumberOfDevices()) { return "<midi-out>" + id + "</midi-out>"; } if(id == -1) { return "<midi-out>" + id + "</midi-out>"; } try { _synthesizer = _midiDevices.getDevice(id);//hw output } catch(ArrayIndexOutOfBoundsException e1) { return "<error id='setOutPort'>" + e1 + "</error><midi-out>-1</midi-out>"; } try { _synthesizer.open(); } catch(MidiUnavailableException e2) { return "<error id='setOutPort'>" + e2 + "</error><midi-out>-1</midi-out>"; } if(_keyboard == null || !_keyboard.isOpen()) { _midiDevices.setSynthesizer(_synthesizer); return "<message id='setOutPort'>no keyboard</message><midi-out>" + id + "</midi-out>"; } Transmitter trans2 = null; try { trans2 = _keyboard.getTransmitter(); trans2.setReceiver(_synthesizer.getReceiver()); } catch(MidiUnavailableException e) { return "<error id='setOutPort'>" + e + "</error><midi-out>-1</midi-out>"; } _midiDevices.setSynthesizer(_synthesizer); return "<midi-out>" + id + "</midi-out>"; }
afee891b-89fe-4167-b1e4-6c13c80870b2
9
public int compare(boolean[] class_list, int datapoint) throws BoostingAlgorithmException{ int c; int class_index = -1; int classification = -1; //determine what class in the classlist the datapoint has for (c = 0; c < classes; c++) { if (data.classes[datapoint].equals(data.classlist[c])) { class_index = c; } } if (class_index == -1) { throw new BoostingAlgorithmException("Class \"" + data.classes[datapoint] + "\" not found in class list"); } //Check if the correct class is indicated if (class_list[class_index]) { //the correct class is selected classification = 0; } else { //the correct class is not selected classification = 3; } for (c = 0; c < classes; c++) { //check if any other classes are indicated if (c != class_index && class_list[c]) { if (classification == 0) { //the correct class is selected, but so are other classes classification = 1; } else if (classification == 3) { //the correct class is not selected, but other classes are selected classification = 2; } } } return classification; }
3c041f8e-2334-476c-b05b-5ef9194ce36c
9
@Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(args.length != 3) { printArgsError(args); printHelp(sender, label); return true; } String target = findTarget(args[1]); int chargeId = -1; try { chargeId = Integer.valueOf(args[2]); } catch (NumberFormatException ex) { printHelp(sender, label); return true; } Record found = Rapsheet.getManager().getCharge(target, chargeId); if(found == null) { sender.sendMessage(COULD_NOT_FIND_CHARGE.replace("<PLAYER>", target)); return true; } if(found.getState() != RecordState.CHARGED) { String message = ChatColor.RED + "You cannot convict for a charge that "; switch(found.getState()) { case CONVICTED: message += "they are already convicted for!"; break; case PARDONED: message += "have been pardoned for!"; break; } sender.sendMessage(message); return true; } if(found.isSealed() && !sender.hasPermission("rapsheet.viewsealed")) { sender.sendMessage(CANNOT_MODIFY_SEALED); return true; } boolean success = Rapsheet.getManager().convictPlayer(target, sender.getName(), chargeId, NotifyChanges.BOTH); if(!success) { plugin.getLogger().severe("Error trying to convict player " + target + " of chargeId: " + chargeId); } return true; }
33e9d150-c47f-4016-95fa-6bfd298cb070
0
@Before public void setUp() { a = new DynamicArray(); }
21988dca-d3c9-4609-a13e-6faa3fb1b640
1
public void addAnnouncementToDB() { try { String statement = new String("INSERT INTO " + DBTable + " (title, content, time)" + " VALUES (?, ?, NOW())"); PreparedStatement stmt = DBConnection.con.prepareStatement(statement, new String[] {"aid"}); stmt.setString(1, title); stmt.setString(2, content); stmt.executeUpdate(); ResultSet rs = stmt.getGeneratedKeys(); rs.next(); announcementID = rs.getInt("GENERATED_KEY"); rs.close(); } catch (SQLException e) { e.printStackTrace(); } }
3bebfe26-58a7-484f-b84f-93b3a9d2c8ba
7
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { final MOB target=this.getTarget(mob,commands,givenTarget); if(target==null) return false; if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success) { invoker=mob; final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?"":L("^S<S-NAME> incant(s) to <T-NAMESELF>.^?")); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); if(msg.value()<=0) { if(target.maxState().getFatigue()>Long.MIN_VALUE/2) target.curState().adjFatigue(CharState.FATIGUED_MILLIS+((mob.phyStats().level()) * 5l * CMProps.getTickMillis()),target.maxState()); mob.location().show(target,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> feel(s) incredibly fatigued!")); } } } else return maliciousFizzle(mob,target,L("<S-NAME> incant(s) to <T-NAMESELF>, but the spell fades.")); // return whether it worked return success; }
7803ca14-3329-4266-8e9d-e0784b5eb9ae
2
private void verifyResource(String attributeName, String nameRes, String resType) { if (nameRes == null || !nameRes.startsWith("@"+resType+"/")) throw new InvalidPackConfiguration(mFileName, "Node "+mNodeName+" has an invalid "+attributeName+" "+resType+" resource !"); }
885c2908-09aa-4da7-80f0-011740e878ec
2
public void testFactory_parseWeeks_String() { assertEquals(0, Weeks.parseWeeks((String) null).getWeeks()); assertEquals(0, Weeks.parseWeeks("P0W").getWeeks()); assertEquals(1, Weeks.parseWeeks("P1W").getWeeks()); assertEquals(-3, Weeks.parseWeeks("P-3W").getWeeks()); assertEquals(2, Weeks.parseWeeks("P0Y0M2W").getWeeks()); assertEquals(2, Weeks.parseWeeks("P2WT0H0M").getWeeks()); try { Weeks.parseWeeks("P1Y1D"); fail(); } catch (IllegalArgumentException ex) { // expeceted } try { Weeks.parseWeeks("P1WT1H"); fail(); } catch (IllegalArgumentException ex) { // expeceted } }
b61e621c-0feb-47da-8f84-be41896cc364
5
public static void verify(FastaFile obj1, FastaFile obj2) { boolean equal=true; if(obj1.getDataBase().size()!=obj2.getDataBase().size()) { equal=false; } for(int i=0;i<obj1.getDataBase().size();i++) { for(int j=0;j<obj1.getDataBase().get(i).getFoundPositionList().size();j++) if((obj1.getDataBase().get(i).getFoundPositionList().get(j)!=obj2.getDataBase().get(i).getFoundPositionList().get(j))) { equal=false; } } if(equal==true) { System.out.println("Verify: same matches"); } else { System.out.println("Verify: not same matches!"); } }
71fe6331-76bf-4077-bdf5-988df175a329
0
public Player cPlayer(){ Player player = new Player(); return player; }
84bf8a72-fae4-45b6-9da6-4431244098fa
3
private int adjustedHandStrength(int rawHandStrength) { int ahs = 0; for(int j = 0; j < 15; j++) { if(rawHandStrength < boundaries[j]) { ahs = j; break; } else if(j == 14) { ahs = j; break; } else { rawHandStrength -= boundaries[j]; } } return Math.min(ahs, 15); }
a17f32ff-d13d-4a3c-8bf6-15a761d36fa3
4
private void getResultCategorization(CategoryPOJO spreadCategory) { // verifica a maior tipo de ocorrencia e diz o tipo de categoria correspondente Object[] keyCount = count.keySet().toArray(); for (int j = 0; j < keyCount.length; j++) { // adiciona 1 na linha, pois o DDex comeca com zero e a planilha com 1 spreadCategory.setRowScheme(rowSchema + 1); // keycont armazena as categorias e os pontos recebidos pelas mesmas de acordo com a ordem em que os // campos aparecerem e o numero de ocorrencias. se tiver somente uma categoria sera ela a armazenada if (keyCount.length == 1) { spreadCategory.setOccurrenceNumber(count.get(keyCount[j].toString())); spreadCategory.setCategoryType(keyCount[j].toString()); lstSpreadsheetCategory.add(spreadCategory); // senao, teremos que verificar qual categoria teve mais pontos } else if ((j + 1) < keyCount.length) { // verifica entre duas categorias qual teve mais pontos if ((Integer) count.get(keyCount[j]) > (Integer) count.get(keyCount[j + 1])) { spreadCategory.setOccurrenceNumber(count.get(keyCount[j].toString())); spreadCategory.setCategoryType(keyCount[j].toString()); lstSpreadsheetCategory.add(spreadCategory); } else { spreadCategory.setOccurrenceNumber(count.get(keyCount[j + 1].toString())); spreadCategory.setCategoryType(keyCount[j + 1].toString()); lstSpreadsheetCategory.add(spreadCategory); } } } }
637a41d5-e899-4342-b3dc-a935d8a55ccf
0
public void setDecisionAnswer(ArrayList<String> answ, ArrayList<String> numbers) { questAnswer=answ; goToList=numbers; }
db6e2570-889d-41f7-8e2f-e8087ef8bad8
7
@Override /** Questo è il listener per la menuBar */ public void actionPerformed(ActionEvent arg0) { /** Per salvare prende la lista di locazioni e la salva */ if (arg0.getSource().equals(save)) { JFileChooser fc = new JFileChooser(); fc.setFileSelectionMode(JFileChooser.FILES_ONLY); fc.showSaveDialog(null); String path = fc.getSelectedFile().getPath(); try { // Se l'utente non ha inserito alcun percorso salvo nella home: if (path == null || path.equals("")) { io.IO.saveToFile(Singleton.getLocations()); } else { io.IO.saveToFile(Singleton.getLocations(), path); } } catch (IOException e) { System.out.println("Impossibile salvare il file, assicurarsi di aver inserito un percorso esisnte e di avere i permessi di scrittura."); } Singleton.getFrame().getBottomPanel().updateConsole("La partita è stata salvata."); } // Per il caricamento ricostruisco da capo il frame else if (arg0.getSource().equals(load)) { String path = MainFrame.loadPath(); Singleton.getFrame().setVisible(false); Singleton.setFrame(new MainFrame(MainFrame.startFromLoad(path))); Singleton.getFrame().setVisible(true); } else if (arg0.getSource().equals(clear)) { Singleton.getPlayer().perdiMemoria(); Singleton.getFrame().getBottomPanel().updateConsole("Il giocatore ha perso la memoria."); } else if (arg0.getSource().equals(info)) { JOptionPane.showMessageDialog(Singleton.getFrame(), "Progetto di Metodologie di programmazione, a.a 2012.\nAdriano Di Luzio.", "About", JOptionPane.INFORMATION_MESSAGE, new ImageIcon(Toolkit.getDefaultToolkit().getImage(ClassLoader.getSystemClassLoader().getResource("icon.png")))); } Singleton.getFrame().validate(); }
43ca87b3-37c5-4140-bf29-a46b78ee403f
4
@Override public boolean move(int row, int col) { if (this.row == row && this.col != col) { this.col = col; return true; } else if (this.row != row && this.col == col) { this.row = row; return true; } return false; }
664f23bd-5767-4193-8408-d05f2d24f127
8
protected boolean validate() { m_file = new File(m_fileCombo.getText()); if (!m_file.exists() || !m_file.isFile()) { m_errorMsg = "File not found:\n" + m_fileCombo.getText(); return false; } if (!m_file.canRead()) { m_errorMsg = "Cannot read file:\n" + m_fileCombo.getText(); return false; } try { if (m_wholeFileButton.getSelection()) { // They want whole file. m_numLines = Integer.MAX_VALUE; } else { Integer i = new Integer(m_numLinesText.getText()); if (i.intValue() < 0) { throw new NumberFormatException(); } m_numLines = i.intValue(); } } catch (NumberFormatException e) { m_errorMsg = "Number of lines to show must be a positive integer."; return false; } try { Integer i = new Integer(m_intervalText.getText()); if (i.intValue() <= 0) { throw new NumberFormatException(); } m_interval = i.intValue(); } catch (NumberFormatException e) { m_errorMsg = "Refresh interval must be a positive integer."; return false; } return true; }
4ed823e0-412e-4fea-a2f7-dac6dc739405
2
public ArrayList<String> getList() { String line; try { while((line=reader.readLine())!=null) { list.add(line); } } catch (IOException e) { e.printStackTrace(); } return list; }
f7ea3b80-1c01-4f86-9ca1-f11261880824
5
public TreeNode<Integer> findNext(TreeNode<Integer> n) { if (n == null) return null; if (n.right != null) { TreeNode<Integer> p = n.right; while (p.left != null) { p = p.left; } return p; } else { TreeNode<Integer> p = n.parent; while (p.parent != null) { if (p == p.parent.left) return p; p = p.parent; } return null; } }
883bfa69-6fb1-4634-a447-566409746465
7
private String postResult(String URL){ StringBuffer sb= new StringBuffer(); try { String finalUrl=""; String[] parsedUrl=URL.split("\\?"); String params=URLEncoder.encode(parsedUrl[1], "UTF-8").replace("%3D","=").replace("%26","&"); URL url= new URL(parsedUrl[0]+"?"+params); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Accept", "application/json"); conn.setRequestProperty("Authorization","Bearer "+getAccessToken()); conn.setDoOutput(true); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(params); wr.flush(); wr.close(); boolean redirect = false; // normally, 3xx is redirect int status = conn.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) redirect = true; } if (redirect) { // get redirect url from "location" header field String newUrl = conn.getHeaderField("Location"); // open the new connnection again conn = (HttpURLConnection) new URL(newUrl).openConnection(); conn.setRequestProperty("Accept", "application/json"); conn.setRequestProperty("Authorization","Bearer "+getAccessToken()); } BufferedReader in = new BufferedReader( new InputStreamReader(conn.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { sb.append(inputLine); } in.close(); } catch (Exception e) { e.printStackTrace(); } return sb.toString(); }
eb96df40-013f-4f09-b1f9-8004150223ef
3
protected void tallennaActionPerformed() { String kurssinNimi = kurssinNimiField.getText().trim(); if (kurssinNimi.equals("")) { JOptionPane.showMessageDialog(this, "Kurssin nimi ei voi olla tyhjä!", "Virhe! Kurssilta puuttuu nimi.", JOptionPane.ERROR_MESSAGE); return; } if (kurssinNimi.length() > 50) { JOptionPane.showMessageDialog(this, "Kurssin nimi ei voi olla yli 50 merkkiä pitkä.", "Virhe", JOptionPane.ERROR_MESSAGE); return; } kurssi.setNimi(kurssinNimi); boolean onnistui = Database.updateKurssi(kurssi); if (onnistui) { JOptionPane.showMessageDialog(this, "Tietojen päivitys onnistui"); ikkuna.edellinenPaneeli(); } else { JOptionPane.showMessageDialog(this, "Tietojen päivitys epäonnistui"); } }
151048c8-3b4b-4e0f-9b8a-18c03c5b9319
5
public boolean epoch(Player p){ if (noimprove < noimprove_max){ noimprove++; //Update our average EPOCH statistics if (!new_model){ //Update the "noimprove" and DL_max/DL_min variables if (p.MODEL_allmoves-min_allmoves+EPSILON < 0){ min_allmoves = p.MODEL_allmoves; noimprove = 0; } if (p.MODEL_badmoves-min_badmoves+EPSILON < 0){ min_badmoves = p.MODEL_badmoves; noimprove = 0; } if (p.MODEL_wins-max_wins-EPSILON > 0){ max_wins = p.MODEL_wins; noimprove = 0; } } //If it is the start of an epoch, just set averages to current //In most situations, this should work fine, since accuracy is not at it's peak at the start else{ new_model = false; min_allmoves = p.MODEL_allmoves; min_badmoves = p.MODEL_badmoves; max_wins = p.MODEL_wins; } } return noimprove >= noimprove_max; }
c49d3e15-448d-4064-a280-4bb22b8feaaf
3
public static void main(String[] args){ //create instance of "Class" Class<?> c = null; try{ c=Class.forName("Foo"); }catch(Exception e){ e.printStackTrace(); } //create instance of "Foo" Foo f = null; try { f = (Foo) c.newInstance(); } catch (Exception e) { e.printStackTrace(); } f.print(); }
d7f9d52f-f4af-4347-a527-f42b7db81c29
5
public static int[][] openMatrixfile(String filename) throws FileNotFoundException { File inputFile = new File("src" + File.separator + "gol" + File.separator + filename); if(!inputFile.exists()){ return null; } Scanner lengthScanner = new Scanner(inputFile); int arrayLength =1; String linje = lengthScanner.nextLine(); for (int i=0; i<linje.length(); i++){ if (linje.charAt(i)==' '){ arrayLength++; } } lengthScanner.close(); Scanner fileScanner = new Scanner(inputFile); int[][] matrixContent = new int[arrayLength][arrayLength]; for (int i=0; i<arrayLength; i++){ for (int j=0; j<arrayLength; j++){ matrixContent[i][j]=fileScanner.nextInt(); } } fileScanner.close(); return matrixContent; }
0b29bc50-ad82-4a07-9ddf-0d81b82d0d88
8
@Override public Map<String, ?> resourceMap( DrawingContext context ) throws MojoExecutionException { for ( String range : StringUtils.split( ranges, ',' ) ) { try { String[] members = StringUtils.split( range, '-' ); if ( ArrayUtils.isEmpty( members ) || members.length > 2 ) { throw new MojoExecutionException( "Invalid range [" + range + "]." ); } if ( StringUtils.isNumeric( members[0] ) ) { if ( members.length == 1 ) { final int from = Integer.parseInt( members[0] ); return numericRangeResources( from, from, context ); } else { return numericRangeResources( Integer.parseInt( members[0] ), Integer.parseInt( members[1] ), context ); } } else { if ( members.length == 1 ) { final char from = members[0].charAt( 0 ); return charRangeResources( from, from, context ); } else { return charRangeResources( members[0].charAt( 0 ), members[1].charAt( 0 ), context ); } } } catch ( NumberFormatException e ) { throw new MojoExecutionException( "Unable to parse range " + range + "." ); } } return null; }
19f03597-59cb-411b-a1cb-88e1552525c3
5
public static void disposeImages() { // dispose loaded images { for (Image image : m_imageMap.values()) { image.dispose(); } m_imageMap.clear(); } // dispose decorated images for (int i = 0; i < m_decoratedImageMap.length; i++) { Map<Image, Map<Image, Image>> cornerDecoratedImageMap = m_decoratedImageMap[i]; if (cornerDecoratedImageMap != null) { for (Map<Image, Image> decoratedMap : cornerDecoratedImageMap.values()) { for (Image image : decoratedMap.values()) { image.dispose(); } decoratedMap.clear(); } cornerDecoratedImageMap.clear(); } } }
f4e6eab9-07f3-4d6b-8a77-0f6bf3cc6104
5
@Override public boolean equals(Object o) { if (o == null) return false; if (o == this) return true; if (o.getClass() != this.getClass()) return false; Vector3D other = (Vector3D)o; return x == other.x && y == other.y && z == other.z; }
b0572a6d-20ce-4932-b073-ab5324d3aa68
5
public int getSelection() { if(selectionOvalY == 94) return 1; else if(selectionOvalY == 114) return 2; else if(selectionOvalY == 134) return 3; else if(selectionOvalY == 154) return 4; else if(selectionOvalY == 174) return 5; return 0; }
08bd0788-7de1-405f-b204-b239748afee9
4
public void init(int mode, byte[] key, byte[] iv) throws Exception{ String pad="NoPadding"; byte[] tmp; if(iv.length>ivsize){ tmp=new byte[ivsize]; System.arraycopy(iv, 0, tmp, 0, tmp.length); iv=tmp; } if(key.length>bsize){ tmp=new byte[bsize]; System.arraycopy(key, 0, tmp, 0, tmp.length); key=tmp; } try{ SecretKeySpec keyspec=new SecretKeySpec(key, "AES"); cipher=javax.crypto.Cipher.getInstance("AES/CBC/"+pad); cipher.init((mode==ENCRYPT_MODE? javax.crypto.Cipher.ENCRYPT_MODE: javax.crypto.Cipher.DECRYPT_MODE), keyspec, new IvParameterSpec(iv)); } catch(Exception e){ cipher=null; throw e; } }
8253dd21-4952-458a-8929-e649ad8b3955
4
public final boolean matchesSub(Identifier ident, String name) { if (ident instanceof PackageIdentifier) return true; if (ident instanceof ClassIdentifier) { ClassIdentifier clazz = (ClassIdentifier) ident; return (clazz.isSerializable() && (!onlySUID || clazz.hasSUID())); } return false; }
a5e9c194-ea51-4817-9b6a-83563be59515
7
private void updateChangesFull(DnBData data, Node changes) throws ParseException { // changes = <MON_PROD_RS> for(int i=0;i<changes.getChildNodes().getLength();i++) // this should be length 1, should I check ? { Node changeNode = changes.getChildNodes().item(i); // this is <ArrayOfMON_PROD_RSItem>, if anyone's interested NodeList children = changeNode.getChildNodes(); for(int j=0;j<children.getLength();j++) { if(children.item(j).getNodeName()=="PRIM_SIC") data.setPrimarySicCode(SICCode.getSICFromCode(children.item(j).getTextContent())); else if(children.item(j).getNodeName()=="OUT_BUS_IND" && children.item(j).getTextContent().equalsIgnoreCase("y")) data.setOutOfBusiness(true); else if(children.item(j).getNodeName()=="CRCY_CD") data.setDefaultCurrency(Currency.getCurrencyFromCode(children.item(j).getTextContent())); else if(children.item(j).getNodeName()=="MAX_CR_CRCY_CD") data.setMaximumCreditRecommendationCurrency(Currency.getCurrencyFromCode(children.item(j).getTextContent())); } } }
59945ad7-1e29-4e0a-b651-1e8886a2ecc0
2
public boolean deplaceSoldat(Position pos, Soldat soldat){ Position posSoldat = soldat.getPos(); Element depart = getElement(posSoldat.getX(), posSoldat.getY()); Element arrivee = getElement(pos); if (!arrivee.estLibre() || soldat.aJoue()) // Si le terrain d'arrivee n'est pas libre ou si le soldat a déja employé son tour return(false); soldat.joueTour(); soldat.seDeplace(pos); depart.enleveSoldat(); cacher(depart.getPos(), soldat.getPortee()); arrivee.ajouteSoldat(soldat); decouvrir(arrivee.getPos(), soldat.getPortee()); return(true); }
bc67b461-c917-4b5c-a84f-3d5b946862cc
3
public void setMarkedAccessible(boolean markedAccessible) { if(this.e.getType() != BackgroundEnum.water || (!this.e.estLibre() && this.e.getSoldat() instanceof Heros)) this.markedAccessible = markedAccessible; }
ee8ead90-2b66-462f-975f-ba07b42c52e8
8
protected void resetQueue() { queueNode trc; queueNode trcPrev = null; //Delete expired nodes trc = jHead; while(trc!=null) { if(trc.getExpired()) { if(trcPrev == null) { jHead = trc.getNext(); if(jHead == null) jTail = null; } else if(trc.getNext()==null) { trcPrev.setNext(null); jTail = trcPrev; } else { trcPrev.setNext(trc.getNext()); } } trcPrev = trc; trc = trc.getNext(); } //Timer tick the whole list trc = jHead; while(trc!=null) { trc.tick(); trc = trc.getNext(); } //Transfer the old output queue to the holding queue if(pHead != null) { if(jHead == null) jHead = pHead; else jTail.setNext(pHead); jTail = pTail; } //Delete the old output queue pHead = null; pTail = null; }
cad0df94-48be-4180-9bdf-1b6bc79a6639
0
public KeyInfoType getKeyInfo() { return keyInfo; }
e14b070c-534d-4c4d-9cd2-9c4f5d9f403d
6
Space getForkSpace(Piece piece) { Space[] oppSpaceArray = getSpacesWithPiece(piece); Space[][] openSetsLast = getOpenSets(lastSpaceMoved); for (Space oppSpace : oppSpaceArray) { if (oppSpace != lastSpaceMoved) { Space[][] openOppSets = getOpenSets(oppSpace); for (Space[] oppSet : openOppSets) { for (Space[] setLast : openSetsLast) { Space space = getCommonSpace(setLast, oppSet); if (space != null && space.piece == N) return space; } } } } return null; }
f5374fd4-a522-4c86-9901-404193348491
4
@Override public void ParseIn(Connection Main, Server Environment) { int UserId = Main.DecodeInt(); Player Client = Environment.ClientManager.GetClient(UserId); if(Client == null) return; if((Client.Flags & Server.plrOnline) != Server.plrOnline) // Is Online? { return; } Room Room = Environment.RoomManager.GetRoom(Client.CurrentRoom); if (Room == null || !Room.CheckRights(Main.Data, true)) { return; } Room.RemoveUserFromRoom(Client.Connection, true, false, false); Client.Connection.SendNotif("Kicked!", 1); }
1be9a025-ccdb-403b-b135-1362be9aff08
1
@Override protected void done() { try{ out = get(); System.out.println("done!"); }catch(Exception e){ e.printStackTrace(); } }
0b17f95f-701b-4fcd-958f-dbc29cff668d
2
public boolean TryConnect(Configuration Config) { try { Class.forName("com.mysql.jdbc.Driver"); Connection = (new DatabasePool(Config)).GrabConnection(); Statement = Connection.createStatement(); return true; } catch (ClassNotFoundException CNF) { return false; } catch (SQLException SQL) { Grizzly.WriteOut(SQL.getMessage()); return false; } }
c37f6585-6a0d-4987-af58-4ceb15effc18
4
private static BigDecimal processCoinEntry(int[] coin_totals, BigDecimal balance, Coin inserted_coin) { // convert value to String String insert_Coin_str = inserted_coin.getValue().toString(); switch (insert_Coin_str) { case "1": addCoinToCategoryTotal(coin_totals, 0); balance = addInsertedCoinToBalance(inserted_coin.getValue(), balance); break; case "0.5": addCoinToCategoryTotal(coin_totals, 1); balance = addInsertedCoinToBalance(inserted_coin.getValue(), balance); break; case "0.2": addCoinToCategoryTotal(coin_totals, 2); balance = addInsertedCoinToBalance(inserted_coin.getValue(), balance); break; case "0.1": addCoinToCategoryTotal(coin_totals, 3); balance = addInsertedCoinToBalance(inserted_coin.getValue(), balance); break; } return balance; }
98579e14-9838-4408-8fa0-a4bb64a9e678
4
public static void main(String[] args) throws IOException { // On cherche le datastore enregistré précédemment. String workingDir = System.getProperty("user.dir"); try { BufferedReader br = new BufferedReader(new FileReader(workingDir + "/dataStoreLocation.loc")); String sCurrentLine; while ((sCurrentLine = br.readLine()) != null) { // Ceci est la localisation du DataStore // On essaie de le charger DataStore dataStore = null; try { FileInputStream inputFileStream = new FileInputStream(sCurrentLine); ObjectInputStream objectInputStream = new ObjectInputStream(inputFileStream); dataStore = (DataStore)objectInputStream.readObject(); objectInputStream.close(); inputFileStream.close(); } catch(ClassNotFoundException e) { JOptionPane.showMessageDialog(null, "Erreur. Le fichier de sauvegarde semble corrumpu. Veuillez réessayer ou recréer une nouvelle base de données.", "Fichier de sauvegarde corrompu", JOptionPane.ERROR_MESSAGE); new WelcomeFrame(); } catch(IOException i) { JOptionPane.showMessageDialog(null, "Le fichier de sauvegarde est introuvable ; merci de le localiser à nouveau.", "Fichier de sauvegarde introuvable", JOptionPane.ERROR_MESSAGE); new WelcomeFrame(); } //new MainFrame(dataStore); } } catch (FileNotFoundException e) { // On n'arrive pas à localiser le DataStore précédent, on affiche donc la welcome frame. new WelcomeFrame(); } }
ab48ef7b-04b7-473b-8c04-1969a40ca905
6
@EventHandler public void GiantHarm(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.getGiantConfig().getDouble("Giant.Harm.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if (plugin.getGiantConfig().getBoolean("Giant.Harm.Enabled", true) && damager instanceof Giant && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.HARM, plugin.getGiantConfig().getInt("Giant.Harm.Time"), plugin.getGiantConfig().getInt("Giant.Harm.Power"))); } }
90c6a91e-a858-4efd-958c-b385bd672d31
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; } }
12210e4a-59ac-46d3-8828-ae1b31ff809b
6
public static void backTrack(Graph_ST<Vertex_ST, Edge_ST> gST, String esWFF) { if (!gST.edgeSet().isEmpty()) { for (Edge_ST e : gST.edgeSet()) { // build up links between effect scenarios if (gST.getEdgeTarget(e).esWFF.equals(esWFF)) { a.e.println("Given an effect scenario, locate the task and effect scenario it most likely resulted from"); a.e.println("Given effect scenario: " + esWFF); a.e.println("Found accumulation: " + gST.getEdgeSource(e).esWFF + " --> " + gST.getEdgeTarget(e).esWFF); a.e.println(""); } } } if(_DEBUG){ //test for edges in the new built graph System.out.println("edges count " + gST.edgeSet().size()); for(Edge_ST e: gST.edgeSet()){ a.e.println(gST.getEdgeSource(e).esWFF + " to " + gST.getEdgeTarget(e).esWFF); // System.out.println(gST.getEdgeSource(e).esWFF); } //test for display of the vertices in the new Graph_ST System.out.println("\nThe number of nodes in Graph_ST: " + gST.vertexSet().size()); for(Vertex_ST vst: gST.vertexSet()){ a.e.println("\n---Begin a node in the graph---"); a.e.println("taskName: " + vst.taskName); a.e.println("immediate effect: " + vst.immWFF); a.e.println("cummulative effect: " + vst.esWFF); a.e.println("---End a node in the graph----\n"); } } }
22a1bc53-e5d3-4a74-ad0f-250f9d9c14eb
1
private void setUpVisibleRowOfCards(Card[][] cards) { /* * Stage 3 (4 Marks) */ for (Card tempCard : cards[2]) { tempCard.setIsFaceUp(true); } }
cb44c252-7da3-4044-b4b0-ac0eaff977a0
2
synchronized void getGuichet(Voyageurs voyageur) { while (nbGuichetDispo == 0) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } nbGuichetDispo--; voyageur.setAUnGuichet(true); }
a1693736-582f-406d-88ed-79f517df5799
5
@Override public void onUpdate(float delta) { percentComplete += 100 * delta / waitTime; if (percentComplete > 100) { percentComplete = 100; Activity.stopCurrentActivity(); try { level.load(null); } catch (IOException e) { e.printStackTrace(); } Material material = new Material(); material.setModelGenerator(new SimpleModelGenerator()); MaterialEntity entity = new MaterialEntity(); entity.setLevel(level); entity.setMaterial(material); Vec2[] verts = { new Vec2(-1, -1), new Vec2(1, -1), new Vec2(1, 1), new Vec2(-1, 1)}; entity.setShape(verts); BodyDef objectDef = new BodyDef(); objectDef.setType(BodyType.DYNAMIC); Body body = entity.setPhysicsObject(objectDef); for (Shape shape : shapeFromPolygon(verts)) { FixtureDef fixture = new FixtureDef(); fixture.setFriction(0.5f); fixture.setRestitution(0.15f); fixture.setDensity(1); fixture.setShape(shape); body.createFixture(fixture); } entity.setLayer(1, 1); Entity player = new Entity(); PlayerController controller = new PlatformerPlayerController(); controller.setPawn(player); level.players.add(controller); player.setLevel(level); Vec2[] playerVertices = { new Vec2(-0.35f, 0), new Vec2(0.35f, 0), new Vec2(0.35f, 1.8f), new Vec2(-0.35f, 1.8f)}; objectDef = new BodyDef(); objectDef.setType(BodyType.DYNAMIC); Body playerObject = player.setPhysicsObject(objectDef); for (Shape shape : shapeFromPolygon(playerVertices)) playerObject.createFixture(shape, 0); Mat4 transform = Mat4.identity(); Transform.setPosition(transform, new Vec3(-3, 0, 0)); player.setTransform(transform); //lambda expressions make this pretty ResourceManager.getResource( "Player.obj", loadedResource -> player.setModel((ModelLoader) loadedResource), ModelLoader.class); Entity button = new Entity(); button.setLevel(level); Vec2[] buttonVertices = { new Vec2(-0.5f, 0), new Vec2(0.5f, 0), new Vec2(0.5f, 0.175f), new Vec2(-0.5f, 0.175f)}; objectDef = new BodyDef(); objectDef.setType(BodyType.DYNAMIC); Body buttonObject = button.setPhysicsObject(objectDef); for (Shape shape : shapeFromPolygon(buttonVertices)) { FixtureDef fixture = new FixtureDef(); fixture.setFriction(10f); fixture.setDensity(1); fixture.setShape(shape); buttonObject.createFixture(fixture); } transform = Mat4.identity(); Transform.setPosition(transform, new Vec3(3, 0, 0)); button.setTransform(transform); ResourceManager.getResource( "button.obj", model -> button.setModel((ModelLoader) model), ModelLoader.class); ResourceManager.getResource( "button.png", image -> { button.getModel().texture = (Texture) image; button.getModel().setUserData(null); }, Texture.class); } loadingText.setText(String.format(loadingMessage, (int) percentComplete)); }
9c65d495-9b2e-4528-95a0-2e56c5905097
3
int computeColumnIntersect (int x, int startColumn) { CTableColumn[] orderedColumns = getOrderedColumns (); if (orderedColumns.length - 1 < startColumn) return -1; int rightX = orderedColumns [startColumn].getX (); for (int i = startColumn; i < orderedColumns.length; i++) { rightX += orderedColumns [i].width; if (x < rightX) return i; } return -1; }
692b1dfa-9341-45a7-a093-f531c89acd2e
9
private static Class[] getClasses(Object[] parameters){ Class[] classes = new Class[parameters.length]; for(int j = 0; j < parameters.length; j++){ classes[j] = parameters[j].getClass(); if(classes[j]==Integer.class)classes[j] = int.class; else if(classes[j]==Double.class)classes[j] = double.class; else if(classes[j]==Float.class)classes[j] = float.class; else if(classes[j]==Long.class)classes[j] = long.class; else if(classes[j]==Short.class)classes[j] = short.class; else if(classes[j]==Character.class)classes[j] = char.class; else if(classes[j]==Byte.class)classes[j] = byte.class; else if(classes[j]==Boolean.class)classes[j] = boolean.class; } return classes; }
39122922-27a2-492e-ba32-172721260b9e
4
@Override public int hashCode() { int result = (int) (orderId ^ (orderId >>> 32)); result = 31 * result + (driverId != null ? driverId.hashCode() : 0); result = 31 * result + (source != null ? source.hashCode() : 0); result = 31 * result + (target != null ? target.hashCode() : 0); result = 31 * result + (state != null ? state.hashCode() : 0); return result; }
5f307b8b-f48a-40e5-8d5d-8438bc8da0ef
8
@Override public boolean ActUpon() { if(getArguments()!= null){ if(getArguments()[0].equalsIgnoreCase("Stop")){ if(hasPermission("cloud.server.stop")){ getPlayer().sendMessage(ChatColor.RED+"Tried Stopping The Service!"); ClientHandler.getCH().Stop(); return true; }else{noPermissions(); return true;} } if(getArguments()[0].equalsIgnoreCase("Restart")){ if(hasPermission("cloud.server.restart")){ Bukkit.getServer().reload(); getPlayer().sendMessage(ChatColor.LIGHT_PURPLE+"Tried Restarting The Service!"); return true; }else{noPermissions(); return true;} } if(getArguments()[0].equalsIgnoreCase("Start")){ if(hasPermission("cloud.server.start")){ Bukkit.getServer().reload(); getPlayer().sendMessage(ChatColor.GREEN+"Tried Starting The Service!"); return true; }else{noPermissions();return true;} } if(getArguments()[0].equalsIgnoreCase("console")){ new CloudTerminal(getPlayer()); } } return true; }
c220975c-fab6-4e43-88c0-92a02db783fd
9
public static TimeValue parseTimeValue(String sValue, TimeValue defaultValue) { if (sValue == null) { return defaultValue; } long millis; if (sValue.endsWith("S")) { millis = Long.parseLong(sValue.substring(0, sValue.length() - 1)); } else if (sValue.endsWith("ms")) { millis = (long) (Double.parseDouble(sValue.substring(0, sValue.length() - "ms".length()))); } else if (sValue.endsWith("s")) { millis = (long) (Double.parseDouble(sValue.substring(0, sValue.length() - 1)) * 1000); } else if (sValue.endsWith("m")) { millis = (long) (Double.parseDouble(sValue.substring(0, sValue.length() - 1)) * 60 * 1000); } else if (sValue.endsWith("H") || sValue.endsWith("h")) { millis = (long) (Double.parseDouble(sValue.substring(0, sValue.length() - 1)) * 60 * 60 * 1000); } else if (sValue.endsWith("d")) { millis = (long) (Double.parseDouble(sValue.substring(0, sValue.length() - 1)) * 24 * 60 * 60 * 1000); } else if (sValue.endsWith("w")) { millis = (long) (Double.parseDouble(sValue.substring(0, sValue.length() - 1)) * 7 * 24 * 60 * 60 * 1000); } else { millis = Long.parseLong(sValue); } return new TimeValue(millis, TimeUnit.MILLISECONDS); }
acde5fdc-bba9-4adf-9c84-f1dcb9b32a1c
4
public void stopMoving(Direction dir) { boolean foundDir = false; for(int i = 0; i < queuedMoveDirectionPreferences.length - 1; i++) { if(!foundDir && queuedMoveDirectionPreferences[i] == dir) foundDir = true; if(foundDir) queuedMoveDirectionPreferences[i] = queuedMoveDirectionPreferences[i + 1]; } queuedMoveDirectionPreferences[queuedMoveDirectionPreferences.length - 1] = null; }
264a012c-491f-496d-8512-495eeda5b89e
7
public void gameSolo() throws IOException{ // Changement du titre this.setTitle("Vous jouez à Tetra Word en Solo"); this.setPreferredSize(new Dimension(1024,768)); // Arrière plan JPanel panel = setBackgroundImage(this, new File("src/fr/univ/graphicinterface/game.jpg")); panel.setMaximumSize(new Dimension(1024, 768)); panel.setMinimumSize(new Dimension(600, 400)); panel.setPreferredSize(new Dimension(1024, 768)); // Fonts Font copperplate = new Font("Copperplate Gothic Bold",0,22); try{ File fis = new File("data/COPRGTB.TTF"); copperplate = Font.createFont(Font.TRUETYPE_FONT, fis); copperplate = copperplate.deriveFont((float)22.0); } catch (Exception e) { System.out.println("Police non chargée"); } Font bigCentury = new Font("Century Gothic",0,26); Font smallCentury = new Font("Century Gothic",0,18); Composants=new HashMap<String,JComponent>(); // Boutons JWelcomeButton buttonRetour = new JWelcomeButton("Retour"); buttonRetour.setFont(bigCentury); buttonRetour.setForeground(Color.WHITE); buttonRetour.setFocusPainted(false); buttonRetour.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent evt) { try { retourActionPerformed(evt); } catch (IOException ex) { Logger.getLogger(MainGame.class.getName()).log(Level.SEVERE, null, ex); } } }); JWelcomeButton buttonRegles = new JWelcomeButton("?"); buttonRegles.setFont(smallCentury); buttonRegles.setForeground(Color.WHITE); buttonRegles.setFocusPainted(false); buttonRegles.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent evt) { try { firstReglesActionPerformed(evt); } catch (IOException ex) { Logger.getLogger(MainGame.class.getName()).log(Level.SEVERE, null, ex); } } }); JButton buttonWorddle = new JButton(""); if(buttonWorddle==null)exit(1); buttonWorddle.setFocusPainted(false); Composants.put("Worddle",buttonWorddle); JWelcomeButton buttonNiveau = new JWelcomeButton(""); if(buttonNiveau==null)exit(1); buttonNiveau.setFont(bigCentury); buttonNiveau.setForeground(Color.WHITE); buttonNiveau.setFocusPainted(false); Composants.put("Niveau",buttonNiveau); JWelcomeButton buttonScore = new JWelcomeButton(""); if(buttonScore==null)exit(1); buttonScore.setFont(bigCentury); buttonScore.setForeground(Color.WHITE); buttonScore.setFocusPainted(false); Composants.put("Score",buttonScore); JWelcomeButton buttonSaisie = new JWelcomeButton(""); buttonSaisie.setFont(bigCentury); buttonSaisie.setForeground(Color.WHITE); buttonSaisie.setFocusPainted(false); Composants.put("Saisie",buttonSaisie); JLabel labelTime = new JLabel(); labelTime.setFont(copperplate); labelTime.setForeground(new Color(33,91,201)); labelTime.setText("Temps"); Composants.put("Temps",labelTime); JWelcomeButton buttonSauvegarde = new JWelcomeButton("Sauvegarder la partie"); buttonSauvegarde.setFont(smallCentury); buttonSauvegarde.setForeground(Color.WHITE); buttonSauvegarde.setFocusPainted(false); buttonSauvegarde.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent evt) { try { sauvegardeActionPerformed(evt); } catch (IOException ex) { Logger.getLogger(MainGame.class.getName()).log(Level.SEVERE, null, ex); } } }); // Création du jeu Games=new Vector<Game>(); Game game=new Game(Composants,false,options); game.start(); Games.add(game); // Grille de Jeu JPanel grille=Games.get(0).getGridInterface(); // Prochaine piece JPanel buttonPiece = Games.get(0).getNextInterface(); // Labels JLabel labelWorddle = new JLabel(); labelWorddle.setFont(copperplate); labelWorddle.setForeground(new Color(33,91,201)); labelWorddle.setText("Worddle"); JLabel labelNiveau = new JLabel(); labelNiveau.setFont(copperplate); labelNiveau.setForeground(new Color(33,91,201)); labelNiveau.setText("Niveau"); JLabel labelScore = new JLabel(); labelScore.setFont(copperplate); labelScore.setForeground(new Color(33,91,201)); labelScore.setText("Score"); JLabel labelSaisie = new JLabel(); labelSaisie.setFont(copperplate); labelSaisie.setForeground(new Color(33,91,201)); labelSaisie.setText("Saisie"); GroupLayout jPanel1Layout = new GroupLayout(panel); panel.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(91, 91, 91) .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(grille, GroupLayout.PREFERRED_SIZE, 349, GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 114, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.TRAILING, false) .addComponent(labelSaisie, GroupLayout.Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(labelScore, GroupLayout.Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(labelNiveau, GroupLayout.Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING, false) .addComponent(buttonNiveau, GroupLayout.DEFAULT_SIZE, 160, Short.MAX_VALUE) .addComponent(buttonScore, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(buttonSaisie, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(19, 19, 19) .addComponent(labelTime, GroupLayout.PREFERRED_SIZE, 240, GroupLayout.PREFERRED_SIZE))) .addGap(162, 162, 162)) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(140, 140, 140) .addComponent(buttonSauvegarde, GroupLayout.PREFERRED_SIZE, 258, GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(160, 160, 160) .addComponent(buttonPiece, GroupLayout.PREFERRED_SIZE, 180, GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(152, 152, 152) .addComponent(labelWorddle, GroupLayout.PREFERRED_SIZE, 160, GroupLayout.PREFERRED_SIZE) .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(buttonWorddle, GroupLayout.PREFERRED_SIZE, 35, GroupLayout.PREFERRED_SIZE))) .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(buttonRetour, GroupLayout.PREFERRED_SIZE, 130, GroupLayout.PREFERRED_SIZE) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(buttonRegles, GroupLayout.PREFERRED_SIZE, 50, GroupLayout.PREFERRED_SIZE) .addGap(63, 63, 63)))) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(28, 28, 28) .addComponent(buttonRetour, GroupLayout.PREFERRED_SIZE, 35, GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(53, 53, 53) .addComponent(labelTime, GroupLayout.PREFERRED_SIZE, 35, GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(20, 20, 20) .addComponent(buttonRegles, GroupLayout.PREFERRED_SIZE, 50, GroupLayout.PREFERRED_SIZE))) .addGap(23, 23, 23) .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(buttonPiece, GroupLayout.PREFERRED_SIZE, 180, GroupLayout.PREFERRED_SIZE) .addGap(49, 49, 49) .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING, false) .addComponent(labelWorddle, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(buttonWorddle, GroupLayout.PREFERRED_SIZE, 35, GroupLayout.PREFERRED_SIZE)) .addGap(50, 50, 50) .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(labelNiveau, GroupLayout.PREFERRED_SIZE, 35, GroupLayout.PREFERRED_SIZE) .addComponent(buttonNiveau, GroupLayout.PREFERRED_SIZE, 35, GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(labelScore, GroupLayout.PREFERRED_SIZE, 35, GroupLayout.PREFERRED_SIZE) .addComponent(buttonScore, GroupLayout.PREFERRED_SIZE, 35, GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(labelSaisie, GroupLayout.PREFERRED_SIZE, 35, GroupLayout.PREFERRED_SIZE) .addComponent(buttonSaisie, GroupLayout.PREFERRED_SIZE, 35, GroupLayout.PREFERRED_SIZE)) .addGap(50, 50, 50) .addComponent(buttonSauvegarde, GroupLayout.PREFERRED_SIZE, 40, GroupLayout.PREFERRED_SIZE)) .addComponent(grille, GroupLayout.PREFERRED_SIZE, 590, GroupLayout.PREFERRED_SIZE)) .addContainerGap(67, Short.MAX_VALUE)) ); this.pack(); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.requestFocusInWindow(); }
faecbfff-6b7a-47b5-b83d-90e85db23dc9
2
@Override public int play(){ //If we've gone so many moves without progress, do a random move //This will hopefully prevent deadlock over a zugzwang situation Model m = (++turns % no_progress) == 0 ? random : learner; boolean fromDiscard = m.decideDraw(turns); int drawn = game.deck.draw(fromDiscard), pos = m.decidePlay(turns, drawn, fromDiscard); return pos == -1 ? drawn : rack.swap(drawn, pos, fromDiscard); }
278cc780-0083-4aed-b7cf-73e310094952
7
public EvaluationResult evaluate(List inputs, EvaluationCtx context) { // Evaluate the arguments AttributeValue [] argValues = new AttributeValue[inputs.size()]; EvaluationResult evalResult = evalArgs(inputs, context, argValues); if (evalResult != null) return evalResult; // setup the two bags we'll be using BagAttribute [] bags = new BagAttribute[2]; bags[0] = (BagAttribute)(argValues[0]); bags[1] = (BagAttribute)(argValues[1]); AttributeValue result = null; Set set = new HashSet(); switch(getFunctionId()) { // *-intersection takes two bags of the same type and returns // a bag of that type case ID_BASE_INTERSECTION: // create a bag with the common elements of both inputs, removing // all duplicate values Iterator it = bags[0].iterator(); // find all the things in bags[0] that are also in bags[1] while (it.hasNext()) { AttributeValue value = (AttributeValue)(it.next()); if (bags[1].contains(value)) { // sets won't allow duplicates, so this addition is ok set.add(value); } } result = new BagAttribute(bags[0].getType(), set); break; // *-union takes two bags of the same type and returns a bag of // that type case ID_BASE_UNION: // create a bag with all the elements from both inputs, removing // all duplicate values Iterator it0 = bags[0].iterator(); while (it0.hasNext()) { // first off, add all elements from the first bag...the set // will ignore all duplicates set.add(it0.next()); } Iterator it1 = bags[1].iterator(); while (it1.hasNext()) { // now add all the elements from the second bag...again, all // duplicates will be ignored by the set set.add(it1.next()); } result = new BagAttribute(bags[0].getType(), set); break; } return new EvaluationResult(result); }
acb25c2c-d4c0-4ab6-8539-653647801e60
8
public List<Cliente> buscar(Cliente filtro) { try { String sql = "select * from pessoa p join cliente c on p.IdPessoa = c.IdPessoa where ativo = 1 "; String where = ""; if (filtro.getNome().length() > 0) { if (where.length() > 0) { where = where + " and "; } where = "and nome like '%" + filtro.getNome() + "%'"; } if (filtro.getCodigo() > 0) { if (where.length() > 0) { where = where + " and "; } where = where + " Idpessoa = " + filtro.getCodigo(); } if (where.length() > 0) { sql = sql + where; } Statement comando = bd.getConexao().createStatement(); ResultSet resultado = comando.executeQuery(sql); // Cria uma lista de produtos vazia List<Cliente> clientes = new LinkedList<>(); while (resultado.next()) { // Inicializa um objeto de produto vazio Cliente tmp = new Cliente(); // Pega os valores do retorno da consulta e coloca no objeto try { tmp.setCodigo(resultado.getInt("IdPessoa")); tmp.setNome(resultado.getString("Nome")); tmp.setCPF(resultado.getString("CPF")); tmp.setRG(resultado.getString("RG")); tmp.setDataNascimento(resultado.getDate("DataNascimento")); //tmp.setCnpj(resultado.getString("CNPJ")); tmp.setAtivo(resultado.getInt("Ativo")); tmp.setFisicaouJuridica(resultado.getInt("FisicaouJuridica")); } catch (Exception ex) { Logger.getLogger(ClienteDAO.class.getName()).log(Level.SEVERE, null, ex); } // Pega o objeto e coloca na lista clientes.add(tmp); } return clientes; } catch (SQLException ex) { Logger.getLogger(ClienteDAO.class.getName()).log(Level.SEVERE, null, ex); return null; } }
472a6cc9-95ea-42d1-8be4-a84db41e70de
1
public boolean noChildren() { if(propChildren == null) return true; else return false; }
38d36c2f-8c5e-48cb-9e77-3d71322b6c72
9
public static void main(String[] args) throws InterruptedException { Thread.currentThread().sleep(20000l); int row; int col; ArrayList<String> colNameList = new ArrayList(); Object[][] data; String sql; String[] colName; // File f=new File("D:\\sqlite\\logs\\log.out"); BufferedReader br =null; String reqString = ""; HashMap<Integer, HashMap<String, String>> map = new HashMap(); String datePattern="\\d\\d\\d\\d-\\d\\d-\\d\\d \\d\\d:\\d\\d:\\d\\d,\\d\\d\\d"; String date = ""; int i = 0; // String datePattern = args[0]; String fileName="C:\\sqlite\\log1.out"; try { System.out.println("Log file is :: "+fileName); br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName))); String line=""; while( (line=br.readLine())!=null ){ if (line.indexOf("error")>0) { System.out.println(line); reqString = line; // System.out.println("adding "+reqString); // System.out.println(datePattern); Pattern p = Pattern.compile(datePattern); Matcher m = p.matcher(reqString); date = ""; // System.out.println("datePattern is " + m.pattern()); while (m.find()) { System.out.println(m.start() + ">>" + m.group()); date = m.group(); break; } if (date == "") { continue; } i++; // if(i>100)break; HashMap temp = new HashMap(); // System.out.println("putting :: "+date+" :: & :: "+reqString); temp.put(date, reqString); map.put(i, temp); // System.out.println(map.get(i)); } } br.close(); } catch (Exception e) { e.printStackTrace(); } row = map.keySet().size(); // System.out.println("rows " + row); colName = new String[]{"date", "level", "message"}; col = colName.length; data = new Object[row][col]; int j = 0, k = 0; Object b; for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) { Integer type = (Integer) iterator.next(); date = map.get(type).keySet().toArray()[0].toString(); // reqString=map.get(type).get(map.get(type).keySet().toArray()[0]); for (int l = 1; l <= col; l++) { k = l; k--; if (k == 0) { data[j][k] = date; // System.out.println(date); } else if (k == 1) { data[j][k] = "ERROR"; } else { data[j][k] = reqString; // System.out.println(reqString); } // System.out.println(j+" "+k+" "+b); } j++; } }
b9116c96-7dda-49b2-9b34-92d6f3e442a2
1
public boolean receptionConfirmation() throws IOException { boolean conf = input.readBoolean(); String msg = input.readUTF(); if (conf) System.out.println("OK : "+msg); else System.err.println("KO : "+msg); return conf; }
f4be6e8e-f378-47eb-97c5-33f6141bdd33
4
private void configureDetails() { if (details != null) { details.setVisible(false); } if (details != null) { details.addEventFilter(EventType.ROOT, new EventHandler<Event>() { @Override public void handle(Event event) { if (event.getEventType() == MouseEvent.MOUSE_RELEASED || event.getEventType() == KeyEvent.KEY_RELEASED) { updateSaveIssueButtonState(); } } }); } }
9ce6c289-929e-42be-9945-8f643e11e7a8
5
private static final void method702(int i) { Widget class46 = AbstractFontRasterizer.getWidget(i); if (class46 != null) { int i_3_ = i >>> 16; Widget[] class46s = Class369_Sub2.aClass46ArrayArray8584[i_3_]; if (class46s == null) { Widget[] class46s_4_ = Class348_Sub40_Sub33.aClass46ArrayArray9427[i_3_]; int i_5_ = class46s_4_.length; class46s = Class369_Sub2.aClass46ArrayArray8584[i_3_] = new Widget[i_5_]; ArrayUtils.arrayCopy(class46s_4_, 0, class46s, 0, class46s_4_.length); } int i_6_; for (i_6_ = 0; i_6_ < class46s.length; i_6_++) { if (class46s[i_6_] == class46) break; } if (i_6_ < class46s.length) { ArrayUtils.arrayCopy(class46s, 0, class46s, 1, i_6_); class46s[0] = class46; } } }
79e98b3d-9f89-4a71-8d73-e6b110465c7b
7
public static void main(String[] args){ Scanner cin = new Scanner(System.in); str = cin.next(); int limit = cin.nextInt(); int steps; for (steps = 0; steps < limit; steps ++){ //check if palindromic,break boolean flag = true; for (int j = 0, k = str.length() - 1; j < k; j ++, k --) if (str.charAt(j) != str.charAt(k)){ flag = false; break; } if (flag) break; //str --> new str StringBuilder sb = new StringBuilder(); int carry = 0; int length = str.length(); for (int i = length - 1; i >= 0; i --){ int sum = getInt(i)+getInt(length - i -1) + carry; carry = sum/10; sb.append(sum%10); } if(carry != 0) sb.append(carry); str = sb.toString(); } //output str and i for (int i = str.length() - 1; i >= 0; i --) System.out.print(str.charAt(i)); System.out.println(); System.out.println(steps); }
21c3317d-2d4f-42b5-b8e8-5fb78815a799
1
private void callUserAction() { try { callAction(UserAction.getByActionCode(readUserActionCode())); } catch (UnsupportedOperationException | InputMismatchException e) { String excMsg = "entered an incorrect value!"; view.printExceptionMsg(excMsg); logger.warn("User {}", excMsg, e); callUserAction(); } }