method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
442b8e60-cab3-4db2-aa17-80d1486c8275
0
public Listener getListener(String name) { return this.listeners.get(name); }
8c6abb55-85d6-4798-bd07-b52d1ca3f110
8
private static void computeDerivatives(Image image, Mask gaussian, double[][] lx2, double[][] ly2, double[][] lxy) { int w = image.getWidth(), h = image.getHeight(); Image gx = MaskUtils.applyMask(image, MaskFactory.buildSobelMask(Direction.HORIZONTAL)); Image gy = MaskUtils.applyMask(image, MaskFactory.buildSobelMask(Direction.VERTICAL)); for (int x = 0; x < w; x++) { for (int y = 0; y < h; y++) { for (int dx = -gaussian.getHeight() / 2; dx <= gaussian.getWidth()/2 ; dx++) { for (int dy = -gaussian.getHeight() / 2; dy <= gaussian.getHeight()/2; dy++) { int xk = x + dx; int yk = y + dy; if (xk >= 0 && xk < w && yk >= 0 && yk < h) { double f = gaussian.getValue(dx, dy); double gxp = gx.getPixel(xk, yk, RED), gyp = gy .getPixel(xk, yk, RED); lx2[x][y] += f * gxp * gxp; ly2[x][y] += f * gyp * gyp; lxy[x][y] += f * gxp * gyp; } } } } } }
83a18a6c-4c3f-4e38-a0cd-9668523e84a6
6
@Override public void ParseIn(Connection Main, Server Environment) { List<Integer> SendTo = new ArrayList<Integer>(); List<Integer> Failed = new ArrayList<Integer>(); int count = Main.DecodeInt(); for (int i = 0; i < count; i++) { SendTo.add(Main.DecodeInt()); } ServerMessage Message = new ServerMessage(); Environment.InitPacket(135, Message); Environment.Append(Main.Data.Id, Message); Environment.Append(Main.DecodeString(), Message); for(int UserId : SendTo) { Player Client = Environment.ClientManager.GetClient(UserId); if(Client == null) { Failed.add(UserId); continue; } if((Client.Flags & Server.plrOnline) != Server.plrOnline) { Failed.add(UserId); continue; } Environment.EndPacket(Client.Connection.Socket, Message); } if(!Failed.isEmpty()) { Environment.InitPacket(262, Main.ClientMessage); Environment.Append(1, Main.ClientMessage); Environment.Append(Failed.size(), Main.ClientMessage); for(int UserId : Failed) { Environment.Append(UserId, Main.ClientMessage); } Environment.EndPacket(Main.Socket, Main.ClientMessage); } }
639f43d3-98df-42bc-9056-f1c06229bd8e
6
public void actionPerformed(ActionEvent e) { String[] args = getArgs(e); String channel = args[0]; String sender = args[1]; String source = args[2]; String message = args[3]; if (isCommand("accountage", message)) { if (acebotCore.hasAccess(channel, sender, channelAccess, userAccess, accessExceptionMap)) { BufferedReader reader; String target; if (!message.contains(" ")) target = sender; else target = message.split(" ")[1]; try { URL url = new URL("https://api.twitch.tv/kraken/users/" + target); reader = new BufferedReader(new InputStreamReader(url.openStream())); String blah = reader.readLine(); if(!(blah.startsWith("{\"error\""))){ blah = blah.split("\"created_at\":\"")[1]; String time = blah.split("\"")[0].replace("T", " at "); acebotCore.addToQueue(channel, target + " created the account at " + time, Integer.parseInt(source)); } else { acebotCore.addToQueue(channel, "That user does not exist.", Integer.parseInt(source)); } } catch (MalformedURLException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } } } }
c9af2450-b583-49f1-9b23-dc11731e874e
0
public Rectangle2D getBounds() { return this; }
9ea6d67b-113b-4d8a-ad6e-add455dbaa27
2
public void ClearGrid() { for (int r=0; r < ROWS; r++) { for (int c=0; c < COLS; c++) { colorGrid[r][c] = new Colors(); } } }
33263bc2-9bcd-4783-9a43-1a788c43f7bf
7
public List<Log_record> GetLog(access_level acc_level, Date begin_dat, Date end_dat) { String all_file = ""; InputStream file_in = null; try { file_in = c.get("/var/log/sunprint/business/business.inf"); byte[] buf = new byte[1024]; int reded_buf_size = buf.length; while(reded_buf_size == buf.length) { try { //StringReader sr = new StringWriter(); reded_buf_size = file_in.read(buf, 0, buf.length); all_file += new String(buf,0,reded_buf_size); System.out.println("= " + reded_buf_size); } catch (IOException e) { e.printStackTrace(); } } try { file_in.close(); } catch (IOException e) { e.printStackTrace(); } } catch (SftpException e) { e.printStackTrace(); } List<Log_record> out_list = new ArrayList<Log_record>(); List<Log_record> from_file = Log_record.FileToRecords(all_file); for(Log_record lr : from_file) if(lr.GetDate().getTime() > begin_dat.getTime() && lr.GetDate().getTime() < end_dat.getTime() ) out_list.add(lr); return out_list; }
35fa510f-7b9a-4962-a3e1-19c246d0b684
9
public static boolean hasIntersection(final Collection a, final Collection b) { if (a.size() < 50 && b.size() < 50) { Iterator it = a.iterator(); while(it.hasNext()) if (b.contains(it.next())) return true; } else if (a.size() < b.size()) { HashSet bSet = new HashSet(b); Iterator it = a.iterator(); while(it.hasNext()) if (bSet.contains(it.next())) return true; } else { HashSet aSet = new HashSet(a); Iterator it = b.iterator(); while(it.hasNext()) if (aSet.contains(it.next())) return true; } return false; }
b2650897-f669-40d0-992b-5ba581928401
0
public void addText(String text) { this.text.append(text); }
ee24309c-4270-40f6-be81-4596f4edf44d
5
public CustomPanel(int row, int col, Player p1, Player p2, TicTacToeBoard state) { location = new Position(); location.row = row; location.col = col; chosen = false; player1 = p1; player2 = p2; turnState = state; addMouseListener( new MouseAdapter() { /** * This is the mouseClicked event handler. It passes information * about which JPanel was chosen to the appropriate human player. * @param event The reference to the MouseEvent information */ public void mouseClicked (MouseEvent event) { if(!CustomPanel.this.chosen) { if((turnState.getTurn() == TicTacToeBoard.PLAYER_X) && (player1.getPlayerType() == Player.HUMAN_PLAYER)) { ((Human)player1).setChosenSquare(location.row, location.col); CustomPanel.this.chosen = true; } else if((turnState.getTurn() == TicTacToeBoard.PLAYER_O) && (player2.getPlayerType() == Player.HUMAN_PLAYER)) { ((Human)player2).setChosenSquare(location.row, location.col); CustomPanel.this.chosen = true; } } } } ); }
a6614ceb-51b0-4cb3-96bb-7e12ba06d066
0
protected ConnectionProcessor getConnectionProcessor() { return connectionProcessor; }
7d44bb9a-e465-42fc-8741-d9ff18900b91
4
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Troupes other = (Troupes) obj; if (!Objects.equals(this.nom, other.nom)) { return false; } if (!Objects.equals(this.couleur, other.couleur)) { return false; } return true; }
bd589614-d3ef-4c0c-8c97-ef1eedf8f971
7
protected Item getPoison(MOB mob) { if(mob==null) return null; if(mob.location()==null) return null; for(int i=0;i<mob.location().numItems();i++) { final Item I=mob.location().getItem(i); if((I!=null) &&(I instanceof Drink) &&(((Drink)I).containsDrink()) &&(((Drink)I).liquidType()==RawMaterial.RESOURCE_LAMPOIL)) return I; } return null; }
8ae5e801-579d-4c90-82e0-c0f1cd7f7bb9
9
public static void parseMeshRenderer(String line) { int intIndex; intIndex = line.indexOf("path"); if (intIndex == -1) System.out.println("MeshRenderers require a path!"); else { int t = intIndex + 4; char c = "a".charAt(0); String number = ""; while (c != "\"".charAt(0)) { c = line.charAt(t); number = number + line.charAt(t); if (t < line.length() - 1) t++; } number.replace(" ", ""); System.out.println("Camera FOV: " + number); intIndex = line.indexOf("near="); if (intIndex == -1) System.out.println("Camera type GameComponents require a near setting!"); else { t = intIndex + 5; number = ""; c = "a".charAt(0); while (c != " ".charAt(0)) { c = line.charAt(t); number = number + line.charAt(t); if (t < line.length() - 1) t++; } number.replace(" ", ""); System.out.println("Camera NEAR: " + number); intIndex = line.indexOf("far="); if (intIndex == -1) System.out.println("Camera type GameComponents require a far setting!"); else { t = intIndex + 4; number = ""; c = "a".charAt(0); while (c != " ".charAt(0)) { c = line.charAt(t); number = number + line.charAt(t); if (t < line.length()) t++; } number.replace(" ", ""); System.out.println("Camera FAR: " + number); } } } }
c55c9751-ce80-4893-b61d-f4ea4075abb6
2
public static String IPToString(int ip){ StringBuilder sb = new StringBuilder(); for(int i=3; i>=0; i--){ sb.append((ip & (0xFF << (i*8))) >>> (i*8)); if(i > 0) sb.append('.'); } return sb.toString(); }
877e197d-d3f6-492c-88ea-1ee68e9aaae8
8
private static boolean isDirectObservation(Term term) { if (term.var != null) { return true; } else if (term.operation.isBehavorial()) { // check whether it has hidden varable boolean found = false; for (int i=0; i<term.subterms.length; i++) { if (term.subterms[i].var != null && term.subterms[i].var.sort.isHidden()) { found = true; break; } } if (found) { return ! term.operation.resultSort.isHidden(); } else { for (int i=0; i<term.subterms.length; i++) { if (!isDirectObservation(term.subterms[i])) { return false; } } return true; } } else { return false; } }
e0e5523f-d916-4f81-a49b-d04f3ea3b0ef
8
public double compute( RowD1Matrix64F mat ) { if( width != mat.numCols || width != mat.numRows ) { throw new RuntimeException("Unexpected matrix dimension"); } // make sure everything is in the proper state before it starts initStructures(); // System.arraycopy(mat.data,0,minorMatrix[0],0,mat.data.length); int level = 0; while( true ) { int levelWidth = width-level; int levelIndex = levelIndexes[level]; if( levelIndex == levelWidth ) { if( level == 0 ) { return levelResults[0]; } int prevLevelIndex = levelIndexes[level-1]++; double val = mat.get((level-1)*width+levelRemoved[level-1]); if( prevLevelIndex % 2 == 0 ) { levelResults[level-1] += val * levelResults[level]; } else { levelResults[level-1] -= val * levelResults[level]; } putIntoOpen(level-1); levelResults[level] = 0; levelIndexes[level] = 0; level--; } else { int excluded = openRemove( levelIndex ); levelRemoved[level] = excluded; if( levelWidth == minWidth ) { createMinor(mat); double subresult = mat.get(level*width+levelRemoved[level]); subresult *= UnrolledDeterminantFromMinor.det(tempMat); if( levelIndex % 2 == 0 ) { levelResults[level] += subresult; } else { levelResults[level] -= subresult; } // put it back into the list putIntoOpen(level); levelIndexes[level]++; } else { level++; } } } }
317998bd-2f6e-48ed-bb75-0138177cf4c6
2
private List<LightGrenade> getLightGrenadesOfGrid(Grid grid) { final List<LightGrenade> lightGrenades = new ArrayList<LightGrenade>(); for (Element e : grid.getElementsOnGrid()) if (e instanceof LightGrenade) lightGrenades.add((LightGrenade) e); return lightGrenades; }
45a8963f-ad75-41fc-b1a7-44f05ad01d3a
4
public HashSet<BigInteger> getFactors(BigInteger n) { HashSet<BigInteger> factors = new HashSet<BigInteger>(); while (true) { for (BigInteger i : primes) { if (n.remainder(i).equals(ZERO)) { n = n.divide(i); factors.add(i); break; } } if (n.equals(ONE)) return factors; } }
fc092fba-9070-46fd-8d7e-73aa7cdc1773
0
public String location() { return "Acceptable only at select locations."; }
44c090b0-2bdb-4394-8da1-a7d721fe25d7
7
final int method1714(int i, int i_2_) { anInt5926++; if (((Class239) this).aClass348_Sub51_3136.method3425(-114)) return 3; if (((Class239) this).aClass348_Sub51_3136.method3422(674) == Class10.aClass230_186) { if ((i_2_ ^ 0xffffffff) == -1) { if (((Class348_Sub51) ((Class239) this).aClass348_Sub51_3136) .aClass239_Sub16_7247.method1789(-32350) == 1) return 2; if ((((Class348_Sub51) ((Class239) this).aClass348_Sub51_3136) .aClass239_Sub24_7235.method1820(i + -32353) ^ 0xffffffff) == -2) return 2; if ((((Class348_Sub51) ((Class239) this).aClass348_Sub51_3136) .aClass239_Sub18_7259.method1800(-32350) ^ 0xffffffff) < -1) return 2; } return 1; } if (i != 3) method1710(57); return 3; }
df9e5905-3394-4a03-85f2-bd8c8a6f49ec
0
public int getMax() { return seat.length; }
74cd81cf-ccff-45d7-a9d6-295f796e9fc2
1
public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { Spel spel = new Spel(); KiesOnderwerp ko = new KiesOnderwerp(spel); spel.openPanel(ko); ko.updateUI(); } catch (Exception e) { e.printStackTrace(); } } }); }
5c6ab0c8-0ee3-4d25-ba21-5d1643a6f0dd
6
protected void checkEdge() { if ((xmin < containerXMin || getXMax() > containerXMax) && run != 0) { run *= -1; } if ((ymin < 0 || getYMax() > containerYMax) && rise != 0) { rise *= -1; } }
00a4a35d-4efd-410a-bcc6-448e91f753cf
5
private void readNext() //exclusively for token { current = next; if(current != null) buffer = new StringTokenizer(current); StringTokenizer temp = null; do { try { next = myInFile.readLine(); } catch (IOException e) { e.printStackTrace(); } if(next != null) temp = new StringTokenizer(next); } while(!(next == null || temp.hasMoreTokens())); }
db6e22ae-153e-4e48-ba55-4f0a56abb486
5
@Override public Response info(InfoRequest request) throws IOException { Mac hmac=null; try { hmac = Mac.getInstance("HmacSHA256"); } catch (NoSuchAlgorithmException e) { System.err.println("NoSuchAlgorithmException (HmacSHA256 not valid): " + e.getMessage()); return new HmacErrorResponse("Integrity check failed."); } try { hmac.init(secretKey); } catch (InvalidKeyException e) { System.err.println("InvalidKeyException: " + e.getMessage()); return new HmacErrorResponse("Integrity check failed."); } hmac.update(request.toString().getBytes()); byte[] computedHash = hmac.doFinal(); boolean validHash = false; if(request.getKey()!=null){ byte[] receivedHash = Base64.decode(request.getKey()); validHash = MessageDigest.isEqual(computedHash,receivedHash); } if(validHash){ byte[] data = FileUtils.readFile(dir,request.getFilename()); if(data == null) return new MessageResponse("File does not exist!"); else { return new InfoResponse(request.getFilename(),data.length); } } else { shell.writeLine(request.toString()); return new HmacErrorResponse("Integrity check failed in info Request."); } }
9d991f94-a3e1-4d37-b5fa-4c1146a6c00a
6
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if(commandLabel.equalsIgnoreCase("playerlogger")){ if (args.length == 0) { sender.sendMessage(ChatColor.RED+"Usage: /playerlogger reload"); return false; } else if (args.length == 1){ //Reload if (args[0].equalsIgnoreCase("reload") && sender.hasPermission("PlayerLogger.reload")) { plugin.reloadConfig(); getConfig.getValues(); mysql.createDatabase(); sender.sendMessage(ChatColor.GREEN+"PlayerLogger Config Reloaded"); } } else if (args.length < 2) { return false; } } return false; }
3f1100ce-4c81-42cc-9577-e021c13e4676
4
public void mouseClicked(int var1, int var2, int var3) { boolean var4 = this.isEnabled && var1 >= this.xPos && var1 < this.xPos + this.width && var2 >= this.yPos && var2 < this.yPos + this.height; this.setFocused(var4); }
0dc799c1-117a-4991-9a20-6b6e65730c81
8
public double proximity(CharSequence cSeq1, CharSequence cSeq2) { // really only need to create one of these; other can just it and add ObjectToCounterMap<String> tf1 = termFrequencyVector(cSeq1); ObjectToCounterMap<String> tf2 = termFrequencyVector(cSeq2); double len1 = 0.0; double len2 = 0.0; double prod = 0.0; for (Map.Entry<String,Counter> entry : tf1.entrySet()) { String term = entry.getKey(); Counter count1 = entry.getValue(); double tfIdf1 = tfIdf(term,count1); len1 += tfIdf1 * tfIdf1; Counter count2 = tf2.remove(term); if (count2 == null) continue; double tfIdf2 = tfIdf(term,count2); len2 += tfIdf2 * tfIdf2; prod += tfIdf1 * tfIdf2; } // increment length for terms in cSeq2 but not in cSeq1 for (Map.Entry<String,Counter> entry : tf2.entrySet()) { String term = entry.getKey(); Counter count2 = entry.getValue(); double tfIdf2 = tfIdf(term,count2); len2 += tfIdf2 * tfIdf2; } if (len1 == 0) return len2 == 0.0 ? 1.0 : 0.0; if (len2 == 0) return 0.0; double prox = prod / Math.sqrt(len1 * len2); return prox < 0.0 ? 0.0 : (prox > 1.0 ? 1.0 : prox); }
402d6262-49c4-4cd7-930e-336830ecb5d0
5
public void initializeForView(AutomatonPane view){ myView = view; setLocationManually(myAutoPoint); this.setDisabledTextColor(Color.BLACK); this.setBackground(new Color(255, 255, 150)); this.addMouseMotionListener(new MouseMotionListener(){ public void mouseDragged(MouseEvent e) { if (e.isPopupTrigger()) return; if(!((Note)e.getSource()).isEditable()){ int diffX = e.getPoint().x - initialPointClick.x; int diffY = e.getPoint().y - initialPointClick.y; int nowAtX = initialPointState.x+ diffX; int nowAtY = initialPointState.y +diffY; ((Note)e.getSource()).setLocationManually(new Point(nowAtX, nowAtY)); initialPointState = new Point(((Note)e.getSource()).getAutoPoint()); } else { //do normal select functionality } myView.repaint(); } public void mouseMoved(MouseEvent e) { // TODO Auto-generated method stub } }); this.addMouseListener(new MouseListener(){ public void mouseClicked(MouseEvent e) { if (myView.getDrawer().getAutomaton().getEnvironmentFrame() !=null) ((AutomatonEnvironment)myView.getDrawer().getAutomaton().getEnvironmentFrame().getEnvironment()).saveStatus(); ((Note)e.getComponent()).setEnabled(true); ((Note)e.getComponent()).setEditable(true); ((Note)e.getComponent()).setCaretColor(null); } public void mousePressed(MouseEvent e) { if (myView.getDrawer().getAutomaton().getEnvironmentFrame() !=null){ ((AutomatonEnvironment)myView.getDrawer().getAutomaton().getEnvironmentFrame().getEnvironment()).saveStatus(); ((AutomatonEnvironment)myView.getDrawer().getAutomaton().getEnvironmentFrame().getEnvironment()).setDirty(); } initialPointState = new Point(((Note)e.getSource()).getAutoPoint()); initialPointClick = new Point(e.getPoint().x, e.getPoint().y); //delete the text box EditorPane pane = myView.getCreator(); Tool curTool = pane.getToolBar().getCurrentTool(); if(curTool instanceof DeleteTool){ myView.remove((Note)e.getSource()); myView.getDrawer().getAutomaton().deleteNote((Note)e.getSource()); myView.repaint(); } } public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } }); myView.add(this); setEnabled(true); setEditable(true); setCaretColor(null); this.setSelectionStart(0); this.setSelectionEnd(this.getColumnWidth()); this.requestFocus(); }
fc771297-c6da-45e6-82c6-e0fd313dc353
6
@Override /** * A button has been clicked. */ public void actionPerformed( ActionEvent e ) { // get the action string String action = e.getActionCommand(); // the user has chosen to add a file if( action.equalsIgnoreCase( ADD_FILE ) ) { addFileToIndex(); } // the user has chosen to show files parsed else if( action.equalsIgnoreCase( SHOW_FILES ) ) { showFiles(); } // the user has chosen to remove a file else if( action.equalsIgnoreCase( REMOVE_FILE ) ) { removeFile(); } // the user has chosen to list the index else if( action.equalsIgnoreCase( LIST_INDEX ) ) { listIndex(); } // the user has chosen to search the index else if( action.equals( SEARCH_INDEX ) ) { searchIndex(); } // the user has chosen to exit the program else if( action.equalsIgnoreCase( EXIT_PROGRAM ) ) { exitProgram(); } }
33e61b14-395e-49d6-b118-1ddc66dd1272
2
public void clearShoppingCar(Map<?,?>shoppingCar){ shoppingCar.clear();; }
acdd892d-8f31-4cb0-836b-a4d9a3aa976f
7
public void unregisterListener(Listener listener){ listenerLock.lock(); try{ for(ListenerPriority priority : listeners.keySet()){ Set<RegisteredEventListener> toRemove = new HashSet<RegisteredEventListener>(); for(RegisteredEventListener regListener : listeners.get(priority)){ if(regListener.getListener() == listener){ toRemove.add(regListener); } } for(RegisteredEventListener regListener : toRemove){ listeners.get(priority).remove(regListener); } } }finally{ listenerLock.unlock(); } monitorLock.lock(); try{ Set<RegisteredEventMonitor> toRemove = new HashSet<RegisteredEventMonitor>(); for(RegisteredEventMonitor monitor : monitors){ if(monitor.getListener() == listener){ toRemove.add(monitor); } } for(RegisteredEventMonitor monitor : toRemove){ monitors.remove(monitor); } }finally{ monitorLock.unlock(); } }
cb7d6de7-8d92-4d4b-aad0-26bd923b387e
9
private String multiLineCommentFilter(String line) { if (line == null || line.equals("")) { return ""; } StringBuffer buf = new StringBuffer(); int index; //First, check for the end of a multi-line comment. if (inMultiLineComment && (index = line.indexOf("*/")) > -1 && !isInsideString(line,index)) { inMultiLineComment = false; buf.append(line.substring(0,index)); buf.append("*/").append(commentEnd); if (line.length() > index+2) { buf.append(inlineCommentFilter(line.substring(index+2))); } return buf.toString(); } //If there was no end detected and we're currently in a multi-line //comment, we don't want to do anymore work, so return line. else if (inMultiLineComment) { return line; } //We're not currently in a comment, so check to see if the start //of a multi-line comment is in this line. else if ((index = line.indexOf("/*")) > -1 && !isInsideString(line,index)) { inMultiLineComment = true; //Return result of other filters + everything after the start //of the multiline comment. We need to pass the through the //to the multiLineComment filter again in case the comment ends //on the same line. buf.append(inlineCommentFilter(line.substring(0,index))); buf.append(commentStart).append("/*"); buf.append(multiLineCommentFilter(line.substring(index+2))); return buf.toString(); } //Otherwise, no useful multi-line comment information was found so //pass the line down to the next filter for processesing. else { return inlineCommentFilter(line); } }
5141fdb6-339f-4cd4-ae6f-727da5a524d8
3
public void connect() throws Exception { if (!isDriverInitialized) { try { initDriver(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } this.readFile(); try { System.out.println(getDbURL()); System.out.println(getUser()); //Connection mit Oracle connection = (DriverManager.getConnection(getDbURL(), getUser(), getPass())); //Connection mit MySql //connection = (DriverManager.getConnection("jdbc:mysql://localhost/bla?" // + "user=" + getUser() + "&password=" + getPass())); } catch (SQLException e) { e.printStackTrace(); throw e; } }
421048e9-e1ef-4924-b3b9-8a470be407ae
2
private void siftDown(int pos) { if (2 * pos >= size) return; int maxI = getMaxInd(2 * pos, 2 * pos + 1); if (heap.get(maxI).compareTo(heap.get(pos)) > 0) { swap(pos, maxI); siftDown(maxI); } }
aef4784b-8880-4ddf-bc5a-42aa605136cf
9
public List<char[]> getResult(Combination guess, int[] score) { if(remainingCombos.size() == 0) { ComboMaker builder = new ComboMaker(charSet, length); for(char[] combo: builder) { Combination test; int[] testScore = new int[2]; try { test = new Combination(combo, charSet); testScore = test.judge(guess.clone()); } catch (Exception e) { e.printStackTrace(); } if(testScore[0] == score[0] && testScore[1] == score[1]) { remainingCombos.add(combo); } } } else { List<char[]> newCombos = new ArrayList<char[]>(); for(char[] combo: remainingCombos) { Combination test; int[] testScore = new int[2]; try { test = new Combination(combo, charSet); testScore = test.judge(guess.clone()); } catch (Exception e) { e.printStackTrace(); } if(testScore[0] == score[0] && testScore[1] == score[1]) { newCombos.add(combo); } } remainingCombos = newCombos; } return remainingCombos; }
b8287a94-43e9-42eb-9411-46981f595001
0
public QuestionCostLabel() { PriceManager.getInstance().addListener(this); setText(INIT_TEXT + PriceManager.getInstance().getPrice()); setFont(DefaultUIProvider.getQuestionPriceFont()); // priceLabel.setBorder(DefaultUIProvider.getDefaultEmptyBorder()); }
51dcf15d-c8c0-42ad-844d-0a6d2bdfdb05
9
public static void main(String[] args) { Scanner sc = new Scanner(System.in); while(true){ int n = sc.nextInt(); int m = sc.nextInt(); if((n|m)==0)break; int[] h = new int[n]; for(int i=0;i<n;i++)h[i]=sc.nextInt(); int[] w = new int[m]; for(int i=0;i<m;i++)w[i]=sc.nextInt(); int[] wh = new int[1500001]; int[] ww = new int[1500001]; for(int i=0;i<n;i++){ int s = 0; for(int j=i;j<n;j++){ s+=h[j]; wh[s]++; } } for(int i=0;i<m;i++){ int s = 0; for(int j=i;j<m;j++){ s+=w[j]; ww[s]++; } } int c = 0; for(int i=0;i<1500001;i++)c+=wh[i]*ww[i]; System.out.println(c); } }
6c66df1b-b1f6-4fe3-8654-a55f83faabf6
0
public ModeleApplication() { // ArrayList<Metadonnee> listeMetaDonnees = new // ArrayList<Metadonnee>(); metadonnee = new Metadonnee(new File("docs//test1.txt")); liste = new Liste(); }
05e1bda5-5fd0-4a31-a9fe-ca65915305d7
9
@Override public void run(){ stop = false; play = true; line.start(); while (!end){ if (play){ try { while (((bytesRead = audioInputStream.read(bytes, 0, bytes.length)) != -1) && !stop && play) { this.adjustVolume(); line.write(bytes, 0, bytesRead); } if(bytesRead == -1){ if(isLooping()){ this.RESTART(); this.START(); }else{ this.STOP(); } } } catch (IOException ex) {} } else{ try { Thread.sleep(99); } catch (InterruptedException ex) {} } } }
ab456798-e013-4202-bb9c-2bfcd019e0d5
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(dlgUsuariosMantenimiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(dlgUsuariosMantenimiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(dlgUsuariosMantenimiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(dlgUsuariosMantenimiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { dlgUsuariosMantenimiento dialog = new dlgUsuariosMantenimiento(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); }
769160bf-7a5d-4196-8650-6e9e049d8820
8
AbstractRegex parseClosure(StringStream stream) { switch (stream.peek()) { case '^': stream.poll(); return new HatRegex(); case '$': stream.poll(); return new DollarRegex(); } AbstractRegex term = parseTerm(stream); if (term == null) { return null; } switch (stream.peek()) { case '*': stream.poll(); return new ClosureRegex(term, 0); case '+': stream.poll(); return new ClosureRegex(term, 1); case '?': stream.poll(); return new ClosureRegex(term, 0, 1); case '{': stream.poll(); int start = parseNumber(stream); int end = start; if (stream.peek() == ',') { stream.poll(); end = parseNumber(stream); verify(start <= end, stream.getPos(), "Invalid repeat range"); } verify(stream.poll() == '}', stream.getPos(), "Missing '}'"); return new ClosureRegex(term, start, end); default: return term; } }
5ff5d7f2-a9d9-46e7-ba89-1ac08e4f73f2
1
public static void main(String[] args) { Sort_List s = new Sort_List(); // int[] list= {5,4,3,2,1}; // s.Merge(list); ListNode head = null; ListNode temp = new ListNode(0); head = temp; for (int i = 5; i > 0; i--) { ListNode node = new ListNode(i); temp.next = node; temp = node; } // s.listMergeSort(head.next); printList(s.sortList(head.next)); }
d86b2b6e-cb3b-4d84-a5f1-a7714c43ffb0
7
private long rec(int i, int current) { if (DP[i][current] != -1) return DP[i][current]; if (i >= M.length()) { return 1; } Integer x = M.charAt(i) - '0'; int next = 10 * current + x; long res = 0; if (next > 0 && next <= N) { res = rec(i + 1, next)%MOD; } if (i > 0 && x != 0 && x <= N) { res = (res + rec(i + 1, x))%MOD; } return DP[i][current] = res%MOD; }
4ac4b57b-ab9e-43d6-8763-b9f7ccc818b7
1
@Test public void ensureCoreBudgetItemsInBudgetContainsDifferentFormObjectTestTwo() { List<CoreBudgetItem> coreBudgetItemList = new ArrayList<CoreBudgetItem>(); coreBudgetItemList.add(new CoreBudgetItem("Test Description", new BigDecimal("200"))); when(budgetFormData.getCoreBudgetItemsList()).thenReturn(coreBudgetItemList); try { budget.buildBudget(budgetFormData); } catch (Exception e) { e.printStackTrace(); } assertTrue(budget.getCoreBudgetItemList().get(0).getItemMonetaryAmount().intValue() != 200); }
62d62f99-0b47-4fb2-a97c-58b060282ebe
2
public void onRemove(Player senderPlayer, String[] args) { Block targetBlock = senderPlayer.getTargetBlock(null, 100); if(targetBlock == null) { senderPlayer.sendMessage(ChatColor.DARK_RED + "You must be looking at a block while using this command!"); return; } if(FancyRoulette.instance.tableManager.removeBlockFromRoulette(targetBlock)) senderPlayer.sendMessage("You removed this block from the roulette."); else senderPlayer.sendMessage("This block isn't even in a roulette!"); }
e61d3461-6749-4d2e-8b76-1f620ec72350
5
public void incColonists(Object args[]) { final Background b = (Background) args[0] ; final int inc = (Integer) args[1], index = Visit.indexOf(b, COLONIST_BACKGROUNDS) ; int amount = colonists[index], total = 0 ; for (int i : colonists) total += i ; if (inc < 0 && amount <= 0) return ; if (inc > 0 && total >= MAX_COLONISTS) return ; colonists[index] += inc ; configForLanding(null) ; }
8741ee88-8308-4104-a191-da7b663ea6ec
8
public static List<List<String>> GoGraph(Stack<WordNode> path, List<List<String>> result, String end, List<WordNode> nextNode, Stack<Integer> Soncount) { int son = Soncount.firstElement(); while(!nextNode.isEmpty()) { int nextNodeson = 0; boolean noway = true; WordNode currentNode = nextNode.get(0); nextNode.remove(0); son--; // WordNode currentNode = path.firstElement(); // currentNode.inStack = true; if(currentNode.word.equals(end)) { List<String> newpath = new ArrayList<String>(); for(WordNode node : path) { newpath.add(node.word); } result.add(newpath); return result; }else { for(WordNode relation : currentNode.relations) { if(!relation.inStack) { nextNode.add(relation); relation.inStack = true; // path.remove(0).inStack = false; // break; noway = false; nextNodeson++; } } if(noway) { } else { Soncount.add(Integer.valueOf(nextNodeson)); if(son == 0) { path.add(currentNode); Soncount.remove(0); } GoGraph(path, result, end, nextNode, Soncount); if(path.size() != 1) { path.pop().inStack = false; } } } } return result; }
d92dc4b8-63bf-4c93-81a2-6664eb48ef68
4
protected void changeSelection(Collection<Object> added, Collection<Object> removed) { if ((added != null && !added.isEmpty()) || (removed != null && !removed.isEmpty())) { mxSelectionChange change = new mxSelectionChange(this, added, removed); change.execute(); mxUndoableEdit edit = new mxUndoableEdit(this, false); edit.add(change); fireEvent(new mxEventObject(mxEvent.UNDO, "edit", edit)); } }
696e7839-ffd1-4e2b-a010-80c83a001651
6
public static void solver(int input) { int leftVal = 0; int rightVal = 0; boolean leftFlag = false; boolean rightFlag = false; int valIn = input; while(leftFlag == false || rightFlag == false) { //left if(leftFlag == false) { if(checkLeft(valIn)) { leftVal = valIn; leftFlag = true; } } //right if(rightFlag == false) { if(checkRight(valIn)) { rightVal = valIn; rightFlag = true; } } //clean up valIn--; } System.out.println(leftVal); System.out.println(rightVal); }
d91b809e-7aaf-401e-96c1-67388364986a
4
public void updateSubTypes() { int offset = 0; if (!isStatic()) { subExpressions[offset++].setType(Type.tSubType(getClassType())); } Type[] paramTypes = methodType.getParameterTypes(); for (int i = 0; i < paramTypes.length; i++) { Type pType = (hints != null && hints[i + 1] != null) ? hints[i + 1] : paramTypes[i]; subExpressions[offset++].setType(Type.tSubType(pType)); } }
73a6ad14-47b8-4ccf-b918-4e6c71d3735a
4
public static double[][] subtract(double A[][], double B[][]){ if(A.length != B.length || A[0].length != B[0].length) return null; double T[][] = new double[A.length][A[0].length]; for(int i = 0; i<T.length; i++){ for(int j = 0; j<T[0].length; j++){ T[i][j] = A[i][j]-B[i][j]; } } return T; } //end subtract method
2e7af19d-846e-45e0-9b1c-41e1a29d4b55
3
private String buildPath() { StringBuffer builder = new StringBuffer(); if (this.protocol != null) { builder.append(this.protocol); } if (this.host != null) { builder.append("://"); builder.append(this.host); } if (this.port > 0) { builder.append(":"); builder.append(this.port); } return builder.toString(); }
2bbd088d-2f70-4ab7-80c5-7929dd87e356
0
public Items getLast() { return last; }
2d4c3228-144f-47e2-9ef0-16bef2cd5b30
9
public String eventDescription(Event e){ //by Budhitama Subagdja String desc = ""; desc = desc + "At (" + e.x + "," + e.z +") "; desc = desc + "Health: " + e.curHealth + " "; if(e.emeDistance<1){ desc = desc + "Enemy Detected! Distance: " + e.emeDistance; } desc = desc + "\n"; if(!e.hasAmmo) desc = desc + "|Empty Ammo| "; if(e.reachableItem) desc = desc + "|Item detected|"; if(e.behave1) desc = desc + "|Doing A|"; if(e.behave2) desc = desc + "|Doing B|"; if(e.behave3) desc = desc + "|Doing C|"; if(e.behave4) desc = desc + "|Doing D|"; if(e.reward >=1){ desc = desc + "\n"; desc = desc + "FEELS GOOD!"; } if(e.reward <=0){ desc = desc + "\n"; desc = desc + "HURT!"; } return desc; }
b5a1d784-0b22-4a0d-a5e4-fe788a900296
8
public static void main(String args[]) { Scanner scan = new Scanner(System.in); System.out.println("Digite a palavra:"); String[] word = scan.nextLine().split(""); int errors = 0; boolean right; String[] player = new String[word.length]; player[0] = ""; for (int i = 1; i < player.length; i++) { player[i] = "_"; } while (8 >= errors) { System.out.println(); System.out.println("Digite o seu chute:"); String guess = scan.next(); right = false; for (int i = 1; i < word.length; i++) { if (word[i].equals(guess)) { player[i] = guess; right = true; } } System.out.println(); for (int i = 1; i < player.length; i++) { System.out.print(player[i]); } System.out.println(); if (Arrays.equals(player, word)) { System.out.println("Parabéns você acertou!"); break; } else if (!right) { errors++; } } if (errors >= 8) { System.out.println("Forca :/"); } }
870369d3-2a48-42d9-8110-cfceaa1181b3
8
private boolean checkAutoInsert() { if (autoInsert && lastKeyPressedEvent != null) { // down in the last row triggers auto-insert if (prevRowIndex == (this.getRowCount()-1) && (lastKeyPressedEvent.getKeyCode() == KeyEvent.VK_DOWN)) { this.invokeRowInsert(); return true; // tab or enter in the last cell triggers auto-insert } else if (prevRowIndex == (this.getRowCount()-1) && (prevColumnIndex == this.getColumnCount()-1) && (lastKeyPressedEvent.getKeyCode() == KeyEvent.VK_TAB || lastKeyPressedEvent.getKeyCode() == KeyEvent.VK_ENTER)){ this.invokeRowInsert(); return true; } } return false; }
4aec176e-f8b9-44e4-a386-9273a9929739
2
@Override public Object execute(HttpServletRequest request, HttpServletResponse response) throws Exception { Contexto oContexto = (Contexto) request.getAttribute("contexto"); oContexto.setVista("jsp/mensaje.jsp"); ProfesorBean oProfesorBean = new ProfesorBean(); ProfesorDao oProfesorDao = new ProfesorDao(oContexto.getEnumTipoConexion()); ProfesorParam oProfesorParam = new ProfesorParam(request); oProfesorBean = oProfesorParam.loadId(oProfesorBean); try { oProfesorBean = oProfesorParam.load(oProfesorBean); } catch (NumberFormatException e) { return "Tipo de dato incorrecto en uno de los campos del formulario"; } try { oProfesorDao.set(oProfesorBean); } catch (Exception e) { throw new ServletException("PofesorController: Update Error: Phase 2: " + e.getMessage()); } return "Se ha modificado la información del profesor con id=" + Integer.toString(oProfesorBean.getId()); }
f7bd07f9-894f-4e91-ad8f-ec9ba28d48ef
2
public void setName(String name) { mName = name == null || name.length() == 0 ? " " : name; //$NON-NLS-1$ }
f81ad19e-7ef5-45a7-83a0-29766e03871e
5
public void run() { if (!inputFile.exists()) { return; } try { final FileReader reader = new FileReader(inputFile); parser = new TencTokenMaker(reader); parser.parse(); syntaxTreeBuilder = new AbstractSyntaxTreeBuilder(parser); final Program program = syntaxTreeBuilder.build(); System.out.println(program.toString()); final Generator generator = new Generator(program); final List<AssemblyLine> assembly = generator.generate(); List<String> lines = Lists.newLinkedList(); for (AssemblyLine line : assembly) { if (line instanceof Comment && comments) { lines.add(line.generate()); } else { lines.add(line.generate()); } } IOUtils.writeLines(lines, null, new FileOutputStream(outputFile)); } catch (final Exception e) { e.printStackTrace(); } }
26276813-47da-49b6-a39d-aa08f264bb46
7
public void move(int xa, int ya) { if (xa != 0 && ya != 0) { move(xa, 0); move(0, ya); return; } //determine direction if (xa > 0) { dir = 1; } else if (xa < 0) { dir = 3; } else if (ya > 0) { dir = 2; } else if (ya < 0) { dir = 0; } if (!collision(xa, ya)) { x += xa; y += ya; } }
cf1cd1be-4177-49ba-95cb-ccc84c7d7275
9
int insertKeyRehash(char val, int index, int hash, byte state) { // compute the double hash final int length = _set.length; int probe = 1 + (hash % (length - 2)); final int loopIndex = index; int firstRemoved = -1; /** * Look until FREE slot or we start to loop */ do { // Identify first removed slot if (state == REMOVED && firstRemoved == -1) firstRemoved = index; index -= probe; if (index < 0) { index += length; } state = _states[index]; // A FREE slot stops the search if (state == FREE) { if (firstRemoved != -1) { insertKeyAt(firstRemoved, val); return firstRemoved; } else { consumeFreeSlot = true; insertKeyAt(index, val); return index; } } if (state == FULL && _set[index] == val) { return -index - 1; } // Detect loop } while (index != loopIndex); // We inspected all reachable slots and did not find a FREE one // If we found a REMOVED slot we return the first one found if (firstRemoved != -1) { insertKeyAt(firstRemoved, val); return firstRemoved; } // Can a resizing strategy be found that resizes the set? throw new IllegalStateException("No free or removed slots available. Key set full?!!"); }
052ac6df-85fc-4c81-b523-6bf65387322c
4
private static int produceValue(ArrayList<Integer> values) { // Calculates the average value int average = getAverageValue(values); //System.out.println("Average: " + average); // Finds and removes additional 0:s // And recalculates the average value (if needed) if (removeZeros(values, average)) average = getAverageValue(values); // Finds and removes too large values // And recalculates the average value (if needed) if (removeTooLargeValues(values, average)) average = getAverageValue(values); // Finds the most usual value int mostusual = getMostUsualValue(values); //System.out.println("Most usual: " + mostusual); // Returns the most usual value, if applicable // Also, if average is within the mistake margin, returns the // Average since it's more accurate if (mostusual != -1 && Math.abs(mostusual - average) > 5) return mostusual; // Recalculates the average value and returns it return average; }
2b783b1f-f94a-48e2-9732-201c5656a2ce
7
private static void freq(File file) throws Exception { //t@C=eretweetƂɓxz쐬o InputStreamReader isr = new InputStreamReader(new FileInputStream(file)); BufferedReader br = new BufferedReader(isr); String head = br.readLine(); //擪s(URL) int max = 0; int min = Integer.MAX_VALUE; HashMap<Integer, Integer> logMap = new HashMap<Integer, Integer>(); String line = new String(); int key; while((line = br.readLine()) != null) { StringTokenizer st = new StringTokenizer(line, ","); int lineInt = Integer.parseInt(st.nextToken()); key = lineInt/pitch; if (key > max) max = key; if (key < min) min = key; int value; if (logMap.containsKey(key)) { value = logMap.get(key); value++; logMap.put(key, value); } else { logMap.put(key, 1); } } br.close(); isr.close(); File outFile = new File(file.getPath().replaceFirst("\\.csv", "\\.freq.csv")); OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(outFile)); BufferedWriter bw = new BufferedWriter(osw); if (outFile.length() == 0) { bw.write(head); bw.newLine(); bw.write("Min = ," + min*pitch + ", Max = ," + max*pitch); //Ot`pMin-Max𖾋LĂ bw.newLine(); } for (int i = min; i <= max; i++) { if (logMap.containsKey(i)) bw.write(String.format("%d,%d", i*pitch, logMap.get(i))); else bw.write(String.format("%d,%d", i*pitch, 0)); bw.newLine(); } System.out.println("Complete: " + outFile.getName()); bw.close(); osw.close(); }
35e34f14-5323-4204-84a2-193965f20c77
1
public static void sendMailSynchron(String subject, String content, String email, Boolean force) { // 先判断是否开启发邮件功能,如果未开启,直接退出。 // String enable = "1";// PropertyManager.getInstance().getDbProperty(PropertyManager.DB_EMAIL_ENABLE); // if (!force && !enable.equals("0")) { // return; // } // 邮件服务器发送代码。 try { JavaMailSender javaMailSenderImpl = getMailSender(); MimeMessage msg = javaMailSenderImpl.createMimeMessage(); MimeMessageHelper helper; helper = new MimeMessageHelper(msg, false, "utf-8"); String from = "52673406@qq.com";//PropertyManager.getInstance().getDbProperty(PropertyManager.DB_EMAIL_FROM); // if (StringUtil.isBlank(from)) { // throw new MessagingException("发送地址不能为空"); // } // if (StringUtil.isBlank(email)) { // throw new MessagingException("收信地址不能为空"); // } // if (StringUtil.isBlank(subject)) { // throw new MessagingException("主题不能为空"); // } // if (StringUtil.isBlank(content)) { // throw new MessagingException("内容不能为空"); // } helper.setFrom(from); helper.setTo(email); helper.setSubject(subject); helper.setText(content, true); javaMailSenderImpl.send(msg); } catch (Exception e) { e.printStackTrace(); } }
8a1b2055-0573-4e98-8082-066ea07a04eb
6
final void method2874(int i, boolean bool, Class348_Sub43 class348_sub43) { try { anInt8909++; int i_94_ = (((Class348_Sub19_Sub1) (((Class348_Sub43) class348_sub43) .aClass348_Sub19_Sub1_7077)) .aByteArray8984).length; int i_95_; if (bool && (((Class348_Sub19_Sub1) (((Class348_Sub43) class348_sub43) .aClass348_Sub19_Sub1_7077)) .aBoolean8987)) { int i_96_ = (i_94_ + i_94_ + -((Class348_Sub19_Sub1) (((Class348_Sub43) class348_sub43) .aClass348_Sub19_Sub1_7077)).anInt8986); i_95_ = (int) ((long) (((Class348_Sub16_Sub3) this) .anIntArray8914 [(((Class348_Sub43) class348_sub43) .anInt7067)]) * (long) i_96_ >> 1439097542); i_94_ <<= 8; if (i_94_ <= i_95_) { i_95_ = i_94_ + i_94_ - 1 - i_95_; ((Class348_Sub43) class348_sub43) .aClass348_Sub16_Sub5_7081.method2891(true); } } else i_95_ = (int) (((long) i_94_ * (long) (((Class348_Sub16_Sub3) this) .anIntArray8914 [(((Class348_Sub43) class348_sub43) .anInt7067)])) >> -1975078330); if (i > 93) ((Class348_Sub43) class348_sub43).aClass348_Sub16_Sub5_7081 .method2924(i_95_); } catch (RuntimeException runtimeexception) { throw Class348_Sub17.method2929(runtimeexception, ("ma.WA(" + i + ',' + bool + ',' + (class348_sub43 != null ? "{...}" : "null") + ')')); } }
5602a4bb-d8e8-414c-b9f6-3aec9769e855
3
public static void bubbleSort(int[] unsorted){ System.out.println("unsorted array before sorting : " + Arrays.toString(unsorted)); // Outer loop - need n-1 iteration to sort n elements for(int i=0; i<unsorted.length -1; i++){ //Inner loop to perform comparision and swapping between adjacent numbers //After each iteration one index from last is sorted for(int j= 1; j<unsorted.length -i; j++){ //If current number is greater than swap those two if(unsorted[j-1] > unsorted[j]){ int temp = unsorted[j]; unsorted[j] = unsorted[j-1]; unsorted[j-1] = temp; } } System.out.printf("unsorted array after %d pass %s: %n", i+1, Arrays.toString(unsorted)); } }
2625713b-e28a-41fc-bfc5-0625280c9205
1
@Override public String toString () { if ( this.socketFile == null ) { return super.toString(); } return super.toString() + " (socket: " + this.socketFile + ")"; }
18d1cc95-3757-404b-bd20-3f3a6cd9212d
0
public void notifyAllRemoteListeners(Message message) { distributedService.sendMessage(message); }
52d9dcb0-2081-4c80-9c63-d7ec276efba8
0
public void delete(int id){ travelTripDao.delete(id); }
20b74565-8bef-4c7a-ae90-8b39feb66e7a
1
public DrawableImage(String imageURL) { this.imageURL=imageURL; //Loading the image from URL into bufferedImage ImageLoader=new BufferedImageLoader(); try { bufferedImage=ImageLoader.loadImage(imageURL); } catch (IOException e) { e.printStackTrace(); } }
69ed877a-ec9e-4a9a-9af3-07ae451774a2
3
private void update(DocumentEvent e){ Integer key = null; Document eventDocument = e.getDocument(); //find the key for (Entry<Integer, Document> entry: textBoxDocuments.entrySet()){ if (entry.getValue() == eventDocument){ key = entry.getKey(); break; } } //find textbox and value JTextField textBox = textBoxes.get(key); TileObjectDisplayDatum datum = data.get(key); //process the data datum.setValue(textBox.getText()); if (datum.isValid()){ textBox.setBackground(Color.WHITE); } else { textBox.setBackground(Color.PINK); } infoPanel.setDirty(true); }
8d3ed302-b570-4fd9-bf4d-732cdd7ee19f
8
@Override public void unInvoke() { final Physical P=affected; super.unInvoke(); if((P instanceof MOB)&&(this.canBeUninvoked)&&(this.unInvoked)) { if((!P.amDestroyed())&&(((MOB)P).amFollowing()==null)) { final Room R=CMLib.map().roomLocation(P); if(!CMLib.law().doesHavePriviledgesHere(invoker(), R)) { if((R!=null)&&(!((MOB)P).amDead())) R.showHappens(CMMsg.MSG_OK_ACTION, P,L("<S-NAME> wander(s) off.")); P.destroy(); } } } }
28e91c50-4b48-4e7c-9dd4-91a0751841b4
8
static public void formatStandard(Writer w, Object obj) throws IOException{ if(obj == null) w.write("null"); else if(obj instanceof String) { w.write('"'); w.write((String) obj); w.write('"'); } else if(obj instanceof Character) { w.write('\\'); char c = ((Character) obj).charValue(); switch(c) { case '\n': w.write("newline"); break; case '\t': w.write("tab"); break; case ' ': w.write("space"); break; case '\b': w.write("backspace"); break; case '\f': w.write("formfeed"); break; default: w.write(c); } } else w.write(obj.toString()); }
00ef3a84-28a6-4d45-b000-1135f3b2ab33
7
public Set<ANode> getConnectedNodes(ANode root, int level) { if (level < 0) { throw new IllegalArgumentException(); } if (level == 0) { return Collections.singleton(root); } final Set<ANode> result = new HashSet<ANode>(); if (level == 1) { for (ALink link : links) { if (link.getNode1() == root) { result.add(link.getNode2()); } else if (link.getNode2() == root) { result.add(link.getNode1()); } } } else { for (ANode n : getConnectedNodes(root, level - 1)) { result.addAll(getConnectedNodes(n, 1)); } } return Collections.unmodifiableSet(result); }
7b52d84d-6e64-41b5-99e6-64499d83bede
0
public void eatDiamant(Diamant dia) { stomache += dia.getPoints(); dia.setCatched(); }
8e245ad8-dc22-4a88-bdaa-1769c0b46f38
5
public static void setOccupance(int x, int y){ for(int a = 0; a < 80; a++){ for(int b = 0; b < 60; b++){ if(tile[a][b].preOccupied == true){ tile[a][b].occupied = true; }else if((x/Tile.tileSize) == a && (y/Tile.tileSize) == b){ tile[a][b].occupied = true; } else { tile[a][b].occupied = false; } } } }
cf0688da-785d-4ce5-b4c7-3963cb824ec7
4
public void setPaused(boolean paused) { if (rp != null && rp.isGameOver()) { gameIsPaused = false; return; } gameIsPaused = paused; if (rp != null && rp.getMenu() != null) rp.getMenu().popMenu(gameIsPaused); }
931b1b80-7830-42c5-b7ba-1cb982a18c26
7
@Override public int doStartTag() throws JspTagException { if (pages <= 0) { return SKIP_BODY; } try { JspWriter out = pageContext.getOut(); out.write("<table class='parameterRowB' border='1'><colgroup span='2' title='title' />"); if (head != null && !head.isEmpty()) { out.write("<thead><tr><th scope='col'>" + head + "</th></tr></thead>"); } if (pageNo != 0) { out.write("<thead><tr><th scope='col'>"); for (int i = 1; i <= pages; i++) { if (i != pageNo) { out.write("<a class='small labelH' href='controller?command=showpage&currPageNo=" + i + "'>" + i + "</a>"); } else { out.write("<a class='small labelH'>" + pageNo + "</a>"); } } out.write("</th></tr></thead>"); } out.write("<tbody><tr><td>"); } catch (IOException e) { throw new JspTagException(e.getMessage()); } return EVAL_BODY_INCLUDE; }
f6dfa501-6988-493d-b155-ca555159b5ba
6
public static VcfInfoType parse(String str) { str = str.toUpperCase(); if (str.equals("STRING")) return VcfInfoType.String; if (str.equals("INTEGER")) return VcfInfoType.Integer; if (str.equals("FLOAT")) return VcfInfoType.Float; if (str.equals("FLAG")) return VcfInfoType.Flag; if (str.equals("CHARACTER")) return VcfInfoType.Character; if (str.equals("UNKNOWN")) return VcfInfoType.UNKNOWN; throw new RuntimeException("Unknown VcfInfoType '" + str + "'"); }
0524e68e-4fd4-49e7-820d-6a3b3b947147
1
private void compute_pcm_samples7(Obuffer buffer) { final float[] vp = actual_v; //int inc = v_inc; final float[] tmpOut = _tmpOut; int dvp =0; // fat chance of having this loop unroll for( int i=0; i<32; i++) { final float[] dp = d16[i]; float pcm_sample; pcm_sample = (float)(((vp[7 + dvp] * dp[0]) + (vp[6 + dvp] * dp[1]) + (vp[5 + dvp] * dp[2]) + (vp[4 + dvp] * dp[3]) + (vp[3 + dvp] * dp[4]) + (vp[2 + dvp] * dp[5]) + (vp[1 + dvp] * dp[6]) + (vp[0 + dvp] * dp[7]) + (vp[15 + dvp] * dp[8]) + (vp[14 + dvp] * dp[9]) + (vp[13 + dvp] * dp[10]) + (vp[12 + dvp] * dp[11]) + (vp[11 + dvp] * dp[12]) + (vp[10 + dvp] * dp[13]) + (vp[9 + dvp] * dp[14]) + (vp[8 + dvp] * dp[15]) ) * scalefactor); tmpOut[i] = pcm_sample; dvp += 16; } // for }
37ea3b70-af42-4395-9957-b542575c88fa
9
protected void _realSendMessage() { if(null == _m_scSocket) return ; if(!_m_scSocket.isConnected()) { ALBasicSendingClientManager.getInstance().addSendSocket(this); return ; } boolean needAddToSendList = false; _lockBuf(); while(!_m_lSendBufferList.isEmpty()) { //Socket 允许写入操作时 ByteBuffer buf = _m_lSendBufferList.getFirst(); if(buf.remaining() <= 0) { ALServerLog.Error("try to send a null buffer"); ALServerLog.Error("Wrong buffer:"); for(int i = 0; i < buf.limit(); i++) { ALServerLog.Error(buf.get(i) + " "); } } try { _m_scSocket.write(buf); //判断写入后对应数据的读取指针位置 if(buf.remaining() <= 0) _m_lSendBufferList.pop(); else break; } catch (IOException e) { ALServerLog.Error("Client Socket send message error! socket id[" + getID() + "]"); e.printStackTrace(); break; } } //当需要发送队列不为空时,继续添加发送节点 if(!_m_lSendBufferList.isEmpty()) needAddToSendList = true; _unlockBuf(); if(needAddToSendList) ALBasicSendingClientManager.getInstance().addSendSocket(this); }
63e776a0-4186-46b6-a45a-3d607789ec95
9
public Color colores(int i){ Color c; switch (i) { case 0: c = new Color(153,153,153); //Gris break; case 1: case 2: case 3: case 4: c = new Color(195,255,104); //Verde break; case 5: case 6: case 7: case 8: c = new Color(255,152,94);//Azul break; default: c = new Color(0,0,0); //Negro break; } return c; }
eefd565a-6f6a-47e9-bd97-2e52bac838b5
2
public void testPropertySetMinute() { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40); LocalDateTime copy = test.minuteOfHour().setCopy(12); check(test, 2005, 6, 9, 10, 20, 30, 40); check(copy, 2005, 6, 9, 10, 12, 30, 40); try { test.minuteOfHour().setCopy(60); fail(); } catch (IllegalArgumentException ex) {} try { test.minuteOfHour().setCopy(-1); fail(); } catch (IllegalArgumentException ex) {} }
e6ba825e-c73c-4782-b432-4b714f5ea550
3
public void readFromSave(DataTag tag){ reloadMap(tag.readString("map")); GameTime = tag.readInt("gametime"); nightAlhpa = tag.readFloat("nightshade"); DataList list = tag.readList("content"); for(int i = 0; i < list.data().size(); i ++){ DataTag dt = list.readArray(i); String uin = dt.readString("UIN"); MapObject mo = Blocks.loadMapObjectFromString(uin, tileMap, this); if(mo == null) mo = Entity.createEntityFromUIN(uin, tileMap, this); if(mo != null){ mo.readFromSave(dt); listWithMapObjects.add(mo); }else{ System.out.println("The Entity for " + uin + " was not recognized. Skipped loading this entity"); } } }
4147d8dc-f563-4cde-8430-3ff6f3d4f113
0
public void driver() { System.out.println("bmw drive"); }
ee4e21b0-4c49-449f-9543-f192484c25dd
4
private String runAnOperation(int i, int j){ Double a=Double.parseDouble(calculatorSequence.get(i)); String s=calculatorSequence.get(i+1); Double b=Double.parseDouble(calculatorSequence.get(j)); double z=0; if (s.equals("+")) z= Add(a,b); if (s.equals("-")) z= Subtract(a,b); if (s.equals("*")) z= Multiply(a,b); if (s.equals("/")) z= Divide(a,b); return getDouble(z); }
2f6382d5-62d5-472f-b92a-79be0e404486
3
public void deleteOrderInfo(int orderID) throws SQLException{ try{ databaseConnector=myConnector.getConnection(); stmnt=(Statement) databaseConnector.createStatement(); SQLQuery="DELETE FROM familydoctor.order WHERE orderID="+"'"+orderID+"'"; stmnt.executeUpdate(SQLQuery); } catch(SQLException e){ System.out.println(e.getMessage()); } finally{ if(stmnt!=null) stmnt.close(); if(databaseConnector!=null) databaseConnector.close(); } }
724c0bf9-2cad-44af-a027-43f98506ebb2
7
public static void main(String[] args) throws IOException{ AdaptiveHuffmanTree aTree = new AdaptiveHuffmanTree(); int count = 0; int read = 0; String str = ""; while(StdIn.hasNextChar()){ char c = StdIn.readChar(); str = str+c; if(aTree.characterInTree(c)){ char[] chs = (aTree.getCodeWordFor(c).toString() ).toCharArray() ; for(char i : chs ){ BinaryStdOut.write(i =='1'); } aTree.update(c); count += chs.length; }else{ char[] chs = aTree.getCodeWordForNYT().toString().toCharArray(); for(char i : chs ){ BinaryStdOut.write(i =='1'); } aTree.update(c); BinaryStdOut.write(c); count += chs.length + 8; } read+=8; } if(count %8 !=0){ char[] chs = aTree.getCodeWordForNYT().toString().toCharArray(); for(int i = 0; i < 8 - (count%8); i++ ){ BinaryStdOut.write(chs[i%chs.length]=='1'); } } BinaryStdOut.flush(); String s = ""; s += str+"\n"; s += "bits read = "+read+"\n"; s += "bits transmitted = "+count+"\n"; double r = ((double)count/(double) read )*100; r = 100 -r; r = Math.round(r * 10); r = r/10; s += "compression ration = " + r+ "\n\n"; try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("statistics.txt", true)))) { out.write(s); }catch (IOException e) { //exception handling left as an exercise for the reader } }
c37110aa-dbaa-4371-8e38-bfd48815e816
9
private JSONObject serveAsJson(IHTTPSession request, Session session) { try { // get the handler class by URI // for example, "/welcome/login" => "api.welcome.login" String uri = request.getUri(); Class<?> cls = Class.forName("api" + uri.replaceAll("/", ".")); try { ApiHandler apiHandler = ((Class<ApiHandler>) cls).newInstance(); // get params Map<String, String> files = new HashMap<String, String>(); Method method = request.getMethod(); if (Method.PUT.equals(method) || Method.POST.equals(method)) { request.parseBody(files); } Map<String, String> params = request.getParms(); // give some help text if(params.containsKey("_help")) { JSONObject rtn = new JSONObject(); rtn.put("rtnCode", "200 ok"); rtn.put("help", apiHandler.showHelp()); return rtn; } // check if login is required if(apiHandler.requireLogin && session.getActiveUserId()<=0) { return CommonResponses.showUnauthorized(); } // check params if(!apiHandler.checkParams(params)) { JSONObject rtn = CommonResponses.showParamError(); rtn.put("help", apiHandler.showHelp()); return rtn; } // pass the request to the handler return apiHandler.main(params, session); } catch (Exception e) { return CommonResponses.showException(e); } } catch (ClassNotFoundException e) { // handler class not found return CommonResponses.showNotFound(); } }
2f40e51e-4885-4857-81a8-36686c8242d0
9
public void keyTyped(KeyEvent event) { if (viewType == MULTI_TEXTFIELD_VIEW) { char typed = event.getKeyChar(); if (! Character.isDigit(typed)) event.consume(); else if (event.getSource() != yearField) { JTextField field = (JTextField) event.getSource(); String text = field.getText(); if (text.length() == 2 && (field.getSelectedText() == null || field.getSelectedText().length() != 2)) event.consume(); } else { String text = yearField.getText(); if (text.length() == 4 && (yearField.getSelectedText() == null || yearField.getSelectedText().length() != 4)) event.consume(); } } }
4977f29a-23b6-4a6c-a3a9-5f0c32f316b2
2
private static void method500(char arg0[]) { for (int i = 0; i < 2; i++) { for (int chars = Censor.aCharArrayArray621.length - 1; chars >= 0; chars--) { Censor.method509(Censor.aByteArrayArrayArray622[chars], arg0, Censor.aCharArrayArray621[chars]); } } }
af6c76aa-7896-43c5-a3e9-a97170a34ac7
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 ("Windows".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Elevapp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Elevapp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Elevapp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Elevapp.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 Elevapp().setVisible(true); } }); }
0acc7dba-1796-40d3-914b-f09937fcb9f9
2
private int setupOrderPosition(int valuePosition, int startIndex, int endIndex) { swap(valuePosition, endIndex); int firstBiggerValuePosition = startIndex; for (int i = startIndex; i <= endIndex; i++) { if(array[i] <= array[endIndex]) { swap(i, firstBiggerValuePosition++); } } return firstBiggerValuePosition - 1; }
cebd24be-6e72-4429-b77d-9ff8bd6a9feb
0
public void loadDimension(Dimension dim){ this.current = dim; attachChild(current); }
d290e183-b8f6-4e34-aa71-c29a5808fbb4
8
public final TLParser.indexes_return indexes() throws RecognitionException { TLParser.indexes_return retval = new TLParser.indexes_return(); retval.start = input.LT(1); Object root_0 = null; Token char_literal153=null; Token char_literal155=null; TLParser.expression_return expression154 = null; Object char_literal153_tree=null; Object char_literal155_tree=null; RewriteRuleTokenStream stream_CBracket=new RewriteRuleTokenStream(adaptor,"token CBracket"); RewriteRuleTokenStream stream_OBracket=new RewriteRuleTokenStream(adaptor,"token OBracket"); RewriteRuleSubtreeStream stream_expression=new RewriteRuleSubtreeStream(adaptor,"rule expression"); try { // src/grammar/TL.g:196:3: ( ( '[' expression ']' )+ -> ^( INDEXES ( expression )+ ) ) // src/grammar/TL.g:196:6: ( '[' expression ']' )+ { // src/grammar/TL.g:196:6: ( '[' expression ']' )+ int cnt35=0; loop35: do { int alt35=2; int LA35_0 = input.LA(1); if ( (LA35_0==OBracket) ) { alt35=1; } switch (alt35) { case 1 : // src/grammar/TL.g:196:7: '[' expression ']' { char_literal153=(Token)match(input,OBracket,FOLLOW_OBracket_in_indexes1480); stream_OBracket.add(char_literal153); pushFollow(FOLLOW_expression_in_indexes1482); expression154=expression(); state._fsp--; stream_expression.add(expression154.getTree()); char_literal155=(Token)match(input,CBracket,FOLLOW_CBracket_in_indexes1484); stream_CBracket.add(char_literal155); } break; default : if ( cnt35 >= 1 ) break loop35; EarlyExitException eee = new EarlyExitException(35, input); throw eee; } cnt35++; } while (true); // AST REWRITE // elements: expression // 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.tree:null); root_0 = (Object)adaptor.nil(); // 196:28: -> ^( INDEXES ( expression )+ ) { // src/grammar/TL.g:196:31: ^( INDEXES ( expression )+ ) { Object root_1 = (Object)adaptor.nil(); root_1 = (Object)adaptor.becomeRoot((Object)adaptor.create(INDEXES, "INDEXES"), root_1); if ( !(stream_expression.hasNext()) ) { throw new RewriteEarlyExitException(); } while ( stream_expression.hasNext() ) { adaptor.addChild(root_1, stream_expression.nextTree()); } stream_expression.reset(); adaptor.addChild(root_0, root_1); } } retval.tree = root_0; } retval.stop = input.LT(-1); retval.tree = (Object)adaptor.rulePostProcessing(root_0); adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); } catch (RecognitionException re) { reportError(re); recover(input,re); retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re); } finally { } return retval; }
8a32faf9-f41d-431b-92a8-f154bdefa2ad
4
private CtClass lookupClass0(String classname, boolean notCheckInner) throws NotFoundException { CtClass cc = null; do { try { cc = classPool.get(classname); } catch (NotFoundException e) { int i = classname.lastIndexOf('.'); if (notCheckInner || i < 0) throw e; else { StringBuffer sbuf = new StringBuffer(classname); sbuf.setCharAt(i, '$'); classname = sbuf.toString(); } } } while (cc == null); return cc; }
3ed923ce-2f0e-4356-9395-3668d90e7284
9
public void BuscaHorarioAula(String anoletivo, Date datahorario) { try { hapmb = new HorarioAulaProfMatDao().RetornaHorarioProfMat(anoletivo, datahorario); DefaultTableModel tabelahorario = (DefaultTableModel) jThorario.getModel(); tabelahorario.setNumRows(0); for (int i = 0; i < hapmb.size(); i++) { tabelahorario.addRow(new Object[]{hapmb.get(i).getCurso(), hapmb.get(i).getPeriodo(), hapmb.get(i).getInicio(), hapmb.get(i).getTermino(), (hapmb.get(i).getProfessorsegunda() + " : " + hapmb.get(i).getMateriasegunda()).equals(" : ")?"" :hapmb.get(i).getProfessorsegunda() + " : " + hapmb.get(i).getMateriasegunda(), (hapmb.get(i).getProfessorterca() + " : " + hapmb.get(i).getMateriaterca()).equals(" : ")?"" :hapmb.get(i).getProfessorterca() + " : " + hapmb.get(i).getMateriaterca(), (hapmb.get(i).getProfessorquarta() + " : " + hapmb.get(i).getMateriaquarta()).equals(" : ")?"" :hapmb.get(i).getProfessorquarta() + " : " + hapmb.get(i).getMateriaquarta(), (hapmb.get(i).getProfessorquinta() + " : " + hapmb.get(i).getMateriaquinta()).equals(" : ")?"" :hapmb.get(i).getProfessorquinta() + " : " + hapmb.get(i).getMateriaquinta(), (hapmb.get(i).getProfessorsexta() + " : " + hapmb.get(i).getMateriasexta()).equals(" : ")?"" :hapmb.get(i).getProfessorsexta() + " : " + hapmb.get(i).getMateriasexta(), (hapmb.get(i).getProfessorsabado() + " : " + hapmb.get(i).getMateriasabado()).equals(" : ")?"" :hapmb.get(i).getProfessorsabado() + " : " + hapmb.get(i).getMateriasabado(), (hapmb.get(i).getProfessordomingo() + " : " + hapmb.get(i).getMateriadomingo()).equals(" : ")?"" :hapmb.get(i).getProfessordomingo() + " : " + hapmb.get(i).getMateriadomingo(), hapmb.get(i).getAnoletivo(), new SimpleDateFormat("dd.MM.yyyy").format(hapmb.get(i).getDatageracao())}); } } catch (SQLException ex) { JOptionPane.showMessageDialog(null, "Erro ao Buscar Horario\n" + ex, "Gera Horario", JOptionPane.ERROR_MESSAGE); } }
1b71a42a-716f-441b-90a9-4c4c242aedb8
3
@Override public void onEndermanPickup(EndermanPickupEvent event) { if (event.isCancelled()) { return; } if (!this.config.yml.getBoolean("Enderman.Disable Pickup", true)) { return; } if (!event.isCancelled()) { event.setCancelled(true); } return; }