method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
b9205a14-8c54-4c66-b994-d7b007598203
8
public void run() { if (action == SAVE) { try { PrintStream out = new PrintStream(new GZIPOutputStream( new FileOutputStream(file)), false, Constantes.ASI_ENCODING); out.println("<?xml version=\"1.0\" encoding=\"" + Constantes.ASI_ENCODING + "\"?>"); out.println("<analyse>"); out.println("<about>"); out.println("<release release=\"" + Constantes.RELEASE + "\" />"); out.println("<company>"); out.println ("<name>"+ Constantes.COMPANY + "</name>" ) ; out.println ("<email>"+ Constantes.CONTACT_EMAIL + "</email>" ) ; out.println("</company>"); out.println("</about>"); AnalyseModule mod; FilterModule fm; Iterator<Entry<String, AnalyseModule>> e = Main.modules.entrySet().iterator(); while ( e.hasNext() ) { mod = e.next().getValue(); out.println("<module id=\"" + mod.getID().toLowerCase() + "\">"); fm = mod.getFiltre(ID); if (fm != null && fm.canSave()) ((SaveModule) fm).save(out); out.println("</module>"); } out.println("</analyse>"); out.flush(); out.close(); } catch (IOException e) { GUIUtilities.error("Impossible de sauvegarder le fichier " + file.getName()); } } else //if (action == OPEN) { try { InputStream inStream = new GZIPInputStream(new FileInputStream(file)); BufferedReader in = new BufferedReader(new InputStreamReader(inStream, Constantes.ASI_ENCODING)); ASIHandler handler = new ASIHandler(); XmlParser parser = new XmlParser(); parser.setHandler(handler); try { parser.parse(null, null, in); } catch (XmlException e) { System.err.println(e); } catch (Exception e) { // Should NEVER happend ! e.printStackTrace(); } in.close(); } catch (IOException e) { GUIUtilities.error("Impossible d'ouvrir le fichier \"" + file.getName() + "\""); } } }
616eb456-9803-48ae-a0a6-6eef1d39504f
3
public static synchronized Socket opensocket(int i) throws IOException { for (Signlink.socketreq = i; Signlink.socketreq != 0;) { try { Thread.sleep(50L); } catch (Exception exception) { } } if (Signlink.socket == null) { throw new IOException("could not open socket"); } else { return Signlink.socket; } }
f6612b3a-3e4d-4c0c-ab71-d027fe0090d9
0
public BarServiceImpl(PersistenceService<BeerEntity> persistenceService) { this.persistenceService = persistenceService; }
c3c1218a-d858-42fc-bbaa-8efa9a34c623
6
@Override protected boolean puedoUsarEsteConstructor(Constructor<?> constructor) { Class<?>[] parameterTypes = constructor.getParameterTypes(); boolean hasSameParams = false; int i = 0; for (Class<?> paramClass : parameterTypes) { hasSameParams = hasSameParams || ( this.params[i].getClazz().equals(paramClass) ); if (!hasSameParams) break; i++; } return hasSameParams; }
a69e798f-86ae-452d-8189-d5b7656abf6f
9
public boolean searchMatrix(int[][] matrix, int target) { int rows = matrix.length; if (rows == 0) return false; int columns = matrix[0].length; if (columns == 0) return false; int row = -1; for (int i = 0; i < rows; i ++) if (matrix[i][0] == target) return true; else if (matrix[i][0] > target) { row = i; break; } if (row == 0) return false; else if (row == -1) row = rows; for (int i = 0; i < columns; i ++) { if (matrix[row - 1][i] == target) return true; } return false; }
d913caff-acc0-49c6-8213-c5dee99c9b23
5
private void actualizarLabelIva(){ r_con.Connection(); ResultSet rs=r_con.Consultar("select * from tasas_iva where '"+fecha_factura.getText()+"' between tasa_desde and tasa_hasta"); try{ while(rs.next()){ if(rs.getString("tasa_tipo").equals("01")){ jLabel3.setText("IVA "+rs.getFloat("tasa_tasa")+"%"); } if(rs.getString("tasa_tipo").equals("02")){ jLabel4.setText("IVA "+rs.getFloat("tasa_tasa")+"%"); } if(rs.getString("tasa_tipo").equals("03")){ jLabel5.setText("IVA "+rs.getFloat("tasa_tasa")+"%"); } } } catch(Exception e){} finally{r_con.cierraConexion();} }
b170563a-a829-403f-851d-89ee116206cd
8
private static void submit(String[] args) throws IOException, ClassNotFoundException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException { // TODO Auto-generated method stub //hadoop mapred submit jar /usr/foo.jar package.ClassName inputPath outputPath String type = args[3]; String jarPath = args[4]; String mainClassName = args[5]; String intputPath = args[6]; String outoutPath = args[7]; JobClient.jarPath = jarPath; JarFile jarFile = new JarFile(jarPath); Enumeration<JarEntry> e = jarFile.entries(); URL[] urls = { new URL("jar:file:" + jarPath +"!/") }; ClassLoader cl = URLClassLoader.newInstance(urls); Class<?> mainClass = null; while (e.hasMoreElements()) { JarEntry je = e.nextElement(); if(je.isDirectory() || !je.getName().endsWith(".class")){ continue; } String className = je.getName().substring(0, je.getName().length() - 6); className = className.replace('/', '.'); if (className.equals(mainClassName)) { mainClass = cl.loadClass(className); } } Method m = mainClass.getMethod("main", new Class[] {String[].class}); m.setAccessible(true); int mods = m.getModifiers(); if (m.getReturnType() != void.class || !Modifier.isStatic(mods) || !Modifier.isPublic(mods)) { throw new NoSuchMethodException("main"); } String[] newArgs = new String[args.length - 6]; newArgs = Arrays.copyOfRange(args, 6, args.length); System.out.println("DEBUG Utility.subit(): newArgs = " + Arrays.toString(newArgs)); m.invoke(null, new Object[] { newArgs }); }
c8254d67-79d0-4a8e-83fe-0db67501d7e8
4
private void updateRefreshTime(final String inBase64Key) { try { /** * Might this client no longer exist by the time this update is attempted? Sure, but that's okay. Aside from a * scary error message, no harm done. */ mLazyDBQueue.put(new Runnable() { public void run() { (new SQLStatementProcessor<Void>("UPDATE registered_keys SET last_refresh_timestamp = CURRENT_TIMESTAMP WHERE public_key = ?") { public Void process( PreparedStatement s ) throws SQLException { s.setString(1, inBase64Key); if( s.executeUpdate() != 1 ) { logger.warning("Couldn't update last_refresh_timestamp for: " + inBase64Key + " not (or no longer) in DB"); } else { KeyRegistrationRecord rec = key_to_record.get(inBase64Key); if( rec == null ) { logger.warning("Inconsistent DB/cache state in updateRefreshTime() for key: " + inBase64Key); } else { rec.setLastRefresh( new Date() ); } } return null; } }).doit(); } }); KeyRegistrationRecord rec = key_to_record.get(inBase64Key); if( rec == null ) { logger.warning("Got update refresh time for a key that wasn't in soft state: " + inBase64Key); } else { rec.setLastRefresh(new java.util.Date()); } } catch( InterruptedException e ) { e.printStackTrace(); logger.warning(e.toString()); } }
bb5f3ad4-66be-4890-b73a-4fbdbbf1dda5
4
public void setChildComparator(Comparator<Entry> childComparator) { if (childComparator == null) { throw new IllegalArgumentException("childComparator cannot be null"); } this.childComparator = childComparator; if (this.children != null) { //TODO loop detection? for (Map.Entry<Long, Entry> entry : this.children.entrySet()) { final Entry child = entry.getValue(); if (child instanceof Folder) { ((Folder)child).setChildComparator(childComparator); } } } }
964aa144-a168-4f16-8ba2-54a73a9907a8
7
private LowLevelTextObject getLowLevelTextObjectAt(LowLevelTextContainer parent, int x, int y, LowLevelTextType type) { if (parent == null) return null; //Iterate over all child text objects for (int i=0; i<parent.getTextObjectCount(); i++) { LowLevelTextObject obj = parent.getTextObject(i); //Is the child of the type we are looking for? if (type.equals(obj.getType())) { //Check if the given point is inside the childs polygon Polygon polygon = ((GeometricObject)obj).getCoords(); if (polygon != null && polygon.isPointInside(x, y)) { return obj; } } //Is the child a text object container itself? else if (obj instanceof LowLevelTextContainer){ //Recursion obj = getLowLevelTextObjectAt((LowLevelTextContainer)obj, x, y, type); if (obj != null) return obj; } else //If the child is neither of the type we're looking for nor a container, we can leave the recursion now. return null; } return null; }
3d6ff2c9-61d9-4e07-a2ed-f1aa4f79c676
7
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Token token = (Token) o; if (!begin.equals(token.begin)) return false; if (!end.equals(token.end)) return false; if (type != token.type) return false; if (!value.equals(token.value)) return false; return true; }
debd39a3-c7c4-4304-ab41-b6de2619c9d8
0
public Student(final String number) { this.number = number; scores = new ArrayList<String>(); }
a6cb5257-4a8e-4afb-8ddd-e0571194a204
0
public double getPaybackMoney(){ return this.paybackMoney; }
ab7cbfe8-0323-4e0a-a614-57281a6341e6
6
public ItemStack transferStackInSlot(int par1) { ItemStack var2 = null; Slot var3 = (Slot)this.inventorySlots.get(par1); if (var3 != null && var3.getHasStack()) { ItemStack var4 = var3.getStack(); var2 = var4.copy(); if (par1 != 0) { return null; } if (!this.mergeItemStack(var4, 1, 37, true)) { return null; } if (var4.stackSize == 0) { var3.putStack((ItemStack)null); } else { var3.onSlotChanged(); } if (var4.stackSize == var2.stackSize) { return null; } var3.onPickupFromSlot(var4); } return var2; }
448a6579-7d58-4717-8a03-48aaba3aad07
7
public static UndirectedGraph<Vertex> createGraph(int n, double p) { int rows = (int) Math.sqrt(n); int cols = (int) Math.ceil((double) n / rows); UndirectedGraph<Vertex> g = new UndirectedGraph<Vertex>(rows, cols); Random rands = new Random(); for(int i = 0; i < n; i++) { g.addVertex(new Vertex(i / cols, i % cols)); } int[] offs = { 1, cols - 1, cols, cols + 1 }; for(int u = 0; u < n; u++) { for(int j = 0; j < offs.length; j++) { int v = u + offs[j]; if(v >= 0 && v < n && rands.nextDouble() < p) { Vertex uu = g.getVertex(u); Vertex vv = g.getVertex(v); if(Math.abs(uu.getColumn() - vv.getColumn()) <= 1) { g.addEdge(uu, vv); } } } } return g; }
7bf547d0-abb8-478b-a4db-1d1c5604d29d
2
@Override public void keyReleased(KeyEvent e) { if (e.getKeyChar() == 's') { plateau.resetVitesse(); } if (e.getKeyChar() == '2') { plateau.resetVitesse(); } }
198ac512-261a-43c1-8239-dbe407d28a22
5
private boolean findPictures(String address, boolean UserInput) { //open url, establish connection and read content try { URL url = new URL(address); URLConnection connection = url.openConnection(); String line; StringBuilder builder = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((line = reader.readLine()) != null) { builder.append(line); } reader.close(); // construct a JSONObject from page content JSONObject json = new JSONObject(builder.toString()); if (json.getJSONObject("responseData").getJSONArray("results").length() == 0) { return false; } else { int randNumb = (int) (Math.random() * 6); //chooses random picture of first 6 url returned String imageUrl = json.getJSONObject("responseData").getJSONArray("results").getJSONObject(randNumb).getString("unescapedUrl"); //get the url-property of a json object helper.add(imageUrl); // add founded picture to helper list if (UserInput == true) { return true; } else { return false; } } } catch (UnknownHostException e) { // if no internet connection System.out.println("no internet connection"); return false; } catch (Exception e) { // catch all other exceptions System.out.println("something went wrong in the google search api"); return false; } }
dc0ec9a9-9166-4839-8325-dbdd325b7f93
5
public static Color getRiverColor (int wwTopLevel) { if (wwTopLevel == 2) return Color.decode("0xC0FFC0"); if (wwTopLevel == 3) return Color.decode("0x80FF80"); if (wwTopLevel == 4) return Color.decode("0xFFFF60"); if (wwTopLevel == 5) return Color.decode("0xFFA0A0"); if (wwTopLevel == 6) return Color.decode("0xFF8080"); return Color.WHITE; }
0d2cfd92-d171-4dd0-9d4b-b9b6d0382371
7
public static void optimizeSeparators(JPopupMenu menu) { boolean lastSeparator = true; for (int i = 0; i < menu.getComponentCount();) { if (menu.getComponent(i).isVisible() && menu.getComponent(i) instanceof JMenu) optimizeSeparators(((JMenu) menu.getComponent(i)).getPopupMenu()); boolean separator = menu.getComponent(i) instanceof JPopupMenu.Separator; if (lastSeparator && separator) menu.remove(i); else i++; lastSeparator = separator; } if (menu.getComponentCount() > 0 && menu.getComponent(menu.getComponentCount() - 1) instanceof JPopupMenu.Separator) menu.remove(menu.getComponentCount() - 1); }
8ed323be-dcb7-4084-9622-e7fde668f240
5
public Deck() { this.cards = new ArrayList<Card>(); String[] familyNames = { CardFamily.kEspadasFamily, CardFamily.kBastosFamily, CardFamily.kCopasFamily, CardFamily.kOrosFamily }; for ( String aFamily : familyNames ) { for ( int i = 1; i < 13; i++ ) { if ( i > 7 && i < 10 ) i = 10; try { this.cards.add( new Card( i, aFamily ) ); } catch( Exception e ) { System.err.println( e.getMessage() ); System.exit( -1 ); } } } this.cards = unsort( this.cards ); }
7c9f7791-9ee5-4aad-9679-29b169d2996c
5
public void movePlayer(){ int direction = 0; if(left &&right){ direction=0; } else{ direction = mover.movePlayer(player, imageList, left, right, getBounds().width); } if (direction ==0 ){ playerMovePosX = false; playerMoveNegX = false; } if (direction <0){ playerMoveNegX = true; playerMovePosX = false; } if (direction >0){ playerMoveNegX = false; playerMovePosX = true; } }
0cb0af15-5b6d-4aa0-ab7f-10037ee67d64
7
public void addToComponent(Canvas component) { if (freeColClient.getGame() == null || freeColClient.getGame().getMap() == null) { return; } // // Relocate GUI Objects // infoPanel.setLocation(component.getWidth() - infoPanel.getWidth(), component.getHeight() - infoPanel.getHeight()); miniMapPanel.setLocation(0, component.getHeight() - miniMapPanel.getHeight()); compassRose.setLocation(component.getWidth() - compassRose.getWidth() - 20, 20); if (!unitButtons.isEmpty()) { final int WIDTH = this.unitButtons.get(0).getWidth(); final int SPACE = 5; int length = unitButtons.size(); int x = miniMapPanel.getWidth() + 1 + ((infoPanel.getX() - miniMapPanel.getWidth() - length * WIDTH - (length - 1) * SPACE - WIDTH) / 2); int y = component.getHeight() - 40; int step = WIDTH + SPACE; for (UnitButton button : unitButtons) { button.setLocation(x, y); x += step; } } // // Add the GUI Objects to the container // component.addToCanvas(infoPanel, CONTROLS_LAYER); component.addToCanvas(miniMapPanel, CONTROLS_LAYER); if (freeColClient.getClientOptions() .getBoolean(ClientOptions.DISPLAY_COMPASS_ROSE)) { component.addToCanvas(compassRose, CONTROLS_LAYER); } if (!freeColClient.isMapEditor()) { for (UnitButton button : unitButtons) { component.addToCanvas(button, CONTROLS_LAYER); button.refreshAction(); } } }
07f7cdc3-db22-4b35-9ff6-4676f4ac4881
3
@Test public void testIterator2(){ Set<String> set = new HashSet<String>(); set.add("Mon "); set.add("Nom "); set.add("Est "); set.add("Gaylor "); for(Iterator<String> i = set.iterator(); i.hasNext();){ System.out.println(i.next()); } System.out.println("------------"); set.remove("Gaylor "); for(Iterator<String> i = set.iterator(); i.hasNext();){ System.out.println(i.next()); } System.out.println("------------"); set.remove("Mon "); set.remove("Nom "); for(Iterator<String> i = set.iterator(); i.hasNext();){ System.out.println(i.next()); } assertEquals(1, set.size()); }
8128518a-27d1-4300-98f1-5661100990ed
3
private void closeApplication() { int response = JOptionPane.showOptionDialog(myCP, "Exit AIMerger?", "Exit", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, null, JOptionPane.YES_OPTION); switch (response) { default: // This should never happen throw new IllegalArgumentException("not an option"); case JOptionPane.CLOSED_OPTION: case JOptionPane.CANCEL_OPTION: offerNewMerge(); break; case JOptionPane.OK_OPTION: System.exit(0); break; } }
726e5222-ed80-4168-b449-2d2e2c12084b
7
public void destroy(String id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); Perifericos perifericos; try { perifericos = em.getReference(Perifericos.class, id); perifericos.getIdPeriferico(); } catch (EntityNotFoundException enfe) { throw new NonexistentEntityException("The perifericos with id " + id + " no longer exists.", enfe); } List<String> illegalOrphanMessages = null; Collection<ItItem> itItemCollectionOrphanCheck = perifericos.getItItemCollection(); for (ItItem itItemCollectionOrphanCheckItItem : itItemCollectionOrphanCheck) { if (illegalOrphanMessages == null) { illegalOrphanMessages = new ArrayList<String>(); } illegalOrphanMessages.add("This Perifericos (" + perifericos + ") cannot be destroyed since the ItItem " + itItemCollectionOrphanCheckItItem + " in its itItemCollection field has a non-nullable perifericosidPeriferico field."); } if (illegalOrphanMessages != null) { throw new IllegalOrphanException(illegalOrphanMessages); } em.remove(perifericos); em.getTransaction().commit(); } catch (Exception ex) { try { em.getTransaction().rollback(); } catch (Exception re) { throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re); } throw ex; } finally { if (em != null) { em.close(); } } }
606a35b3-c6d1-49ef-8af6-e25683dc24f4
6
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; State other = (State) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; }
eb9ec6fa-7fff-4ebe-ae2d-7b66aa8c8c9e
4
public static String readFile(String fileName) { StringBuilder sb = new StringBuilder(); BufferedReader br = null; try { br = new BufferedReader(new FileReader(fileName)); String line; while (true) { line = br.readLine(); if (line == null) break; sb.append(line); } } catch (Exception e) { e.printStackTrace(); } finally { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); }
4dba63c4-020b-4fee-be79-4a0ffd863289
9
private void searchUp(boolean doReplace, boolean showWarnings) { page.getHighlighter().removeAllHighlights(); Object[] entry = embeddedTextComponents.values().toArray(); int n = entry.length - 1; for (int i = n; i > 0; i--) { if (entry[i] instanceof JTextComponent) { if (findNext(doReplace, false, (JTextComponent) entry[i]) == StringFinder.STRING_FOUND) return; ((JTextComponent) entry[i]).getHighlighter().removeAllHighlights(); } else if (entry[i] instanceof Searchable) { if (findNext(doReplace, false, ((Searchable) entry[i]).getTextComponent()) == StringFinder.STRING_FOUND) return; ((Searchable) entry[i]).getTextComponent().getHighlighter().removeAllHighlights(); } } if (entry[0] instanceof JTextComponent) { if (findNext(doReplace, false, (JTextComponent) entry[0]) == StringFinder.STRING_FOUND) return; ((JTextComponent) entry[0]).getHighlighter().removeAllHighlights(); } else if (entry[0] instanceof Searchable) { JTextComponent tc = ((Searchable) entry[0]).getTextComponent(); if (findNext(doReplace, false, tc) == StringFinder.STRING_FOUND) return; tc.getHighlighter().removeAllHighlights(); } findNext(doReplace, showWarnings, page); }
59f21864-c9cf-49fc-bc1e-939662ddf4a2
0
public void SetNextbusStop(int nextBusStop) { //set the next bus stop to visit this.nextBusStop = nextBusStop; }
8b4fa26d-6931-43b1-a34b-bf1cb6c9c6f7
1
private void writeImport() { ImportGenerator imports = new ImportGenerator( filePath ); if ( hasSearch ) imports.addImport( "import java.util.List;" ); imports.addImport( "import " + table.getPackage() + ".domain." + table.getDomName() + ";" ); imports.addImport( "import " + table.getPackage() + ".util." + "DaoException;" ); imports.addImport( "import org.apache.ibatis.annotations.Param;" ); write( imports.toString() ); }
0b9ae71e-95d3-429d-88fc-469c3d0972ee
1
public BeanType build() { try { BeanType beanType = constructor.get(); setDelayedSetters(beanType); return beanType; } catch (Exception e) { // if (e instanceof InstantiationException || e instanceof IllegalAccessException) { // throw new RuntimeException("Failed to construct new instance of " + constructor.getName(), e); // } throw new RuntimeException(e); } }
16afba5d-09a4-428b-a65d-2d4f4da838a1
0
public Gui(ProBotGame game) { this.game = game; }
334fc684-0d08-4c5a-b596-b87668056662
3
public boolean checkScore(int score){ if(list.length==0) return true; for(int i=0; i<list.length; i++) if(score>str2Int(list[i][0])) return true; return false; }
fa4788ed-4cab-4c95-9c5b-3451ae3492bb
4
public Version getVersion(String userAgentString) { Pattern pattern = this.getVersionRegEx(); if (userAgentString != null && pattern != null) { Matcher matcher = pattern.matcher(userAgentString); if (matcher.find()) { String fullVersionString = matcher.group(1); String majorVersion = matcher.group(2); String minorVersion = "0"; if (matcher.groupCount() > 2) // usually but not always there is a minor version minorVersion = matcher.group(3); return new Version (fullVersionString,majorVersion,minorVersion); } } return null; }
a97f769d-8105-4277-9077-c0c9b1992329
4
public void body() { // get the resource characteristics object to be used dynamics = (ResourceDynamics)super.resource_; // Gets the information on number of PEs and rating // of one PE assuming that the machines are homogeneous ratingPE = dynamics.getMIPSRatingOfOnePE(); // creates the profile responsible to keep resource availability info profile = new SingleProfile(super.totalPE_); visualizer = GridSim.getVisualizer(); // a loop that is looking for internal events only // This loop does not stop when the policy receives an // end of simulation event because it needs to handle // all the internal events before it finishes its // execution. This is particularly important for the // GUI to show the completion of advance reservations Sim_event ev = new Sim_event(); while ( Sim_system.running() ) { super.sim_get_next(ev); // if the simulation finishes then exit the loop if (ev.get_tag() == GridSimTags.END_OF_SIMULATION || super.isEndSimulation()) { break; } processEvent(ev); } // CHECK for ANY INTERNAL EVENTS WAITING TO BE PROCESSED while (super.sim_waiting() > 0) { // wait for event and ignore super.sim_get_next(ev); logger.info("Ignore internal events"); } waitingJobs.clear(); runningJobs.clear(); lastSchedUpt = 0.0D; dynamics.resetFreePERanges(); }
b2c88ca4-ce59-4814-b4b5-4393dd29b851
8
@Override public void run() { do { Collection<Car> carsCopy = new ArrayList<>(); carsCopy.addAll(allCars.values()); for (Car car : carsCopy) { if (!car.isSignificant()) { continue; } try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { pushPosition(car); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { fetchPositions(car); } catch (IOException e) { if (e instanceof FileNotFoundException) { if (MapsRacer.DEBUG) { System.out.println("no positions on server"); } } else { // TODO Auto-generated catch block e.printStackTrace(); } } } } while (true); }
8d88416f-4bb0-47a3-a240-04ef87283f8a
8
private boolean tarkistaMusta(Sotilas sotilas, Kentta kentta, int xa, int ya, int xl, int yl) { if(ya == yl) { if(xl - xa == -1 && kentta.nappulaKoordinaatissa(xl, yl) == null) return true; if(avausSiirtoMusta(sotilas, kentta, xa, ya, xl, yl)) return true; } if( (ya - yl)*(ya - yl) == 1 ) { if(kentta.nappulaKoordinaatissa(xl, yl) == null) return false; if(kentta.nappulaKoordinaatissa(xl, yl).omistajanPelinumero() == 2) return false; if(xl - xa == -1) return true; } return false; }
3ac211f5-5057-4fbb-b860-8f34c43b4f44
8
public static void main(String[] args) { // Create a variable for the connection string. String connectionUrl = "jdbc:sqlserver://localhost:1433;" + "databaseName=AdventureWorks;integratedSecurity=true;"; // Declare the JDBC objects. Connection con = null; Statement stmt = null; ResultSet rs = null; try { // Establish the connection. Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); con = DriverManager.getConnection(connectionUrl); // Create and execute an SQL statement that returns some data. String SQL = "SELECT TOP 10 * FROM Person.Contact"; stmt = con.createStatement(); rs = stmt.executeQuery(SQL); // Iterate through the data in the result set and display it. while (rs.next()) { System.out.println(rs.getString(4) + " " + rs.getString(6)); } } // Handle any errors that may have occurred. catch (Exception e) { e.printStackTrace(); } finally { if (rs != null) try { rs.close(); } catch(Exception e) {} if (stmt != null) try { stmt.close(); } catch(Exception e) {} if (con != null) try { con.close(); } catch(Exception e) {} } }
604bf947-7012-49fc-994a-e0922cb8ccfc
0
public String dodajOsobe() { oo.dodajOsobe(osoba); return "pokazOsobe"; //return null; }
20791f87-122b-480b-b041-63bca8d397d5
7
private boolean checkVictoryConditions() { Specification spec = getSpecification(); if (singlePlayerGame && spec.getBoolean(GameOptions.VICTORY_DEFEAT_EUROPEANS) && !spec.getBoolean(GameOptions.VICTORY_DEFEAT_REF)) { int n = 0; for (Entry<Nation, NationState> e : getGame().getNationOptions().getNations().entrySet()) { if (e.getKey().getType().isEuropean() && e.getValue() != NationState.NOT_AVAILABLE) n++; } if (n == 0) { getGUI().errorMessage("victory.noEuropeans"); return false; } } return true; }
d2cb4774-ccfc-43c4-a3d0-1ec0ff97b6f8
0
public void setDiagnostico(String diagnostico) { this.diagnostico = diagnostico; }
7fc839cf-4810-4bf6-9b50-2e408a6388f7
1
public SystemdJournalTest () throws IOException { super(); File socketFile = new File("/run/systemd/journal/socket"); if ( !socketFile.exists() ) { return; } this.socketAddress = new AFUNIXSocketAddress(socketFile, 0, false, true); }
8a6b7de1-bd5c-4dd7-bcd1-ed5420c27d30
5
public boolean start() { // try to connect to the server try { keyPair = KeyPairFactory.generateKeyPair(); socket = new Socket(server, port); } // if it failed not much I can so catch (Exception ec) { display("Error connectiong to server:" + ec); return false; } String msg = "Connection accepted " + socket.getInetAddress() + ":" + socket.getPort(); display(msg); /* Creating both Data Stream */ try { sInput = new ObjectInputStream(socket.getInputStream()); sOutput = new ObjectOutputStream(socket.getOutputStream()); } catch (IOException eIO) { display("Exception creating new Input/output Streams: " + eIO); return false; } try { serverKey = (PublicKey) sInput.readObject(); // System.out.println(serverKey); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // creates the Thread to listen from the server new ListenFromServer().start(); // Send our username to the server this is the only message that we // will send as a String. All other messages will be ChatMessage objects try { sOutput.writeObject(username); } catch (IOException eIO) { display("Exception doing login : " + eIO); disconnect(); return false; } // success we inform the caller that it worked return true; }
8270f915-1aef-4bd3-832f-81b3c8bde507
9
private String getTypeAsString(String typeName, boolean isParam, String prefix, String suffix) { if (typeName.equals("boolean")) { if (isParam) { return "bool "; } else { return "bool"; } } else if (typeName.equals("String")) { if (isParam) { return "const std::string &"; } else { return "std::string"; } } else if (nativeTypes.contains(typeName)) { if (isParam) { if (typeName.equals("int64")) { return "int64_t "; } else { return typeName + " "; } } else { if (typeName.equals("int64")) { return "int64_t"; } else { return typeName; } } } else { if (isParam) { return "std::shared_ptr<" + prefix + typeName + suffix + "> "; } else { return "std::shared_ptr<" + prefix + typeName + suffix + ">"; } } }
b69528e5-bca7-4fb7-a448-e60b83fed433
0
public static String getName(int bookId) { return bookNames[bookId-300]; }
bf883e84-1ffa-43f7-8e11-9a3c7822f3c7
8
private static void mergePhiVersions(SSAConstructorSparseEx ssa, DirectGraph graph) { // collect phi versions List<Set<VarVersionPair>> lst = new ArrayList<>(); for (Entry<VarVersionPair, FastSparseSet<Integer>> ent : ssa.getPhi().entrySet()) { Set<VarVersionPair> set = new HashSet<>(); set.add(ent.getKey()); for (Integer version : ent.getValue()) { set.add(new VarVersionPair(ent.getKey().var, version.intValue())); } for (int i = lst.size() - 1; i >= 0; i--) { Set<VarVersionPair> tset = lst.get(i); Set<VarVersionPair> intersection = new HashSet<>(set); intersection.retainAll(tset); if (!intersection.isEmpty()) { set.addAll(tset); lst.remove(i); } } lst.add(set); } Map<VarVersionPair, Integer> phiVersions = new HashMap<>(); for (Set<VarVersionPair> set : lst) { int min = Integer.MAX_VALUE; for (VarVersionPair paar : set) { if (paar.version < min) { min = paar.version; } } for (VarVersionPair paar : set) { phiVersions.put(new VarVersionPair(paar.var, paar.version), min); } } updateVersions(graph, phiVersions); }
a4a39c2e-400b-4181-a87b-7adff30f1bee
7
@ Override public boolean writeToFile(final File file, T object, boolean replaceIfExists) { // Delete file if it exists if (file.exists () && replaceIfExists) { file.delete (); } else return false; FileOutputStream fOS = null; ObjectOutputStream oOS = null; try { // Write object to file using FileOutputStream and ObjectOutputStream fOS = new FileOutputStream (file); oOS = new ObjectOutputStream (fOS); oOS.writeObject (object); oOS.close (); } catch (IOException e) { e.printStackTrace (); return false; } finally { // Close FileOutputStream and ObjectOutputStream if (fOS != null) { try { fOS.close (); } catch (IOException e) {} } if (oOS != null) { try { oOS.close (); } catch (IOException e) {} } } return true; }
bb215dc2-f026-49ff-be2c-79393f9a32ed
2
public final void remove(Object gameComponent) { // Remove this object from our logical list if its a logical object if (gameComponent instanceof ILogical) { ILogical logicalObject = (ILogical) gameComponent; logicalQueue.remove(logicalObject); logicalObject.cleanUp(); } // Remove this object from the drawable list, if it's a drawable object if (gameComponent instanceof IDrawable) { drawableList.remove((IDrawable) gameComponent); } }
91877f28-6ce0-4f22-902c-60fab6298227
5
public static void main(String[] args) { try { AudioInputStream in = AudioSystem.getAudioInputStream(new File("Agogo.ogg")); if (in != null) { AudioFormat baseFormat = in.getFormat(); AudioFormat targetFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, baseFormat.getSampleRate(), 16, baseFormat.getChannels(), baseFormat.getChannels() * 2, baseFormat.getSampleRate(), false); AudioInputStream dataIn = AudioSystem.getAudioInputStream(targetFormat, in); byte[] buffer = new byte[4096]; // get a line from a mixer in the system with the wanted format DataLine.Info info = new DataLine.Info(SourceDataLine.class, targetFormat); SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info); if (line != null) { line.open(); line.start(); int nBytesRead = 0, nBytesWritten = 0; while (nBytesRead != -1) { nBytesRead = dataIn.read(buffer, 0, buffer.length); if (nBytesRead != -1) { nBytesWritten = line.write(buffer, 0, nBytesRead); } } line.drain(); line.stop(); line.close(); dataIn.close(); } in.close(); // playback finished } } catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) { // failed } }
f2afdefd-100c-4160-b4bc-03284bc46f6c
1
public Transition modifyTransition(Transition transition, TableModel model) { String input = (String) model.getValueAt(0, 0); String pop = (String) model.getValueAt(0, 1); String push = (String) model.getValueAt(0, 2); PDATransition t = (PDATransition) transition; try { return new PDATransition(t.getFromState(), t.getToState(), input, pop, push); } catch (IllegalArgumentException e) { reportException(e); return null; } }
6f3a92f6-d38b-4646-acc8-4d2d7d3d16eb
0
public boolean isStackEmpty(){ return operandStack.empty(); }
0bd339ae-e6aa-4730-8d5c-127c3eb9805a
9
public static int[] path(int[] queue) { int esimene = queue[0]; int[] resultPath = new int[queue.length]; resultPath[0] = esimene; int i = 0; int j = 0; int u = 0; for (int k : queue) { if (k < esimene) { i++; } else if (k > esimene) { j++; } else { u++; } } int[] vaiksemad = new int[i]; int[] suuremad = new int[j]; int p = 0; int p2 = 0; for (int k = 0; k < queue.length; k++) { if (queue[k] < esimene) { vaiksemad[p] = queue[k]; p++; } } for (int k = 0; k < queue.length; k++) { if (queue[k] > esimene) { suuremad[p2] = queue[k]; p2++; } } Arrays.sort(vaiksemad); for (int k = vaiksemad.length - 1, o = 1; k >= 0; k--, o++) { resultPath[o] = vaiksemad[k]; } Arrays.sort(suuremad); int asd = i + u; for (int ko = suuremad.length - 1; ko >= 0; ko--) { resultPath[asd] = suuremad[ko]; asd++; } return resultPath; }
d49181f2-58fa-4faf-89fe-09fbc8cc6e8c
0
@Override public void down() { System.out.println("Lighter Down!"); }
0999e0c8-a4f4-4c5c-8ebd-d1b77d2d962c
7
void syncFromTemplate(AbstractProject template, AbstractProject implementation) throws IOException { if( implementation == null || !(implementation instanceof BuildableItemWithBuildWrappers) || !(implementation instanceof Describable) || template == null || !(template instanceof BuildableItemWithBuildWrappers) || !(template instanceof Describable) ) { return; } ImplementationBuildWrapper implementationBuildWrapper = this; TemplateBuildWrapper templateBuildWrapper = BuildWrapperUtils.findBuildWrapper(TemplateBuildWrapper.class, template); if(templateBuildWrapper == null) { return; } Map<Pattern, String> propertiesMap = getPropertiesMap(template, implementation, implementationBuildWrapper); String oldDescription = implementation.getDescription(); boolean oldDisabled = implementation.isDisabled(); Map<TriggerDescriptor, Trigger> oldTriggers = implementation.getTriggers(); XmlFile implementationXmlFile = replaceConfig(template, implementation, propertiesMap); refreshAndSave(template, implementationBuildWrapper, implementationXmlFile, oldDescription, oldDisabled, oldTriggers); }
3593748a-cbc5-40c2-8c23-0eef1cf26d35
8
@Override public boolean okMessage(final Environmental myHost, final CMMsg msg) { if((beingSpoken(ID())) &&(affected instanceof MOB) &&(msg.amISource((MOB)affected)) &&(msg.sourceMessage()!=null) &&(msg.tool()==null) &&((msg.sourceMinor()==CMMsg.TYP_SPEAK) ||(msg.sourceMinor()==CMMsg.TYP_TELL) ||(CMath.bset(msg.sourceMajor(),CMMsg.MASK_CHANNEL)))) { msg.modify(msg.source(),msg.target(),msg.tool(), msg.sourceCode(),tup(msg.sourceMessage()), msg.targetCode(),tup(msg.targetMessage()), msg.othersCode(),tup(msg.othersMessage())); } return super.okMessage(myHost,msg); }
64b117cd-4ba3-45fc-aa06-6066cfb46fc5
2
void writeCrud() { write( TAB + "public int create( " ); write( table.getDomName() ); write( " value ) throws BoException {\n" ); writeMethodBodyCreateUpdate( "create" ); write( NEWLINE ); write( TAB + "public int update( " ); write( table.getDomName() ); write( " value ) throws BoException {\n" ); writeMethodBodyCreateUpdate( "update" ); String param = ""; for(Column col : keyColumns){ param += col.getFldType() + " " + col.getFldName() + ", "; } param = param.substring( 0, param.length() - 2 ); write( NEWLINE ); write( TAB ); write( "public int delete( " ); write( param + " ) throws BoException {\n" ); writeMethodBodyReadDelete( "delete" ); write( NEWLINE ); write( TAB ); write( "public " ); write( table.getDomName() ); write( " read( " + param);; write( " ) throws BoException {\n" ); writeMethodBodyReadDelete( "read" ); write( NEWLINE ); if ( !table.getIndexList().isEmpty() ) { writeIndexKeys(); } }
56fa3014-4eca-4224-857b-c43d3d5f286f
6
static final void handleMessage(String string, int type, int intArg, String string_2_, String subStr, String subStr2) { do { try { Class318_Sub1_Sub3_Sub5.handleMessage(string, string_2_, -1, subStr, null, type, intArg, subStr2); anInt6203++; friendListGamenames = null; } catch (RuntimeException runtimeexception) { throw Class348_Sub17.method2929 (runtimeexception, ("di.G(" + (string != null ? "{...}" : "null") + ',' + type + ',' + intArg + ',' + (string_2_ != null ? "{...}" : "null") + ',' + (subStr != null ? "{...}" : "null") + ',' + (subStr2 != null ? "{...}" : "null") + ')')); } break; } while (false); }
30ab8ff2-03fe-43bf-bef4-45a87ccdf30e
2
public static void main(String[] args) { try { ctx = new Renamer(); ctx.run(); } catch (Throwable e) { e.printStackTrace(); try { Thread.sleep(1000); } catch (InterruptedException e2) { } System.exit(1); } }
9503b67c-154b-4ca6-9413-816894bc09be
7
private void create(int[] init, Color bg, String fieldTitle) { setPreferredSize(new Dimension(GUIConstants.DEFAULT_FIELD_WIDTH, FIELDHEIGHT)); setBackground(bg); setBorder(BorderFactory.createTitledBorder(fieldTitle)); setLayout(new VerticalLayout(0, VerticalLayout.CENTER)); setToolTipText(Field.strPaddingTooltip); JPanel panel = new JPanel(); panel.setBackground(bg); this.add(panel); final JTextField left = new JTextField(); left.setColumns(NUMBERLENGTH + 1); left.setToolTipText(Field.strPaddingTooltip); panel.add(left); final JTextField top = new JTextField(); top.setColumns(NUMBERLENGTH + 1); top.setToolTipText(Field.strPaddingTooltip); panel.add(top); final JTextField right = new JTextField(); right.setColumns(NUMBERLENGTH + 1); right.setToolTipText(Field.strPaddingTooltip); panel.add(right); final JTextField bottom = new JTextField(); bottom.setColumns(NUMBERLENGTH + 1); bottom.setToolTipText(Field.strPaddingTooltip); panel.add(bottom); if (init != null) { left.setText(init[0] + ""); top.setText(init[1] + ""); right.setText(init[2] + ""); bottom.setText(init[3] + ""); } left.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { if (controlThicknessInput(left, NUMBERLENGTH, true)) { leftFieldOnKeyReleased(left.getText()); } } }); top.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { if (controlThicknessInput(top, NUMBERLENGTH, true)) { topFieldOnKeyReleased(top.getText()); } } }); right.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { if (controlThicknessInput(right, NUMBERLENGTH, true)) { rightFieldOnKeyReleased(right.getText()); } } }); bottom.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { if (controlThicknessInput(bottom, NUMBERLENGTH, true)) { bottomFieldOnKeyReleased(bottom.getText()); } } }); JButton reset = new JButton(Field.strReset); reset.setBackground(bg); this.add(reset); reset.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { int[] tmp = reset(); if ((tmp != null) && (tmp.length == 4)) { left.setText(tmp[0] + ""); top.setText(tmp[1] + ""); right.setText(tmp[2] + ""); bottom.setText(tmp[3] + ""); } } }); }
5cf069a3-6d76-4701-a00f-c953229de6d9
4
private List<Number> getKeysFromKeyHolder(KeyHolder keyHolder) { List<Map<String, Object>> generatedKeys = keyHolder.getKeyList(); int length = generatedKeys.size(); List<Number> keys = new ArrayList<Number>(); for (int i = 0; i < length; i++) { Iterator<Object> keyIterator = generatedKeys.get(i).values().iterator(); if (keyIterator.hasNext()) { Object key = keyIterator.next(); if (!(key instanceof Number)) { String className = null; if (key != null) { className = key.getClass().getName(); } throw new RetrievalIdException("数据库生成的主键不是系统支持的数值类型. " + "无法将[" + className + "]类型转换为[" + Number.class.getName() + "]类型"); } keys.add((Number) key); } } return keys; }
a0571a02-a09e-4ba0-8785-7a9168e6f666
1
@RequestMapping(value = "/{imageId}", method = RequestMethod.GET) public String imagePage(@PathVariable String imageId, Model model, HttpServletRequest paramHttpServletRequest) { Image image = imageService.getImageMetadatabyId(imageId); if (image != null) { model.addAttribute("comment", image.getComment()); model.addAttribute("url", paramHttpServletRequest.getRequestURL()); model.addAttribute("date", new Date(image.getTimestamp())); } else { return "resourceNotFoundPage"; } return "imagePage"; }
a76ef9d9-d014-4e4b-a86b-fcdeb2ed97dc
9
public void movimientoMaquina(){ if(turno == FICHA_BLANCA){ if(jug1.getTipo()==Jugador.HUMANO){ //esperar click }else{ if(nivel1 == FACIL){ System.out.println("Entre a nivel facil"); int jug[] = buscarJugadaFacil(FICHA_BLANCA); colocarFichaBlanca(jug[0], jug[1]); } if(nivel1 == MEDIO){ System.out.println("Entre a nivel medio"); int jug[] = buscarJugadaMedio(FICHA_BLANCA); colocarFichaBlanca(jug[0], jug[1]); // <editor-fold defaultstate="collapsed" desc="Estrategia MEDIO"> // </editor-fold> } if(nivel1 == EXPERTO){ System.out.println("Entre a nivel medio"); int jug[] = buscarJugadaExperto(FICHA_BLANCA); colocarFichaBlanca(jug[0], jug[1]); // <editor-fold defaultstate="collapsed" desc="Estrategia EXPERTO"> // </editor-fold> } } }else{ if(jug2.getTipo()==Jugador.HUMANO){ //esperar click }else{ if(nivel2 == FACIL){ int jug[] = buscarJugadaFacil(FICHA_NEGRA); colocarFichaNegra(jug[0], jug[1]); } if(nivel2 == MEDIO){ int jug[] = buscarJugadaMedio(FICHA_NEGRA); colocarFichaNegra(jug[0], jug[1]); // <editor-fold defaultstate="collapsed" desc="Estrategia MEDIO"> // </editor-fold> } if(nivel2 == EXPERTO){ int jug[] = buscarJugadaExperto(FICHA_NEGRA); colocarFichaNegra(jug[0], jug[1]); // <editor-fold defaultstate="collapsed" desc="Estrategia EXPERTO"> // </editor-fold> } } } }
d5b19500-1502-48fb-9f5f-c7ef960bc77c
2
@Override protected AbstractPage parseChild(Element element) throws ProblemsReadingDocumentException { try { String href = element.getAttributeValue("href"); AbstractPage c; String newURL = Paths.get(url.toURI()).resolveSibling(href.substring(1)).toUri().toString(); if (href.equals("/emancipator-children/elephant-survival.htm")) c = new Track(newURL, getChildrenSaveTo(), this); else c = new Album(newURL, getChildrenSaveTo(), this); c.setTitle(element.getText()); return c; } catch (NullPointerException|IllegalArgumentException| IOException | URISyntaxException e) { throw new ProblemsReadingDocumentException(e); } }
afa9b62f-f38a-48db-b700-c639bc238c80
9
public List<String> similarities(String s, Iterable<String> words, int top) { if (s == null || words == null) { throw new IllegalArgumentException("Can not deal with null strings"); } if (top < 1) { throw new IllegalArgumentException("At least one suggestion should desired"); } PriorityQueue<CostSimilarity> queue = new PriorityQueue<CostSimilarity>(top, new Comparator<CostSimilarity>() { public int compare(CostSimilarity o1, CostSimilarity o2) { if(o1.cost == o2.cost) return 0; if(o1.cost > o2.cost) return 1; return -1; } }); for(String word: words){ int cost = getLevenshteinDistance(s, word); CostSimilarity sc = new CostSimilarity(word, cost); if(queue.size() == top && queue.peek().cost > sc.cost){ queue.poll(); } queue.add(sc); } String similarities[] = new String[top]; for(int i = 0; i < top; i++){ similarities[i] = queue.poll().word; } return Arrays.asList(similarities); }
7765be8b-8041-493c-abb1-5d5ad7bb5080
4
public int broadcast(FrameQueue queue, boolean immediate, int... exceptSessionID) { int count = 0; LOOP: for (AuthFrameAdapter adapter : this.adapters) { for (int i : exceptSessionID) { if (adapter.getSessionID() == i) continue LOOP; } adapter.getOutgoing().addAll(queue); if (immediate) adapter.send(); count++; } return count; }
4109f8c3-be70-486e-9e4d-6a225f9f213f
7
public void generateMoves(Piece[][] squares, ArrayList<Move> validMoves, ArrayList<Move> validCaptures) { // for each possible direction (NE, SE, SW, NW) int xPos; int yPos; for (int direction = 0; direction < xMoves.length; direction++) { xPos = xPosition + xMoves[direction]; yPos = yPosition + yMoves[direction]; while (0 <= xPos && xPos <= 7 && 0 <= yPos && yPos <= 7) { if (squares[xPos][yPos] == null) { //if the square is empty validMoves.add(new Move(xPosition, yPosition, xPos, yPos)); } else { //if the square contains a piece if (squares[xPos][yPos].colour == this.colour) { //if the square contains a friendly piece break; } else { validCaptures.add(new Move(xPosition, yPosition, xPos, yPos)); break; //if the square contains an enemy piece } } //increment the position xPos += xMoves[direction]; yPos += yMoves[direction]; } } }
69a16704-b599-46c0-b0fe-05e7fbc20839
6
public static void main(String[] args) { if (args.length < 1) { usage(); return; } File dataFile = new File(args[0]); File directory = dataFile.getParentFile(); File trimmed = new File(directory, "data-trimmed.xml"); try { if (dataFile.isDirectory() == false) { FileInputStream fin = new FileInputStream(dataFile); BufferedReader br = new BufferedReader(new InputStreamReader( fin)); FileWriter fw = new FileWriter(trimmed); String line = br.readLine(); while (line != null) { boolean open = false; StringTokenizer tokens = new StringTokenizer(line, "\""); while (tokens.hasMoreTokens()) { String token = tokens.nextToken(); if (open) { token = "\"" + token.trim() + "\""; } fw.write(token); open = !open; } fw.write("\n"); line = br.readLine(); } fin.close(); fw.close(); } } catch (Exception e) { e.printStackTrace(); } }
e3462989-440c-44b0-a599-341b459eb092
2
public void draw(Rectangle2D box) { for(int row = 0; row < 3; row++) { for(int col = 0; col < 3; col++) { setTransform(row, col, box); SpriteList.get(frame).draw(transform); } } }
9a240ef3-071f-4f99-b6c9-fa24b3985a9e
4
public static Map<Integer, Integer> getPrimeFactorisation(int number) { Map<Integer, Integer> primes = new HashMap<>(); if (number == 1) { primes.put(2, 0); } for (int prime = 2; number != 1; prime++) { int count = 0; while (number % prime == 0) { count++; number /= prime; } if (count != 0) { primes.put(prime, count); } } return primes; }
1271573b-2d6a-4ffd-816c-b483bbc0ae7c
6
static public String numberToString(Number n) throws JSONException { if (n == null) { throw new JSONException("Null pointer"); } testValidity(n); // Shave off trailing zeros and decimal point, if possible. String s = n.toString(); if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) { while (s.endsWith("0")) { s = s.substring(0, s.length() - 1); } if (s.endsWith(".")) { s = s.substring(0, s.length() - 1); } } return s; }
da02b799-a0ea-4f42-8857-cdabeadc95ef
3
@Override public void update(Observable o, Object arg) { if (o instanceof ActivityDao || o instanceof TimeDao || o instanceof Dao) { loadCmbActivities(); } }
9a4be5bb-1d73-4e45-8ee8-d2cdaa87bac0
9
private void routeInput(InputPort inputPort) { Flit flit = inputPort.peekNextFlit(); if(flit != null) { int inputVC = flit.getVC(); int outputPort = -1; int outputVC = -1; // Work out the output port and vc number if(flit instanceof HeaderFlit) { int flitSrc = ((HeaderFlit)flit).getSrc(); int flitDest = ((HeaderFlit)flit).getDest(); int procId = m_outputPorts[m_procOutputPort].getDownStreamNodeId(); // Select an output port and output virtual channel if(flitDest == procId) { outputPort = m_procOutputPort; outputVC = m_outputPorts[outputPort].allocVC(); } else { outputPort = flitDest == procId ? m_procOutputPort : m_routingFunction.getOutputPort(m_nodeId, inputVC, flitSrc, flitDest); int routedVC = m_routingFunction.getOutputVC(m_nodeId, inputVC, flitSrc, flitDest); outputVC = routedVC == -1 ? m_outputPorts[outputPort].allocVC() : m_outputPorts[outputPort].allocVC(routedVC); } // If could not allocate VC then replace flit and wait, otherwise open a connection if(outputVC == -1) { inputPort.setWaitingVC(inputVC); console("could not allocate a VC for I["+inputPort.getPortNum()+":"+inputVC+"] on O["+outputPort+":?]"); return; } else { inputPort.setupConnection(inputVC, outputPort, outputVC); m_outputPorts[outputPort].setupConnection(outputVC, inputPort.getPortNum(), inputVC); console(flit+" opening connection I["+inputPort.getPortNum()+":"+inputVC+"] to O["+outputPort+":"+outputVC+"] on dsn VC "+outputVC); } } else if(flit instanceof BodyFlit || flit instanceof TailFlit) { outputPort = inputPort.getOutputPort(flit.getVC()); outputVC = inputPort.getOutputVC(flit.getVC()); } // Only poll the input flit if the output is empty //m_outputPorts[outputPort].setCurrVC(outputVC); if(m_outputPorts[outputPort].isEmpty(outputVC)) { m_outputPorts[outputPort].addFlit(outputVC, inputPort.takeNextFlit()); //console("Routing link "+linkInput.getPortNum()+" flit "+flit.toShortStr()+" to OP["+outputPort+":"+flit.getVC()+"]"); } } }
de84d73b-6a10-44e1-a743-12a77fc54bb4
5
public static Object cast(String obj, Class clazz) { if (clazz.equals(String.class)) { return obj; } else if (clazz.equals(boolean.class)) { return Boolean.parseBoolean(obj.toString()); } else if (clazz.equals(Boolean.class)) { return (Boolean) Boolean.parseBoolean(obj.toString()); } else if (clazz.equals(Double.class)) { return (Double) Double.parseDouble(obj.toString()); } else if(clazz.equals(Integer.class)) { return Integer.parseInt(obj); } return obj; }
3c2019c2-764d-40c0-ae01-30d7509f1d5b
8
private static String initialise(Token currentToken, int[][] expectedTokenSequences, String[] tokenImage) { String eol = System.getProperty("line.separator", "\n"); StringBuffer expected = new StringBuffer(); int maxSize = 0; for (int i = 0; i < expectedTokenSequences.length; i++) { if (maxSize < expectedTokenSequences[i].length) { maxSize = expectedTokenSequences[i].length; } for (int j = 0; j < expectedTokenSequences[i].length; j++) { expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' '); } if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) { expected.append("..."); } expected.append(eol).append(" "); } String retval = "Encountered \""; Token tok = currentToken.next; for (int i = 0; i < maxSize; i++) { if (i != 0) retval += " "; if (tok.kind == 0) { retval += tokenImage[0]; break; } retval += " " + tokenImage[tok.kind]; retval += " \""; retval += add_escapes(tok.image); retval += " \""; tok = tok.next; } retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn; retval += "." + eol; if (expectedTokenSequences.length == 1) { retval += "Was expecting:" + eol + " "; } else { retval += "Was expecting one of:" + eol + " "; } retval += expected.toString(); return retval; }
3956d4d0-40b4-4322-a0f4-0abe7a44b3fb
4
public Graph(Integer[][] matrix) { adjacencyList = new ArrayList<>(); int n = matrix.length; if (n != 0) { //create list for 0 vertex adjacencyList.add(new ArrayList<Integer>()); for (int i = 1; i < n; i++) { //create list for i-th vertex adjacencyList.add(new ArrayList<Integer>()); for (int j = 0; j < i; j++) { if (matrix[i][j] == 1) { adjacencyList.get(i).add(j); adjacencyList.get(j).add(i); } } } } }
8febf082-f01a-4d96-8045-e977c99f4cf3
2
public synchronized void keyReleased(KeyEvent e) { int keyCode = e.getKeyCode(); if (keyCode >= 0 && keyCode < KEY_COUNT) { currentKeys[keyCode] = false; } }
3216f3df-3b88-4279-9059-8d7c86dbbf61
3
public static void dfs(boolean[][] nabomatrise, boolean[] visited, int node) { visited[node] = true; for (int i = 0; i < nabomatrise[node].length; i++) { if(nabomatrise[node][i] == true && !visited[i]) { dfs(nabomatrise, visited, i); } } }
c519552a-d70d-496a-b7dd-4c65e7681a02
7
public final void shutdown() { try { if(this.soundPlayer != null) { SoundPlayer var1 = this.soundPlayer; this.soundPlayer.running = false; } if(this.resourceThread != null) { ResourceDownloadThread var4 = this.resourceThread; this.resourceThread.running = true; } } catch (Exception var3) { ; } Minecraft var5 = this; if(!this.levelLoaded) { try { if(var5.level.creativeMode) { LevelIO.save(var5.level, (OutputStream)(new FileOutputStream(new File(mcDir, "levelc.dat")))); } else { LevelIO.save(var5.level, (OutputStream)(new FileOutputStream(new File(mcDir, "levels.dat")))); } } catch (Exception var2) { var2.printStackTrace(); } } Mouse.destroy(); Keyboard.destroy(); if(!isSystemShuttingDown()) { Display.destroy(); } }
e2673b41-41b8-4ebe-98a4-e9bc12524000
9
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final EventLogRecord other = (EventLogRecord) obj; if (choice == null) { if (other.choice != null) return false; } else if (!choice.equals(other.choice)) return false; if (timestamp == null) { if (other.timestamp != null) return false; } else if (!timestamp.equals(other.timestamp)) return false; return true; }
1fe944ac-7292-43a4-a683-73a294cf5d45
4
public void draw() { for (int j = 0; j < height; j ++) { for (int i = 0; i < width; i ++) { Graphics.setColour(128, 128, 128); Graphics.rectangle(true, i * TILE_SIZE, j * TILE_SIZE, TILE_SIZE, TILE_SIZE); Graphics.setColour(64, 64, 64); Graphics.rectangle(false, i * TILE_SIZE, j * TILE_SIZE, TILE_SIZE, TILE_SIZE); } } for (Pellet p : pellets) { Graphics.setColour(128, 255, 128); Graphics.circle(true, (p.x + 0.5) * TILE_SIZE, (p.y + 0.5) * TILE_SIZE, 4); } for (Bullet b : bullets) { b.draw(); } }
c3f2b17d-e70d-4cd2-a532-501acee0c85a
0
public static void m(){ System.out.println("ok"); }
dff43447-fd5e-4a5f-93a2-98da696b132f
9
final Object[] getNames(boolean getAll, Object[] extraEntries) { Object[] names = null; int count = 0; for (int id = 1; id <= maxId; ++id) { Object value = ensureId(id); if (getAll || (attributeArray[id - 1] & DONTENUM) == 0) { if (value != NOT_FOUND) { int nameSlot = (id - 1) * SLOT_SPAN + NAME_SLOT; String name = (String)valueArray[nameSlot]; if (names == null) { names = new Object[maxId]; } names[count++] = name; } } } if (count == 0) { return extraEntries; } else if (extraEntries == null || extraEntries.length == 0) { if (count != names.length) { Object[] tmp = new Object[count]; System.arraycopy(names, 0, tmp, 0, count); names = tmp; } return names; } else { int extra = extraEntries.length; Object[] tmp = new Object[extra + count]; System.arraycopy(extraEntries, 0, tmp, 0, extra); System.arraycopy(names, 0, tmp, extra, count); return tmp; } }
b3a5a41f-1fc7-4f45-9f50-d2b05a571f6a
3
@Override public void nextCard(){ CardImpl nextCard = null; int boxToCheck = this.curBox; boolean firstLoop = true; while (nextCard == null){ nextCard = this.model.getTopic().getRandomCard(boxToCheck); if (firstLoop){ boxToCheck = 0; firstLoop = false; } else { boxToCheck +=1; } if (boxToCheck > Application.boxCount){ break;//boxToCheck = 1; } } this.model = nextCard; this.view.cardChanged(); }
c54376d3-428d-48eb-8342-ad3a9ee46d1e
5
public void fileNew(SimpleFrame frame) { frame.setAction(false); frame.setIsFileNameSetted(false); frame.setTitle("Text Editor"); JFileChooser chooser = new JFileChooser(); if(frame.getIsChanged()) { int selection = JOptionPane.showConfirmDialog(null,"Do you want save document?", "Warrning", JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE); if(selection == JOptionPane.NO_OPTION) { frame.getText().setText(""); frame.setIsChanged(false); frame.setTitle("Text Editor"); } if(selection == JOptionPane.YES_OPTION) { chooser.setCurrentDirectory(new File(".")); int result = chooser.showSaveDialog(null); if (result == JFileChooser.APPROVE_OPTION) { frame.fileName = chooser.getSelectedFile().getPath(); PrintWriter out; try { out = new PrintWriter(new FileWriter(frame.fileName)); String str = frame.getText().getText(); out.print(str); out.close(); } catch (IOException e) { JOptionPane.showMessageDialog(frame, "Saving error"); } } frame.getText().setText(""); frame.setIsChanged(false); frame.setTitle("Text Editor"); } } else { frame.getText().setText(""); } frame.setAction(true); }
3023612e-3670-44f5-a987-d466d8014652
1
public static synchronized void startProfiling() { subLCommandProfiling = true; if (subLCommandProfiler != null) { Logger.getLogger("org.opencyc.api.DefaultSubLWorker").log(Level.INFO, "SubL command profiling already started."); return; } Logger.getLogger("org.opencyc.api.DefaultSubLWorker").log(Level.INFO, "Start of SubL command profiling."); subLCommandProfiler = new SubLCommandProfiler(); }
6d64bdaa-476a-4bea-98d5-9605dfa5ee5d
0
public void setArea(String area) { Area = area; }
5fa34f8d-ca02-4776-857d-e0d15631b603
6
public void increaseExp() { int e; if (level >= 1 && level <= 7) { e = Randomizer.nextInt(10) + 15; } else if (level >= 8 && level <= 15) { e = Randomizer.nextInt(13) + 15 / 2; } else if (level >= 16 && level <= 24) { e = Randomizer.nextInt(23) + 18 / 2; } else { e = Randomizer.nextInt(28) + 25 / 2; } setExp(exp + e); }
9063e2df-2dc6-43d3-b4e7-b82133929ea4
5
private void controlarXeque() { /* se for a vez do branco, valida o cheque no rei preto */ if (jogo.getVez().equals(jogo.getBranco())) { /* verifica xeque */ if (validarXeque(jogo.getTabuleiro().getPosicaoReiPreto(), jogo .getTabuleiro().getPecasBrancas())) { /* verifica xeque-mate */ if (validarXequeMate(jogo.getTabuleiro().getPosicaoReiPreto(), jogo.getTabuleiro().getPecasBrancas())) { finalizarJogo(jogo.getBranco(), jogo.getPreto()); } else { GUIControl.getInstanceOf().enviarMensagemXeque(jogo.getVez()); } } /* senao, valida o xeque no rei branco */ } else { /* verifica xeque */ if (validarXeque(jogo.getTabuleiro().getPosicaoReiBranco(), jogo .getTabuleiro().getPecasPretas())) { /* verifica xeque-mate */ if (validarXequeMate(jogo.getTabuleiro().getPosicaoReiBranco(), jogo.getTabuleiro().getPecasPretas())) { finalizarJogo(jogo.getPreto(), jogo.getBranco()); } else { GUIControl.getInstanceOf().enviarMensagemXeque(jogo.getVez()); } } } }
9e9b12d3-127c-453a-8169-ca95cb913e42
0
public void setCatched() { catched = true; }
af2c152e-ce60-4483-81ec-bcc639d6478c
2
protected void open(String fileName) { if (!Gpr.canRead(fileName)) throw new RuntimeException("Cannot read file '" + fileName + "'"); if (lineFileIterator != null) lineFileIterator.close(); lineFileIterator = new LineFileIterator(fileName); }
ab43ec6b-1ca7-45f1-92f9-3f93c49540d1
0
public void removeDocumentListener(DocumentListener l) { documentListeners.remove(l); }
98779e09-a2d5-461d-adf8-62af513de9e0
3
@Override public boolean equals(Object obj) { boolean equals = false; if (obj instanceof AndroidDeviceClient) { AndroidDeviceClient deviceClient = (AndroidDeviceClient) obj; if (deviceClient.getModel().equals(model) && deviceClient.getSerialNumber().equals(serialNumber)) { equals = true; } } return equals; }
cd1e7be5-7dfd-4639-ae58-4b6def663668
0
public static void main(String[] args) { // Wissel de comment tekens om de andere klasse aan te roepen. //new OpdrachtVierTweeEen(); new OpdrachtVierTweeTwee(); }
d8f6a0dd-a2f8-4869-a216-938e92562229
6
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Occurrence other = (Occurrence) obj; if (word == null) { if (other.word != null) return false; } else if (!word.equals(other.word)) return false; return true; }
600192ea-eb53-4bff-be67-57b6d6b6892c
7
@Override public LegalWarrant getLawResister(Area A, LegalBehavior behav, MOB mob) { final String[] lawResistInfo=basicCrimes().get("RESISTINGARREST"); if(lawResistInfo!=null) for(int i=0;i<warrants.size();i++) { final LegalWarrant W=warrants.elementAt(i); if((W.criminal()==mob) &&(W.crime().equals(lawResistInfo[Law.BIT_CRIMENAME])) &&(W.victim()!=null) &&(behav.isStillACrime(W,false)) &&(behav.isAnyOfficer(A,W.victim()))) return W; } return null; }
e2dfc005-aa20-4e13-8733-672e57981763
5
public int upgradeBonus(Object refers) { if (upgrades == null) return 0 ; int bonus = 0 ; for (int i = 0 ; i < upgrades.length ; i++) { final Upgrade u = upgrades[i] ; if (u == null || upgradeStates[i] != STATE_INTACT) continue ; if (u.refers == refers) bonus += u.bonus ; } return bonus ; }
050a5191-f988-453b-9a52-75cead564438
1
public void removeAll() { for (int i = 0; i < data.length; i++) { data[i][0] = null; data[i][1] = null; data[i][2] = null; data[i][3] = null; } }
d1feee40-6dd5-4d32-a8bc-2ef23f0c203b
7
@Override public void mouseClicked(MouseEvent me) { if ( this.window.isLocked() ) return; Coords coords = this.getCoords(me.getPoint()); if ( coords == null ) return; Color color = com.github.abalone.elements.Board.getInstance().elementAt(coords); if ( !color.isPlayer() ) return; else if(this.selectedBalls.contains(coords)) this.selectedBalls.remove(coords); else if ( this.selectedBalls.size() < 3 ) this.selectedBalls.add(coords); else return; this.repaint(); Set<Direction> directions; Set<Direction> validDirections = GameController.getInstance().validDirections(this.selectedBalls); if ( this.reversed ) { directions = new HashSet<Direction>(); for ( Direction d : validDirections ) directions.add(d.reversed()); } else directions = new HashSet<Direction>(validDirections); this.selector.updateButtons(directions); }
25316bad-51f0-4c0a-902d-7675f1184fb4
9
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub Convertors ut = new Convertors(); String args[]=ut.SplitRequestPath(request); response.setContentType("text/html"); //We are expecting /Math/Math/mult/1/2 or // /Math/Math/root/24 PrintWriter out=null; out = new PrintWriter(response.getOutputStream()); if (args.length <3){ error("Warning too few args",out); return; } int command; try{ command =(Integer)CommandsMap.get(args[2]); }catch(Exception et){ error("Bad Operator",out); return; } System.out.println("Cammand"+command); float x; float y; try{ x=Float.parseFloat(args[3]); y=Float.parseFloat(args[4]); }catch(Exception et){ error("Bad numbers in calc",out); return; } switch (command){ case 1: mult(x,y,out); break; case 2: div(x,y,out); break; case 3: add(x,y,out); break; case 4: sub(x,y,out); break; case 5: root(x,out); break; case 6: power(x,y,out); break; default: error("Bad Operator",out); } }
b466f5d0-abfb-4f2b-89f6-70b301105188
3
public Vec3D getIntermediateWithXValue(Vec3D var1, double var2) { double var4 = var1.xCoord - this.xCoord; double var6 = var1.yCoord - this.yCoord; double var8 = var1.zCoord - this.zCoord; if(var4 * var4 < 1.0000000116860974E-7D) { return null; } else { double var10 = (var2 - this.xCoord) / var4; return var10 >= 0.0D && var10 <= 1.0D?createVector(this.xCoord + var4 * var10, this.yCoord + var6 * var10, this.zCoord + var8 * var10):null; } }