method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
13fc6888-9c3b-4568-8ed4-a5d33043661f
4
public String getHeader() { StringBuffer buffer = new StringBuffer(); String outputEncoding = this.outputEncoding; if ( outputEncoding == null ) { outputEncoding = "UTF-8"; } // header buffer .append( "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" ) .append( "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"" ).append( locale ) .append( "\" lang=\"" ).append( locale ).append( "\">\n" ).append( "<head>\n" ) .append( "<meta http-equiv=\"content-type\" content=\"text/html; charset=" ).append( outputEncoding ) .append( "\" />\n" ); // title ("classname xref") buffer.append( "<title>" ); try { JavaFile javaFile = fileManager.getFile( this.getCurrentFilename() ); // Use the name of the file instead of the class to handle inner classes properly if ( javaFile.getClassType() != null && javaFile.getClassType().getFilename() != null ) { buffer.append( javaFile.getClassType().getFilename() ); } else { buffer.append( this.getCurrentFilename() ); } buffer.append( " " ); } catch ( IOException e ) { e.printStackTrace(); } finally { buffer.append( "xref</title>\n" ); } // stylesheet link buffer.append( "<link type=\"text/css\" rel=\"stylesheet\" href=\"" ).append( this.getPackageRoot() ) .append( STYLESHEET_FILENAME ).append( "\" />\n" ); buffer.append( "</head>\n" ).append( "<body>\n" ).append( this.getFileOverview() ); // start code section buffer.append( "<pre>" ); //Remove a new line to facilitate styling return buffer.toString(); }
48f64a07-0b39-4fb4-8570-af4386fbecb9
4
private void updateOptions() { options = new ArrayList(); try { options.add(getIndoorText()); options.add(getOutdoorText()); } catch(DataFormatException e) { //JOptionPane.showMessageDialo(frame,"input error",e.getMessage()); } BookingOptions[] tempOptions = new BookingOptions[2]; try { tempOptions[0]=getIndoorText(); } catch (DataFormatException ex) { Logger.getLogger(OptionsGui.class.getName()).log(Level.SEVERE, null, ex); } try { tempOptions[1]=getOutdoorText(); } catch (DataFormatException ex) { Logger.getLogger(OptionsGui.class.getName()).log(Level.SEVERE, null, ex); } try { bom.updateAll(tempOptions); } catch (SQLException ex) { Logger.getLogger(OptionsGui.class.getName()).log(Level.SEVERE, null, ex); } }
902e31f9-950a-4791-96a0-740e9db1b8cb
0
public void close() { terminer = true; }
28b73a7c-0333-4aa1-9486-ddb508b07009
5
public String explainScore(StringWrapper s, StringWrapper t) { BagOfSourcedTokens sBag = (BagOfSourcedTokens) s; BagOfSourcedTokens tBag = (BagOfSourcedTokens) t; StringBuilder buf = new StringBuilder(""); PrintfFormat fmt = new PrintfFormat("%.3f"); buf.append("Common tokens: "); for (Iterator<Token> i = sBag.tokenIterator(); i.hasNext();) { Token sTok = i.next(); Token tTok = null; if ((tTok = tBag.getEquivalentToken(sTok))!=null) { buf.append(" " + sTok.getValue() + ": "); buf.append(fmt.sprintf(sBag.getWeight(sTok))); buf.append("*"); buf.append(fmt.sprintf(tBag.getWeight(tTok))); } else { // find best matching token double matchScore = tokenMatchThreshold; Token matchTok = null; for (Iterator<Token> j = tBag.tokenIterator(); j.hasNext();) { Token tokJ = j.next(); double distItoJ = tokenDistance.score(sTok.getValue(), tokJ.getValue()); if (distItoJ >= matchScore) { matchTok = tokJ; matchScore = distItoJ; } } if (matchTok != null) { buf.append(" '" + sTok.getValue() + "'~='" + matchTok.getValue() + "': "); buf.append(fmt.sprintf(sBag.getWeight(sTok))); buf.append("*"); buf.append(fmt.sprintf(tBag.getWeight(matchTok))); buf.append("*"); buf.append(fmt.sprintf(matchScore)); } } } buf.append("\nscore = " + score(s, t)); return buf.toString(); }
73f6abba-9578-49d6-908f-8364019ac178
7
private boolean validateBsDate(int bsYear, int bsMonth, int bsDayOfMonth) { if (bsYear < lookupNepaliYearStart) { throw new CustomerDiedException(); } else if (bsYear > (lookupNepaliYearStart + monthDays.size() - 1)) { throw new CustomerYetToBornException(); } if (lookupNepaliYearStart <= bsYear && bsYear <= (lookupNepaliYearStart + monthDays.size() - 1)) { logger.debug("debug: converter supports year " + bsYear); if (bsMonth >= 1 && bsMonth <= 12) { logger.debug("debug: month between 1 and 12"); int dayOfMonth = monthDays.get(getLookupIndex(bsYear))[bsMonth - 1]; logger.debug("debug:total days in month " + dayOfMonth); if (bsDayOfMonth <= dayOfMonth) { return true; } else { logger.warn("invalid day of month " + bsDayOfMonth + " for year " + bsYear + " and month " + bsMonth); throw new InvalidBsDayOfMonthException( "invalid day of month " + bsDayOfMonth + " for year " + bsYear + " and month " + bsMonth); } } } return false; }
eb0195ad-0e99-46ee-b48a-bdea6fc5ae79
4
void readSetDesktopName(int x, int y, int w, int h) { String name = is.readString(); if (x != 0 || y != 0 || w != 0 || h != 0) { vlog.error("Ignoring DesktopName rect with non-zero position/size"); } else { handler.setName(name); } }
92ad745a-0567-4925-8531-c83fd9611122
7
public static Instances clusterInstances(Instances data) { XMeans xmeans = new XMeans(); Remove filter = new Remove(); Instances dataClusterer = null; if (data == null) { throw new NullPointerException("Data is null at clusteredInstances method"); } //Get the attributes from the data for creating the sampled_data object ArrayList<Attribute> attrList = new ArrayList<Attribute>(); Enumeration attributes = data.enumerateAttributes(); while (attributes.hasMoreElements()) { attrList.add((Attribute) attributes.nextElement()); } Instances sampled_data = new Instances(data.relationName(), attrList, 0); data.setClassIndex(data.numAttributes() - 1); sampled_data.setClassIndex(data.numAttributes() - 1); filter.setAttributeIndices("" + (data.classIndex() + 1)); data.remove(0);//In Wavelet Stream of MOA always the first element comes without class try { filter.setInputFormat(data); dataClusterer = Filter.useFilter(data, filter); String[] options = new String[4]; options[0] = "-L"; // max. iterations options[1] = Integer.toString(noOfClassesInPool - 1); if (noOfClassesInPool > 2) { options[1] = Integer.toString(noOfClassesInPool - 1); xmeans.setMinNumClusters(noOfClassesInPool - 1); } else { options[1] = Integer.toString(noOfClassesInPool); xmeans.setMinNumClusters(noOfClassesInPool); } xmeans.setMaxNumClusters(data.numClasses() + 1); System.out.println("No of classes in the pool: " + noOfClassesInPool); xmeans.setUseKDTree(true); //xmeans.setOptions(options); xmeans.buildClusterer(dataClusterer); System.out.println("Xmeans\n:" + xmeans); } catch (Exception e) { e.printStackTrace(); } //System.out.println("Assignments\n: " + assignments); ClusterEvaluation eval = new ClusterEvaluation(); eval.setClusterer(xmeans); try { eval.evaluateClusterer(data); int classesToClustersMap[] = eval.getClassesToClusters(); //check the classes to cluster map int clusterNo = 0; for (int i = 0; i < data.size(); i++) { clusterNo = xmeans.clusterInstance(dataClusterer.get(i)); //Check if the class value of instance and class value of cluster matches if ((int) data.get(i).classValue() == classesToClustersMap[clusterNo]) { sampled_data.add(data.get(i)); } } } catch (Exception e) { e.printStackTrace(); } return ((Instances) sampled_data); }
c1a9c47b-2c0f-4189-badf-b703fde7f80f
4
protected Dimension computeLayoutSize(Container parent, int hp, int vp) { if (!validWidths) return null; Component[] components = parent.getComponents(); int preferredWidth = 0, preferredHeight = 0; widths = new int[COLUMNS]; heights = new int[components.length / COLUMNS]; // System.out.println("Grid: " + widths.length + ", " + heights.length); int i; // Pass One: Compute largest widths and heights. for (i=0; i<components.length; i++) { int row = i / widthPercentages.length; int col = i % widthPercentages.length; Component c = components[i]; Dimension d = c.getPreferredSize(); widths[col] = Math.max(widths[col], d.width); heights[row] = Math.max(heights[row], d.height); } // Pass two: agregate them. for (i=0; i<widths.length; i++) preferredWidth += widths[i] + hp; for (i=0; i<heights.length; i++) preferredHeight += heights[i] + vp; // Finally, pass the sums back as the actual size. return new Dimension(preferredWidth, preferredHeight); }
ab915794-6b7c-48ea-9b70-fc465107b8f9
3
private void showWinners() { if (posFido >= tracksize -1) { System.out.println("Fido Wins!"); } if (posSpot >= tracksize -1) { System.out.println("Spot Wins!"); } if (posRover >= tracksize -1) { System.out.println("Rover Wins!"); } }
a3081d26-6a11-4aa5-9e71-a18b5e06fcc8
0
public void setPrice(String price) { this.price = price; }
b655481a-9a5d-4817-beaa-e453fbb02d40
7
protected synchronized void buildClassifiers(final Instances data) throws Exception { for (int i = 0; i < m_Classifiers.length; i++) { if (m_numExecutionSlots > 1) { final Classifier currentClassifier = m_Classifiers[i]; final int iteration = i; Runnable newTask = new Runnable() { public void run() { try { if (m_Debug) { System.out.println("Training classifier (" + (iteration +1) + ")"); } currentClassifier.buildClassifier(data); if (m_Debug) { System.out.println("Finished classifier (" + (iteration +1) + ")"); } completedClassifier(iteration, true); } catch (Exception ex) { ex.printStackTrace(); completedClassifier(iteration, false); } } }; // launch this task m_executorPool.execute(newTask); } else { m_Classifiers[i].buildClassifier(data); } } if (m_numExecutionSlots > 1 && m_completed + m_failed < m_Classifiers.length) { block(true); } }
36ded91c-b367-4a56-af0a-48912c43bbd5
7
@Override public MailPiece parsePostalItemData(String data) { final MailPiece piece = new MailPiece(); for(int i=0;i<5;i++) { final int x=data.indexOf(';'); if(x<0) { Log.errOut("StdPostman","Man formed postal data: "+data); return null; } switch(i) { case 0: piece.from = data.substring(0, x); break; case 1: piece.to = data.substring(0, x); break; case 2: piece.time = data.substring(0, x); break; case 3: piece.cod = data.substring(0, x); break; case 4: piece.classID = data.substring(0, x); break; } data=data.substring(x+1); } piece.xml = data; return piece; }
f4696196-32f6-4463-864f-8b7c5596754d
1
public List<String> getLines() { synchronized (lines) { if (line.length() > 0) { addLine(); } return new ArrayList<String>(lines); } }
fa34c47f-8582-4c50-af93-8af7a1508bdc
1
public void interrupt() { Thread t = threadVar.get(); if (t != null) { t.interrupt(); } threadVar.clear(); }
5ae45dae-01db-4bef-88f3-2a5daf46e4df
7
public void importFunctions() { File f = Tools.showOpenDialog("Importer"); if (f != null) { String ext = f.getName().substring(f.getName().length() - 3, f.getName().length()); if (ext.compareTo("txt") != 0) JOptionPane.showMessageDialog( null, Tools.getLocalizedString("ERROR_IMPORT") + " " + f.getName() + " " + Tools.getLocalizedString("ERROR_IMPORT2"), Tools.getLocalizedString("ERROR"), JOptionPane.ERROR_MESSAGE); else { String functions = ""; try { BufferedReader br = new BufferedReader(new FileReader(f)); String line = br.readLine(); while (line != null) { functions += line + ";"; line = br.readLine(); } isChanged = false; br.close(); functions = functions.substring(0, functions.length() - 1); } catch (FileNotFoundException e) { System.err.println(e.getMessage()); } catch (IOException e) { System.err.println(e.getMessage()); } catch (Exception e) { System.err.println(e.getMessage()); } if (functions.length() != 0) { program.getMainPanel().getTextField().setText(functions); simplify(SolutionType.DETAILLED_SOLUTION); } else { JOptionPane .showMessageDialog( null, Tools.getLocalizedString("ERROR_IMPORT") + " " + f.getName() + " " + Tools.getLocalizedString("ERROR_IMPORT3"), Tools.getLocalizedString("ERROR"), JOptionPane.ERROR_MESSAGE); } } } }
e6762a4b-5283-41db-bd9e-1cc631fd8bd3
3
public void testXMLParser(){ String s = "<a>value</a>"; DocumentBuilder parser = null; Document document = null; try { parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); document = parser.parse(new InputSource(new StringReader(s))); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } String res = document.getElementsByTagName("a").item(0).getTextContent(); assertEquals("value", res); }
676032bf-3fe8-4745-aad5-d1e7cfb0e507
7
@Override public ArrayList<String> getTopKills() { ArrayList<String> top_Players = new ArrayList<String>(); PreparedStatement pst = null; ResultSet rs = null; try { pst = conn.prepareStatement("SELECT player_name FROM `ffa_leaderboards` ORDER BY `killcount` DESC"); rs = pst.executeQuery(); int count = 0; while (rs.next() & count < 10) { if (!rs.getString("player_name").equals("")) { top_Players.add(rs.getString("player_name")); } count++; } } catch (SQLException ex) { } finally { if (pst != null) { try { pst.close(); } catch (SQLException ex) { } } if (rs != null) { try { rs.close(); } catch (SQLException ex) { } } } return top_Players; }
16adb52a-7485-449e-acb2-93899cdfc821
1
public void prependKnooppunt(Knooppunt knooppunt)throws IllegalArgumentException { if(knooppunt == null) throw new IllegalArgumentException("Je hebt geen knooppunt meegegeven"); this.kortsteWeg.add(0, knooppunt); }
e8350ff7-e4ee-44d9-a05e-bba16977df6e
5
public static void cocktailSort(int[] array) { printArray(array); int a = 0; for (int i = 0; i < array.length / 2; i++) { for (int m = 1; m < array.length - i; m++) { if (array[m - 1] > array[m]) { a = array[m - 1]; array[m - 1] = array[m]; array[m] = a; } } for (int n = array.length - i - 2; n > i; n--) { if (array[n - 1] > array[n]) { a = array[n - 1]; array[n - 1] = array[n]; array[n] = a; } } printArray(array); } printArray(array); }
c893caad-30a8-4fc5-82a3-4ded1b717776
2
protected void computeArgumentsByteArray(OSCJavaToByteArrayConverter stream) { stream.write(','); if (null == arguments) { return; } stream.writeTypes(arguments); for (Object argument : arguments) { stream.write(argument); } }
d5815e90-077f-4f1c-a846-b59b381e43b5
8
public Picture getOppositeInversedImage() { Color[][] col = new Color[h][w]; Color c; int r=0; int g=0; int b=0; for (int i=green.length-1; i>=0; i--) { for (int j=green[0].length-1;j>=0; j--) { for (int k=green[0][0].length-1; k>=0; k--) { if (green[i][j][k]==1) { g = k; for (int m=red[0][0].length-1; m>=0; m--) { if (red[i][j][m]==1) { r = m; } } for (int n=blue[0][0].length-1; n>=0; n--) { if (blue[i][j][n]==1) { b = n; } } c = new Color(255-r,255-g,255-b); col[h-i-1][w-j-1] = c; } } } } Picture pic = new Picture(col); return pic; }
fa65c191-6bbd-441d-873a-f068cf929073
3
protected double getNextFailureLengthSample() { double sample; if (failureLengthPatternDiscrete_ != null) { sample = failureLengthPatternDiscrete_.sample(); return Math.abs(sample); } else if (failureLengthPatternCont_ != null) { sample = failureLengthPatternCont_.sample(); return Math.abs(sample); } else if (failureLengthPatternVariate_ != null) { sample = failureLengthPatternVariate_.gen(); return Math.abs(sample); } else return -1; }
fd3c0193-60e7-4541-a20d-408fbec7d358
9
public void setSelectedEditor(final int selectedEditor) { final int oldEditor = this.selectedRootEditor; if (oldEditor == selectedEditor) { // no change - so nothing to do! return; } this.selectedRootEditor = selectedEditor; // make sure that only the selected editor is active. // all other editors will be disabled, if needed and // not touched if they are already in the correct state for (int i = 0; i < this.rootEditors.size(); i++) { final boolean shouldBeActive = (i == selectedEditor); final RootEditor container = (RootEditor) this.rootEditors.get(i); if (container.isActive() && (shouldBeActive == false)) { container.setActive(false); } } if (this.currentToolbar != null) { closeToolbar(); this.toolbarContainer.removeAll(); this.currentToolbar = null; } for (int i = 0; i < this.rootEditors.size(); i++) { final boolean shouldBeActive = (i == selectedEditor); final RootEditor container = (RootEditor) this.rootEditors.get(i); if ((container.isActive() == false) && (shouldBeActive == true)) { container.setActive(true); setJMenuBar(createEditorMenubar(container)); this.currentToolbar = container.getToolbar(); if (this.currentToolbar != null) { this.toolbarContainer.add (this.currentToolbar, BorderLayout.CENTER); this.toolbarContainer.setVisible(true); this.currentToolbar.setVisible(true); } else { this.toolbarContainer.setVisible(false); } this.getJMenuBar().repaint(); } } }
4fac6d8c-96ae-4835-9c14-083feedd9ce8
3
public WorkloadFileReader(String fileName, int rating) { if (fileName == null || fileName.length() == 0) { throw new IllegalArgumentException("Invalid trace file name."); } else if (rating <= 0) { throw new IllegalArgumentException("Resource PE rating must be > 0."); } this.fileName = fileName; this.rating = rating; }
dd47b8b5-e328-4d24-af33-08aa65e3f310
7
public String longestCommonPrefix(String[] strs) { if (strs.length == 0) { return ""; } if (strs.length == 1) { return strs[0]; } String common = ""; for (int j = 0; j < strs[0].length(); j++) { char c = strs[0].charAt(j); boolean isCommon = true; for (int i = 1; i < strs.length; i++) { if (strs[i].length() <= j || strs[i].charAt(j) != c) { isCommon = false; break; } } if (isCommon) { common += c; } else { break; } } return common; }
64315eff-00f6-4b69-abb5-afd7fc087e08
2
public static void main(final String args[]) { UserListRoot list = new UserListRoot(); User u = new User(); u.setName("danny"); u.setPassword("danny"); u.setPhoneNumber("123243"); u.setType(0); User u2 = new User(); u2.setName("aly"); u2.setPassword("aly"); u2.setPhoneNumber("123243"); u2.setType(0); list.getUserList().add(u); list.getUserList().add(u2); UserXMLHandler usHandler = new UserXMLHandler(); try { // usHandler.writeToFile(list); UserListRoot list2 = (UserListRoot)usHandler.readFromFile(); System.out.println(list2.getUserList().get(0).getName()); } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
09c8459b-9fcb-43ac-a2f7-070c77ffd58a
3
public void setOutput(AudioBus newOutput) { if(this.isMaster()) return; if(newOutput == null) newOutput = AudioBus.getMasterBus(); if(this.output != newOutput) { this.output.removeAsInputBus(this); this.output = newOutput; newOutput.addAsInputBus(this); } }
53d26454-aade-4c72-beac-9896cde34fc8
8
private boolean checkStartEndBounds(int xp, int yp){ //TODO: Still prettu buggy, can still erase edges of start and end rooms. for(int y = 0; y < 9; y++){ int ya = y + (32 / 2) - (9 / 2); for(int x = 0; x < 10; x++){ int xa = x - 1 + (64 - 10); if(xp == x && yp == ya) return false; if(xp == xa && yp == y) return false; if(xp == xa && yp == ya) return false; } } return true; }
7e2a476f-3ef3-48ce-9293-d507c376f58d
5
public static Batch <Recreation> audienceFor(Boardable venue, Performance p) { final Batch <Recreation> audience = new Batch <Recreation> () ; for (Mobile m : venue.inside()) if (m instanceof Actor) { final Actor a = (Actor) m ; for (Behaviour b : a.mind.agenda()) if (b instanceof Recreation) { final Recreation r = (Recreation) b ; if (p.matches(r)) { audience.add(r) ; break ; } } } return audience ; }
d8edb1d5-b2a0-47a0-b4fd-731bfcf03a9c
0
public ClusterNode(double distance, Cluster cluster) { this.distance = distance; this.cluster = cluster; }
f05f1ad0-63b1-4c2a-b14a-01261eeb89ad
7
public Double aStarSearch(Vertex[] vertices, int start, int goal) { PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>(); vertices[start].gScore = 0.0; vertices[goal].isGoal = true; vertexQueue.add(vertices[start]); while (!vertexQueue.isEmpty()) { Vertex current = vertexQueue.poll(); if (current.isGoal) { return vertices[goal].gScore; } current.visited = true; vertices[current.vertexID].visited = true; // for all vertex adjacent to current do for (int n = 0; n < vertices.length; n++) { if (current.adjList.contains(n) && !vertices[n].visited) { Vertex adj = vertices[n]; Double gScore = current.gScore + euclidianDistance(current, adj); // if adj not in Q or gScore < adj.gScore if (!vertexQueue.contains(adj) || gScore < adj.gScore) { // Update the Scores for the adjacent vertex. vertexQueue.remove(adj); adj.gScore = gScore; adj.hScore = euclidianDistance(adj, vertices[goal]); adj.fScore = adj.gScore + adj.hScore; // Add this vertex back into the priority queue with updated information. vertexQueue.add(adj); } } } } // Failed. return Double.POSITIVE_INFINITY; }
aa1db958-96bf-4a13-862a-09151f3b43cd
2
public void updateConfigFile() { // Only do this if the old configuration is present if (getConfig().isConfigurationSection("Warnings.warned")) { // Get all the currently warned players and put them in a HashMap Map<String,Object> userList= getConfig().getConfigurationSection("Warnings.warned").getValues(false); Integer c = 0; // Iterate the hashmap for(Map.Entry<String,Object> entry : userList.entrySet()) { String name = entry.getKey(); Integer warn = (Integer) entry.getValue(); // Get the current timestamp, we use this for the warned time Long secs = System.currentTimeMillis(); // Write the new entries getConfig().set("Warned."+name.toLowerCase()+".remaining", warn); getConfig().set("Warned."+name.toLowerCase()+".timestamp", secs); // Delete the old entry getConfig().set("Warnings.warned."+name.toLowerCase(), null); c++; } // Remove the old section getConfig().set("Warnings.warned", null); // Remove the "kick" option getConfig().set("Action.kick", null); saveConfig(); this.logger.info("[BadWords] ** Updated config file to new format. " + c + " users updated **"); } }
2818864d-6a8c-4888-ab3d-c0f66071799b
2
private static boolean isPropertyAnnotated(String line, List<String> annotatedVariables){ boolean contains = false; for (String property : annotatedVariables){ if (line.contains(property)) contains = true; } return contains; }
f208c94f-5a55-412b-9880-12a10f01672d
2
public static Rank getRank(String r) { char test = r.charAt(0); for (Rank rank : Rank.values()) { if (rank.shortName == test) { return rank; } } throw new RuntimeException("Rank not recognized!!!"); }
e71d35ba-6db5-4912-8557-b678fb0b2ffd
3
@Override public void deserialize(Buffer buf) { super.deserialize(buf); playerId = buf.readInt(); if (playerId < 0) throw new RuntimeException("Forbidden value on playerId = " + playerId + ", it doesn't respect the following condition : playerId < 0"); playerName = buf.readString(); breed = buf.readByte(); if (breed < PlayableBreedEnum.Feca.value() || breed > PlayableBreedEnum.Steamer.value()) throw new RuntimeException("Forbidden value on breed = " + breed + ", it doesn't respect the following condition : breed < PlayableBreedEnum.Feca.value() || breed > PlayableBreedEnum.Steamer.value()"); sex = buf.readBoolean(); }
77b896b8-1c7a-40ee-87b6-c9835ce3ba6a
5
public static void main(String[] args) { Conf.init(); boolean nicequit = false; while(!nicequit) { try { Wrapper serv = new Wrapper(); serv.start(); while(!serv.hasStopped()) { try { serv.join(); } catch (Exception e) { e.printStackTrace(); } } nicequit = serv.wasNiceQuit(); if(!nicequit) { System.err.println("[WARNING] The server crashed or was stopped from whithin the game. Restarting…"); } } catch(Exception e) { e.printStackTrace(); System.exit(1); } } System.exit(0); }
27cac8ec-1bfd-4378-8281-c26dd830ba59
5
public static void prepareNodes() { try { CoordinatorGUI.textArea.append("Transmitting ready checks to nodes..." + "\n" + "\n"); String ready = "ready?"; buf = ready.getBytes(); packet = new DatagramPacket(buf, buf.length, group, 4446); socket.send(packet); CoordinatorGUI.textArea.append("Ready checks sent to nodes..." + "\n" + "\n"); getResponses(); if (hasResponse) { CoordinatorGUI.textArea.append("Responses from nodes regarding ready state: " + "\n" + "\n"); for (int j = 0; j < nodes; j++) { CoordinatorGUI.textArea.append(" " + responses.get(j) + "\n" + "\n"); if (responses.get(j).equals("no")) { nodesReady = false; } } if (nodesReady) { commit = true; String taskToSend = "task "; task = br.readLine(); taskToSend += task; buf = taskToSend.getBytes(); packet = new DatagramPacket(buf, buf.length, group, 4446); socket.send(packet); } else { commit = false; abort(); } } } catch (IOException ex) { System.err.println(ex); } }
4cb76f01-856b-4562-a228-49b324140ca2
7
public void onTick() { if (timeLeftInFog>0) timeLeftInFog--; else setFog(false); if (getTimeleft() > 0) { setTimeleft(getTimeleft() - speed); listener.onTowerAction(this); return; } if (isInFog()) { for (Road r : closeNeighbours) { if (r.hasEnemy() != null) { Enemy e = r.hasEnemy(); listener.onTowerAction(this); e.shoot(this); setTimeleft(defTimeleft); return; } } } else { for (Road r : neighbours) { if (r.hasEnemy() != null) { Enemy e = r.hasEnemy(); listener.onTowerAction(this); setTimeleft(defTimeleft); e.shoot(this); return; } } } }
bc645617-a994-4097-9a1c-8af32b8449ac
9
@SuppressWarnings("rawtypes") @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BasicFamilyObject other = (BasicFamilyObject) obj; if (children == null) { if (other.children != null) return false; } else if (!children.equals(other.children)) return false; if (parent == null) { if (other.parent != null) return false; } else if (!parent.equals(other.parent)) return false; return true; }
0c007026-d0bb-40db-b3c0-c70f98fd709c
3
public String printParkInfoBySingle(){ String text=""; if(park == null && getParkBoyList().size() == 0) { text="目前没有管理任何停车场!" ; return text; } int emptyNum = 0; int totalNum = 0; if(park != null) { text= " 停车场编号:" + park.getCode() +"\n"; text=text+ " 停车场名称:" + park.getParkName() +"\n"; text=text+" 车位数:" + park.getTotalNum()+"\n"; text=text+" 空位数:" + park.getEmptyNum()+"\n"; emptyNum += park.getEmptyNum(); totalNum += park.getTotalNum(); } text =text + " 共计车位数:" + totalNum+"\n"; text =text + " 共计空位数:" + emptyNum+"\n"; return text; }
17427dc5-3ca0-49eb-bb7c-a337ba846f7f
4
@Override public Object getValue(Method method, Map<Class<?>, ClassBuilder<?>> hows) { List<Object> objects = new ArrayList<Object>(); for (Class<?> clazz : this.classes) { objects.add( hows.get(clazz).build(hows) ); } return objects; }
35e00a34-5e43-4730-83a0-dbfbaf29bc1a
8
void output(int code, OutputStream outs) throws IOException { cur_accum &= masks[cur_bits]; if (cur_bits > 0) cur_accum |= (code << cur_bits); else cur_accum = code; cur_bits += n_bits; while (cur_bits >= 8) { char_out((byte) (cur_accum & 0xff), outs); cur_accum >>= 8; cur_bits -= 8; } if (free_ent > maxcode || clear_flg) { if (clear_flg) { maxcode = MAXCODE(n_bits = g_init_bits); clear_flg = false; } else { ++n_bits; if (n_bits == maxbits) maxcode = maxmaxcode; else maxcode = MAXCODE(n_bits); } } if (code == EOFCode) { while (cur_bits > 0) { char_out((byte) (cur_accum & 0xff), outs); cur_accum >>= 8; cur_bits -= 8; } flush_char(outs); } }
5a37957b-a1b2-44f6-98d9-6ec85f308674
6
private final void drawHudItems(Graphics2D drawScreen, int offsetX, int offsetY) { for (IHudItem hudItem : hudItemQueue) { // Decide where the object should be drawn. Call the draw method of // the hudItem as IHudItem extends IDrawable switch (hudItem.getRelativeDraw()) { case CENTER: hudItem.draw(drawScreen, (int) (offsetX + (GameSettings.getGameWidth() / 2) - (hudItem.getSpatial().width / 2)), (int) (offsetY + (GameSettings.getGameHeight() / 2) - (hudItem.getSpatial().height / 2))); break; case TOP_LEFT: hudItem.draw(drawScreen, (int) (offsetX + HudPadding), offsetY + HudPadding); break; case TOP_RIGHT: hudItem.draw(drawScreen, (int) (offsetX + (GameSettings.getGameWidth() - hudItem.getSpatial().width)) - HudPadding, offsetY + HudPadding); break; case BOTTOM_LEFT: hudItem.draw(drawScreen, (int) (offsetX + HudPadding), (int) (offsetY + (GameSettings.getGameHeight() - hudItem.getSpatial().height - HudPadding))); break; case BOTTOM_RIGHT: hudItem.draw(drawScreen, (int) (offsetX + (GameSettings.getGameWidth() - hudItem.getSpatial().width)) - HudPadding, (int) (offsetY + (GameSettings.getGameHeight() - hudItem.getSpatial().height - HudPadding))); break; default: // This shouldn't really happen, but I guess there's always // null that could appear out of no where. logger.error("type not supported within drawHudItems ", hudItem.getRelativeDraw()); break; } } }
274ee647-bec5-4cf3-943d-e0040952de45
4
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeBytes(1, getTeamNameBytes()); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeBytes(2, getColorHexBytes()); } if (((bitField0_ & 0x00000004) == 0x00000004)) { output.writeBytes(3, getVersionNumberBytes()); } if (((bitField0_ & 0x00000008) == 0x00000008)) { output.writeBytes(4, getAuthenticationBytes()); } getUnknownFields().writeTo(output); }
72807d8c-838f-4e6e-930b-b947bd97754c
0
@Test public void testGame() { // barely anything to test here.. _underTest = new Game(_paperPlayer, _rockPlayer); assertNotNull(_underTest); }
26c782cf-c925-4c23-a526-023a82ffc4a5
8
void saveImages(File parentFile) { if (((MDView) getView()).getFillMode() instanceof FillMode.ImageFill) { String url = ((FillMode.ImageFill) ((MDView) getView()).getFillMode()).getURL(); String s = url; String base = FileUtilities.getCodeBase(url); /* * if background image is set using the filechooser the URL field of the ImageFill will be set to be the real HD address of the image. If background image transfers from another model because of downloading or saving, the URL field of the ImageFill will be set to the file name of that image ONLY. */ if (base == null) { base = FileUtilities.getCodeBase((String) getProperty("old url")); if (base == null) base = FileUtilities.getCodeBase((String) getProperty("url")); s = base + url; saveImage(s, parentFile); } else { if (FileUtilities.isRemote(s)) { saveImage(s, parentFile); } else { copyFile(s, new File(parentFile, FileUtilities.getFileName(s))); } } } ImageComponent[] img = ((MDView) getView()).getImages(); if (img.length > 0) { for (int i = 0; i < img.length; i++) { String url = img[i].toString(); String s = url; String base = FileUtilities.getCodeBase(url); if (base == null) { base = FileUtilities.getCodeBase((String) getProperty("old url")); if (base == null) base = FileUtilities.getCodeBase((String) getProperty("url")); s = base + url; saveImage(s, parentFile); } else { copyFile(s, new File(parentFile, FileUtilities.getFileName(s))); } } } }
038b4ef7-f6ec-4c73-b025-857da6d12354
9
public TabletStatus startApps(int type, int quantity) throws InvalidOperationException, IllegalArgumentException { TabletStatus status = getCurrentStatus(); if (quantity <= 0) throw new IllegalArgumentException(); if (type < 0) throw new IllegalArgumentException(); if (status.cpuSpeed < 10) throw new InvalidOperationException(); if (status.isOverloaded) throw new InvalidOperationException(); if (type > 5) type = 1; status.cpuSpeed += quantity * 50 + (type == 1 ? 5 : type == 2 ? 3 : 5); if (quantity * 50 * type > status.freeMemory) { status.freeMemory = 0; } else { status.freeMemory -= quantity * 50 * type; } status.applications += quantity; status.isOverloaded = status.cpuSpeed > 3000 || status.freeMemory < 50; return status; }
96d1eb68-defe-4463-8b7c-750190dd6427
2
private void copyWorld() { //gespeicherte Welt löschen Lines.clear(); Goals.clear(); //Alles kopieren for(int i=0; i<Reflines.size(); i++) { int[] a = new int[4]; a[0] = Reflines.elementAt(i)[0]; a[1] = Reflines.elementAt(i)[1]; a[2] = Reflines.elementAt(i)[2]; a[3] = Reflines.elementAt(i)[3]; Lines.add(a); } numlines = Lines.size(); for(int j=0; j<Refgoals.size(); j++) { int[] b = new int[4]; b[0] = Refgoals.elementAt(j)[0]; b[1] = Refgoals.elementAt(j)[1]; Goals.add(b); } numgoals = Goals.size(); }
3dea9cf1-d516-40eb-8af6-52dcf377b3fe
9
@Override public void train() { double sim = 0; String[] t = socialNeighbourhood.split("_"); int k = new Integer(t[1]); for (Integer user1 : data.getItemsByUser().keySet()) { if (data.getUserFriends().get(user1) == null) { // User has no friends :) continue; } ArrayList<Integer> friendsKthLevel = getFriendsKthLevel(user1, k); for (Integer user2 : friendsKthLevel) { if (user1 < user2) { sim = computeSimilarity(user1, user2); if (socialThreshold != null) { if (sim < socialThreshold) { continue; } } // this is for user1's list if (userSimilarities.containsKey(user1)) { userSimilarities.get(user1).put(user2, sim); } else { LinkedHashMap<Integer, Double> s = new LinkedHashMap<Integer, Double>(); s.put(user2, sim); userSimilarities.put(user1, s); } // this is for user2's list if (userSimilarities.containsKey(user2)) { userSimilarities.get(user2).put(user1, sim); } else { LinkedHashMap<Integer, Double> s = new LinkedHashMap<Integer, Double>(); s.put(user1, sim); userSimilarities.put(user2, s); } } } } // Calculate the average size of the similarity lists int similaritiesCount = 0; for (Map.Entry<Integer, LinkedHashMap<Integer, Double>> entry : userSimilarities.entrySet()) { similaritiesCount += entry.getValue().size(); } Recommender.setAverageSizeOfSimilarityListUsers((double) similaritiesCount / (double) userSimilarities.size()); }
52ca6341-5120-4aef-8992-94ffb1cc7027
1
private static String getStringFromDocument(Document doc) { try { DOMSource domSource = new DOMSource(doc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.transform(domSource, result); return writer.toString(); } catch (TransformerException ex) { ex.printStackTrace(); return null; } }
46bc20c1-37ff-40ee-b05d-3fe36071c746
2
@Override public void boot() { running = true; this.configuration = getAudioInputConfiguration(); try { lsr = new LiveSpeechRecognizer(configuration); } catch (IOException e) { System.out.println("Eva was unable to configure Ears."); e.printStackTrace(); } try { ssr = new StreamSpeechRecognizer(configuration); } catch (IOException e) { System.out.println("Eva was unable to configure Ears."); e.printStackTrace(); } lsr.startRecognition(true); /* //some testing: System.out.println("testing some audio files:"); String[] filenames = { "src/main/resources/mp3/GetOnTheHorse.mp3", "src/main/resources/mp3/TheSunIsUp.mp3" }; for(String filename : filenames) { InputStream inputStream = getInputStreamByFilename(filename); SpeechResult speechResult = listenToStream(inputStream); System.out.println(speechResult.getHypothesis()); } */ }
38aa7085-bd58-4f65-a1db-be90919be6cd
0
public int genotypeSize(){ return this.bins.size(); }
b5f8f5a1-780a-40ee-a788-ada04d74f686
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(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Login.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 Login().setVisible(true); } }); }
f4e99db1-99c2-4201-aa92-e3c780aea1ce
6
public void CreateTextureSetsSkinBodyFemale_1RBS_old() throws Exception { // it copies SkinBodyFemale and changes the textures getting out of RBS folders. for (TXST t : ListRBSTXSTMerger) { if (t.getEDID().equals("SkinBodyFemale_1")) { NumberFormat formatter = new DecimalFormat("000"); String sourcePath = SkyProcStarter.path + "textures" + File.separator + "RBS" + File.separator + "female" + File.separator; String targetPath = "RBS" + File.separator + "female" + File.separator; int counter = 1; File sourcePath1 = new File(sourcePath + "color" + File.separator); File[] colormaps = sourcePath1.listFiles(); File sourcePath2 = new File(sourcePath + "detail" + File.separator); File[] detailmaps = sourcePath2.listFiles(); File sourcePath3 = new File(sourcePath + "normal" + File.separator); File[] normalmaps = sourcePath3.listFiles(); File sourcePath4 = new File(sourcePath + "specular" + File.separator); File[] specularmaps = sourcePath4.listFiles(); for (int n = 0; n < normalmaps.length; n++) { for (int c = 0; c < colormaps.length; c++) { for (int d = 0; d < detailmaps.length; d++) { for (int s = 0; s < specularmaps.length; s++) { counter = counter + 1; n2 = n + 1; c2 = c + 1; d2 = d + 1; s2 = s + 1; TXST tt = (TXST) SkyProcStarter.patch.makeCopy(t, t.getEDID() + "RBS_F_TEXT" + n2 + "_" + c2 + "_" + d2 + "_" + s2); tt.setNormalMap(normalmaps[n].toString().replace(SkyProcStarter.path + "textures", "")); tt.setDetailMap(detailmaps[d].toString().replace(SkyProcStarter.path + "textures", "")); tt.setColorMap(colormaps[c].toString().replace(SkyProcStarter.path + "textures", "")); tt.setSpecularityMap(specularmaps[s].toString().replace(SkyProcStarter.path + "textures", "")); // SkyProcStarter.patch.addRecord(tt); } } } } } } }
57aee8ff-2bf7-4cd8-b9c0-37e7a4236683
3
public ArrayList<String> leerArchivo(String nombre) { ArrayList<String> datos = new ArrayList(); try { FileReader fr = new FileReader("./Data/" + nombre + ".o"); BufferedReader br = new BufferedReader(fr); String line; while ((line = br.readLine()) != null){ datos.add(line); } fr.close(); } catch (FileNotFoundException ex) { crearArchivo(nombre); } catch (IOException ex) { System.out.println("\nDATA CORRUPTED!!!"); System.out.println(ex.getMessage() + "\n"); } return datos; }
96978265-8a36-4365-b3fa-6e93956fd440
4
public void coreWorkflow(Configuration config) { // Build a list of files to validate try { System.out.print(" -- Finding files to process"); AbstractQueue<String> queue = new ArrayBlockingQueue<String>(100000); findDNGFiles(queue, config.inputDir); int qs = queue.size(); System.out.println("\n -- Files loaded. " + qs + " files found"); if (qs == 0) { return; } // Keep track of the threads ArrayList<Thread> activeThreads = new ArrayList<Thread>(config.threads); // Start threads to do the work System.out.println(" -- Starting processing threads " + config.inputDir); logManager.logValidationError("Starting processing " + config.inputDir); for (int i = 0; i < config.threads; i++) { WorkerThread wt = new WorkerThread("Thread" + i, logManager, queue, config); Thread t = new Thread(wt); activeThreads.add(t); t.start(); } System.out.println(" -- Processing threads started. This could take some time..."); System.out.println("\nInitial queue size is " + qs); // Wait until all threads have finished long startTime = System.currentTimeMillis(); for (Thread thread : activeThreads ) { thread.join(); } System.out.println("\n -- finished processing"); logManager.logValidationError("Finished processing"); long endTime = System.currentTimeMillis(); long ms = (endTime - startTime); long sec = ms / 1000; float rate = sec / qs; DecimalFormat df = new DecimalFormat(); df.setMaximumFractionDigits(1); String rateStr = df.format(rate); int errors = WorkerThread.getValidationErrors(); int warnings = WorkerThread.getValidationWarnings(); String message = "Verified " + qs + " file(s) in " + sec + " seconds, " + rateStr + " seconds per file.\n" + errors + " file(s) failed validation, " + warnings + " file(s) couldn't be validated due to Adobe DNG library limitations"; System.out.println(message); logManager.logGeneral(message); logManager.logValidationError(message); } catch (Exception e) { logManager.logGeneral(e.getMessage()); logManager.logGeneral("Program exiting"); System.err.println(e.getMessage()); System.err.println("Program exiting"); } }
81e1855c-3fe6-4dcb-b348-014dc1e60f53
8
private static int pivot(int[] a, int low, int high) { int i1 = low, i2 = high - 1, i3 = (low + high) / 2; int a1 = a[i1], a2 = a[i2], a3 = a[i3]; int n = (a1 > a2) ? a1 : a2; int m = (a2 > a3) ? a2 : a3; if (m > n) { return (a1 > a2) ? i1 : i2; } else if (n > m) { return (a2 > a3) ? i2 : i3; } else if (n == m) { return (a1 > a3) ? i1 : i3; } return -1; }
54fac5a4-388a-43a2-b4c8-9cd157828cd5
6
public static int[] countSort(int[] a, int k){ int[] b = new int[a.length]; int[] c = new int[10]; for(int i=0; i<b.length; i++){ b[i] = 0; } for(int i=0; i<c.length; i++){ c[i] = 0; } int s = 1; for(int i=0; i<k; i++){ s = s * 10; } int temp1 = 0; for(int i=0; i<a.length; i++){ temp1 = a[i]%s; temp1 = temp1 * 10 / s; c[temp1] = c[temp1] + 1; } for(int i=1; i<c.length; i++){ c[i] = c[i] + c[i-1]; } int temp2 = 0; for(int i=a.length-1; i>=0; i--){ temp1 = a[i]; temp2 = a[i]%s; temp2 = temp2 * 10 / s; b[c[temp2]-1] = temp1; c[temp2] = c[temp2] - 1; } return b; }
8282c5ef-e7b6-4796-9678-0a8b9d5a499a
4
private void showCrewEditor( final CrewSprite crewSprite ) { final String NAME = "Name"; final String RACE = "Race"; final String HEALTH = "Health"; final String PILOT_SKILL = "Pilot Skill"; final String ENGINE_SKILL = "Engine Skill"; final String SHIELD_SKILL = "Shield Skill"; final String WEAPON_SKILL = "Weapon Skill"; final String REPAIR_SKILL = "Repair Skill"; final String COMBAT_SKILL = "Combat Skill"; final String REPAIRS = "Repairs"; final String COMBAT_KILLS = "Combat Kills"; final String PILOTED_EVASIONS = "Piloted Evasions"; final String JUMPS_SURVIVED = "Jumps Survived"; final String PLAYER_CONTROLLED = "Player Ctrl"; final String ENEMY_DRONE = "Enemy Drone"; final String GENDER = "Male"; int pilotInterval = SavedGameParser.CrewState.MASTERY_INTERVAL_PILOT; int engineInterval = SavedGameParser.CrewState.MASTERY_INTERVAL_ENGINE; int shieldInterval = SavedGameParser.CrewState.MASTERY_INTERVAL_SHIELD; int weaponInterval = SavedGameParser.CrewState.MASTERY_INTERVAL_WEAPON; int repairInterval = SavedGameParser.CrewState.MASTERY_INTERVAL_REPAIR; int combatInterval = SavedGameParser.CrewState.MASTERY_INTERVAL_COMBAT; int maxHealth = SavedGameParser.CrewState.getMaxHealth( crewSprite.getRace() ); String title = "Crew"; final FieldEditorPanel editorPanel = new FieldEditorPanel( false ); editorPanel.addRow( NAME, FieldEditorPanel.ContentType.STRING ); editorPanel.getString(NAME).setText( crewSprite.getName() ); editorPanel.addRow( RACE, FieldEditorPanel.ContentType.COMBO ); editorPanel.getCombo(RACE).addItem("battle"); editorPanel.getCombo(RACE).addItem("crystal"); editorPanel.getCombo(RACE).addItem("energy"); editorPanel.getCombo(RACE).addItem("engi"); editorPanel.getCombo(RACE).addItem("human"); editorPanel.getCombo(RACE).addItem("mantis"); editorPanel.getCombo(RACE).addItem("rock"); editorPanel.getCombo(RACE).addItem("slug"); editorPanel.getCombo(RACE).setSelectedItem( crewSprite.getRace() ); editorPanel.addRow( HEALTH, FieldEditorPanel.ContentType.SLIDER ); editorPanel.getSlider(HEALTH).setMaximum( maxHealth ); editorPanel.getSlider(HEALTH).setValue( crewSprite.getHealth() ); editorPanel.addRow( PILOT_SKILL, FieldEditorPanel.ContentType.SLIDER ); editorPanel.getSlider(PILOT_SKILL).setMaximum( pilotInterval*2 ); editorPanel.getSlider(PILOT_SKILL).setValue( crewSprite.getPilotSkill() ); editorPanel.addRow( ENGINE_SKILL, FieldEditorPanel.ContentType.SLIDER ); editorPanel.getSlider(ENGINE_SKILL).setMaximum( engineInterval*2 ); editorPanel.getSlider(ENGINE_SKILL).setValue( crewSprite.getEngineSkill() ); editorPanel.addRow( SHIELD_SKILL, FieldEditorPanel.ContentType.SLIDER ); editorPanel.getSlider(SHIELD_SKILL).setMaximum( shieldInterval*2 ); editorPanel.getSlider(SHIELD_SKILL).setValue( crewSprite.getShieldSkill() ); editorPanel.addRow( WEAPON_SKILL, FieldEditorPanel.ContentType.SLIDER ); editorPanel.getSlider(WEAPON_SKILL).setMaximum( weaponInterval*2 ); editorPanel.getSlider(WEAPON_SKILL).setValue( crewSprite.getWeaponSkill() ); editorPanel.addRow( REPAIR_SKILL, FieldEditorPanel.ContentType.SLIDER ); editorPanel.getSlider(REPAIR_SKILL).setMaximum( repairInterval*2 ); editorPanel.getSlider(REPAIR_SKILL).setValue( crewSprite.getRepairSkill() ); editorPanel.addRow( COMBAT_SKILL, FieldEditorPanel.ContentType.SLIDER ); editorPanel.getSlider(COMBAT_SKILL).setMaximum( combatInterval*2 ); editorPanel.getSlider(COMBAT_SKILL).setValue( crewSprite.getCombatSkill() ); editorPanel.addBlankRow(); editorPanel.addRow( REPAIRS, FieldEditorPanel.ContentType.INTEGER ); editorPanel.getInt(REPAIRS).setText( ""+crewSprite.getRepairs() ); editorPanel.addRow( COMBAT_KILLS, FieldEditorPanel.ContentType.INTEGER ); editorPanel.getInt(COMBAT_KILLS).setText( ""+crewSprite.getCombatKills() ); editorPanel.addRow( PILOTED_EVASIONS, FieldEditorPanel.ContentType.INTEGER ); editorPanel.getInt(PILOTED_EVASIONS).setText( ""+crewSprite.getPilotedEvasions() ); editorPanel.addRow( JUMPS_SURVIVED, FieldEditorPanel.ContentType.INTEGER ); editorPanel.getInt(JUMPS_SURVIVED).setText( ""+crewSprite.getJumpsSurvived() ); editorPanel.addRow( PLAYER_CONTROLLED, FieldEditorPanel.ContentType.BOOLEAN ); editorPanel.getBoolean(PLAYER_CONTROLLED).setSelected( crewSprite.isPlayerControlled() ); editorPanel.getBoolean(PLAYER_CONTROLLED).addMouseListener( new StatusbarMouseListener(frame, "Player controlled vs NPC.") ); editorPanel.addRow( ENEMY_DRONE, FieldEditorPanel.ContentType.BOOLEAN ); editorPanel.getBoolean(ENEMY_DRONE).setSelected( crewSprite.isEnemyBoardingDrone() ); editorPanel.getBoolean(ENEMY_DRONE).addMouseListener( new StatusbarMouseListener(frame, "Turn into a boarding drone (clobbering other fields).") ); editorPanel.addRow( GENDER, FieldEditorPanel.ContentType.BOOLEAN ); editorPanel.getBoolean(GENDER).setSelected( crewSprite.isMale() ); editorPanel.getBoolean(GENDER).addMouseListener( new StatusbarMouseListener(frame, "Only humans can be female (no effect on other races).") ); sidePanel.add( editorPanel ); final Runnable applyCallback = new Runnable() { public void run() { String newString; crewSprite.setName( editorPanel.getString(NAME).getText() ); crewSprite.setRace( (String)editorPanel.getCombo(RACE).getSelectedItem() ); crewSprite.setHealth( editorPanel.getSlider(HEALTH).getValue() ); crewSprite.setPilotSkill( editorPanel.getSlider(PILOT_SKILL).getValue() ); crewSprite.setEngineSkill( editorPanel.getSlider(ENGINE_SKILL).getValue() ); crewSprite.setShieldSkill( editorPanel.getSlider(SHIELD_SKILL).getValue() ); crewSprite.setWeaponSkill( editorPanel.getSlider(WEAPON_SKILL).getValue() ); crewSprite.setRepairSkill( editorPanel.getSlider(REPAIR_SKILL).getValue() ); crewSprite.setCombatSkill( editorPanel.getSlider(COMBAT_SKILL).getValue() ); newString = editorPanel.getInt(REPAIRS).getText(); try { crewSprite.setRepairs( Integer.parseInt(newString) ); } catch (NumberFormatException e) {} newString = editorPanel.getInt(COMBAT_KILLS).getText(); try { crewSprite.setCombatKills( Integer.parseInt(newString) ); } catch (NumberFormatException e) {} newString = editorPanel.getInt(PILOTED_EVASIONS).getText(); try { crewSprite.setPilotedEvasions( Integer.parseInt(newString) ); } catch (NumberFormatException e) {} newString = editorPanel.getInt(JUMPS_SURVIVED).getText(); try { crewSprite.setJumpsSurvived( Integer.parseInt(newString) ); } catch (NumberFormatException e) {} crewSprite.setPlayerControlled( editorPanel.getBoolean(PLAYER_CONTROLLED).isSelected() ); crewSprite.setEnemyBoardingDrone( editorPanel.getBoolean(ENEMY_DRONE).isSelected() ); crewSprite.setMale( editorPanel.getBoolean(GENDER).isSelected() ); crewSprite.makeSane(); clearSidePanel(); } }; createSidePanel( title, editorPanel, applyCallback ); addSidePanelSeparator(6); JButton moveBtn = new JButton("Move To..."); moveBtn.setAlignmentX( Component.CENTER_ALIGNMENT ); sidePanel.add(moveBtn); sidePanel.add( Box.createVerticalStrut(6) ); JButton removeBtn = new JButton("Remove"); removeBtn.setAlignmentX( Component.CENTER_ALIGNMENT ); sidePanel.add(removeBtn); moveBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { moveCrew( crewSprite ); } }); removeBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { clearSidePanel(); crewSprites.remove( crewSprite ); shipPanel.remove( crewSprite ); } }); showSidePanel(); }
a39e614f-adf9-41bb-b19f-750aaa0fa9cf
5
public void printPSolutions() { String coord = ""; String solutions = ""; for (int j = 0 ; j < 9 ; j++) { for (int i = 0 ; i < 9 ; i++) { solutions = ""; if (getSolver().getGridModel().getValue(i, j) == ' ') { coord = "["+i+","+j+"]"; for (int n = 0 ; n < 9 ; n++) { if (getPSolution(i,j,n) != 'X') { solutions = solutions + getPSolution(i,j,n) + ","; } } System.out.println(coord+" "+solutions); } else { coord =""; System.out.println(getSolver().getGridModel().getValue(i, j)); } } } }
21a86265-4dba-44cd-9664-4b51958e14d9
2
public Document toDOM(java.io.Serializable structure) { Grammar grammar = (Grammar) structure; Document doc = newEmptyDocument(); Element se = doc.getDocumentElement(); // Add the productions as subelements of the structure element. Production[] productions = grammar.getProductions(); if (productions.length > 0) se.appendChild(createComment(doc, COMMENT_PRODUCTIONS)); for (int i = 0; i < productions.length; i++) se.appendChild(createProductionElement(doc, productions[i])); // Return the completed document. return doc; }
58442f10-fbfd-4c50-9775-3e491c98c98f
5
@Override public void setBuffer() { if (isDirty()) { int numTempoChangeBytes = 0; for(TempoChange tempoChange : tempoChanges) numTempoChangeBytes += ((tempoChange.getBeatsPerMinute() < 256 ? 1 : 2) + 4); buffer = new byte[1 + numTempoChangeBytes]; int index = 0; buffer[index] = (byte)timeStampFormat.getValue(); index++; for(TempoChange tempoChange : tempoChanges) { int bpm = tempoChange.getBeatsPerMinute(); if (bpm != 0xFF) { buffer[index] = (byte)bpm; index++; } else { buffer[index] = (byte)0xFF; buffer[index + 1] = (byte)(bpm - 0xFF); index += 2; } System.arraycopy(intToBytes(tempoChange.getTimeStamp()), 0, buffer, index, 4); } dirty = false; // data has already been saved } }
31108463-aa92-4291-ab60-3d74df9cae62
3
public Database(Logger log, String prefix, String dp) throws DatabaseException { if (log == null) throw new DatabaseException("Logger cannot be null."); if (prefix == null || prefix.length() == 0) throw new DatabaseException("Plugin prefix cannot be null or empty."); this.log = log; this.PREFIX = prefix; this.DATABASE_PREFIX = dp; // Set from child class, can never be null or empty this.connected = false; }
edb1ff32-3f9c-4620-803b-5a9c66477207
6
@Override public void run() { nextAntiBan.endIn(Random.nextInt(5000, 45000)); final Dimension dimension = ctx.game.dimensions(); switch (Random.nextInt(0, 5)) { case 0: ctx.camera.angle(Random.nextBoolean() ? Random.nextInt(0, 360) : Random.nextInt(-359, 0)); break; case 1: ctx.input.move(Random.nextInt(0, (int) (dimension.getWidth() + 1)), Random.nextInt(0, (int) (dimension.getHeight() + 1))); break; case 2: //Util.mouseOffScreen(); ctx.input.defocus(); ctx.sleep(5000); break; case 3: for (GameObject object : ctx.objects.select().select(new Filter<GameObject>() { @Override public boolean accept(GameObject gameObject) { return Random.nextInt(0, 10) == 0; } }).first()) { ctx.camera.turnTo(object, 20); } break; default: wiggleMouse(); break; } ctx.sleep(100); }
e015c8cf-b005-45ed-b31b-f634a9982380
2
public static boolean inBounds(String position) { String file_bounds = "abcdefgh"; String rank_bounds = "12345678"; if(file_bounds.contains(position.substring(0,1))&&rank_bounds.contains(position.substring(1))) { return true; } return false; }
cca770c8-b23b-4203-aea8-65b4d92e9268
3
public List<Field> findAllAnnotatedFields(Class<? extends Annotation> annotationClass) { List<Field> annotatedFields = new LinkedList<Field>(); for(Field field : getFields()) { if(field.isAnnotationPresent(annotationClass)) { annotatedFields.add(field); } } getFieldDetailStore().addAllFields(annotatedFields); return annotatedFields; }
a6733f58-4d23-4124-b04d-f6c6d529d175
6
private void printOptions() { Scanner s = new Scanner(System.in); int option; System.out.println("\n \n"); do { System.out.println("Select one of the options: \n \n"); System.out.println("[1] Make a cell alive"); System.out.println("[2] Next generation"); System.out.println("[3] Undo"); System.out.println("[4] Redo"); System.out.println("[5] Halt"); System.out.print("\n \n Option: "); option = parseOption(s.nextLine()); }while(option == 0); switch(option) { case MAKE_CELL_ALIVE : makeCellAlive(); break; case NEXT_GENERATION : nextGeneration(); break; case UNDO : undo(); break; case REDO : redo(); break; case HALT : halt(); } }
5779a6aa-8561-44b1-b1a2-7866db21ff44
3
private void loadConfig(){ this.getConfig().addDefault("config.settings.enable", true); this.getConfig().addDefault("config.material.door", Material.QUARTZ.name()); this.getConfig().options().copyDefaults(true); saveConfig(); doorMaterial = Material.getMaterial(getConfig().getString("config.material.door")); enable = getConfig().getBoolean("config.settings.enable"); doorPath = getDataFolder().getPath() + "/doors"; instance = this; if(!new File(doorPath).exists()){ new File(doorPath).mkdirs(); } if(!new File(this.getDataFolder().getPath() + "/signs.yml").exists()){ try { new File(this.getDataFolder().getPath() + "/signs.yml").createNewFile(); } catch (IOException e) { e.printStackTrace(); } } tool = new ItemStack(Material.STICK); ItemMeta toolMeta = tool.getItemMeta(); toolMeta.setDisplayName(messagePrefix + "Tool"); toolMeta.addEnchant(Enchantment.DURABILITY, 5, true); tool.setItemMeta(toolMeta); }
5ffe5eb0-5d92-4e81-8540-74373f5fb0b7
9
private Object parse(Class<?> type, String argument) { try { for (Types t : Types.values()) { if (t.getWrapper() == type) return Types.parseArg(t.getPrimitive(), argument, savedObjects); } return Types.parseArg(type, argument, savedObjects); } catch (IllegalArgumentException e) { } catch (SecurityException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } catch (NoSuchMethodException e) { } catch (InstantiationException e) { } return null; }
4b4d685d-a921-4880-819d-1bd998d85dc3
1
private String getDate(String path) { File file = new File(path+ File.separator+ "Info.plist"); String date; try { NSDictionary rootDict = (NSDictionary)PropertyListParser.parse(file); date = rootDict.objectForKey("Last Backup Date").toString(); } catch (Exception e) { e.printStackTrace(); return null; } return date; }
a64b0e62-5fe1-4931-866f-8b832637edc3
9
@Override public byte[] write(DataOutputStream out, PassthroughConnection ptc, KillableThread thread, boolean serverToClient) { if(!serverToClient || (!ptc.clientInfo.getLocalCache())) { return super.write(out, ptc, thread, serverToClient); } else { int length = super.lengthUnit.getValue(); byte[] buffer = super.getValue(); if(Globals.compressInfo()) { ptc.printLogMessage("Hashes stored at client:" + ptc.setHashes.size()); ptc.printLogMessage("Initial size:" + length); } ChunkScan chunkScan = ptc.chunkScan; if(chunkScan.expandChunkData(buffer, length, buffer, ptc) == null) { if(Globals.compressInfo()) { ptc.printLogMessage("Expansion of chunk failed"); } return super.write(out, ptc, thread, serverToClient); } chunkScan.generateHashes(ptc, buffer); boolean[] matches = new boolean[40]; for(int cnt=0;cnt<40;cnt++) { Long hash = ptc.hashes[cnt]; matches[cnt] = ptc.setHashes.contains(hash); ptc.setHashes.add(hash); } chunkScan.wipeBuffer(ptc, buffer, matches); Integer newLength = chunkScan.recompressChunkData(buffer, true, ptc.hashes, ptc); if(newLength == null) { if(Globals.compressInfo()) { ptc.printLogMessage("Expansion of chunk failed"); } return super.write(out, ptc, thread, serverToClient); } super.lengthUnit.setValue(-newLength); if(Globals.compressInfo()) { ptc.printLogMessage("Recompressed size: " + newLength); } return super.write(out, ptc, thread, serverToClient); } }
79cc802f-932c-4b35-8c7a-ee2342e9438c
3
public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); int a[] = new int[n]; //int diff[]=new int[n]; int sum=0; // HashMap<Integer,Integer> map=new HashMap<Integer,Integer>(n); for(int a_i=0; a_i < n; a_i++){ a[a_i] = in.nextInt(); //System.out.println(a[a_i]); } ArrayList list=createComboSum(a); for(int c=0; c<list.size();c++){ //System.out.println(list.get(c)); if((Integer)list.get(c) %k==0){ sum=sum+1; } } System.out.println(sum); }
fae208f1-886d-4e90-b0e1-bdda5fe27130
1
public void writeAssertion(CycAssertion cycAssertion) throws IOException { if (trace == API_TRACE_DETAILED) { Log.current.println("writeAssertion = " + cycAssertion.toString()); } write(CFASL_EXTERNALIZATION); write(CFASL_ASSERTION); writeList(cycAssertion.getFormula()); writeObject(cycAssertion.getMt()); }
66504366-6c2f-4556-abea-babfc00308ba
6
public final WaiprParser.statdefs_return statdefs() throws RecognitionException { WaiprParser.statdefs_return retval = new WaiprParser.statdefs_return(); retval.start = input.LT(1); CommonTree root_0 = null; Token char_literal36=null; Token char_literal38=null; ParserRuleReturnScope statdef35 =null; ParserRuleReturnScope statdef37 =null; CommonTree char_literal36_tree=null; CommonTree char_literal38_tree=null; RewriteRuleTokenStream stream_17=new RewriteRuleTokenStream(adaptor,"token 17"); RewriteRuleTokenStream stream_IE=new RewriteRuleTokenStream(adaptor,"token IE"); RewriteRuleSubtreeStream stream_statdef=new RewriteRuleSubtreeStream(adaptor,"rule statdef"); try { // Waipr.g:36:9: ( statdef ( ',' statdef )* ';' -> ( statdef )* ) // Waipr.g:36:11: statdef ( ',' statdef )* ';' { pushFollow(FOLLOW_statdef_in_statdefs253); statdef35=statdef(); state._fsp--; stream_statdef.add(statdef35.getTree()); // Waipr.g:36:19: ( ',' statdef )* loop10: while (true) { int alt10=2; int LA10_0 = input.LA(1); if ( (LA10_0==17) ) { alt10=1; } switch (alt10) { case 1 : // Waipr.g:36:20: ',' statdef { char_literal36=(Token)match(input,17,FOLLOW_17_in_statdefs256); stream_17.add(char_literal36); pushFollow(FOLLOW_statdef_in_statdefs258); statdef37=statdef(); state._fsp--; stream_statdef.add(statdef37.getTree()); } break; default : break loop10; } } char_literal38=(Token)match(input,IE,FOLLOW_IE_in_statdefs262); stream_IE.add(char_literal38); // AST REWRITE // elements: statdef // token labels: // rule labels: retval // token list labels: // rule list labels: // wildcard labels: retval.tree = root_0; RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.getTree():null); root_0 = (CommonTree)adaptor.nil(); // 36:38: -> ( statdef )* { // Waipr.g:36:41: ( statdef )* while ( stream_statdef.hasNext() ) { adaptor.addChild(root_0, stream_statdef.nextTree()); } stream_statdef.reset(); } retval.tree = root_0; } retval.stop = input.LT(-1); retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0); adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); } catch (RecognitionException re) { reportError(re); recover(input,re); retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re); } finally { // do for sure before leaving } return retval; }
d8a461f2-c3d8-4a09-bd6d-dc3cd523118a
3
public void setMaxParticleNumber(int maxParticles) { if (maxParticles <= 0) { throw new IllegalArgumentException("The maximum particle number cannot be set to zero or less!"); } if (particleArray == null || maxParticles != particleArray.length) { particleArray = new Particle[maxParticles]; } }
c502adef-c1da-4db6-a608-7d2ada678758
1
public Date getDateTime() throws ParseException { if (dateTime == null) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); dateTime = sdf.parse(dateTimeStr); } return dateTime; }
01c6bb2b-e470-476d-afed-c25712a3c505
2
private boolean contensFuncionario(String nome) { for (Funcionario f : funcionarios) { if (f.getNome().equalsIgnoreCase(nome)) { return true; } } return false; }
fb9a7c51-812d-4e78-8080-8d8172bdf9b7
1
private static Schedule getSchedule(Schedule bean, PreparedStatement stmt, ResultSet rs) throws SQLException{ stmt.setDate(1, bean.getWorkDay()); stmt.setString(2, bean.getUsername()); rs = stmt.executeQuery(); if (rs.next()) { Schedule newBean = new Schedule(); newBean.setWorkDay(rs.getDate("work_day")); newBean.setFrom(rs.getTime("work_from")); newBean.setTo(rs.getTime("work_till")); newBean.setHourRate(rs.getBigDecimal("hourly_rate")); newBean.setVacationDays(rs.getInt("vac_days")); newBean.setUsername(rs.getString("username")); return newBean; } else { System.out.println("unable to retrieve schedule info"); return null; } }
b1c3b585-1242-46e4-8bf1-cd900b882939
2
public static void main(String[] args) { int x = 5; if (x < 5) if (x > 5) System.out.println('b'); else System.out.println('a'); }
588e1c4f-1aaa-4abd-9574-675b8718f2d8
0
public int getPageSize() { return pageSize; }
d5e32f25-6634-4241-b30f-76aca6e667fa
4
private void updateLasers(){ Iterator l = map.getLasers(); Laser laser; Object player; double x1, y1, x2, y2; while(l.hasNext()){ laser = (Laser)l.next(); player = laser.getParent(); if(player instanceof Ship){ //moves the players laser with reguards to his/her mouse. x1 = (float)((Ship)player).getNose().noseX; y1 = (float)((Ship)player).getNose().noseY; double mouseX = inputManager.getMouseX(); double mouseY = inputManager.getMouseY(); x2 = ((Ship)player).getX()-(screen.getWidth()/2-mouseX)+(32); y2 = ((Ship)player).getY()-(screen.getHeight()/2-mouseY)+(32); //remove x totalPower from parent ship for each second //the laser has been going, where x is the current power of the laser. double elapsedLaserTime = System.currentTimeMillis() - laser.getLastUpdate(); double powerDiff = Laser.getPowerDifference(laser, elapsedLaserTime); double newTotalPower = ((Ship)player).getTotalPower()-powerDiff; if(newTotalPower <3 )newTotalPower = 3; ((Ship)player).setTotalPower(newTotalPower); }else{ Object target = ((Turret)player).getTarget(); if(target instanceof Ship){ Ship s = (Ship)target; x2 = s.getX()+s.getWidth()/2; y2 = s.getY()+s.getHeight()/2; }else{ Sprite p = (Sprite)target; x2 = p.getX()+p.getWidth()/2; y2 = p.getY()+p.getHeight()/2; } x1 = (float)((Turret)player).getX(); y1 = (float)((Turret)player).getY(); } laser.setLastUpdate(System.currentTimeMillis()); laser.getLine().setLine(x1, y1, x2, y2); checkLaserCollisions(laser); } }
cd3cbecb-2bd0-40ff-ba5e-7a893401258a
2
@Override public boolean equals(Object o) { if(o instanceof VariableReference) { VariableReference v = (VariableReference)o; return this.getInnerValue().equals(v.getInnerValue()) && this.getVariable().equals(v.getVariable()); } return false; }
73074180-5978-4758-a882-874d9e1fea00
4
public static void main(String[] args) { if (args.length < 4) { System.err .println("Usage: JPLEphemerisSerialiser filename start-date end-date outputfile"); System.exit(1); } String filename = args[0]; double jdstart = Double.parseDouble(args[1]); double jdfinis = Double.parseDouble(args[2]); String outputfilename = args[3]; JPLEphemeris ephemeris = null; try { ephemeris = new JPLEphemeris(filename, jdstart, jdfinis); } catch (JPLEphemerisException jee) { jee.printStackTrace(); System.err.println("JPLEphemerisException ... " + jee); System.exit(1); } catch (IOException ioe) { ioe.printStackTrace(); System.err.println("IOException ... " + ioe); System.exit(1); } try { FileOutputStream ostream = new FileOutputStream(outputfilename); ObjectOutputStream oos = new ObjectOutputStream(ostream); oos.writeObject(ephemeris); oos.close(); } catch (IOException ioe) { ioe.printStackTrace(); System.err.println("IOException when serialising ephemeris ... " + ioe); System.exit(1); } }
2c85d16b-853f-448f-8ce9-c21588cd7dea
2
@Override public String toString() { String name = getName(); String append = ""; if(name != null && !name.equals("")) { append = "(\"" + this.getName() + "\")"; } return "TAG_Double" + append + ": " + value; }
afa05904-c27d-4331-898a-d533684d6fc8
3
protected void getImagePixels() { int w = image.getWidth(); int h = image.getHeight(); int type = image.getType(); if ((w != width) || (h != height) || (type != BufferedImage.TYPE_3BYTE_BGR)) { // create new image with right size/format BufferedImage temp = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR); Graphics2D g = temp.createGraphics(); g.drawImage(image, 0, 0, null); image = temp; } pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData(); }
0623f2d1-7ada-4d2b-b45b-620f7f388bd5
0
public String getType() { return type; }
ea18ea2e-c11b-464f-8d94-a6001902f5fc
7
@Override public void log(LogLevel logLevel, boolean isAuditMessage, Class<?> clazz, Throwable throwable, String pattern, Object... arguments) { switch (logLevel) { case DEBUG: debug(clazz, isAuditMessage, throwable, pattern, arguments); break; case ERROR: error(clazz, isAuditMessage, throwable, pattern, arguments); break; case FATAL: fatal(clazz, isAuditMessage, throwable, pattern, arguments); break; case INFO: info(clazz, isAuditMessage, throwable, pattern, arguments); break; case TRACE: trace(clazz, isAuditMessage, throwable, pattern, arguments); break; case WARN: warn(clazz, isAuditMessage, throwable, pattern, arguments); break; } }
1383156e-c97e-4d50-9b56-286c8a30eb54
7
public void runProtocoloDHCP() { try { // DHCPMessage messageIn = new DHCPMessage(); byte[] datos = new byte[1024]; DatagramPacket messageIn = new DatagramPacket(datos, datos.length); socket.receive(messageIn); pack = new PaqueteDHCP(messageIn.getData()); switch (pack.existInOption(53).getIntValue()) { case PaqueteDHCP.DISCOVER: System.out.println("DISCOVERY " + pack.getStringHexa(pack.getCHADDR())); DHCPlog.reportar("Recibido DISCOVERY de: [" + pack.getStringHexa(pack.getCHADDR()) + "] || FECHA: " + new Date()); try { manejarDiscovery(); } catch (NoRouteToHostException e) { // TODO Auto-generated catch block System.err .println("No pudo ser mandado: " + e.getMessage()); } break; case PaqueteDHCP.REQUEST: System.out.println("REQUEST " + pack.getStringHexa(pack.getCHADDR())); DHCPlog.reportar("Recibido REQUEST de: [" + pack.getStringHexa(pack.getCHADDR()) + "] || FECHA: " + new Date()); manejarRequest(); break; case PaqueteDHCP.DECLINE: System.out.println("DECLINE " + pack.getStringHexa(pack.getCHADDR())); DHCPlog.reportar("Recibido DECLINE de: [" + pack.getStringHexa(pack.getCHADDR()) + "] || FECHA: " + new Date()); manejarDecline(); break; case PaqueteDHCP.RELEASE: System.out.println("RELEASE " + pack.getStringHexa(pack.getCHADDR())); DHCPlog.reportar("Recibido RELEASE de : [" + pack.getStringHexa(pack.getCHADDR()) + "] || FECHA: " + new Date()); manejarRelease(); break; case PaqueteDHCP.INFORM: System.out.println("INFORM " + pack.getStringHexa(pack.getCHADDR())); DHCPlog.reportar("Recibido INFORM de : [" + pack.getStringHexa(pack.getCHADDR()) + "] || FECHA: " + new Date()); manejarInform(); break; default: System.out.println("Mensaje desconocido"); DHCPlog.reportar("Mensaje recibido es desconocido... Ignorando..."); break; } } catch (Exception e) { System.out.println(e); e.printStackTrace(); } }
5514ef9c-f8c7-468d-bbff-a05a327a7918
5
public boolean equals(Object obj) { if (obj instanceof ProgramImpl) { List<Reaction> otherProgramReactions = ((ProgramImpl) obj).getReactions(); for (Reaction r : otherProgramReactions) { if (!this.reactions.contains(r)) { return false; } } for (Reaction r : this.reactions) { if (!otherProgramReactions.contains(r)) { return false; } } return true; } else { return false; } }
a55ee992-3fea-4249-b2ed-c573fafb012e
5
private void cargarTemporadajButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cargarTemporadajButtonActionPerformed // Carga la temporada que se ha seleccionado. int tempIndex = temporadaList.getSelectedIndex();// se obtiene el indice en cual se encuentra la temporada this.rutaCategoriaActual = categorias.get(tempIndex).getRuta(); this.temporadaActual = categorias.get(tempIndex).getName(); this.listDriversModel.removeAllElements(); this.listaTeamsModel.removeAllElements(); pilotos.clear(); pistasList.removeAll(); this.temporadas.getScenes().clear(); this.temporadas.setFullTrackList(new ArrayList()); if(ruta.contains("F1 Challenge 99-02")){ leerArchivoRfm(this.rutaCategoriaActual,true); buscarDirectorio(ruta.concat("\\" + this.temporadas.getVehDir()), crearRegex("*.veh"), true, false); } else{ leerArchivoRfm(this.rutaCategoriaActual,false); buscarDirectorio(ruta.concat("\\" + this.temporadas.getVehDir()), crearRegex("*.veh"), true, false); } teamList.setModel(this.listaTeamsModel); // aplicar el Listmodel de equipos pilotosList.setModel(this.listDriversModel); //aplicar el ListModel de pilotos pistasList.setModel(this.temporadas.getScenes()); for (int i = 0; i < pilotos.size(); i++) { if (this.listaTeamsModel.contains(pilotos.get(i).getTeam())) { this.listaTeamsModel.addElement(pilotos.get(i).getTeam()); } } for (int i = 0; i < pilotos.size(); i++) { if (pilotos.get(i).getNumber() < 10) { this.listDriversModel.addElement("0" + pilotos.get(i).getNumber() + " - " + pilotos.get(i).getName()); } else { this.listDriversModel.addElement(pilotos.get(i).getNumber() + " - " + pilotos.get(i).getName()); } } jTabbedPane1.setEnabled(true); checkState(); }//GEN-LAST:event_cargarTemporadajButtonActionPerformed
248bd07c-daa2-4cdf-9ea9-3ce7b705d92c
0
public List findByOutputFormat(Object outputFormat) { return findByProperty(OUTPUT_FORMAT, outputFormat); }
c94f9d0e-18bb-4f53-bc09-f5198db191f0
5
private void readMaze (String filePath){ try (Scanner scan = new Scanner(new File(filePath));){ this.width = scan.nextInt(); this.height = scan.nextInt(); scan.nextLine(); for (int i=0; i<height; i++){ String[] myList = scan.nextLine().split(" "); List<Integer> row = Arrays.asList(myList).stream(). mapToInt(Integer::parseInt).boxed().collect(Collectors.toList()); for (int j=0; j<width; j++){ if (row.get(j).intValue() == START) startP = new Point(j, i); if (row.get(j).intValue() == EXIT) exitP = new Point(j, i); } map.add(row); } } catch (FileNotFoundException e) { System.out.println("No such file " + filePath); System.exit(1); } }
b6205207-6dba-4452-949d-06f000246c3c
7
public void mergeSets(){ //System.out.println(""); // We repeat this process until we have at least 3 clusters while (spagenumbers.size()>3){ ArrayList<RGB> averages = new ArrayList<RGB>(); // Obtaining the average color for each cluster for (int i = 0; i<this.spagenumbers.size(); i++){ ArrayList<Integer> pages = this.spagenumbers.get(i); RGB ave = this.averageColorInSet(pages, this.rgbs); averages.add(ave); } //System.out.println(averages); //System.out.println(""); ArrayList<Double> distances = new ArrayList<Double>(); // Obtaining the distances between each set of pages for (int i = 0; i<averages.size()-1; i++){ double distance = distanceRGB(averages.get(i),averages.get(i+1)); distances.add(distance); } //System.out.println("Distances: "+distances); // Search for the minimum distance between a pair of sets Double min = Double.MAX_VALUE; for (int i = 0; i<distances.size(); i++){ if (distances.get(i)<min) min = distances.get(i); } int index = distances.indexOf(min); // Now that we know what sets we have to join, lets just join them ArrayList<Integer> newset = new ArrayList<Integer>(); for (int i=0; i<spagenumbers.get(index).size(); i++) newset.add(spagenumbers.get(index).get(i)); for (int i=0; i<spagenumbers.get(index+1).size(); i++) newset.add(spagenumbers.get(index+1).get(i)); spagenumbers.remove(index+1); spagenumbers.set(index, newset); //System.out.println(spagenumbers); } //System.out.println(""); }
cff140c0-21ca-475c-9ddc-749077928deb
8
public boolean accept(File f) { if (f.isDirectory()) { return true; } String extension = Utils.getExtension(f); if (extension != null) { if (extension.equals(Utils.tiff) || extension.equals(Utils.tif) || extension.equals(Utils.gif) || extension.equals(Utils.jpeg) || extension.equals(Utils.jpg) || extension.equals(Utils.png)) { return true; } else { return false; } } return false; }
eb082e0e-cf65-4ca8-b3ae-f9822a544563
6
public static void main(String[] args) { CutOperations operations = new CutOperations(); MyFileReader readContent = new MyFileReader(); String fileContent; if (args.length == 3) { // for delimiter String separator = args[1].substring(2, 3); int fieldNumber = Integer.parseInt(args[0].substring(2, 3)); fileContent = readContent.readFile(args[2]); String data = operations.cutByFieldAndSeparator(fieldNumber, separator, fileContent); String[] result = data.split("\r\n"); for (Object o : result) System.out.println(o); } try { if (args.length == 2) { // for field and character fileContent = readContent.readFile(args[1]); int fieldNumber = Integer.parseInt(args[0].substring(2, 3)); String character = args[0].substring(0, 2); String data; if (0 == character.compareTo("-f")) data = operations.cutByField(fileContent); else data = operations.cutByCharacter(fieldNumber, fileContent); String[] result = data.split("\r\n"); for (Object o : result) System.out.println(o); } } catch (Exception e) { System.err.println("Error"); } }
136f2584-e80a-4428-ab36-1be2cb596844
7
private JSONWriter append(String string) throws JSONException { if (string == null) { throw new JSONException("Null pointer"); } if (this.mode == 'o' || this.mode == 'a') { try { if (this.comma && this.mode == 'a') { this.writer.write(','); } this.writer.write(string); } catch (IOException e) { throw new JSONException(e); } if (this.mode == 'o') { this.mode = 'k'; } this.comma = true; return this; } throw new JSONException("Value out of sequence."); }
092b7a5e-24e4-4ec8-ac0c-fb38946aa7cc
9
public void reduce(Text prefix, Iterator<Text> iter, OutputCollector<Text, Text> output, Reporter reporter) throws IOException { //Map<String, Node> nodes = new HashMap<String, Node>(); List<Node> nodes = new ArrayList<Node>(); Map<String, Node> nodes_fr = new HashMap<String, Node>(); while(iter.hasNext()) { String msg = iter.next().toString(); String [] vals = msg.split("\t"); if (vals[2].equals(Node.NODEMSG)) { Node node = new Node(vals[1]); //node.fromNodeMsg(msg); node.parseNodeMsg(vals, 2); nodes_fr.put(node.getNodeId() + "|" + vals[0], node); if (vals[0].equals("f")) { //nodes.put(node.getNodeId(), node); nodes.add(node); } } else { throw new IOException("Unknown msgtype: " + msg); } } //Map<String, Node> Contained_Nodes = new HashMap<String, Node>(); //Map<String, Node> Filter_Nodes = new HashMap<String, Node>(); for (int i = 0; i < nodes.size(); i++) { Node node = nodes.get(i); for(String nodeid_dir : nodes_fr.keySet()) { //System.err.println(nodeid_dir + " XX"); String id = nodeid_dir.substring(0, nodeid_dir.indexOf("|")); String dir = nodeid_dir.substring(nodeid_dir.indexOf("|")+1); if (node.getNodeId().equals(id)) { continue; } Node verify_node = nodes_fr.get(nodeid_dir); String verify_str; if (dir.equals("f")){ verify_str = verify_node.str(); } else { verify_str = Node.rc(verify_node.str()); } if (node.str().equals(verify_str)) { if (node.getNodeId().compareTo(verify_node.getNodeId()) < 0) { node.setCoverage(node.cov()+1); node.addPairEnd(verify_node.getNodeId()); } else { node.setCustom("n", "1"); // n = CONTAINED reporter.incrCounter("Brush", "contained", 1); break; } } else { /* int distance = Node.getLevenshteinDistance(node.str(),verify_str); if (node.str().length() > verify_str.length()) { if ((float)distance/(float)node.str().length() < 0.03f) { if (node.getNodeId().compareTo(verify_node.getNodeId()) < 0) { node.setCoverage(node.cov()+1); node.addPairEnd(verify_node.getNodeId()); } else { node.setCustom("n", "1"); // n = CONTAINED reporter.incrCounter("Brush", "contained", 1); break; } } } else if (node.str().length() < verify_node.str().length()) { if ((float)distance/(float)verify_node.str().length() < 0.03f) { if (node.getNodeId().compareTo(verify_node.getNodeId()) < 0) { node.setCoverage(node.cov()+1); } else { node.setCustom("n", "1"); // n = CONTAINED reporter.incrCounter("Brush", "contained", 1); break; } } } else { if ((float)distance/(float)node.str().length() < 0.03f) { if (node.getNodeId().compareTo(verify_node.getNodeId()) < 0) { node.setCoverage(node.cov()+1); } else { node.setCustom("n", "1"); // n = CONTAINED reporter.incrCounter("Brush", "contained", 1); break; } } }*/ } // for different length /*if (node.str().length() > verify_str.length() && node.str().substring(0, verify_str.length()).equals(verify_str)){ node.setCoverage(node.cov()+1); } else if (node.str().length() < verify_node.str().length() && verify_str.substring(0, node.str().length()).equals(node.str().length())) { node.setCustom("n", "1"); // n = CONTAINED break; }*/ } output.collect(new Text(node.getNodeId()), new Text(node.toNodeMsg())); reporter.incrCounter("Brush", "nodecount", 1); } }
b9b876b1-80d7-4650-8c5a-e53e656c0341
7
public static void main(String[] args) { name = ""; client = new Client(); RegisterClasses.register(client.getKryo()); client.start(); //Input address String address = "127.0.0.1"; String addressInput = getInput("Enter address IP or leave blank for default:"); if (!"".equals(addressInput)){ address = addressInput; } else{ //Search for address System.out.println("Searching for local address..."); InetAddress addr = client.discoverHost(54777, 5000); if (addr!=null){ address = new String(addr.getHostAddress()); } else{ System.out.println("No local address could be found. Please start up a local server or input the IP of a machine that has a server running."); System.exit(0); } } //Request 'login' details name = getInput("What is your name?"); if (name.length()==0) name = "Guest"; //Connect to server try{ System.out.println("Connecting to : "+address+" (TCP:54555) (UDP:54777)"); client.connect(5000, address, 54555, 54777); SomeRequest request = new SomeRequest(); request.text = "("+name+")"+" has connected"; client.sendTCP(request); } catch(Exception e){ e.printStackTrace(); System.out.println("Could not connect to server. Exitting..."); System.exit(0); } //Listen to server client.addListener(new Listener() { public void received (Connection connection, Object object) { if (object instanceof SomeResponse) { SomeResponse response = (SomeResponse)object; System.out.println(response.text); } } }); System.out.println("Welcome ("+name+"). Hit ctrl+c at any point to leave. Type a message below to start chatting"); //Loop application input while(true){ input=""; input = "["+name+"] "+getInput(""); if (input.length()>0){ SomeRequest request = new SomeRequest(); request.text = input; client.sendTCP(request); } } }
25f60d72-0835-4458-992e-b7eba2bdada6
3
private void getDMESG(final Device device) { new Thread() { @Override public void run() { try { final File ADB = adbController.getADB(); ProcessBuilder process = new ProcessBuilder(); List<String> args = new ArrayList<>(); args.add(ADB.getAbsolutePath()); args.add("-s"); args.add(device.getSerial()); args.add("shell"); args.add("dmesg"); process.command(args); process.redirectErrorStream(true); Process pr = process.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(pr.getInputStream())); String line = null; dmesg_androidTextArea.setText(""); while (getLogcat && (line = reader.readLine()) != null) { dmesg_androidTextArea.append(line + "\n"); } } catch (IOException ex) { logger.log(level.ERROR, "Error occurred while reading device's (" + device.getSerial() + ") logcat!\n\tError stack trace will be printed to console!"); JOptionPane.showMessageDialog(null, "ERROR: An error occurred while reading the device's (" + device.getSerial() + ") logcat.\n" + "Please read the program's output and send the stack trace to the developer.", "Error Reading Logcat", JOptionPane.ERROR_MESSAGE); ex.printStackTrace(System.err); interrupt(); } interrupt(); } }.start(); }
64fd9a30-2f57-4c3d-b64f-461e7866e14b
7
public boolean isBlockHere(int x, int y, int z) { if((x >= 0 && y >= 0 && z >= 0) && (x < chunkW && y < chunkH && z < chunkD)) { if (data[x + (y * chunkW) + (z * chunkW * chunkH)]) { return true; } return false; } return false; }