method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
c91d12f8-2107-4c96-95f4-eb746ffa73cc
6
@Override public String log(Iterable<LogItem> items) throws Exception { for (BarItem item : this.items.values()) item.price = item.quantity = 0; for (LogItem item : items) { BarItem currentItem = this.items.get(item.barID); if (currentItem == null) throw new Exception("Item not found (ID=" + item.barID + ")."); currentItem.price += item.price; currentItem.quantity += item.quantity; } URL url = new URL("http://bar.eleves.polytechnique.fr/" + this.bar + "/new-provision/do"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes("login=" + this.login + "&p455w0rd=" + this.password + "&provimoney_0="); for (Entry<Integer, BarItem> entry : this.items.entrySet()) { int price = (int) entry.getValue().price; wr.writeBytes("&provimoney_" + entry.getKey() + "=" + (price / 100) + (price < 10 ? ".0" : ".") + (price % 100)); wr.writeBytes("&proviqty_" + entry.getKey() + "=" + myDblToString(entry.getValue().quantity)); wr.writeBytes("&proviqtybox_" + entry.getKey() + "=1"); } wr.writeBytes("&btn_provision=Valide ton appro !"); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); if (responseCode != 200) System.out.println("Response: " + responseCode); return null; }
66ef0057-9433-4d0c-bc19-2ce3a9f1110a
1
public void save() { try { this.yml.save(configFile); } catch (Exception e) { System.out.println("[BurningCS] Could not save config file!"); e.printStackTrace(); } }
65b33f7c-6b32-42ea-8e84-4d23e5e9eb68
4
protected boolean out_grouping_b(char [] s, int min, int max) { if (cursor <= limit_backward) return false; char ch = current.charAt(cursor - 1); if (ch > max || ch < min) { cursor--; return true; } ch -= min; if ((s[ch >> 3] & (0X1 << (ch & 0X7))) == 0) { cursor--; return true; } return false; }
f648a242-b2d7-41a1-9b55-7dc27573e0d2
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(TimeFrom.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(TimeFrom.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(TimeFrom.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TimeFrom.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 TimeFrom().setVisible(true); } }); }
7b3b0916-b870-4148-b402-7a6c2b7e805c
5
public JSONObject addCategoryAction(String UserID, String action, String ImageId, String TargetId, String targetValue) { try { Class.forName(JDBC_DRIVER); conn=DriverManager.getConnection(DB_URL,USER,PASS); stmt=conn.createStatement(); json=new JSONObject(); String SQL="insert into category_actions(user_id,action,image_id,target_id,target_value) values" + "('"+UserID+"','"+action+"','"+ImageId+"','"+TargetId+"','"+targetValue+"')"; json.put(SUCCESS, -1); json.put("error", SQL); int result=stmt.executeUpdate(SQL); if(result>0) { json.put(SUCCESS, 1); json.put("msg", "Successfully inserted data"); }else { json.put(SUCCESS, -1); json.put("error", SQL); } stmt.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { json.put("error1", e.getMessage()); e.printStackTrace(); } finally { try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); } } return(json); }
117c7579-5123-40da-a5ae-d5c19f6eb65e
4
public void loadTeleporters() { YamlConfiguration config = YamlConfiguration.loadConfiguration(teleportersFile); for (String teleporterName : config.getKeys(false)) { ConfigurationSection teleporterSection = config.getConfigurationSection(teleporterName); Teleporter teleporter = this.createTeleporter(teleporterName); for (String key : teleporterSection.getKeys(false)) { if (key.equals("Ziel")) continue; ConfigurationSection section = teleporterSection.getConfigurationSection(key); World world = Bukkit.getWorld(section.getString("World")); Location loc = new Location(world, section.getInt("X"), section.getInt("Y"), section.getInt("Z")); Block block = world.getBlockAt(loc); teleporter.addBlock(block); } //Ziel if (teleporterSection.contains("Ziel")) { Location zielLoc = new Location(Bukkit.getWorld(teleporterSection.getString("Ziel.World")), teleporterSection.getDouble("Ziel.X"), teleporterSection.getDouble("Ziel.Y"), teleporterSection.getDouble("Ziel.Z"), Float.parseFloat(teleporterSection.getString("Ziel.Yaw")), Float.parseFloat(teleporterSection.getString("Ziel.Pitch"))); teleporter.setZiel(zielLoc); } } }
47e65e66-833b-487f-8fb6-dd19d9e806c9
0
public void setTotalPoints(int total){ totalPoints.setText(Integer.toString(total)); }
8c084d8b-bae0-4112-9664-08328916caef
1
public List<String> getValues() { System.out.println("count cells in row: " + cells.size()); List<String> values = new ArrayList<String>(); for (TableCell cell : cells) { String text = cell.getText(); values.add(text); System.out.println(text); } return values; }
a84fbf9b-b770-403e-8e75-8c9418c1083b
3
public static boolean escribir(Map<String,Producto> array){ try{ BufferedWriter escribe=Files.newBufferedWriter(path, java.nio.charset.StandardCharsets.UTF_8, java.nio.file.StandardOpenOption.TRUNCATE_EXISTING); Iterator it=array.entrySet().iterator(); while(it.hasNext()){ Map.Entry e=(Map.Entry)it.next(); escribe.write(e.getKey()+";"+((Producto)e.getValue()).getDesc()+";"+((Producto)e.getValue()).getStock()+";"+((Producto)e.getValue()).getPrecio()); escribe.newLine(); } escribe.close();//si no no escribe pq? return true; }catch(InvalidPathException e){ System.out.println("Error en leer la ruta del fichero "+e); return false; } catch (IOException e) { e.printStackTrace(); return false; } }
f87851b1-afa1-4052-96b8-b3796cf96f79
5
public CharacterIcons(String getCharacter) { if (getCharacter.equals("White")) setImage(new GreenfootImage("CharacterIcons//FuShu.png")); else if (getCharacter.equals("Bond")) setImage(new GreenfootImage("CharacterIcons//JamesBond.png")); else if (getCharacter.equals("Ninja")) setImage(new GreenfootImage("CharacterIcons//Torato.png")); else if (getCharacter.equals("Mage")) setImage(new GreenfootImage("CharacterIcons//Gajiwala.png")); else if (getCharacter.equals("Ringer")) setImage(new GreenfootImage("CharacterIcons//MarkGreen.png")); }
014b9aca-fa5b-426f-9898-7f4c87c9b2d7
3
public static void insertSubnet(Subnet sub, SubnetData d){ SubnetData data; if (sub!=null) //call from the Rest Interface data = sub.getSubnet(); else //call from createMultiple data=d; //Recover the subnet object (from the Rest Interface) attributes String name = data.getName(); String n = data.getId(); String network = data.getNetwork_id(); String tenant = data.getTenant_id(); AllocationPools alPools = data.getAllocation_pools(); String gateway = data.getGateway_ip(); String ipversion = data.getIp_version(); //query- insert a subnet instance in the OWL knowledge base String queryString = "PREFIX base: <http://www.semanticweb.org/spalazzi/ontologies/2014/1/FedCoT#> "+ "PREFIX owl: <http://www.w3.org/2002/07/owl#/> "+ "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#/> "+ "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#/> "+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#/> "+ "PREFIX dul: <http://www.loa-cnr.it/ontologies/DUL.owl#/> "; for (int i=0; i<alPools.size(); i++) { Pool pool = alPools.get(i); queryString += "INSERT DATA " + "{" + " base:"+pool.getStart()+" rdf:type base:IPaddress;" + " }; "+ "INSERT DATA " + "{" + " base:"+pool.getEnd()+" rdf:type base:IPaddress;" + " }; "; } queryString += "INSERT DATA " + "{" + " base:"+tenant+" rdf:type base:Tenant;" + " }; "+ "INSERT DATA " + "{" + " base:"+gateway+" rdf:type base:IPaddress;" + " }; "+ "INSERT DATA " + "{" + " base:"+n+" rdf:type base:SubNet;" + " base:hasName '"+name+"';" + " base:hasOwner base:"+tenant+";" + " dul:isPartOf base:"+network+";"; for (int i=0; i<alPools.size(); i++) { Pool pool = alPools.get(i); queryString += " base:hasStartIPAddress base:"+pool.getStart()+";" + " base:hasEndIPAddress base:"+pool.getEnd()+";"; } queryString += " base:hasGatewayIP base:"+gateway+";" + " base:hasVersion '"+ipversion+"';" + " }"; ParliamentModel.updateQuery(queryString); }
6ad4d4eb-7b0c-4ad0-badd-38c04b3ca161
2
public void visitInnerClass(final String aname, final String outerName, final String innerName, final int attr_access) { if ((name != null) && name.equals(aname)) { this.access = attr_access; } super.visitInnerClass(aname, outerName, innerName, attr_access); }
7ea3e6e6-2887-4580-99cd-6dbcf2499d24
6
public User convertTxtFileToUserObjSixMonthData(String basePath, String directoryName, String fileName, String extension) throws FileNotFoundException, IOException { String userPostAsString = readTxtFileAsString(basePath, directoryName, fileName, extension); String temp[]; User user = new User(); List postList = new ArrayList(); user.setId(Integer.valueOf(fileName)); if (userPostAsString.contains(IOProperties.DATA_SEPERATOR)) { temp = userPostAsString.split(IOProperties.DATA_SEPERATOR); } else { temp = new String[1]; temp[0] = userPostAsString; } for (int i = 0; i < temp.length; i++) { if (temp[i].matches("[0-9]{2}:[0-9]{2}:[0-9]{2}") || temp[i].length() == 8) { temp[i] = temp[i] + " "; } Posts posts = new Posts(); String time = temp[i].substring(0, 8); String date = temp[i].substring(9, 19); if (time.matches("[0-9]{2}:[0-9]{2}:[0-9]{2}")) { String[] tempMonth = date.split("-"); String month = tempMonth[1]; int monthOfYear = Integer.parseInt(month); if (monthOfYear <= 6) { posts.setTime(time); posts.setDate(date); // posts.setContent(temp[i].substring(20, temp[i].length())); postList.add(posts); } //System.out.println(date); } else { continue; } } user.setUserPost(postList); return user; }
2f01a4a5-1322-432d-a779-9015f37c6fe5
2
public byte evaluate() { if(!type.hasLiteral()) { return type.getCode(); } else { assert(data.checkResolved()); if(hasNextWord()) { return type.getCode(); } else { assert(type == ValueType.LITERAL); return (byte)(0x20+data.getUnresolvedWord()); } } }
7066ac3b-83ab-41f1-97b7-0a267955711e
5
protected PathTraceMaterial nodeIsHomogeneous( SolidNode sn ) throws DereferenceException { if( sn.getType() == SolidNode.Type.HOMOGENEOUS ) return sn.getHomogeneousMaterial(); if( sn.getType() == SolidNode.Type.DENSITY_FUNCTION_SUBDIVIDED ) return null; // lets ignore this possibility for now Object o = nodeHomogeneityCache.get(sn); if( o == null ) { PathTraceMaterial m = regionIsHomogeneous( sn, 0, 0, 0, sn.getDivX(), sn.getDivY(), sn.getDivZ() ); nodeHomogeneityCache.put(sn, o = (m == null ? Boolean.FALSE : m)); } return o == Boolean.FALSE ? null : (PathTraceMaterial)o; }
ba8ed78c-153e-4fc0-81a8-8c0cfb081f67
8
private static int decode4to3( byte[] source, int srcOffset, byte[] destination, int destOffset, int options ) { // Lots of error checking and exception throwing if( source == null ){ throw new NullPointerException( "Source array was null." ); } // end if if( destination == null ){ throw new NullPointerException( "Destination array was null." ); } // end if if( srcOffset < 0 || srcOffset + 3 >= source.length ){ throw new IllegalArgumentException( String.format( "Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset ) ); } // end if if( destOffset < 0 || destOffset +2 >= destination.length ){ throw new IllegalArgumentException( String.format( "Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset ) ); } // end if byte[] DECODABET = getDecodabet( options ); // Example: Dk== if( source[ srcOffset + 2] == EQUALS_SIGN ) { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 ); destination[ destOffset ] = (byte)( outBuff >>> 16 ); return 1; } // Example: DkL= else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 ); destination[ destOffset ] = (byte)( outBuff >>> 16 ); destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 ); return 2; } // Example: DkLE else { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6) | ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) ); destination[ destOffset ] = (byte)( outBuff >> 16 ); destination[ destOffset + 1 ] = (byte)( outBuff >> 8 ); destination[ destOffset + 2 ] = (byte)( outBuff ); return 3; } } // end decodeToBytes
df5b45f0-ed7e-49ff-816a-1232c8ee3321
2
public int observe(int bytes) { if (observer != null && bytes != -1) { totalBytes += bytes; observer.bytesRead(totalBytes, clientId); } log.debug("Total Bytes Read = [" + totalBytes + "]"); return bytes; }
ea997464-823f-4738-851e-39cbfe7f35f1
0
public String toString(){ return "LU: " + ul.toString() + ", " + width + " x " + height; }
33a697a2-1d50-4572-85e1-e59efc3bf1cb
7
@Override public void fuse(Property property) throws PropertyException { if(property != null) { if(property.getClass().equals(getClass())) { MinMaxProperty prop = (MinMaxProperty) property; int newMin; if(min != UNDEFINED) { if(prop.getMin() != UNDEFINED) { newMin = Math.max(min, prop.getMin()); } else { newMin = min; } } else { newMin = prop.getMin(); } int newMax; if(max != UNDEFINED) { if(prop.getMax() != UNDEFINED) { newMax = Math.min(max, prop.getMax()); } else { newMax = max; } } else { newMax = prop.getMax(); } if(newMin > newMax) { throw new PropertyException(this, "Fuse with " +property +" leads to invalid values."); } // set new values only if all is fine min = newMin; max = newMax; } } throw new PropertyException(this, "Can not fuse with wrong type " +property); }
528bbbd6-7ebb-43e5-8ae6-29a590d8e27a
4
public void addVersions( BitSet bs ) { this.versions.or( bs ); for ( int i=0;i<cells.size();i++ ) { FragList fl = cells.get(i); for ( int j=0;j<fl.fragments.size();j++ ) { Atom a = fl.fragments.get(j); if ( a instanceof Fragment ) { Fragment f = (Fragment) a; if ( f.isEmpty() ) f.versions.or(bs); } } } }
8748397a-38c1-420e-9fa0-b365c3c3a43d
9
@Override public void run() { BufferedReader in = null; PrintWriter out = null; try { in = new BufferedReader(new InputStreamReader( this.socket.getInputStream())); out = new PrintWriter(this.socket.getOutputStream(), true); String currentTime = null; String body = null; while (true) { body = in.readLine(); if (body == null) { break; } System.out.println("The time server receive order: " + body); currentTime = "QUERY TIME".equalsIgnoreCase(body) ? new Date( System.currentTimeMillis()).toString() : "BAD ORDER"; out.println(currentTime); } } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (out != null) { out.close(); } if (this.socket != null) { try { this.socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
1125db5f-a596-476d-aa4a-859f004153ca
7
public int getMaxSum() { maxSum = Integer.MIN_VALUE; for (int rowStart = 0; rowStart < width; rowStart++) { for (int colStart = 0; colStart < width; colStart++) { for (int rowEnd = 0; rowEnd < width; rowEnd++) { for (int colEnd = 0; colEnd < width; colEnd++) { int sum = 0; for (int row = rowStart; row <= rowEnd; row++) { for (int col = colStart; col <= colEnd; col++) { sum += matrix[row][col]; } } if (sum > maxSum) { maxSum = sum; } } } } } return maxSum; }
94f0e142-aa96-4a73-9b34-80048e0966d8
9
public boolean isMoveable(String str) { for (Artifacts a : artList) { if(a.name.toUpperCase().equals(str)){ if (a.movability == 1) { return true; } return false; } } for (Keys k : keyList) { if (k.name.toUpperCase().equals(str)){ if (k.movability == 1) { return true; } return false; } } for (Lights l : lightList) { if (l.name.toUpperCase().equals(str)){ if (l.movability == 1) { return true; } return false; } } return false; }
b1e92bcc-0cc2-4965-bb59-465c6fb8b9f6
6
@Override public boolean equals(Object obj) { if (!obj.getClass().equals(Genotype.class)) return false; Genotype other = (Genotype) obj; if (this.generation != other.generation) return false; if (this.hiddenLayersCount != other.hiddenLayersCount) return false; // if (this.genes.equals(other.genes)) return false; if (this.genes.size() != other.genes.size()) return false; for (int i = 0; i < this.genes.size(); i++) { if (Math.abs(this.genes.get(i) - other.genes.get(i)) > 0.000000000000001) return false; } return true; }
278e07ad-6135-405c-b969-a95d25d96951
3
private void RegisterPlayer(Player player) { if (_currentPhase.equals(Phase.Registration)) { if (_registeredPlayers.contains(player)) { player.sendMessage("You have already registered for the games."); } else if (_registeredPlayers.size() < _maxRegistrations) { _registeredPlayers.add(player); player.sendMessage("You have successfully registered for the games."); ChatManager .sendMessageToServer( "GameMaker", String.format( "Tribute '%s' has registered themselves for the hunger games.", player.getName())); } } else { player.sendMessage("You are unable to register at this time. The Current Phase is " + _currentPhase.name()); } }
ac8fd3ee-aff4-48a1-80e8-a841a3911262
9
public boolean MovingBoxIntoBox(int x, int y){ if(map[y][x] != box){ return false; } //move box south if(y_loc+1 == y){ if(map[y+1][x] == box)System.out.println("box in the way"); return true; } //move box north if(y_loc-1 == y){ if(map[y-1][x] == box)System.out.println("box in the way"); return true; } //move box west if(x_loc-1 == x){ if(map[y][x-1] == box)System.out.println("box in the way"); return true; } //move box east if(x_loc+1 == x){ if(map[y][x+1] == box)System.out.println("box in the way"); return true; } return false; }
f480d99a-669b-4c5a-be91-72deba70189b
3
public static List<Mixer> getCompatibleMixers(Class<? extends Line> pLineClass) { Line.Info lineInfo = new Line.Info( pLineClass ); Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo(); List<Mixer> ret = new ArrayList<>(); for ( Mixer.Info info : mixerInfo ) { Mixer current = AudioSystem.getMixer( info ); if ( current.isLineSupported( lineInfo ) ) { ret.add( current ); } } return ret; }
f8087f2d-649b-4e9b-b271-85a373373fde
4
public void drawShakingText(String text, int x, int y, int colour, int elapsed, int tick) { if (text == null) return; /* * Calculate the current amplitude of the * shake based on how long the text has been * shaking for. */ double amplitude = 7D - elapsed / 8D; if (amplitude < 0.0D) amplitude = 0.0D; /* * Place half the text to the left of the * anchor point and half the text to the * right. This centres the text horizontally. */ x -= getTextWidth(text) / 2; /* * Draw text from the top-left instead of * the bottom. */ y -= fontHeight; /* * Iterate through the characters in the text. */ for (int c = 0; c < text.length(); c++) { char character = text.charAt(c); /* * If the character is a space we do not draw it, * but we still move the x position by the width * of the space. */ if (character != ' ') { /* * The vertical position of the text is decided based * on a sine wave, taking into account the current * time and the amount of time the text has been * shaking for. */ drawGlyph( glyphPixels[character], x + horizontalKerning[character], y + verticalKerning[character] + (int) (Math.sin(c / 1.5D + tick) * amplitude), glyphWidth[character], glyphHeight[character], colour); } x += glyphDisplayWidth[character]; } }
ff3571f9-6ad7-4826-9134-de79977d1845
9
public void destroyBody(Body body) { assert (m_bodyCount > 0); assert (isLocked() == false); if (isLocked()) { return; } // Delete the attached joints. JointEdge je = body.m_jointList; while (je != null) { JointEdge je0 = je; je = je.next; if (m_destructionListener != null) { m_destructionListener.sayGoodbye(je0.joint); } destroyJoint(je0.joint); } body.m_jointList = null; // Delete the attached contacts. ContactEdge ce = body.m_contactList; while (ce != null) { ContactEdge ce0 = ce; ce = ce.next; m_contactManager.destroy(ce0.contact); } body.m_contactList = null; Fixture f = body.m_fixtureList; while (f != null) { Fixture f0 = f; f = f.m_next; if (m_destructionListener != null) { m_destructionListener.sayGoodbye(f0); } f0.destroyProxy(m_contactManager.m_broadPhase); f0.destroy(); // TODO djm recycle fixtures (here or in that destroy method) } body.m_fixtureList = null; body.m_fixtureCount = 0; // Remove world body list. if (body.m_prev != null) { body.m_prev.m_next = body.m_next; } if (body.m_next != null) { body.m_next.m_prev = body.m_prev; } if (body == m_bodyList) { m_bodyList = body.m_next; } --m_bodyCount; // TODO djm recycle body }
0437646b-1fed-494d-9922-03b0142ec67f
0
DccManager(PircBot bot) { _bot = bot; }
83b6e8b6-fbc9-4def-8cdb-7300c124f380
9
public ListNode addTwoNumbers(ListNode l1, ListNode l2) { if (l1 == null) { return l2; } if (l2 == null) { return l1; } ListNode resultListNode = new ListNode(0); ListNode temp = new ListNode(0); resultListNode = temp; while (l1 != null || l2 != null || carrier != 0) { if (l1 == null && l2 == null) { ListNode lNode = new ListNode(carrier); temp.next = lNode; temp = lNode; carrier = 0; } else { ListNode lNode = calculate(l1, l2); temp.next = lNode; temp = lNode; } if (l1 != null) { l1 = l1.next; } if (l2 != null) { l2 = l2.next; } } return resultListNode.next; }
a0f28ae2-3b22-4edd-a0d9-ea07a557d65c
3
private boolean resquestIsLegal(String challenge, String validate, String seccode) { if (objIsEmpty(challenge)) { return false; } if (objIsEmpty(validate)) { return false; } if (objIsEmpty(seccode)) { return false; } return true; }
3c1894ec-a33f-4b7f-ba91-c100c2313465
0
public float getH() { return h; }
4fecf491-4149-4405-baf2-7526314cadc0
0
private void setUpgrade(Upgrade upgrade, BodyPart bodyPart){ bodyPart.addUpgrade(upgrade); upgrade.setUsed(true); }
65ff60db-9171-47d2-8222-2f4536eaaee4
8
public static ArrayList<Tile> getTileNeighbors(Tile t, Tile[][] tiles, int size){ ArrayList<Tile> neighbors = new ArrayList<>(); int xStartIndex = t.getX() - 1 < 0 ? 0 : -1; int xEndIndex = t.getX() + 1 >= size ? 0 : 1; int yStartIndex = t.getY() - 1 < 0 ? 0 : -1; int yEndIndex = t.getY() + 1 >= size? 0 : 1; for (int x = xStartIndex; x < xEndIndex + 1; x ++) for (int y = yStartIndex; y < yEndIndex + 1; y ++) if ( x == 0 && y == 0) continue; else neighbors.add(tiles[x + t.getX()][y + t.getY()]); return neighbors; }
8da63aa4-5df1-4b17-be35-5154986685d3
3
private static int rank_iterative(int[] N, int key) { int lo = 0; int hi = N.length - 1; while (lo <= hi) { int mid = findMidpoint(hi, lo); // find the midpoint if (key < N[mid]) { // the key is in the lower half so lower the upper bound hi = --mid; } else if (key > N[mid]) { // the key is in the upper half so raise the lower bound lo = ++mid; } else { return mid; } } return KEY_NOT_FOUND; }
9a5b065d-6439-4adb-a616-2aa0cb8d78ab
4
boolean deleteDirectory(File dir) { if (dir.exists()) { if (dir.isDirectory()) { for (File file : dir.listFiles()) { if (file.isDirectory()) { deleteDirectory(file); } else { file.delete(); } } } return dir.delete(); } else return false; }
d12abe82-8d07-4b99-87f4-96a3319b3456
9
static public Date toDate(String date, String time) { Date retVal = new Date(); if (date != null) { Date d = parseDate(date); Integer s = null; if (time != null) s = secPastMid(time); if (s == null || s < 0) s = secPastMid(); if (d != null && s != null) retVal = new Date(d.getTime() + s * 1000); } else if (time != null) { Integer s = secPastMid(time); if (s != null && s > 0) { String p = formatDate(DATE_FORMAT, retVal); Date d = parseDate(p); retVal = new Date(d.getTime() + s * 1000); } } return retVal; }
3026491c-9cc5-4b72-9c3d-230d56511677
4
public IRouteResult route(GenericNode from, GenericNode to) { // ways est une file qui contiendra tous les chemins possibles tandis que way est une pile qui contiendra un de ces mêmes chemins PriorityQueue ways = new PriorityQueue(); Stack way = new Stack(); // On y met le premier maillon way.push(new Element(from)); // Parcours des chemins while(!ways.empty()){ Stack tmpWay; tmpWay = (Stack) (ways.pop().getValue()); if(tmpWay.empty()){ } } GenericNode nodeTmp = from; List<GenericEdge> edges = nodeTmp.getEdges(); GenericEdge edgeMin = from.getEdges().get(0); for(int i = 1; i < edges.size(); i++){ if(comparator.compare(edges.get(i), edgeMin) < 0) edgeMin = edges.get(i); } way.push(new Element(edgeMin.getOther(nodeTmp))); return null; }
610ac980-4d2e-481e-944c-f9299ba9de7a
2
private void mergeFiles() throws FileNotFoundException { try (OutputStream outStream = new FileOutputStream( "monthlyDataFile.txt"); SequenceInputStream inputStream = new SequenceInputStream( fileStreams.elements());) { byte[] buffer = new byte[4096]; int numberRead = 0; while ((numberRead = inputStream.read(buffer)) != -1) { outStream.write(buffer, 0, numberRead); } } catch (IOException e) { System.out.println("Error reading/writing file"); } System.out.println("Created monthlyDataFile.csv " + "in your current folder"); }
8eb33edc-699d-4997-a99a-eadfe6a08d02
6
public InetAddress discoverHost (int udpPort, int timeoutMillis) { DatagramSocket socket = null; try { socket = new DatagramSocket(); broadcast(udpPort, socket); socket.setSoTimeout(timeoutMillis); DatagramPacket packet = discoveryHandler.onRequestNewDatagramPacket(); try { socket.receive(packet); } catch (SocketTimeoutException ex) { if (INFO) info("kryonet", "Host discovery timed out."); return null; } if (INFO) info("kryonet", "Discovered server: " + packet.getAddress()); discoveryHandler.onDiscoveredHost(packet, getKryo()); return packet.getAddress(); } catch (IOException ex) { if (ERROR) error("kryonet", "Host discovery failed.", ex); return null; } finally { if (socket != null) socket.close(); discoveryHandler.onFinally(); } }
4b8d4f71-1b2e-477f-b968-cd78c6c9ba9d
1
public void writeCBytesA(int len, byte buf[], int off) { // method441 for (int i = (len + off) - 1; i >= len; i--) { payload[offset++] = (byte) (buf[i] + 128); } }
816782ef-ba2b-4498-9ec8-6108b5a09c18
9
private static void showTrainingOptionsAndTrain( ) throws NumberFormatException, IOException { Restaurant restaurant = player.getRestaurant(); System.out.println("\tTrain worker:"); Chef chef = restaurant.getChef(); System.out.println("\t" + "1. Chef: " + chef.getName() + " " + chef.getSurname() + "\t\tExp: " + chef.getExperience() + "\t\tTrainging cost: " + chef.getCourseCost()); Barman barman = restaurant.getBarman(); System.out.println("\t" + "2. Barman: " + barman.getName() + " " + barman.getSurname() + "\tExp: " + barman.getExperience() + "\t\tTrainging cost: " + barman.getCourseCost()); int i = 3; for(Waiter w : restaurant.getWaiters()){ System.out.println("\t" + i + ". Waiter: " + w.getName() + " " + w.getSurname() + "\t\tExp: " + w.getExperience() + "\t\tTrainging cost: " + w.getCourseCost()); i++; } System.out.println("\t"+i+". Back"); Integer input = inputFromPlayer(6); Employee employee = null; switch (input) { case 1: employee = chef; break; case 2: employee = barman; break; case 3: employee = restaurant.getWaiters().get(0); break; case 4: employee = restaurant.getWaiters().get(1); break; case 5: employee = restaurant.getWaiters().get(2); break; case 6: break; default: break; } //Train worker if(employee != null){ if(restaurant.checkIfBudgetEnough(employee.getCourseCost())){ employee.raiseEmployeeExperience(); restaurant.setBudget(restaurant.getBudget()-employee.getCourseCost()); System.out.println("Experience increased!"); }else{ System.out.println("Not enough money."); } } }
76bb6f28-9f0a-487d-b31f-46ccb31a6ac4
2
public boolean showConfirmationDialog() { String name = answerSideManager.getAnswersName(); if (name != null && !name.equals("")) messageLabel.setText(name + ", правильно?"); else messageLabel.setText("Правильно?"); showDialog(); return isCorrect; }
d51962ff-fe15-445c-83c3-5953af5e419d
2
private void trimText() { if(textLimit > 0 && text.length() > textLimit) { text = text.substring(0, textLimit); resize(); } }
fca18047-f857-4b8f-bc3c-2a7d7355cb60
9
public static void main(String[] args) throws IOException { InputStream in = System.in; OutputStream out = System.out; ConChMode mode = ConChMode.UNSET; byte[] source = ConCh.Sigma94; byte[] codeabet = ConCh.C94; for (int index = 0; index < args.length; index++) { switch (args[index]) { case "-i": in = new FileInputStream(new File(args[++index])); break; case "-o": out = new FileOutputStream(new File(args[++index])); break; case "-e": mode = ConChMode.ENCODE; break; case "-d": mode = ConChMode.DECODE; break; case "--help": default: System.out.println("Invalid switch: " + args[index] + "\n" + "Usage: java -jar ConCh.jar " + "(-e | -d) " + "[ -o outputFile ] " + "[ -i inputFile ] " + "[--help]"); return; } } switch (mode) { case ENCODE: Main.copyTo(new ConChEncodeStream(source, codeabet, in), out); break; case DECODE: Main.copyTo(new ConChDecodeStream(source, codeabet, in), out); break; case UNSET: default: System.out.println("You must use -e or -d\n" + "Usage: java -jar ConCh.jar " + "(-e | -d) " + "[ -o outputFile ] " + "[ -i inputFile ] " + "[--help]"); return; } out.write('\n'); out.flush(); }
4f383534-239c-4348-9cc3-9560cb1dd717
9
AudioFormat createAudioFormat(int channels, long sampleRate) { switch(format) { case SoundFileType.FORMAT_PCM_S8: case SoundFileType.FORMAT_PCM_U8: return AudioFormats.pcm().channels(channels).rate(sampleRate).bitDepth(8); case SoundFileType.FORMAT_PCM_16: return AudioFormats.pcm().channels(channels).rate(sampleRate).bitDepth(16); case SoundFileType.FORMAT_PCM_24: return AudioFormats.pcm().channels(channels).rate(sampleRate).bitDepth(24); case SoundFileType.FORMAT_PCM_32: return AudioFormats.pcm().channels(channels).rate(sampleRate).bitDepth(32); case SoundFileType.FORMAT_FLOAT: return AudioFormats.floats().channels(channels).rate(sampleRate).set0DbfValue(1.0).bitDepth(32); case SoundFileType.FORMAT_DOUBLE: return AudioFormats.floats().channels(channels).rate(sampleRate).set0DbfValue(1.0).bitDepth(64); case SoundFileType.FORMAT_ULAW: case SoundFileType.FORMAT_ALAW: return AudioFormats.floats().channels(channels).rate(sampleRate).set0DbfValue(1.0).bitDepth(8); default: return null; } }
8bc73362-904e-416a-86dd-bd778e898865
3
public boolean attachPrevious(Linkable paramLinkable) { boolean b=false; if ((paramLinkable instanceof InstructionList)) { InstructionList localInstructionList = (InstructionList)paramLinkable; if (localInstructionList.getNextInstruction() == null) { localInstructionList.setNextInstruction(this); if ((paramLinkable instanceof Instruction)) this.prev = ((Instruction)localInstructionList); else { this.prev = null; } b = true; } } else { System.out.println("Instruction: Attempt to attach to an incompatible Linkable."); } return b; }
7ac2e374-864f-4b30-895a-6464dc45edd7
4
@Override public void onToggle(Key key, boolean pressed) { InputHandler input = InputHandler.getInstance(); if (pressed) { if (key == input.up) selectionUp(); if (key == input.down) selectionDown(); if (key == input.enter) buttons.get(pointer).press(); } }
c2c8fd50-2e13-4e76-9044-9ee6567d44c9
9
@Override public final String toString(String f) { StringBuilder buffer = new StringBuilder(); if (field == null || !field.equals(f)) { buffer.append(field); buffer.append(":"); } buffer.append("\""); int lastPos = -1; for (int i = 0 ; i < termArrays.length ; ++i) { Term[] terms = termArrays[i]; int position = positions[i]; if (i != 0) { buffer.append(" "); for (int j=1; j<(position-lastPos); j++) { buffer.append("? "); } } if (terms.length > 1) { buffer.append("("); for (int j = 0; j < terms.length; j++) { buffer.append(terms[j].text()); if (j < terms.length-1) buffer.append(" "); } buffer.append(")"); } else { buffer.append(terms[0].text()); } lastPos = position; } buffer.append("\""); if (slop != 0) { buffer.append("~"); buffer.append(slop); } return buffer.toString(); }
bcb6004d-d1b2-4239-98ec-bf5ada257cf8
3
public void addCommand(Command command){ List<Command> previousCommands = new ArrayList<Command>(); if(command.isSameCommand()){ commands.get(commands.size()-1).copyCommand(command); } for(Command com: commands){ if(command.compareCommandTo(com)==1){ previousCommands.add(com); } } commands.removeAll(previousCommands); commands.add(command); }
bd0a5666-4c5e-4557-be74-95052753e038
0
@Override public void setTmp(String value) { this.tmp = convertToHashMap(value); }
beaa2e13-054f-47d5-9ca3-697dfde80f63
3
private void updateCustomComponent() { resetFields(); actionListPanel.removeAll(); actionListPanel.add(actionComponents.get(rtsItem + actionListKeyword).get(0), BorderLayout.NORTH); actionListPanel.revalidate(); actionListPanel.repaint(); customPanel.removeAll(); ArrayList<JComponent> list = actionComponents.get(rtsItem + actionMode); for(int i=0; i < list.size(); i++) customPanel.add(list.get(i)); if((rtsItem + actionMode).equals("LineAdd BusStop")){ customPanel.add(new JTextField("Will be added after " + previousBusStopName)); if (removeDPanel == true){ customPanel.remove(dPanel); removeDPanel = false; } } // Updates the view of the customPanel with new components customPanel.revalidate(); customPanel.repaint(); }
193dd83c-5aa6-419e-85bd-5ebf2aca3ec6
8
public static void main (String[] args) throws IOException { int customPort = 0; int customWorkersNum = 0; try { if (args.length != 0) { customPort = Integer.parseInt(args[0]); customWorkersNum = Integer.parseInt(args[1]); } } catch (IndexOutOfBoundsException ignored) {} catch (NumberFormatException ignored) {} final Parameters serverParams = new Parameters((customPort == 0)?(9000):(customPort), (customWorkersNum == 0)?(8):(customWorkersNum)); final ThreadPool threadPool = new ThreadPool(serverParams); final AsynchronousServerSocketChannel ssc = AsynchronousServerSocketChannel.open(); ssc.bind(new InetSocketAddress(ADDRESS, serverParams.getPort()), serverParams.getBacklog()); System.out.println("Server is starting on port " + serverParams.getPort() + " with " + serverParams.getWorkersNum() + ((serverParams.getWorkersNum() == 1) ? " worker." : " workers.")); ssc.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() { @Override public void completed(AsynchronousSocketChannel result, Void attachment) { ssc.accept(null, this); threadPool.acceptRequest(result); } @Override public void failed(Throwable exc, Void attachment) { exc.printStackTrace(); } }); while (true) { try { Thread.sleep(1000); } catch (InterruptedException ignored) { return; } } }
b60a00fa-56d2-477d-80d6-5cbfebf524be
4
private boolean jj_3R_49() { if (jj_scan_token(LEFTB)) return true; if (jj_3R_9()) return true; if (jj_3R_9()) return true; if (jj_scan_token(RIGHTB)) return true; return false; }
136f4c1a-d68a-4cb9-b862-61ab063910c7
6
private void createRoutes(boolean heuristic) { fromNode.setDistTo(0); if (heuristic) { fromNode.setHeuristic(Math.sqrt(Math.pow((toNode.getxCoord() - fromNode.getxCoord()), 2) + Math.pow(toNode.getyCoord() - fromNode.getyCoord(), 2)) / 1000); } else { fromNode.setHeuristic(Math.sqrt(Math.pow((toNode.getxCoord() - fromNode.getxCoord()), 2) + Math.pow(toNode.getyCoord() - fromNode.getyCoord(), 2)) / (130000)); } edgeTo.put(fromNode, null); // relax vertices in order of distance from s pQueue.add(fromNode); while (!pQueue.isEmpty()) { Node v = (Node) pQueue.poll(); if (v.equals(toNode)) { break; } if (heuristic) { for (Edge e : graph.get(v)) { relaxDriveTime(e, v); } } else { for (Edge e : graph.get(v)) { relaxLength(e, v); } } } }
0b8fcdde-9470-46d2-8cd4-647e399f5804
3
@Override public void calcMove(int delta) { double currentTime = System.currentTimeMillis(); this.delta = delta; if (currentMove == MoveDir.MOVE_NULL) { if (currentTime - lastMoveChange >= waitTime) { lastMoveChange = currentTime; randomMove(); } } else { edgeCheck(); if (currentTime - lastMoveChange >= moveTime) { lastMoveChange = currentTime; setWait(); } } }
9b513d4f-8556-4239-ac2c-bbea7b495cf8
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(Empleado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Empleado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Empleado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Empleado.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 Empleado().setVisible(true); } }); }
7d5b6302-7956-46ed-88d8-a839206ae38e
5
public String executeDijkstra (String nodo) { StringBuilder buffer = new StringBuilder(); final String origen = nodo; int posicion = 0; int costeTotal = 0; // Se obtiene la posición donde se encuentra el nodo origen for (int i=0; i<grafo.size(); i++) { if (grafo.get(i).toString().equalsIgnoreCase(origen)) { posicion = i; } } // Se construye el grafo indicando el nodo origen construirGrafo(grafo.get(posicion)); // Se calculan los caminos mínimos para las asignaturas matriculadas for (int i= 0; i<matriculas.size(); i++) { String clase = matriculas.get(i); int contador = 0; while (!grafo.get(contador).toString().equalsIgnoreCase(clase)) { contador++; } Nodo claseMatriculada = grafo.get(contador); List<Nodo> path = calcularRutaNodo (claseMatriculada); for (int j=0; j<path.size();j++) { buffer.append(path.get(j)).append(" "); } buffer.append("CosteIda = ") .append(claseMatriculada.minDistancia) .append("\n"); costeTotal = costeTotal + claseMatriculada.minDistancia; } buffer.append("Coste Total = ") .append(costeTotal*2); System.out.println("Coste Total = " + costeTotal*2); return buffer.toString(); }
2db70168-fd80-4582-b0ab-0db9370aab05
7
private int buildZone(int x, int maxLength) { int t = random.nextInt(totalOdds); int type = 0; for (int i = 0; i < odds.length; i++) { if (odds[i] <= t) { type = i; } } switch (type) { case ODDS_STRAIGHT: return buildStraight(x, maxLength, false); case ODDS_HILL_STRAIGHT: return buildHillStraight(x, maxLength); case ODDS_TUBES: return buildTubes(x, maxLength); case ODDS_JUMP: return buildJump(x, maxLength); case ODDS_CANNONS: return buildCannons(x, maxLength); } return 0; }
da17f8a7-8d20-448a-b964-d22743595216
8
@Override public void unInvoke() { if(pathOut!=null) { if(currRoom==null) currRoom=CMLib.map().getRandomRoom(); if(theGroup!=null) for(int g=0;g<theGroup.size();g++) { final MOB M=theGroup.elementAt(g); M.tell(L("You are told that it's safe and released.")); currRoom.bringMobHere(M,false); CMLib.commands().postStand(M,true); CMLib.commands().postLook(M,true); } if(storage!=null) for(int s=0;s<storage.size();s++) storage.elementAt(s).destroy(); pathOut=null; currRoom=null; if(storage!=null) storage.clear(); storage=null; if(theGroup!=null) theGroup.clear(); theGroup=null; } super.unInvoke(); }
228dbcac-6990-4698-a90e-3ad541e32306
2
public Builder name(String receivedName) { if (receivedName == null || receivedName.equals("")) { log.warn("Wrong Name. receivedName ={}", name); throw new IllegalArgumentException("Name must be not null. Received value =" + receivedName); } this.name = receivedName; return this; }
1c8500b9-5026-4294-a4d7-28f68524b72c
0
public static void main(String[] args) { ObjectFoo foo1 = new ObjectFoo(); ObjectFoo foo2 = new ObjectFoo(); foo1.setFoo(new Boolean(false)); Boolean b = (Boolean)foo1.getFoo(); foo2.setFoo(new Integer(10)); Integer i = (Integer)foo2.getFoo(); ObjectFoo foo3 = new ObjectFoo(); foo3.setFoo(new Boolean(false)); String str = (String)foo3.getFoo(); /** * Exception in thread "main" java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.String at generics.ObjectFoo.main(ObjectFoo.java:32) */ }
a33820f8-9bc1-48f0-b6d0-63ee453c1cec
1
private boolean jj_3_67() { if (jj_scan_token(GREATER)) return true; return false; }
0a28d2c7-df94-4b75-90f3-20ddb24b434b
3
private void ordenar(){ int m = 0; int j = 0; for(int i = 0; i < individuos; ++i){ m = i; for(j = i+1; j < individuos; ++j){ if(aptitud[j] < aptitud[m]){ m = j; } } int tempAptitud = aptitud[i]; Cromosoma tempCromosoma = poblacion[i]; aptitud[i] = aptitud[m]; poblacion[i] = poblacion[m]; aptitud[m] = tempAptitud; poblacion[m] = tempCromosoma; } }
c0c0dcd0-752b-4f13-b6fe-801980b62809
2
public boolean deleteFile(String sPath) { flag = false; File file = new File(sPath); // 路径为文件且不为空则进行删除 if (file.isFile() && file.exists()) { file.delete(); flag = true; } return flag; }
a73b4f38-53d8-4c3e-a108-e201ca6ef158
5
@Override public boolean move(Player player, int[] position) { // Check if player is the currentPlayer if (player != currentPlayer) { if (currentPlayer == null) { player.message("Game Over!"); } else { player.message("Not your turn!"); } return false; } // Make the move boolean validMove = board.move(player, position); // Check if there are any winners Player winner = getWinner(); Player loser = getLoser(); if (winner != null) { winner.wonGame(board, this); loser.lostGame(board, this); endGame(); return validMove; } // Check if the board is full else if (board.isFull()) { // Game over System.out.println("Draw"); currentPlayer.drawGame(board, this); getNextPlayer(currentPlayer).drawGame(board, this); endGame(); return validMove; } // Check if player's move was successful. if (validMove) { // GOOD: Player's move was valid. Onto the next player. switchPlayer(); } // Ask the next current player to make their move promptPlayerForMove(currentPlayer); // Return return validMove; }
022a924d-1a4a-4830-a50e-742e0a9d3de1
5
private void testr(String userTyped) { errLvl = 0f; if (userTyped.equals("Ping")) outputField.setText("Pong"); else errLvl = errLvl + 1f; if (userTyped.equals("ping")) outputField.setText("Pong"); else errLvl = errLvl + 1f; if (userTyped.equals("Pong")) outputField.setText("Ping"); else errLvl = errLvl + 1f; if (userTyped.equals("pong")) outputField.setText("Ping"); else errLvl = errLvl + 1; if (errLvl >= 4) outputField.setText("No Custom Results Found, You typed " + userTyped + "."); }
2c74f9d6-516f-4ac8-b16c-aab3e5b87d45
5
public int generateDurability(int blockY) { int durability = baseDurability_; if (variance_ > 0) { // variance_ is a max +- adjustment range to add to the durability durability += Citadel.getRandom().nextInt() % (variance_ * 2 + 1); durability -= variance_; } if (yAdjustment_ < 0.00001 || yAdjustment_ > 0.00001) { // yAdjustment_ is a gradient +- adjustment as the block's // Y-value distances from 0. It is a float so the gradient // can be gradual. durability += (int)((float)blockY * yAdjustment_); } if (durability < minDurability_) { return minDurability_; } if (durability > maxDurability_) { return maxDurability_; } return durability; }
e0dec305-1e6e-4513-b9b7-d3e64dd95ed9
6
private Integer negaScout(Board board, Color current, Integer depth, Integer alpha, Integer beta) { if ( depth > 0 ) { Integer best = beta; for ( Move m : board.getPossibleMoves(current) ) { board.apply(m); Integer score = - negaScout(board, current.other(), depth - 1, -best, -alpha); if ( alpha < score && score < beta ) score = - negaScout(board, current.other(), depth - 1, -beta, -alpha); alpha = Math.max(alpha, score); if ( alpha >= beta ) return alpha; best = alpha + 1; board.revert(m); } return best; } else { return ( ( current == selfColor ) ? 1 : -1 ) * this.evaluateBoard(board, current); } }
5861d15d-15c0-4b46-8ef9-053d7e071bdb
8
public String execute() { StringBuilder sb = new StringBuilder(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); if ("json".equalsIgnoreCase(type)) { /* [{ statusCode: 200, method: 'GET', url: 'http://foo.com/index.html', bytes: 12422, start: '2009-03-15T14:23:00.000-0700', end: '2009-03-15T14:23:00.102-0700', timeInMillis: 102, requestHeaders: [{ name: 'Foo', value: 'Bar' }], responseHeaders: [{ name: 'Baz', value: 'Blah' }] },{ ... }] */ sb.append("["); for (Iterator<Entry> iterator = entries.iterator(); iterator.hasNext();) { Entry entry = iterator.next(); sb.append("{\n"); sb.append(" statusCode: ").append(entry.statusCode).append(",\n"); sb.append(" method: ").append(json(entry.method)).append(",\n"); sb.append(" url: ").append(json(entry.url)).append(",\n"); sb.append(" bytes: ").append(entry.bytes).append(",\n"); sb.append(" start: '").append(sdf.format(entry.start)).append("',\n"); sb.append(" end: '").append(sdf.format(entry.end)).append("',\n"); sb.append(" timeInMillis: ").append((entry.end.getTime() - entry.start.getTime())).append(",\n"); sb.append(" requestHeaders:["); jsonHeaders(sb, entry.requestHeaders); sb.append("],\n"); sb.append(" responseHeaders:["); jsonHeaders(sb, entry.responseHeaders); sb.append("]\n"); sb.append("}"); if (iterator.hasNext()) { sb.append(","); } } sb.append("]\n"); } else if ("xml".equalsIgnoreCase(type)) { /* <traffic> <entry statusCode="200" method="GET" url="http://foo.com/index.html" bytes="12422" start="2009-03-15T14:23:00.000-0700" end="2009-03-15T14:23:00.102-0700" timeInMillis="102"> <requestHeaders> <header name=""></header> </requestHeaders> <responseHeaders> <header name=""></header> </responseHeaders> </entry> </traffic> */ sb.append("<traffic>\n"); for (Entry entry : entries) { sb.append("<entry "); sb.append("statusCode=\"").append(entry.statusCode).append("\" "); sb.append("method=\"").append(json(entry.method)).append("\" "); sb.append("url=\"").append(xml(entry.url)).append("\" "); sb.append("bytes=\"").append(entry.bytes).append("\" "); sb.append("start=\"").append(sdf.format(entry.start)).append("\" "); sb.append("end=\"").append(sdf.format(entry.end)).append("\" "); sb.append("timeInMillis=\"").append((entry.end.getTime() - entry.start.getTime())).append("\">\n"); sb.append(" <requestHeaders>\n"); xmlHeaders(sb, entry.requestHeaders); sb.append(" </requestHeaders>\n"); sb.append(" <responseHeaders>\n"); xmlHeaders(sb, entry.responseHeaders); sb.append(" </responseHeaders>\n"); sb.append("</entry>\n"); } sb.append("</traffic>\n"); } else { /* 200 GET http://foo.com/index.html 12422 bytes 102ms (2009-03-15T14:23:00.000-0700 - 2009-03-15T14:23:00.102-0700) Request Headers - Foo => Bar Response Headers - Baz => Blah ================================================================ */ for (Entry entry : entries) { sb.append(entry.statusCode).append(" ").append(entry.method).append(" ").append(entry.url).append("\n"); sb.append(entry.bytes).append(" bytes\n"); sb.append(entry.end.getTime() - entry.start.getTime()).append("ms (").append(sdf.format(entry.start)).append(" - ").append(sdf.format(entry.end)).append("\n"); sb.append("\n"); sb.append("Request Headers\n"); for (Header header : entry.requestHeaders) { sb.append(" - ").append(header.name).append(" => ").append(header.value).append("\n"); } sb.append("Response Headers\n"); for (Header header : entry.responseHeaders) { sb.append(" - ").append(header.name).append(" => ").append(header.value).append("\n"); } sb.append("================================================================\n"); sb.append("\n"); } } clear(); return "OK," + sb.toString(); }
84c3b03c-8905-4470-9eea-7af089448778
8
@Override public AttributeValue getExampleAttributeValue(Example e) { int playerToken = e.getResult().currentTurn; int height = e.getBoard().height; // 6 int width = e.getBoard().width; // 7 int numTokensCountingFor = 3; // checking for 3 in a row int countOfTokensEncounteredVertically = 0; // counter // bottom index is (5, 0) for (int i = height - 1; i > -1; i--) { for (int j = 0; j < width; j++) { if (e.getBoard().boardArray[i][j] == playerToken) { // current player's tokens for (int k = i; k > -1; k--) { if (e.getBoard().boardArray[i][j] == e.getBoard().boardArray[k][j]) { countOfTokensEncounteredVertically++; } else { if (e.getBoard().boardArray[k][j] == 0) { // top of the connection of 3 tokens is empty unbound = true; } else { // since the continuity between tokens is // broken, stop break; } } } } } } if ((countOfTokensEncounteredVertically >= numTokensCountingFor) && (unbound)) { return affirm; } else { return nega; } }
b639a4e5-dff2-4d5d-b75a-7a353e0ad1fb
9
public int[][] up(int grid[][]) { score = 0; for (int xIndex = 0; xIndex < 4; xIndex++) { for (int yIndex = 3; yIndex > 0; yIndex--) { if (grid[yIndex - 1][xIndex] == 0) { for (int a = yIndex - 1; a < 3; a++) { grid[a][xIndex] = grid[a + 1][xIndex]; } grid[3][xIndex] = 0; } } for (int yIndex = 0; yIndex < 3; yIndex++) { if (grid[yIndex + 1][xIndex] == grid[yIndex][xIndex]) { score += grid[yIndex][xIndex]; grid[yIndex][xIndex] += grid[yIndex][xIndex]; grid[yIndex + 1][xIndex] = 0; } } for (int yIndex = 3; yIndex > 0; yIndex--) { if (grid[yIndex - 1][xIndex] == 0) { for (int a = yIndex - 1; a < 3; a++) { grid[a][xIndex] = grid[a + 1][xIndex]; } grid[3][xIndex] = 0; } } } return grid; }
a6eafc37-8d86-4c6f-b93a-aa8d9b17bc72
7
private void incrementTime() { second++; if (second > 59) { second = 0; minute++; if (minute > 59) { minute = 0; hour++; if ((minute != 0 || second != 0) && hour > 23) { hour = 0; } } } else if (second == 1 && hour == 24) { hour = 0; } }
00d3fc93-4677-413a-9959-7706bc4e3d17
4
@Override public void onPluginMessageReceived( String channel, Player player, byte[] message ) { DataInputStream in = new DataInputStream( new ByteArrayInputStream( message ) ); String task = null; try { task = in.readUTF(); } catch ( IOException e ) { e.printStackTrace(); } if ( task.equals( "GetVersion" ) ) { String name = null; try { name = in.readUTF(); } catch ( IOException e ) { } if ( name != null ) { Player p = Bukkit.getPlayer( name ); p.sendMessage( ChatColor.RED + "Bans - " + ChatColor.GOLD + BungeeSuiteBans.instance.getDescription().getVersion() ); } Bukkit.getConsoleSender().sendMessage( ChatColor.RED + "Bans - " + ChatColor.GOLD + BungeeSuiteBans.instance.getDescription().getVersion() ); BansManager.sendVersion(); } }
cc153c74-a772-4366-bf7c-0404919a343f
1
protected Texture load(String ref) throws IOException { if(ref.endsWith(".tga")) { return TextureLoader.getTexture("TGA", ResourceLoader.getResourceAsStream(System.getProperty("resources") + "/sprites/" + ref + ".tga")); } return TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream(System.getProperty("resources") + "/sprites/" + ref + ".png")); }
c387dfad-44ff-4a94-9be2-7463f07ed953
1
@Override public Converter put(String key, Converter value) { Converter v = super.put(key, value); if (v != null) { throw new IllegalArgumentException("Duplicate Converter for " + key); } return v; }
6e725e60-85cb-49d3-b709-3b20affbe46e
8
public void run(TriplesInputStream stream) throws IOException { while (true) { Triple next = stream.nextTriple(); if (next == null) { if (currentSubject != null) { handleSubject(currentSubject, currentProps, currentLinks); } return; } String s = next.getSubject(); // Try to url-decode the subject, errors allowed try { s = URLDecoder.decode(s, "utf8"); } catch (IllegalArgumentException e) { } // And simplify the namespaces s = URISimplifier.simplify(next.getSubject()); if (!s.equals(currentSubject)) { /* New subject, handle the current one before accumulate */ if (currentSubject != null) handleSubject(currentSubject, currentProps, currentLinks); currentSubject = s; currentProps.clear(); currentLinks.clear(); } if (next instanceof DataTriple) { DataTriple dt = (DataTriple)next; URISimplifier.simplify(dt); // System.out.println("SIMPLIFIED TRIPLE --> " + dt.getSubject()); currentProps.add(dt); } else { currentLinks.add((LinkTriple)next); } if (++processedTriples % 20000 == 0) { System.out.println("Processed " + processedTriples + " triples (current subject: " + currentSubject + ")"); // ((MergedInputStream)stream).debug(); // break; } } }
93772f9c-4cca-42df-b4b7-0bb2bfa05826
0
public String getNombre() { return nombre; }
13db75f7-1b15-4c32-8b85-a23e9edb6098
2
public void enqueue(TypeValue val, int prio) { QueueElement current = head; while (current.getNext() != null && current.getNext().getPrio() < prio) { current = current.getNext(); } QueueElement tmp = new QueueElement(val, prio); tmp.setNext(current.getNext()); current.setNext(tmp); }
25025093-135b-4f53-a4f5-b86d1701f172
1
public void accept(final MethodVisitor mv) { AbstractInsnNode insn = first; while (insn != null) { insn.accept(mv); insn = insn.next; } }
1832c89b-afff-4e0b-a241-7ca174e96810
6
public int offset(int i) { switch (npcs[i].npcType) { case 50: return 2; case 2881: case 2882: return 1; case 2745: case 2743: return 1; case 8133: return 3; } return 0; }
d0a0d02d-308b-47b4-b3fd-a8dbb815d676
6
private void decoderChar(char c1,char c2,char[][] c) { int t11; int t12; int t21; int t22; this.chercheTab(c, c1); t11=this.i1; t12=this.i2; this.chercheTab(c, c2); t21=this.i1; t22=this.i2; if(t11==t21) { if(t12==0) { this.t1=c[t11][4]; } else{ this.t1=c[t11][(t12-1)%5]; } if(t22==0) { this.t2=c[t21][4]; } else { this.t2=c[t21][(t22-1)%5]; } } else { if(t12==t22) { if(t11==0) { this.t1=c[4][t12]; } else { this.t1=c[(t11-1)%5][t12]; } if(t21==0) { this.t2=c[4][t22]; } else { this.t2=c[(t21-1)%5][t22]; } } else { this.t1=c[t11][t22]; this.t2=c[t21][t12]; } } }
31ecda45-1728-41ad-b450-67d5c4c52e98
1
private void replyFile(String path) throws Exception { path = path.replace('/', File.separatorChar); File file = new File(path); if (!file.exists()) { System.err.println("File \"" + path + "\" not found"); return; } System.err.println("File \"" + path + "\" found and sent"); // FileInputStream in = new FileInputStream(file); // String head = "HTTP/1.0 200 OK\r\n"; // head += "Content-type: " + "image/png" + "\r\n"; // head += "Content-Length: " + file.length() + "\r\n"; // OutputStream out = connection.getOutputStream(); // out.write(head.getBytes()); // byte[] buf = new byte [4096]; int i; // while ((i = in.read(buf)) > 0) // out.write(buf, 0, i); // in.close(); PrintWriter out = new PrintWriter(connection.getOutputStream()); BufferedOutputStream dataOut = new BufferedOutputStream(connection.getOutputStream()); int fileLength = (int)file.length(); byte[] fileData = new byte[fileLength]; FileInputStream fileIn = new FileInputStream(file); fileIn.read(fileData); fileIn.close(); //send HTTP headers out.println("HTTP/1.0 200 OK"); out.println("Server: Java HTTP Server 1.0"); // out.println("Content-type: " + "image/png"); out.println("Content-length: " + file.length()); out.println(); //blank line between headers and content out.flush(); //flush character output stream buffer dataOut.write(fileData,0,fileLength); //write file dataOut.flush(); //flush binary output stream buffer out.close(); dataOut.close(); connection.close(); }
1bd2a4e5-fe91-40c7-bd9a-2ab458c84627
1
public void checkProduction(Production production) { if (!ProductionChecker.isRightLinear(production)) throw new IllegalArgumentException( "The production is not right linear."); }
5acaa46c-073b-4d82-9c4a-0fa82b572d38
3
public FlowGraph(final MethodEditor method) { this.method = method; subroutines = new HashMap(); catchBlocks = new ArrayList(method.tryCatches().size()); handlers = new HashMap(method.tryCatches().size() * 2 + 1); trace = new LinkedList(); srcBlock = newBlock(); iniBlock = newBlock(); snkBlock = newBlock(); trace.add(iniBlock); // If this method is empty(!) just make some default cfg edges if (method.codeLength() == 0) { addEdge(srcBlock, iniBlock); addEdge(iniBlock, snkBlock); addEdge(srcBlock, snkBlock); buildSpecialTrees(null, null); return; } final Map labelPos = new HashMap(); buildBlocks(labelPos); removeUnreachable(); // Make sure any labels in the removed blocks are saved. saveLabels(); if (FlowGraph.DEBUG || FlowGraph.DB_GRAPHS) { System.out.println("---------- After building tree:"); print(System.out); System.out.println("---------- end print after building tree"); } }
3fc0e8a5-cc6f-4af9-8e42-487a7845fa5d
1
public File getFile() { JFileChooser fc = new JFileChooser(); int result = fc.showOpenDialog(new JFrame()); File sendfile; if (result == JFileChooser.APPROVE_OPTION) { sendfile = fc.getSelectedFile(); filename = sendfile.getAbsolutePath(); filesize = (int)sendfile.length(); jLabel1.setText("傳送檔案" + filename); jLabel2.setText("大小: "+filesize+" bytes"); jLabel3.setText("等待對方接收..."); return sendfile; } else return null; }
3f55c892-c3ab-446e-aa63-d50f011038af
1
private int[] getArrayForHuffman() { String resultDecompression = huffman.getResultDecompress(); char array[] = resultDecompression.toCharArray(); arrayForHuffman = new int[array.length]; int i = 0; int temp = 0; for (char symbol : array) { temp = (int)symbol - 150; arrayForHuffman[i++] = temp; } return arrayForHuffman; }
d34351cd-ddb4-4651-b371-52862832198b
4
public double standardizedPersonRange(int index){ if(!this.dataPreprocessed)this.preprocessData(); if(index<1 || index>this.nPersons)throw new IllegalArgumentException("The person index, " + index + ", must lie between 1 and the number of persons," + this.nPersons + ", inclusive"); if(!this.variancesCalculated)this.meansAndVariances(); return this.standardizedPersonRanges[index-1]; }
25d408b6-fe62-47e5-9abb-c2be692dceb1
3
public void compare() { // could not find the new generated pdf document if(pdfInfoHolder.getDifferent() == DifferenceType.MISSINGDOCUMENT) { missingDocument(pdfInfoHolder.getPDF1()); return; } PDFFile pdf1 = pdfInfoHolder.getPDF1(); PDFFile pdf2 = pdfInfoHolder.getPDF2(); // find all differences on all pages for (int i = 1; i <= pdf1.getNumPages(); i++) { // get the current page PDFPage pagePDF1 = pdf1.getPage(i); PDFPage pagePDF2 = pdf2.getPage(i); // missing a page if(pagePDF2 == null) { missingPage(pagePDF1, i); continue; } // find real visual differences findVisualDifferences(i, pagePDF1, pagePDF2, targetFolder); } // if there is a difference on one of the // pages mark the entire pdf as different pdfInfoHolder.checkDifference(); }
3cd5238c-1fe2-4bfa-ba54-ff45d6676ea1
4
@SuppressWarnings("unused") public boolean outputToFile(String strDirectory, int[] objSave, String strFileName, String[] strStatistics) throws Exception { try { File fObjSave = new File(strDirectory); String strSaved = ""; if(strStatistics != null) { strSaved = "Statistics:\r\n"; strSaved += (strStatistics[0] + "\r\n"); strSaved += (strStatistics[1] + "\r\n"); strSaved += (strStatistics[2] + "\r\n"); strSaved += "Sorted List: \r\n"; } for(int i = 0; i < objSave.length; i ++) { if(i < objSave.length - 1) { strSaved += objSave[i] + ","; } else { strSaved += objSave[i]; } } return false;//writeObject(strFileName, strSaved, fObjSave); } catch (Exception e) { throw e; } }
6e21fa5b-e696-47b1-bb68-38de65136cdf
5
public String readSQL() throws FileNotFoundException{ String resultSql = ""; System.out.println("[INFO]Begin to get SQL from ["+this.sqlFileName+"]"); FileReader fr; try { String sql = ""; fr = new FileReader(new File(sqlFolderPath+sqlFileName)); BufferedReader br = new BufferedReader(fr); while((sql = br.readLine()) != null){ if(sql.isEmpty()){ continue; }else{ resultSql +=sql + "\t"; } } if(br != null && fr != null){ br.close(); fr.close(); } } catch (IOException e) { e.printStackTrace(); } return resultSql; }
70d93b8b-2db9-4fbf-b82d-d4b6b1be857a
1
public static double absVolumeError(double[] obs, double[] sim) { sameArrayLen(obs, sim); double volError = 0; for (int i = 0; i < sim.length; i++) { volError += sim[i] - obs[i]; } return Math.abs(volError); }
d2a5a384-9cfe-4aa3-8682-20f7e6dc206e
6
private double average_efficient(String measure) { int type = get_type(measure); if (type == RATE_BASED) { if (trans_time < 0.0) { trans_time = 0.0; } if (end_time < 0.0) { // Method called at run time return ((double)((Long)data.get(measure)).longValue())/(Sim_system.sim_clock()-trans_time); } else { // Method called after run has completed return ((double)((Long)data.get(measure)).longValue())/(end_time-trans_time); } } else if (type == STATE_BASED) { double[] values = (double[])((Object[])data.get(measure))[0]; if (values[1] == 0.0) { return 0.0; } else { return values[0]/values[1]; } } else { double[] values = (double[])((Object[])data.get(measure))[0]; if (values[3] == 0.0) { return 0.0; } else { return values[0]/values[3]; } } }
da962d69-0ded-45bf-98e2-f1d71b16f5cf
8
private int[] alphaBetaPrunning(int depth, Board b, int alpha, int beta,String player, int bestRow, int bestCol, int score) { if(cutoff(b, depth)) { //need to get score and row and column of move score = evaluate(b); return new int[] {score, bestRow, bestCol }; } //children = all valid moves for this player ArrayList<Board> children = b.generateSuccesors(b, player); //this is max's turn if(player == "X") { //Iterate through the children board for(int i = 0; i < children.size(); i++) { bestRow = children.get(0).getNewMove()[0]; bestCol = children.get(0).getNewMove()[1]; int[] bestMove = alphaBetaPrunning(depth-1, children.get(i), alpha, beta, "O", bestRow, bestCol, score); score = bestMove[0]; //if(score > alpha) alpha = score //if(bestMove[0] > alpha[0]) { alpha = bestMove; }; if(score > alpha ) { alpha = score; bestRow = bestMove[1]; System.out.println("score > alpha executes"); bestCol = bestMove[2]; } if(alpha >= beta) break; } } //opponent's turn else { //Iterate through the children board for(int i = 0; i < children.size(); i++) { bestRow = children.get(i).getNewMove()[0]; bestCol = children.get(i).getNewMove()[1]; int[] bestMove = alphaBetaPrunning(depth-1, children.get(i), alpha, beta, "X", bestRow, bestCol, 0); score = bestMove[0]; //if(score > alpha) alpha = score //if(bestMove[0] > alpha[0]) { alpha = bestMove; }; if(score < beta ) { beta = score; bestRow = bestMove[1]; bestCol = bestMove[2]; } if(alpha >= beta) break; } } return new int[] {score, bestRow, bestCol }; }
d7d1ece0-7d64-4a34-b6c8-a76347c1a921
9
static long function(long i, long j){ if(mem[(int)i][(int)j]>0)return mem[(int)i][(int)j]; if(i==n&&j==1)return an1; if(i<j){ long max = 0; for (long k = i; k < j; k++) max = Math.max(max, function(i, k) + function(k+1, j)); return mem[(int)i][(int)j] = max; } else{ long num = 0, num1 = 0; if(i<n) for (long k = i+1; k <= n; k++) num = Math.max(function(k,1) + function(k,j), num); else num = 0; if(j > 0) for (long k = 1; k < j; k++) num1 = Math.max(function(i,k) + function(n,k), num1); else num1 = 0; return mem[(int)i][(int)j] = num + num1; } }
c0828724-fe57-4127-8c73-3ba6a82fbf85
0
public String getCiudad() { return ciudad; }
0aea3fa9-920f-4a62-919c-100db232e75f
2
public void InsertaFinal(int ElemInser) { if ( VaciaLista()) { PrimerNodo = new NodosProcesos (ElemInser); PrimerNodo.siguiente = PrimerNodo; } else { NodosProcesos Aux = PrimerNodo; while (Aux.siguiente != PrimerNodo) Aux = Aux.siguiente; NodosProcesos Nuevo=new NodosProcesos (ElemInser); Aux.siguiente = Nuevo; Nuevo.siguiente = PrimerNodo; //Referencia hacia primer Nodo } }
3bf290b0-8bd8-4ba3-a983-0d4c3a218b3c
5
public int checkExam(Exam originalExam, Exam answeredExam) { assert (originalExam.getId().equals(answeredExam.getId())); int correctAnswers = 0; if (answeredExam.getQuestions() == null || answeredExam.getQuestions().isEmpty()) { return correctAnswers; } Map<String, Question> answeredQuestions = new HashMap<>(); answeredExam.getQuestions().stream().forEach(q -> answeredQuestions.put(q.getId(), q)); for (Question originalQuestion : originalExam.getQuestions()) { Question answeredQuestion = answeredQuestions.get(originalQuestion.getId()); if (answeredQuestion != null && checkQuestion(originalQuestion, answeredQuestion)) { correctAnswers += 1; } } return correctAnswers; }
ff3bb37b-5728-450c-abea-961302c1d8bc
0
@Test public void runTestRegisterGlobal2() throws IOException { InfoflowResults res = analyzeAPKFile("Callbacks_RegisterGlobal2.apk"); Assert.assertNotNull(res); Assert.assertEquals(1, res.size()); }