method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
03b47972-08c0-4ac1-8855-8427923b9e58
1
public void continueInference(InferenceParameters queryProperties) { String command = createInferenceContinuationCommand(queryProperties); DefaultSubLWorker newWorker = new DefaultSubLWorker(command, getCycServer(), true, getTimeoutMsecs()); /*newWorker.addListener(new SubLWorkerListener() { public void notifySubLWorkerStarted(SubLWorkerEvent event) {} public void notifySubLWorkerDataAvailable(SubLWorkerEvent event) {} public void notifySubLWorkerTerminated(SubLWorkerEvent event) {} });*/ newWorker.addListener(new SubLWorkerListener() { public void notifySubLWorkerStarted(SubLWorkerEvent event) { doSubLWorkerStarted(event); } public void notifySubLWorkerDataAvailable(SubLWorkerEvent event) { doSubLWorkerDataAvailable(event); } public void notifySubLWorkerTerminated(SubLWorkerEvent event) { doSubLWorkerTerminated(event); } }); try { newWorker.start(); } catch (java.io.IOException ioe) { throw new RuntimeException("Failed to continue inference (IOException)."); } //throw new UnsupportedOperationException("continueInference() needs to be implemented."); }
f9fc80aa-6944-45ce-a829-5841681b9bd8
9
String encode(String value) { StringBuffer sb = new StringBuffer(); int len = value.length(); for (int i = 0; i < len; i++) { char c = value.charAt(i); switch (c) { case '<': sb.append("&lt;"); break; case '>': sb.append("&gt;"); break; case '\'': sb.append("&apos;"); break; case '\"': sb.append("&quot;"); break; case '&': int nextSemi = value.indexOf(";", i); if (nextSemi < 0 || !isReference(value.substring(i, nextSemi + 1))) { sb.append("&amp;"); } else { sb.append('&'); } break; default: if (isLegalCharacter(c)) { sb.append(c); } break; } } return sb.substring(0); }
f86775b4-158f-434f-b377-48caad51ea51
7
private boolean checkInput(String input) { try { input = input.toLowerCase(); input = input.replace("$", ""); input = input.trim(); // Get the command, then strip it from the other data String command = input.substring(0,1); input = input.replaceFirst(command, ""); input = input.trim(); if (command.equals("r")) { // Restock restock(); } if (command.equals("q")) { // Quit return false; } if (command.equals("w")) { // Withdraw withdraw(Integer.parseInt(input)); System.out.println("Machine balance:"); status(); } if (command.equals("i")) { // Display denomination(s) String[] denomsString = input.split("\\s+"); Integer[] denomsInt = new Integer[denomsString.length]; for (int i = 0; i < denomsString.length; i++) { denomsInt[i] = Integer.parseInt(denomsString[i]); System.out.println(cashMachine.status(denomsInt[i])); } } } catch (NumberFormatException e) { System.out.println("Failure: Invalid Command"); } catch (Exception e) { System.out.println("Failure: Invalid Command"); } return true; }
df7cc979-ae5a-4fb1-88de-2ed4b5f0fe11
8
public NameNode(Library l, Hashtable h) { super(l, h); Object o = library.getObject(entries, "Kids"); if (o != null && o instanceof Vector) { Vector v = (Vector) o; kidsReferences = v; int sz = kidsReferences.size(); if (sz > 0) { kidsNodes = new Vector(sz); kidsNodes.setSize(sz); } } namesAreDecrypted = false; o = library.getObject(entries, "Names"); if (o != null && o instanceof Vector) { namesAndValues = (Vector) o; } o = library.getObject(entries, "Limits"); if (o != null && o instanceof Vector) { Vector limits = (Vector) o; if (limits.size() >= 2) { lowerLimit = decryptIfText(limits.get(0)); upperLimit = decryptIfText(limits.get(1)); } } }
f5206bf8-bb2b-4af3-85c4-c7599ab08578
0
public String getAccessToken() { return accessToken; }
5f12150c-9d44-4be0-9e99-e2c0e1b999e8
4
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("------------ RunningStatus ------------\n"); sb.append("[taskId] " + taskId + "\n"); sb.append("[RunningPhase] " + runningPhase + "\n"); sb.append("[isInMemMergeRunning] " + isInMemMergeRunning + "\n\n"); sb.append("------------ SegmentsInShuffle ------------\n"); sb.append(segsInShuffle + "\n"); if(mergeCombineFunc != null && mergeCombineFunc.getcCombineInputRecords() != -1) { sb.append("------------ memCombine() ------------\n"); sb.append(mergeCombineFunc + "\n"); } if(segmentsInReduceBuf != null) { sb.append("-------- SegmentsInReduceBuf --------\n"); for(Segment seg : segmentsInReduceBuf) sb.append(seg + "\n"); sb.append("\n"); } sb.append("------------ reduce() ------------\n"); sb.append(reduceFunc + "\n"); return sb.toString(); }
b49dfa8f-68e3-4759-93fb-a70ca077e11f
9
public double ai(int x, int y, int vx, int vy, int l) { double[] e = new double[5]; double d = Math.atan2(-(cy - y), (cx - x)) + Math.PI; // Calculate the // distance // The arc-distance values range from 0 to 2 PI. To solve border-cases // in the from 1.5 PI to 0.5 PI, checking is needed. if ((d - distance) > Math.PI) d -= 2 * Math.PI; if ((d - distance) < -Math.PI) d += 2 * Math.PI; if (l > 0) { // Check borders if (circ.terrain(x, y) <= 0) { vx = 0; vy = 0; if (!grass) l -= 2; // Penalty to get quicker results. } // If we're not done yet, check all possible routes. if (l > 0) { e[0] = ai(x + vx - 1, y + vy, vx - 1, vy, l - 1); e[1] = ai(x + vx + 1, y + vy, vx + 1, vy, l - 1); e[2] = ai(x + vx, y + vy - 1, vx, vy - 1, l - 1); e[3] = ai(x + vx, y + vy + 1, vx, vy + 1, l - 1); e[4] = ai(x + vx, y + vy, vx, vy, l - 1); // Next get the largest distance for (i = 0; i < 5; i++) { if (e[i] > d) { d = e[i]; j = i; } } } } if (l == level) return j; // If this was the top-thread, return the best route return d; // Else return the distance }
0046799b-d2a0-457f-ac42-a1d9ea5002ed
7
public static void calculateDistanceToOpponentBorder(BotState state) { List<Region> guessedOpponentSpots = HeuristicMapModel.getGuessedOpponentRegions(); // Give all guessed opponent spots a distance of 0 for (Region opponentSpot : guessedOpponentSpots) { opponentSpot.setDistanceToOpponentBorder(0); } // Give each other region a distance of 1000 as initialization for (Region region : state.getVisibleMap().getRegions()) { if (!guessedOpponentSpots.contains(region)) { region.setDistanceToOpponentBorder(1000); } } // Now do the real stuff boolean hasSomethingChanged = true; while (hasSomethingChanged) { hasSomethingChanged = false; for (Region region : state.getVisibleMap().getRegions()) { Region closestNeighbor = getClosestNeighborToOpponentBorder(state, region); if (closestNeighbor.getDistanceToOpponentBorder() < region.getDistanceToOpponentBorder() && region.getDistanceToOpponentBorder() != 1 + closestNeighbor.getDistanceToOpponentBorder()) { region.setDistanceToOpponentBorder(closestNeighbor.getDistanceToOpponentBorder() + 1); hasSomethingChanged = true; } } } }
1f9f23a1-998d-4e66-8e1c-50dd563695a2
2
@Override public void checkCollision(){ for(int i = 0; i < collisionThreads.length; ++i) pool.execute(collisionThreads[i]); //Give the collision threads as much time as we can, but this may cull them prematurely try { pool.awaitTermination(COLLISION_TIME, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { e.printStackTrace(); } }
3cc0d993-158c-45eb-bd94-95e64f5678d7
5
public static <T extends Number> ArrayList<ArrayList<T>> mulScalarWithMatrix(T scalar, ArrayList<ArrayList<T>> a, Class<T> type) { ArrayList<ArrayList<T>> result = new ArrayList<ArrayList<T>>(); try { if (a == null) { throw new NullPointerException(); } int rows = a.size(); int columns = a.get(0).size(); for (int i = 0; i < rows; i++) { ArrayList<T> row = new ArrayList<>(); for (int j = 0; j < columns; j++) { T elem = ElementOpUtils.mul(scalar, a.get(i).get(j), type); row.add(elem); } result.add(row); } return result; } catch (NullPointerException e) { Logger.getGlobal().log(Level.SEVERE, "cannot multiply null matrixes"); e.printStackTrace(); return null; } catch (IndexOutOfBoundsException e) { Logger.getGlobal().log(Level.SEVERE, "check your indexes when multiplying matrixes"); e.printStackTrace(); return null; } }
39dcdd02-1eb5-4cc9-a0a6-87439c098690
0
protected void finalize() throws Throwable { super.finalize(); socket.close(); }
15f109eb-8a32-4899-8560-974d1c3ae820
8
private static boolean evaluatePairing () { int toprank = 0; int botrank = 0; int topind = 0; int botind = 0; // gather the rank count data for (int i=Rank.NUM_RANK-1; i>=0; i--) { //int rankhashi = _rankhash[i]; int rankhashi = (int)((_rankhash>>(4*i)) & 0xF); if (rankhashi > toprank) { botrank = toprank; botind = topind; toprank = rankhashi; topind = i; } else if (rankhashi > botrank) { botrank = rankhashi; botind = i; } } // now pick the right hand from the data switch (toprank) { case 4: setFourOfAKind (topind, botind); return true; case 3: if (botrank > 1) { setFullHouse (topind, botind); return true; } else { setThreeOfAKind (topind); return true; } case 2: if (botrank > 1) { setTwoPair (topind, botind); return true; } else { setOnePair (topind); return true; } default: setNoPair (); return false; } }
0f4edabe-4299-4189-a9ef-5643b90c3c2f
3
public static ByteBuffer toBuffer(String value) { if (value == null || value.length() == 0) { return EMPTY; } ByteBuffer buffer = factory.allocate(value.length()); char[] chars = value.toCharArray(); // Convert from chars to bytes for (int i = 0; i < chars.length; i++) { buffer.put((byte)chars[i]); } buffer.flip(); return buffer; }
e1d176f2-4c4e-4826-8cc2-e7749d30165c
7
@Override public String toString() { switch (this) { case TOP_LEFT: return "TL"; case TOP: return "T"; case TOP_RIGHT: return "TR"; case BOT_RIGHT: return "BR"; case BOT: return "B"; case BOT_LEFT: return "BL"; case INIT: return "I"; } return "???"; }
a19ca574-c90e-4607-9aa6-983ae83bfc18
4
private void parseName() throws IOException { int c = in.peek(); while (Character.isLetterOrDigit(c) || c == '_' || c == ':' || c == '.') { out.append((char) in.read()); c = in.peek(); } }
0ca656f3-c1d1-40f6-8148-b6be7400870d
6
public ArrayList ResultSetToString(ResultSet rs) { String temp = ""; ArrayList<String> resultat = new ArrayList<>(); try { ResultSetMetaData rsMetaData = rs.getMetaData(); for (int i = 1; i <= rsMetaData.getColumnCount(); i++) { if (i == 1) { temp = rsMetaData.getColumnName(i); } else { temp = temp + " " + rsMetaData.getColumnName(i); } } resultat.add(temp); while (rs.next()) { temp = ""; for (int i = 1; i <= rsMetaData.getColumnCount(); i++) { if (i == 1) { temp = rs.getString(i); } else { temp = temp + " " + rs.getString(i); } } resultat.add(temp); } } catch (SQLException se) { System.out.println("We got an exception while getting a result:this" + " shouldn't happen: we've done something really bad."); System.out.println(se.getMessage()); } return resultat; }
6aacca22-0c0f-45ca-a528-39c717ded2cf
9
private int get_next_page(Page page, long boundary) { if (boundary > 0) { boundary += offset; } while (true) { int more; if (boundary > 0 && offset >= boundary) { return OV_FALSE; } more = oy.pageseek(page); if (more < 0) { offset -= more; } else { if (more == 0) { if (boundary == 0) { return OV_FALSE; } int ret = get_data(); if (ret == 0) { return OV_EOF; } if (ret < 0) { return OV_EREAD; } } else { int ret = (int) offset; //!!! offset += more; return ret; } } } }
576e037e-9498-451f-a39b-a246e0615218
1
public void action(OutStream outStream) throws IOException { outStream.writeSymbol('\n'); for (int j = 0; j < Format.indentLevel - 1; j++) { outStream.writeString(Format.indentString); } outStream.writeSymbol('}'); outStream.writeSymbol('\n'); Format.indent = true; Format.isNewLine = true; Format.indentLevel = Format.indentLevel - 1; }
23cb3828-184f-43d8-9b37-041b8fab17e7
4
private void orderTrackList() { for (int i = 0; i < calendarTracksListModel.getSize(); i++) { String pistaname = calendarTracksListModel.get(i).toString(); for (Iterator<Track> it = calendarTracks.iterator(); it.hasNext();) { Track pista = it.next(); if (pista.toString().contains(pistaname)) { boolean remove = calendarTracks.remove(pista); if (remove) { calendarTracks.add(i, pista); } break; } } } }
e0ca12cb-01e4-4e9c-8ad3-ca38e46d668b
4
public static Comparator printComparator() { if (Type.printComparator != null) { return (Type.printComparator); } Type.comparator = new Comparator() { public int compare(final Object o1, final Object o2) { // o1 < o2 : -1 // o1 == o2 : 0 // o1 > o2 : 1 if (!(o1 instanceof Type)) { throw new IllegalArgumentException(o1 + " not a Type"); } if (!(o2 instanceof Type)) { throw new IllegalArgumentException(o2 + " not a Type"); } final Type t1 = (Type) o1; final Type t2 = (Type) o2; final String d1 = t1.toString(); final String d2 = t2.toString(); return (d1.compareToIgnoreCase(d2)); } public boolean equals(final Object o) { if (o == this) { return (true); } else { return (false); } } }; return (Type.comparator); }
947ab22d-209e-4690-bfff-2f784b0f9723
2
@Override public String execute(SessionRequestContent request) throws ServletLogicException { String page = ConfigurationManager.getProperty("path.page.users"); String prevPage = (String) request.getSessionAttribute(JSP_PAGE); formUserList(request); if(page == null ? prevPage == null : !page.equals(prevPage)){ request.setSessionAttribute(JSP_PAGE, page); cleanSessionShowUsers(request); } return page; }
793785df-b8d3-4518-a9c9-8acffb9f09dc
1
private void notifyListeners() { for (TimeListener listener : listeners) listener.onTimeChanged(time); }
1d2695fe-1f9b-4aca-8452-999ff3df2d86
9
public static void main(String[] args) throws Exception { HashSet<Integer> placeboSet = getPlaceboSet(); HashMap<String, List<Double>> sampleMap = getsampleToPCOAMap(); System.out.println(sampleMap); BufferedWriter writer = new BufferedWriter(new FileWriter(new File(ConfigReader.getCrossoverExerciseDir() + File.separator + "pairedTTestTreatment.txt"))); writer.write("axis\tlog10PValue\tsampleSize\tpre\tpost\n"); for( int pcoaAxis=0; pcoaAxis<=5; pcoaAxis++) { List<Double> pre = new ArrayList<Double>(); List<Double> post = new ArrayList<Double>(); for(int x=1; x<=27;x++) if ( x != 8) { if(placeboSet.contains(x)) { List<Double> aPre = sampleMap.get(x + "A"); List<Double> aPost = sampleMap.get(x + "B"); if( aPre != null && aPost != null) { pre.add( aPre.get(pcoaAxis) ); post.add( aPost.get(pcoaAxis) ); } } else { List<Double> aPre = sampleMap.get(x + "D"); List<Double> aPost = sampleMap.get(x + "E"); if( aPre != null && aPost != null) { pre.add( aPre.get(pcoaAxis) ); post.add( aPost.get(pcoaAxis) ); } } } writer.write((pcoaAxis+1) + "\t"); writer.write( TTest.pairedTTest(pre, post).getPValue() + "\t" ); if(pre.size() != post.size()) throw new Exception("Logic error"); writer.write(pre.size() + "\t"); writer.write(pre + "\t"); writer.write(post + "\n"); } writer.flush(); writer.close(); }
92640552-e305-4fc1-9569-de70e1d388d8
8
public void setRegion(int left, int top, int width, int height) { if (top < 0 || left < 0) { throw new IllegalArgumentException("Left and top must be nonnegative"); } if (height < 1 || width < 1) { throw new IllegalArgumentException("Height and width must be at least 1"); } int right = left + width; int bottom = top + height; if (bottom > this.height || right > this.width) { throw new IllegalArgumentException("The region must fit inside the matrix"); } for (int y = top; y < bottom; y++) { int offset = y * rowSize; for (int x = left; x < right; x++) { bits[offset + (x >> 5)] |= 1 << (x & 0x1f); } } }
acbaac1a-50ee-428f-8cfa-72943c137341
7
public byte markTokensImpl(byte token, Segment line, int lineIndex) { if(line.count == 0) return Token.NULL; switch(line.array[line.offset]) { case '+': case '>': addToken(line.count,Token.KEYWORD1); break; case '-': case '<': addToken(line.count,Token.KEYWORD2); break; case '@': case '*': addToken(line.count,Token.KEYWORD3); break; default: addToken(line.count,Token.NULL); break; } return Token.NULL; }
2e45b309-aedc-4141-b503-a8623d0afbf0
6
public boolean IsOpt(char c) { if (c == '+' || c == '-' || c == '*' || c == '/' || c == '(' || c == ')') return true; else return false; }
af978ce6-d656-4ad5-bdf8-4364f02ac44c
2
public void offsetMove(Coord offset) { if(!isActual()) return; if(UI.instance.mapview != null) { Coord sz = UI.instance.mapview.sz; Coord sc = new Coord((int) Math.round(Math.random() * 200 + sz.x / 2 - 100), (int) Math.round(Math.random() * 200 + sz.y / 2 - 100)); Coord oc = position().add(offset); UI.instance.mapview.wdgmsg("click", sc, oc, 1, 0, gob_id, oc); } }
25939917-f427-4bb0-b549-da41849c7444
7
public void switchTo(String newFolder) { try { long start = System.currentTimeMillis(); if (songFolderLoc != null && songFolderLoc.equals(newFolder)) { Util.errorMessage( "Please don't try to load your entire osu! Songs Folder here.\n" + "It'll probably take forever and lag your computer.", this); return; } File f = new File(newFolder); // TODO thread properly, have loading screen if (f.exists() && f.isDirectory()) { directory = newFolder; c = new Consolidator(f); panel.remove(tabs); tabs = new AIBatTabbedPane(c); panel.add(tabs, BorderLayout.CENTER); this.invalidate(); this.validate(); fileOpened = true; if (tabs.getTabCount() <= AIBatTabbedPane.NUM_OVERALL) Util.errorMessage("No .osu files found.", this); this.setTitle(VERSION + " - " + Util.cutPath(newFolder)); tabs.requestFocusInWindow(); if (!menu.skipModTrace()) { modTraceThread.interrupt(); modTraceThread = new Thread(new ModTrace(c.getOsuFiles(), tabs, menu)); modTraceThread.start(); } } else Util.errorMessage("Folder not found.", this); Util.logTime(start); } catch (Exception e) { Util.errorException(e, newFolder); } }
a15d2dc3-91fb-4f30-9856-a45a56a540bd
9
public void traineval(Vector vector) { for(int i = 0; i < maxRound; i++) { training = true; BHypothesis.training = true; BHypothesis.MARGIN_RATE = 48D; for(int j = 0; j < sample.size(); j++) { System.err.println((new StringBuilder()).append("Sentence ").append(j).toString()); curSenID = j; BLinTagSample blintagsample = (BLinTagSample)sample.get(j); Vector vector1 = new Vector(); Vector vector2 = new Vector(); int k = 0; int l = -1; int i1 = 0; initCands(vector2, blintagsample); do { if(vector2.size() <= 0) break; inner++; if(k == l) { if(++i1 >= 50) break; } else { l = k; i1 = 0; } BLinIsland blinisland = selectCand(vector2); boolean flag = checkCand(blinisland); if(flag) { applyCand(vector1, vector2, blinisland, blintagsample); k++; } else { vector2.clear(); if(vector1.size() == 0) initCands(vector2, blintagsample); else genAllCands(vector2, vector1, blintagsample); } } while(true); if(k < blintagsample.words.length) System.err.println((new StringBuilder()).append("LOOP: ").append(j).toString()); } training = false; BHypothesis.training = false; SFeatLib sfeatlib = feat; SFeatLib sfeatlib1 = new SFeatLib(feat); sfeatlib1.useVotedFeat(inner); BLinTagLearn blintaglearn = new BLinTagLearn(proj, vector, sfeatlib1); blintaglearn.evaluate(); feat = sfeatlib; } }
082de1aa-07bf-4755-aac7-acfd6c1ade09
1
public static void evaluate(File fingerFile, Song song) throws FileNotFoundException { FileReader fr = new FileReader(fingerFile); BufferedReader br = new BufferedReader(fr); // Loop through the fingerfile String content = new Scanner(fingerFile).useDelimiter("\\Z").next(); //System.out.println(content); String[] fingers = content.split("\\n"); FingerTree.start_index=0; FingerTree.end_index=fingers.length-1; NoteNode root = new NoteNode(0, Integer.parseInt(fingers[0]), Integer.parseInt(fingers[1]), null, song); //root.generateValue(); NoteNode last = root; for(int i = 1 ; i < fingers.length-1 ; i++) { NoteNode current = new NoteNode(i, Integer.parseInt(fingers[i]), Integer.parseInt(fingers[i+1]), last, song); //current.generateValue(); last = current; } root = new NoteNode(last.getIndex()+1, Integer.parseInt(fingers[last.getIndex()+1]), -1, last, song); //root.generateValue(); // Print out chain System.out.println(root.toString()); // Print out final score //System.out.println(root.getCurrentScore()); }
c2978ec5-2665-4513-98a8-4b34fbb03738
8
@Override public void executaExercicio30() { String nome; int idade; Character sexo; double salario; double abono; nome = JOptionPane.showInputDialog("Digite o nome: "); idade = Integer.parseInt(JOptionPane.showInputDialog("Digite a idade: ")); sexo = JOptionPane.showInputDialog("Digite o sexo: ").charAt(0); salario = Double.parseDouble(JOptionPane.showInputDialog("Digite o salário")); if (sexo.equals('M') && idade >= 30){ abono = 100; salario = salario+abono; } if (sexo.equals('M') && idade < 30){ abono = 50; salario = salario+abono; } if (sexo.equals('F') && idade >= 30){ abono = 200; salario = salario+abono; } if (sexo.equals('F') && idade < 30){ abono = 80; salario = salario+abono; } JOptionPane.showMessageDialog(null, "Nome: "+nome+"\nSalário Líquido: "+salario); }
aa7ebcd0-f90c-4d0a-ae08-5e2cb9c7581a
5
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } PieceCoordinate other = (PieceCoordinate) obj; if (x != other.x) { return false; } if (y != other.y) { return false; } return true; }
80e782e0-e1ae-415d-92fb-c7cd18709702
4
void reduce(String s, int a, int b) { for (int i = 0; i < validSet.length; i++) { if (!validSet[i]) { continue; } if ((getA(s, answerSet[i]) != a) || (getB(s, answerSet[i]) != b)) { validSet[i] = false; } } }
9ed6c594-95f9-40fb-aa1e-e4d88dbffcbe
1
public Models.DatabaseModel.Patient findPatient(int id){ String query = "SELECT * FROM `patients` WHERE `id` = %d LIMIT 1;"; Utils.DBA dba = Helper.getDBA(); Patient p = new Patient(); try { ResultSet rs = dba.executeQuery(String.format(query, id)); rs.next(); p.setID(rs.getInt("id")); p.setName(rs.getString("name")); } catch (SQLException sqlEx) { Helper.logException(sqlEx); } return p; }
9ea7d788-f0eb-4157-b935-8ecd4e80a03d
5
public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode sum = new ListNode(-1); int carry = 0; ListNode head = sum; sum.next = head; while (l1 != null && l2 != null) { int s = l1.val + l2.val + carry; carry = s / 10; s = s % 10; head.next = new ListNode(s); head = head.next; l1 = l1.next; l2 = l2.next; } while (l1 != null) { int s = l1.val + carry; carry = s / 10; s = s % 10; head.next = new ListNode(s); head = head.next; l1 = l1.next; } while (l2 != null) { int s = l2.val + carry; carry = s / 10; s = s % 10; head.next = new ListNode(s); head = head.next; l2 = l2.next; } if (carry != 0) { head.next = new ListNode(carry); } return sum.next; }
88e943cc-786b-4919-bf41-769f86fd4604
6
public Boisson rechercheBoisson(String boisson){ for(Categorie cat : Categorie.values()){ ArrayList<Boisson> listes = new ArrayList<Boisson>(); if(cat.equals(Categorie.Bieres)){ listes = listeBoissons.getListeBieres(); } else if(cat.equals(Categorie.Cocktails)) { listes = listeBoissons.getListeCoktails(); }else if(cat.equals(Categorie.Sodas)) { listes = listeBoissons.getListeSodas(); }else{ listes = listeBoissons.getListeVins(); } for(Boisson b : listes){ if(b.getNom().equals(boisson)) return b; } } return null; }
0b93296d-4489-45d7-8690-9b7a26ebfd84
8
private int retrieveEndingPositionAfterOpeningParenthesis(int sourceStart, int sourceEnd, int numberOfParen) { if (this.referenceContext == null) return sourceEnd; CompilationResult compilationResult = this.referenceContext.compilationResult(); if (compilationResult == null) return sourceEnd; ICompilationUnit compilationUnit = compilationResult.getCompilationUnit(); if (compilationUnit == null) return sourceEnd; char[] contents = compilationUnit.getContents(); if (contents.length == 0) return sourceEnd; if (this.positionScanner == null) { this.positionScanner = new Scanner(false, false, false, this.options.sourceLevel, this.options.complianceLevel, null, null, false); } this.positionScanner.setSource(contents); this.positionScanner.resetTo(sourceStart, sourceEnd); try { int token; int previousSourceEnd = sourceEnd; while ((token = this.positionScanner.getNextToken()) != TerminalTokens.TokenNameEOF) { switch(token) { case TerminalTokens.TokenNameRPAREN: return previousSourceEnd; default : previousSourceEnd = this.positionScanner.currentPosition - 1; } } } catch(InvalidInputException e) { // ignore } return sourceEnd; }
5f9c10d8-10b8-40eb-b705-653a2b96a804
6
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); LinkedHashMap<String, Integer> votes = new LinkedHashMap<String, Integer>(); int invalid = 0; while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.startsWith("addCandidate")) { String name = line.trim().substring("addCandidate".length() + 1).trim(); votes.put(name, 0); } else if (line.startsWith("vote")) { String votedName = line.substring("vote".length() + 1).trim(); if (votes.containsKey(votedName)) { votes.put(votedName, votes.get(votedName) + 1); } else { invalid++; } } else if (line.startsWith("getVoteResult")) { for (String name : votes.keySet()) { System.out.println(name + " " + votes.get(name)); } System.out.println(invalid); } } }
f7218268-fe0f-437b-b5cb-56a274a2f18e
1
@Override public void mouseEntered( MouseEvent e ) { for( MouseListener listener : listeners( MouseListener.class )){ listener.mouseEntered( e ); } }
cd8221cd-a88a-4465-8069-beda5037f122
7
public static int findPath(Node node, boolean existed) { if(node.visited) { return -1; } if(!node.inGrouped) { return 0; } node.visited = true; if(existed) { for(Node nextNode : node.neigh) { int result = findPath(nextNode, !existed); if(result != -1) { nextNode.inGrouped = true; node.neigh.remove(nextNode); node.disNeigh.add(nextNode); nextNode.neigh.remove(node); nextNode.disNeigh.add(node); return result+1; } } }else { for(Node nextNode : node.disNeigh) { int result = findPath(nextNode, !existed); if(result != -1) { nextNode.inGrouped = true; node.disNeigh.remove(nextNode); node.neigh.add(nextNode); nextNode.disNeigh.remove(node); nextNode.neigh.add(node); return result+1; } } } return -1; }
47ad8079-f5e7-42c3-a8c3-8f841f704cb4
9
public void removerUsuario(){ if ( this.num_usuarios == 0 ) System.out.println("\nNão existem " + "usuários."); else{ System.out.println("\nQual dos usuários você gostaria de remover? " + "[ 1 - " + this.num_usuarios + " ]" ); int i = 1; for ( Usuario x : this.usuarios ){ System.out.println( i + ")" + x); i++; } System.out.print("\n > "); Scanner scan = new Scanner(System.in); int op; while(true){ if (scan.hasNextInt()) op = scan.nextInt(); else{ System.out.print("Erro. Insira um número.\n\n > "); scan.next(); continue; } break; } op -= 1; if( op < 0 || op > this.num_usuarios - 1 ){ System.out.println("Número inválido."); } else{ System.out.print("\nRemover o usuário " + usuarios.get(op).getUsername() + "? [ s / n ]" + "\n\n > " ); Scanner scan2 = new Scanner(System.in); String resposta = scan2.nextLine(); if ( !"s".equals(resposta) && !"n".equals(resposta) ){ System.out.println("Resposta inválida."); } else{ if ( "s".equals(resposta) ){ this.usuarios.remove(op); this.num_usuarios--; System.out.println("\nUsuário removido com sucesso."); } else{ System.out.println("\nOk. Saindo..."); } } } } }
badd4cd6-075b-4bd3-a3cf-4ced35679df2
1
public String loadProperty(String key) { if (properties != null) { return properties.getString(key); } return null; }
552c5392-e6b1-4122-83b9-157e82a3072e
9
public void run() { // Put a spiffy message in the console try { // Loop while we are active while(active) { MazewarPacket headQueuePacket; headQueuePacket = clientCommandQueue.peek(); if (headQueuePacket == null) { continue; } if (headQueuePacket.name.equals(name)) { clientCommandQueue.poll(); if (headQueuePacket.command == MazewarPacket.MAZEWAR_MOVEFORWARD) forward(); else if (headQueuePacket.command == MazewarPacket.MAZEWAR_MOVEBACKWARD) backup(); else if (headQueuePacket.command == MazewarPacket.MAZEWAR_ROTATELEFT) turnLeft(); else if (headQueuePacket.command == MazewarPacket.MAZEWAR_ROTATERIGHT) turnRight(); else if (headQueuePacket.command == MazewarPacket.MAZEWAR_FIRE) fire(); else { //do nothing } } } } catch(Exception e) { // Shouldn't happen. } }
0f14013b-080f-4e48-b3af-fd268a31eb78
1
private int sumOfSquares(int start, int end) { int sum=0; for(int i=start;i<=end;i++){ sum+=i*i; } return sum; }
3b8ece80-3403-4698-aeb9-da8bfde52ed0
4
@SuppressWarnings("unused") public void connect() throws IOException { if (regLevel != 0) // otherwise disconnected or connect throw new SocketException("Socket closed or already open ("+ regLevel +")"); IOException exception = null; Socket s = null; try { s = new Socket(host, port); exception = null; } catch (IOException exc) { if (s != null) s.close(); s = null; exception = exc; } if (exception != null) throw exception; // connection wasn't successful at any port prepare(s); }
13a99101-0148-4c4d-889d-065ebb3a7b60
8
protected PathNode findNavalTarget(final int maxTurns) { if (!getUnit().isOffensiveUnit()) { throw new IllegalStateException("A target can only be found for offensive units. You tried with: " + getUnit().toString()); } if (!getUnit().isNaval()) { throw new IllegalStateException("A target can only be found for naval units. You tried with: " + getUnit().toString()); } final GoalDecider gd = new GoalDecider() { private PathNode bestTarget = null; private int bestValue = 0; public PathNode getGoal() { return bestTarget; } public boolean hasSubGoals() { return true; } public boolean check(final Unit unit, final PathNode pathNode) { final Tile newTile = pathNode.getTile(); if (newTile == null) return false; final Unit defender = newTile.getDefendingUnit(unit); if (newTile.isLand() || defender == null || defender.getOwner() == unit.getOwner()) { return false; } if (!canAttackPlayer(defender.getOwner())) { return false; } final int value = 1 + defender.getCargoSpaceTaken(); if (value > bestValue) { bestTarget = pathNode; bestValue = value; } return true; } }; return getUnit().search(getUnit().getTile(), gd, CostDeciders.avoidSettlements(), maxTurns, null); }
a9a4fbab-879b-4ec9-ac4f-249a64d94499
1
public List<Problem> findPage(int page,int size) { log.debug("finding page Problem instances"); try { String queryString = "from Problem"; Query queryObject = getSession().createQuery(queryString); queryObject.setFirstResult(page); queryObject.setMaxResults(size); List<Problem> list = queryObject.list(); return list; } catch (RuntimeException re) { log.error("find all failed", re); throw re; } }
fe51a8e7-ca2d-4899-ac0b-ce42fe89e962
4
@Override public <T extends AggregateRoot<?>> Collection<T> loadBy(Class<T> type, Specification<T> specification) { final List<T> satisfied = new ArrayList<T>(); for (final Object aggregate : aggregates.values()) { if (aggregate.getClass().isAssignableFrom(type)) { if (specification.isSatisfiedBy((T) aggregate)) { satisfied.add((T) aggregate); } } } return satisfied; }
f5c5741a-06ec-4b1c-832a-4752432ad41b
3
BrandingVO(Path small, Path medium, Path large) { if ((small == null) || (medium == null) || (large == null)) { IllegalArgumentException iae = new IllegalArgumentException("One or more bitmaps are null!"); Main.handleUnhandableProblem(iae); } this.imgSmall = small; this.imgMedium = medium; this.imgLarge = large; }
e1aee3fb-b1bf-4761-9ed2-4483472890b5
6
public Point getCorner() { System.out.print("Finding corner"); Color edge = new Color(0xbbada0); int total = 500; int current = 0; for (int x = 228; x < GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().getWidth(); x++) { for (int y = 0; y < GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().getHeight(); y++) { if (edge.equals(jFenrir.getPixelColor(x, y))) { current++; if (current % 100 == 0) System.out.print("."); if (current == total) { System.out.println(); return new Point(x, y); } } else { if (current > 0) System.out.println(new Point(x, y)); current = 0; } } System.out.println("Calculating " + x + "th row"); } System.out.println("Please open the 2048 window"); System.out.println(); return getCorner(); }
da86fa2d-43ea-4253-a982-7fc02ea4dae4
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(formaInicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(formaInicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(formaInicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(formaInicio.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 formaInicio().setVisible(true); } }); }
15228b59-9907-4151-96dc-254180416ee2
1
private Map unmarshal(InputStream in) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Document doc; try { factory.setIgnoringComments(true); factory.setIgnoringElementContentWhitespace(true); factory.setExpandEntityReferences(false); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setEntityResolver(entityResolver); InputSource insrc = new InputSource(in); insrc.setSystemId(xmlPath); insrc.setEncoding("UTF-8"); doc = builder.parse(insrc); } catch (SAXException e) { e.printStackTrace(); throw new Exception("Error while parsing map file: " + e.toString()); } buildMap(doc); return map; }
a9c80eed-4f8c-46ee-aa8f-0197637a8eae
3
public void addFieldListener(Identifier ident) { if (ident == null) throw new NullPointerException(); if (fieldListeners == null) fieldListeners = new HashSet(); if (!fieldListeners.contains(ident)) fieldListeners.add(ident); }
562a564c-a7a3-4183-ac60-f58c43b49c06
0
@Override public void restoreTemporaryToDefault() {tmp = def;}
9b12879a-e64d-4ee0-a213-721536d43790
4
public static void save(String filename) { File file = new File(filename); String suffix = filename.substring(filename.lastIndexOf('.') + 1); // png files if (suffix.toLowerCase().equals("png")) { try { ImageIO.write(onscreenImage, suffix, file); } catch (IOException e) { e.printStackTrace(); } } // need to change from ARGB to RGB for jpeg // reference: http://archives.java.sun.com/cgi-bin/wa?A2=ind0404&L=java2d-interest&D=0&P=2727 else if (suffix.toLowerCase().equals("jpg")) { WritableRaster raster = onscreenImage.getRaster(); WritableRaster newRaster; newRaster = raster.createWritableChild(0, 0, width, height, 0, 0, new int[]{0, 1, 2}); DirectColorModel cm = (DirectColorModel) onscreenImage.getColorModel(); DirectColorModel newCM = new DirectColorModel(cm.getPixelSize(), cm.getRedMask(), cm.getGreenMask(), cm.getBlueMask()); BufferedImage rgbBuffer = new BufferedImage(newCM, newRaster, false, null); try { ImageIO.write(rgbBuffer, suffix, file); } catch (IOException e) { e.printStackTrace(); } } else { System.out.println("Invalid image file type: " + suffix); } }
1b337c3c-3400-4b6f-a966-cb00295ad327
4
@Override public void valueChanged(ListSelectionEvent e) { if(e.getSource() == listeClassePersonnage) { afficheStatClasse(); } if(e.getSource() == listeArme) // Si l'objet est une JList Equipement { afficheStatArme(); } if(e.getSource() == listeEquipementMagique) { afficheStatEquipementMagique(); } if(e.getSource() == listeEquipements) //Si l'objet est une JList Classe Personnage { afficheStatEquipement(); } }
ccad3526-7380-456d-928b-a174da3d48fa
0
public void setFixedFee(String fixedFee) { FixedFee = fixedFee; }
d244f689-9bb4-44ea-9f56-455a4704ed3a
5
@Override public Field move() { if (getTime() > Game.getInstance().getTime()) return null; super.move(); if (isDrinking()) { returnTimer--; return null; } List<Comprised> items = getItems(); if (items.isEmpty()) { HoboPathSearcher pathSearcher = new HoboPathSearcher(getField(), Bottle.class); Field result = pathSearcher.getHint(); if (result == null && getField().getGameObject() instanceof Hobo) { return new PolicePathSearcher(getField(), GlassPoint.class).getHint(); } return result; } else { HoboPathSearcher pathSearcher = new HoboPathSearcher(getField(), GlassPoint.class); return pathSearcher.getHint(); } }
0eb4708c-4781-421e-a2b8-627107a7ab3c
6
public boolean has_edges(String point_A, String point_B) { String []split_str; if(point_A.charAt(0) == 'r') { split_str = point_A.split("\\.", 2); point_A = split_str[0]; } if(point_B.charAt(0) == 'r') { split_str = point_B.split("\\.", 2); point_B = split_str[0]; } String edge_one = this.point_A.get_name(); String edge_two = this.point_B.get_name(); if ( (edge_one.equals(point_A) && edge_two.equals(point_B)) || (edge_two.equals(point_A) && edge_one.equals(point_B))) return true; return false; }
c63d9b61-33ef-4ab4-b148-4bbf7860cd0c
2
public Student(ResultSet rs) throws Exception{ rs.beforeFirst(); if(rs.next()){ setPersonID(rs.getInt("personid")); setLastName(rs.getString("lastname")); setFirstName(rs.getString("firstname")); setEmail(rs.getString("email")); setPersonType(rs.getString("persontype")); setPersonTypeID(2); } if(!getPersonType().equals("student")){ throw new Exception("tried to load another persontype into a student"); } }
8d8abd2f-40fa-4dc9-b717-535e3ced9dd7
4
public boolean isOptOut() { synchronized (optOutLock) { try { // Reload the metrics file configuration.load(getConfigFile()); } catch (IOException ex) { if (debug) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); } return true; } catch (InvalidConfigurationException ex) { if (debug) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); } return true; } return configuration.getBoolean("opt-out", false); } }
14d94f4d-da6f-4c11-a606-431b35e41dcc
6
public Genre analyzeBook(Book book) { // This is a fake genre analyzer, do not take the following serious Genre genre = Genre.NA; String details = book.getDetails(); if (details != null) { if (containsKeyword(details, romanceKeyWord)) { genre = Genre.ROMANCE; } else if (containsKeyword(details, comedyKeyWord)) { genre = Genre.COMEDY; } else if (containsKeyword(details, horrorKeyWord)) { genre = Genre.HORROR; } else if (containsKeyword(details, actionKeyWord)) { genre = Genre.ACTION; } else if (containsKeyword(details ,fictionKeyWord)) { genre = Genre.FICTION; } } return genre; }
611b3ed1-9d54-4e91-9945-772d1fa31efd
7
private Geometry createFace(Direction dir){ Geometry geo = new Geometry(dir.name(), quad); geo.setMaterial(blockType.getMaterial()); if(isTransparent()){ geo.setQueueBucket(Bucket.Transparent); } geometries[dir.ordinal()] = geo; switch (dir) { case NORTH: geo.setLocalTranslation(centerX+SIZE, centerY-SIZE, centerZ-SIZE); geo.rotate(0, 180*FastMath.DEG_TO_RAD, 0); break; case SOUTH: geo.setLocalTranslation(centerX, centerY-SIZE, centerZ); //South is already correct rotated break; case EAST: geo.setLocalTranslation(centerX+SIZE, centerY-SIZE, centerZ); geo.rotate(0, 90*FastMath.DEG_TO_RAD, 0); break; case WEST: geo.setLocalTranslation(centerX, centerY-SIZE, centerZ-SIZE); geo.rotate(0, -90*FastMath.DEG_TO_RAD, 0); break; case UP: geo.setLocalTranslation(centerX, centerY, centerZ); geo.rotate(-90*FastMath.DEG_TO_RAD, 0, 0); break; case DOWN: geo.setLocalTranslation(centerX, centerY-SIZE, centerZ-SIZE); geo.rotate(90*FastMath.DEG_TO_RAD, 0, 0); break; } //Add physics to the geometry RigidBodyControl physics = new RigidBodyControl(0.0f); geo.addControl(physics); physicsSpace.add(physics); geo.setUserData("x", x); geo.setUserData("y", y); geo.setUserData("z", z); geo.setUserData("body", physics); return geo; }
e13d0c31-7e16-482d-a31c-2b2cdef85563
9
public Map<String, Object> toConfigurationNode() { Map<String, Object> output = new HashMap<String, Object>(); if (subgroups != null && subgroups.size() != 0) { output.put("subgroups", subgroups); } if (permissions != null && permissions.size() != 0) { Map<String, List<String>> tmp = new LinkedHashMap<String, List<String>>(); for (String world : permissions.keySet()) { tmp.put(world, internalFormatToFile(permissions.get(world))); } output.put("permissions", tmp); } if (info != null && info.size() != 0) { output.put("info", info); } if (globalPermissions != null && globalPermissions.size() != 0) { output.put("globalpermissions", internalFormatToFile(globalPermissions)); } return output; }
cd2d7d9a-835b-4443-b5c8-b6bebdc2e9ca
8
public void setup(Object comp) { if (obs == null || sim == null) { throw new ComponentException("obs/sim variable not set."); } if (comp instanceof Compound) { Compound c = (Compound) comp; c.addListener(new Listener() { @Override public void notice(Type T, EventObject E) { if (T == Type.OUT) { DataflowEvent e = (DataflowEvent) E; if (e.getAccess().getField().getName().equals(obs)) { if (obs_idx == null) { obs_l.add((Number) e.getValue()); } else { obs_l.add((Number) Util.accessArray(obs, e.getValue(), obs_idx)); } } else if (e.getAccess().getField().getName().equals(sim)) { sim_l.add((Number) e.getValue()); //TODO use arrays here too. } if (e.getAccess().getField().getName().equals(precip)) { precip_l.add((Number)e.getValue()); } // System.err.println(E.getAccess().getField().getName() + "/" + // E.getComponent().getClass().getName() + E.getValue()); } } }); } }
17b61982-799d-4925-a046-b255c9ee5a03
7
public void render(Bitmap bitmap, int xOffset, int yOffset) { int yPixPos, xPixPos; int src; for (int y = 0; y < bitmap.getHeight(); y ++) { yPixPos = y + yOffset; if (yPixPos < 0 || yPixPos > width) continue; for (int x = 0; x < bitmap.getWidth(); x++) { xPixPos = x + xOffset; if (xPixPos < 0 || xPixPos > width) continue; src = bitmap.pixels[y*bitmap.getWidth() + x]; if (src > 0) { pixels[yPixPos * width + xPixPos] = src; } } } }
890672e4-4f9a-49e0-ae3e-17362685606c
7
private void login() throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException { Cliente c; Funcionario f; String cpf; int tam; cpf = jTextField1.getText(); cpf = cpf.replaceAll("[^0-9]", ""); //System.out.println(cpf); tam = cpf.length(); if ((tam != 11 && !cpf.matches("[0-9]+")) || tam == 0) { warningLabel.setText("<html>CPF Inválido!!! <br />O CPF deve conter 11 dígitos.</html>"); } else if (tam != 11) { warningLabel.setText("<html>CPF Inválido!!! <br />O CPF deve conter 11 dígitos.</html>"); } else if (!cpf.matches("[0-9]+")) { warningLabel.setText("<html>CPF Inválido!!! <br />O CPF deve conter apenas números.</html>"); } else { c = new Cliente(); f = new Funcionario(); if (c.buscarCliente(cpf)) { new UICMenu(c).setVisible(true); this.dispose(); } else if (f.buscarFuncionario(cpf)) { new UIFMenu(f).setVisible(true); this.dispose(); } else { warningLabel.setText("CPF não cadastrado!"); } } }
9cc069be-d163-45dd-81fc-311d1f5dda71
5
public void setFullScreen(DisplayMode displayMode) { final JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setUndecorated(true); frame.setIgnoreRepaint(true); frame.setResizable(false); device.setFullScreenWindow(frame); if (displayMode != null && device.isDisplayChangeSupported()) { try { device.setDisplayMode(displayMode); } catch (IllegalArgumentException ex) { } // fix for mac os x frame.setSize(displayMode.getWidth(), displayMode.getHeight()); } // avoid potential deadlock in 1.4.1_02 try { EventQueue.invokeAndWait(new Runnable() { public void run() { frame.createBufferStrategy(2); } }); } catch (InterruptedException ex) { // ignore } catch (InvocationTargetException ex) { // ignore } }
002a6a69-0157-4e5f-93a6-1287f74e9164
3
public String getGeraGMP2() throws SQLException, ClassNotFoundException { String sts = new String(); Connection conPol = conMgr.getConnection("PD"); if (conPol == null) { throw new SQLException("Numero Maximo de Conexoes Atingida!"); } try { Statement stmt = conPol.createStatement(); String strQl = "SELECT * FROM tb_gmp; "; ResultSet rs = stmt.executeQuery(strQl); while (rs.next()) { sts = sts + "<option value= " + rs.getInt("cod_gmp") + "> GMP-" + rs.getString("str_gmp") + "</option>"; } } finally { if (conPol != null) { conMgr.freeConnection("PD", conPol); } } return sts; }
c19d3cc9-54c5-4119-8da0-a1e88d770900
3
private void processProjectsForTraining(List<Position> positions) { Iterator<Position> iterator = positions.iterator(); while (iterator.hasNext()) { Position position = iterator.next(); String managerId = position.getCreatedBy(); List<SkillRating> projectSkillRatings = position .getRequiredSkillRatings(); List<Employee> team = getTeamMembers(managerId); for (SkillRating skillRating : projectSkillRatings) { String skillName = skillRating.getSkillName(); int skillId = skillRating.getSkillId(); int ratingId = skillRating.getRatingId(); for (Employee employee : team) { String employeeId = employee.getEmployeeId(); List<SkillRating> employeeSkillRatings = employeeSkills(employeeId); } } } }
6f0fdf70-0849-4927-b4b0-200521a20589
8
private void convertInstanceNumeric(Instance instance) { double [] vals = new double [outputFormatPeek().numAttributes()]; int attSoFar = 0; for(int j = 0; j < getInputFormat().numAttributes(); j++) { Attribute att = getInputFormat().attribute(j); if ((!att.isNominal()) || (j == getInputFormat().classIndex())) { vals[attSoFar] = instance.value(j); attSoFar++; } else { if (instance.isMissing(j)) { for (int k = 0; k < att.numValues() - 1; k++) { vals[attSoFar + k] = instance.value(j); } } else { int k = 0; while ((int)instance.value(j) != m_Indices[j][k]) { vals[attSoFar + k] = 1; k++; } while (k < att.numValues() - 1) { vals[attSoFar + k] = 0; k++; } } attSoFar += att.numValues() - 1; } } Instance inst = null; if (instance instanceof SparseInstance) { inst = new SparseInstance(instance.weight(), vals); } else { inst = new DenseInstance(instance.weight(), vals); } inst.setDataset(getOutputFormat()); copyValues(inst, false, instance.dataset(), getOutputFormat()); inst.setDataset(getOutputFormat()); push(inst); }
5f2f720a-96f0-4d68-a452-e692e722959e
9
public void map(LongWritable lineid, Text nodetxt, OutputCollector<Text, Text> output, Reporter reporter) throws IOException { Node node = new Node(); node.fromNodeMsg(nodetxt.toString()); int fdegree = node.degree("f"); int rdegree = node.degree("r"); float len = node.len() * node.cov(); if ((len <= (float)TIPLENGTH) && (fdegree + rdegree <= 1) /*&& node.isUnique()*/) { reporter.incrCounter("Brush", "tips_found", 1); if ((fdegree == 0) && (rdegree == 0)) { //this node is not connected to the rest of the graph //nothing to do reporter.incrCounter("Brush", "tips_island", 1); } else { // Tell the one neighbor that I'm a tip String linkdir = (fdegree == 0) ? "r" : "f"; for(String adj : Node.dirs) { String key = linkdir + adj; List<String> edges = node.getEdges(key); if (edges != null) { if (edges.size() != 1) { throw new IOException("Expected a single edge from " + node.getNodeId()); } String edge_content = edges.get(0); String p = edge_content.substring(0, edge_content.indexOf("!")); if (p.equals(node.getNodeId())) { // short tandem repeat, trim away reporter.incrCounter("Brush", "tips_shorttandem", 1); } else { String con = Node.flip_dir(adj) + Node.flip_dir(linkdir); output.collect(new Text(p), new Text(Node.TRIMMSG + "\t" + con + "\t" + nodetxt)); } } } } } else { output.collect(new Text(node.getNodeId()), new Text(node.toNodeMsg())); } reporter.incrCounter("Brush", "nodes", 1); }
58fb8c28-bd6c-40ef-b932-8879ec3e2759
2
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { String str1=request.getParameter("q1"); int i1=Integer.parseInt(str1); String st1=request.getParameter("a1"); Connection conn; Statement stmt; PrintWriter out=response.getWriter(); response.setContentType("text/html"); try { Class.forName("com.mysql.jdbc.Driver"); conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/chaitanya","root",""); System.out.println("connected"); stmt=conn.createStatement(); stmt.executeUpdate("insert into answer values("+i1+",'"+st1+"')"); } catch(SQLException e1) { } catch(ClassNotFoundException e2) { } out.println("<html>"); out.println("<head>"); out.println("<h2>"); out.println("ANSWER ENTERED! "); out.println("</h2>"); out.println("</head>"); out.println("<b>GO BACK</b>"); out.println("</html>"); }
3dc618d9-4d15-4d15-a347-a86a7a90d532
7
public boolean firstName(String firstName) { if (firstName == null || firstName.isEmpty()) { return false; } if ((int) firstName.charAt(0) < 65 || (int) firstName.charAt(0) > 90) { return false; } for (int i = 1; i < firstName.length(); i++) { if ((int) firstName.charAt(i) < 97 || (int) firstName.charAt(i) > 122) { return false; } } return true; }
27389f3d-6727-43af-9fd6-565f78251e4e
3
public String reconstructString() { StringBuilder reconstructedString = new StringBuilder(); List<String> listWithAllOutgoingStrings = getListWithAllOutgoingStrings(); List<String> listWithAllIncomingStrings = getListWithAllIncomingStrings(); String start = findStart(listWithAllOutgoingStrings, listWithAllIncomingStrings); String finish = ""; List<String> possibleFinish = findFinish(listWithAllOutgoingStrings, listWithAllIncomingStrings); for (String s : possibleFinish) { if (!start.equals(s)) { finish = s; } } reconstructedString.append(start); while (!start.equals(finish)) { start = nextString(start); int length = start.length(); Character nextChar = start.charAt(length - 1); reconstructedString.append(nextChar); } return reconstructedString.toString(); }
bcea9fba-6ec2-491e-b60c-c14471f8de0c
4
public Race load() { String toLoad = ""; switch( raceName ) { case PROTOSS: toLoad = PROTOSSFILE; break; case TERRAN: toLoad = TERRANFILE; break; case ZERG: toLoad = ZERGFILE; break; default: throw new RuntimeException( "This race does not exist." ); } XStream xstream = new XStream(); xstream.processAnnotations( new Class<?>[]{ Race.class, Building.class, Unit.class } ); Race race = (Race)xstream.fromXML( Loader.class.getResourceAsStream( toLoad ) ); System.out.println( race ); return race; }
fad3a7e5-ccec-47aa-b5f2-2615872a5b9c
5
private static void appendJSONPair(StringBuilder json, String key, String value) throws UnsupportedEncodingException { boolean isValueNumeric = false; try { if (value.equals("0") || !value.endsWith("0")) { Double.parseDouble(value); isValueNumeric = true; } } catch (NumberFormatException e) { isValueNumeric = false; } if (json.charAt(json.length() - 1) != '{') { json.append(','); } json.append(escapeJSON(key)); json.append(':'); if (isValueNumeric) { json.append(value); } else { json.append(escapeJSON(value)); } }
1b093e8a-d9cb-43a9-a8eb-5c00bc817d48
1
public void testConstructor_ObjectStringEx1() throws Throwable { try { new LocalDate("1970-04-06T+14:00"); fail(); } catch (IllegalArgumentException ex) {} }
79671c7c-bfde-4340-bd14-3a752f5e4d1a
8
public CreateNetworkGame(Window owner, GeneralAttribute ga, StartWindows sw) { super(owner, ModalityType.APPLICATION_MODAL); this.generalAttribute = ga; this.startWindow = sw; generalAttribute.addObserver(this); getContentPane().setBackground(new Color(102, 102, 102)); getContentPane().setCursor( Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); setBackground(new Color(0, 51, 51)); getContentPane().setLayout(null); JPanel startLocalGamePanel = new JPanel(); startLocalGamePanel.setBackground(new Color(153, 153, 153)); startLocalGamePanel.setBorder(new TitledBorder(UIManager .getBorder("TitledBorder.border"), "Local Game Settings", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 153))); startLocalGamePanel.setBounds(10, 11, 344, 267); getContentPane().add(startLocalGamePanel); startLocalGamePanel.setLayout(null); JLabel timeOutLabel = new JLabel("Time Out For Player Action: "); timeOutLabel.setForeground(new Color(0, 0, 102)); timeOutLabel.setBackground(new Color(0, 0, 102)); timeOutLabel.setBounds(25, 25, 161, 14); startLocalGamePanel.add(timeOutLabel); timeOutspinner.setToolTipText("Seconds"); timeOutspinner.setOpaque(false); timeOutspinner.setName(""); timeOutspinner.setModel(new SpinnerNumberModel(20, 2, 500, 1)); timeOutspinner.setBounds(263, 20, 61, 24); timeOutspinner.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { if (e.getWheelRotation() == -1 && (int) timeOutspinner.getValue() <= 500) timeOutspinner.setValue((int) timeOutspinner.getValue() + 1); else if (e.getWheelRotation() == 1 && (int) timeOutspinner.getValue() > 2) timeOutspinner.setValue((int) timeOutspinner.getValue() - 1); } }); startLocalGamePanel.add(timeOutspinner); JPanel playerNamePanel = new JPanel(); playerNamePanel.setForeground(new Color(0, 0, 128)); playerNamePanel.setBorder(new TitledBorder(UIManager .getBorder("TitledBorder.border"), "Your Information", TitledBorder.CENTER, TitledBorder.TOP, null, new Color(0, 0, 102))); playerNamePanel.setBounds(35, 81, 272, 167); startLocalGamePanel.add(playerNamePanel); playerNamePanel.setLayout(null); playerAvater = new DrawImageInPanel(GeneralAttribute.getPlayerImage(1), 0, 0, 180, 100); playerAvater.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { new PlayerAvaterManager(CreateNetworkGame.this, generalAttribute, getClass().getResource( "/resource/images/avaters"), 1); } }); playerAvater.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, new Color(255, 0, 0), new Color(255, 0, 0), new Color(0, 0, 128), new Color(0, 0, 128))); playerAvater.setBounds(45, 20, 180, 101); playerNamePanel.add(playerAvater); playerAvater.setLayout(null); playerName = new JTextField(); playerName.setBounds(35, 130, 209, 25); playerNamePanel.add(playerName); playerName.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { GeneralAttribute.setPlayerName(playerName.getText(), 1); } }); playerName.setHorizontalAlignment(SwingConstants.CENTER); playerName.setForeground(new Color(0, 128, 0)); playerName.setFont(new Font("Tahoma", Font.BOLD, 14)); playerName.setText("Ashiq"); playerName.setColumns(10); JLabel lblResulaion = new JLabel("Screen Size: "); lblResulaion.setForeground(new Color(0, 0, 128)); lblResulaion.setBackground(new Color(0, 0, 128)); lblResulaion.setBounds(25, 50, 161, 14); startLocalGamePanel.add(lblResulaion); screenResulationComboBox = new JComboBox(screenResulation); screenResulationComboBox.setSelectedIndex(0); screenResulationComboBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { selectScreenSize = screenSize[screenResulationComboBox .getSelectedIndex()]; } }); screenResulationComboBox.setBounds(188, 50, 136, 20); startLocalGamePanel.add(screenResulationComboBox); JButton okButton = new JButton("Create Game"); okButton.setFont(new Font("Tahoma", Font.PLAIN, 12)); okButton.setOpaque(true); okButton.setBounds(80, 289, 106, 23); getContentPane().add(okButton); okButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { GeneralAttribute.setPlayerName(playerName.getText(), 1); GeneralAttribute.setTimeOut((int) timeOutspinner.getValue()); GameAttribute.SMALL_SCREEN_SIZE = new Dimension( selectScreenSize.x, selectScreenSize.y); GameAttribute.fullScreenMode(false); server = new Server(16720); ClickAdapter.createFreshInstance(server); try { networkWindow = new NetworkWindow(getOwner(), startWindow, server); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e2) { e2.printStackTrace(); } Runnable net = new Runnable() { @Override public void run() { try { server.runNetwork(); } catch (EOFException e) { JOptionPane.showMessageDialog(null, e.getMessage()); } catch (SocketException e) { JOptionPane.showMessageDialog(null, e.getMessage()); } catch (IOException e) { JOptionPane.showMessageDialog(null, e.getMessage()); } finally { server.close(); } } }; Runnable mainGame = new Runnable() { @Override public void run() { networkWindow.start(); } }; pool = Executors.newCachedThreadPool(); pool.execute(mainGame); pool.execute(net); } }); JButton CancelButton = new JButton("Cancel\r\n"); CancelButton.setFont(new Font("Tahoma", Font.PLAIN, 12)); CancelButton.setBounds(220, 289, 106, 23); CancelButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dispose(); } }); getContentPane().add(CancelButton); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setTitle("Create Network Game"); setSize(371, 349); setLocationRelativeTo(startWindow); setIconImage(new ImageIcon(getClass().getResource( "/resource/images/startLocalGame.png")).getImage()); setResizable(false); setVisible(true); }
92e97ff3-ae0c-4769-b0ea-f32689f99199
7
private static int guessFontStyle(String name) { name = name.toLowerCase(); int decorations = 0; if ((name.indexOf("boldital") > 0) || (name.indexOf("demiital") > 0)) { decorations |= BOLD_ITALIC; } else if (name.indexOf("bold") > 0 || name.indexOf("black") > 0 || name.indexOf("demi") > 0) { decorations |= BOLD; } else if (name.indexOf("ital") > 0 || name.indexOf("obli") > 0) { decorations |= ITALIC; } else { decorations |= PLAIN; } return decorations; }
f46770bb-6d4b-4bde-85e2-b209dd3d4f5f
4
/* */ public void paintGUI(Graphics g) /* */ { /* 548 */ int offY = 280; /* 549 */ g.setColor(Color.WHITE); /* 550 */ g.setFont(this.font); /* 551 */ g.drawImage(guiUnits.getTileImage(0), 12, 12 + offY, this); /* */ /* 553 */ if (units.contains(commander)) { /* 554 */ g.setColor(this.green); /* 555 */ g.fillRect(17, 17 + offY, (int)(commander.hp * this.hpPerPixel), 40); /* */ } else { /* 557 */ g.setColor(this.red); /* 558 */ g.fillRect(17, 17 + offY, 40, 40); /* */ } /* 560 */ if (units.contains(radio)) { /* 561 */ g.setColor(this.green); /* 562 */ g.fillRect(17, 61 + offY, (int)(radio.hp * this.hpPerPixel), 40); /* */ } else { /* 564 */ g.setColor(this.red); /* 565 */ g.fillRect(17, 61 + offY, 40, 40); /* */ } /* 567 */ if (units.contains(engineer)) { /* 568 */ g.setColor(this.green); /* 569 */ g.fillRect(17, 105 + offY, (int)(engineer.hp * this.hpPerPixel), 40); /* */ } else { /* 571 */ g.setColor(this.red); /* 572 */ g.fillRect(17, 105 + offY, 40, 40); /* */ } /* 574 */ if (units.contains(machinegunner)) { /* 575 */ g.setColor(this.green); /* 576 */ g.fillRect(17, 149 + offY, (int)(machinegunner.hp * this.hpPerPixel), 40); /* */ } else { /* 578 */ g.setColor(this.red); /* 579 */ g.fillRect(17, 149 + offY, 40, 40); /* */ } /* 581 */ g.setFont(new Font("Arial", 0, 12)); /* */ }
6ad582b3-f21d-46c4-801e-cd890503d4cf
7
public static void main(String[] args){ Set<Integer> amicable = new HashSet<Integer>(); int[] div = new int[10000]; for (int i=1;i<10000;i++){ div[i] = sumOfDivs(i); } for (int i=1;i<10000;i++){ for (int j=1;j<10000;j++){ if (i==j) continue; if (div[i]==j && div[j]==i){ amicable.add(i); amicable.add(j); } } } int sum=0; for(Integer n : amicable){ System.out.println(n); sum+=n; } System.out.println(sum); }
584600a0-5a65-4f30-9547-bbfb05496d95
9
public void scrollCellToView(JTable table, int rowIndex, int vColIndex) { if (!(table.getParent() instanceof JViewport)) { return; } JViewport viewport = (JViewport) table.getParent(); Rectangle rect = table.getCellRect(rowIndex, vColIndex, true); Rectangle viewRect = viewport.getViewRect(); int x = viewRect.x; int y = viewRect.y; if (rect.x >= viewRect.x && rect.x <= (viewRect.x + viewRect.width - rect.width)){ } else if (rect.x < viewRect.x){ x = rect.x; } else if (rect.x > (viewRect.x + viewRect.width - rect.width)) { x = rect.x - viewRect.width + rect.width; } if (rect.y >= viewRect.y && rect.y <= (viewRect.y + viewRect.height - rect.height)){ } else if (rect.y < viewRect.y){ y = rect.y; } else if (rect.y > (viewRect.y + viewRect.height - rect.height)){ y = rect.y - viewRect.height + rect.height; } viewport.setViewPosition(new Point(x,y)); }
5bc67f50-d73e-45e5-b924-dee00a48811f
4
@Override public void deserialize(Buffer buf) { fightId = buf.readInt(); fightType = buf.readByte(); if (fightType < 0) throw new RuntimeException("Forbidden value on fightType = " + fightType + ", it doesn't respect the following condition : fightType < 0"); fightStart = buf.readInt(); if (fightStart < 0) throw new RuntimeException("Forbidden value on fightStart = " + fightStart + ", it doesn't respect the following condition : fightStart < 0"); fightSpectatorLocked = buf.readBoolean(); fightTeams = new FightTeamLightInformations[2]; for (int i = 0; i < 2; i++) { fightTeams[i] = new FightTeamLightInformations(); fightTeams[i].deserialize(buf); } fightTeamsOptions = new FightOptionsInformations[2]; for (int i = 0; i < 2; i++) { fightTeamsOptions[i] = new FightOptionsInformations(); fightTeamsOptions[i].deserialize(buf); } }
f453f55a-9ad9-4e24-9b54-c0040d549a30
8
private static String escapeJSON(String text) { StringBuilder builder = new StringBuilder(); builder.append('"'); for (int index = 0; index < text.length(); index++) { char chr = text.charAt(index); switch (chr) { case '"': case '\\': builder.append('\\'); builder.append(chr); break; case '\b': builder.append("\\b"); break; case '\t': builder.append("\\t"); break; case '\n': builder.append("\\n"); break; case '\r': builder.append("\\r"); break; default: if (chr < ' ') { String t = "000" + Integer.toHexString(chr); builder.append("\\u" + t.substring(t.length() - 4)); } else { builder.append(chr); } break; } } builder.append('"'); return builder.toString(); }
3215b4cf-d4dd-49ef-8b56-c9e75ce1aa91
2
@Test public void testSanitizeHtmlLongLengthMax() throws Exception { String test = ""; for(int i = 0; i < 2001; ++i) { test += 'c'; } try { Sanitizer.sanitizeLongText(test).getCleanHTML(); } catch (org.owasp.validator.html.ScanException e) { return; } throw new RuntimeException(); }
70d83350-1a57-4f29-b70c-274df99e91d5
2
public static Image crop(int height, int width, int x, int y, Image original) { Image image = new RgbImage(width, height); for (int i = 0; i < height; i++) { for (int j = 0; j < height; j++) { image.setPixel(i, j, RED, original.getPixel(i + x, j + y, RED)); image.setPixel(i, j, GREEN, original.getPixel(i + x, j + y, GREEN)); image.setPixel(i, j, BLUE, original.getPixel(i + x, j + y, BLUE)); } } return image; }
f8bf6008-5516-4366-926b-a3dc450fd68f
8
public Void visitDeclarationStatements(DeclarationStatementsContext ctx) { if (ctx.children == null) return null; int loc = 1; for (ParseTree child : ctx.children) { if (child instanceof DeclarationStatementContext) { visitDeclarationStatement((DeclarationStatementContext) child); if (ctx.getParent().getRuleIndex() == FortranParser.RULE_procedure && loc == ctx.children.size()) appendCode("\n"); } else if (child instanceof CppDirectiveContext) { if (ctx.getParent().getRuleIndex() == FortranParser.RULE_procedure && loc == ctx.children.size()) appendCode("\n"); visitCppDirective((CppDirectiveContext) child); } loc++; } return null; }
d2fe92b0-7bf1-4737-a179-a552b2d1477e
9
@SuppressForbidden(reason = "Needs access to private APIs in DirectBuffer and sun.misc.Cleaner to enable hack") private static Object unmapHackImpl() { final Lookup lookup = lookup(); try { final Class<?> directBufferClass = Class.forName("java.nio.DirectByteBuffer"); final Method m = directBufferClass.getMethod("cleaner"); m.setAccessible(true); MethodHandle directBufferCleanerMethod = lookup.unreflect(m); Class<?> cleanerClass = directBufferCleanerMethod.type().returnType(); final MethodHandle cleanMethod; if (Runnable.class.isAssignableFrom(cleanerClass)) { // early Java 9 impl using Runnable (we do the security check early that the Runnable does at runtime): final SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPackageAccess("jdk.internal.ref"); } // cast return value of cleaner() to Runnable: directBufferCleanerMethod = directBufferCleanerMethod.asType(directBufferCleanerMethod.type().changeReturnType(Runnable.class)); cleanerClass = Runnable.class; // lookup run() method on the interface instead of Cleaner: cleanMethod = lookup.findVirtual(cleanerClass, "run", methodType(void.class)); } else { // can be either the old internal "sun.misc.Cleaner" or // the new Java 9 "java.lang.ref.Cleaner$Cleanable": cleanMethod = lookup.findVirtual(cleanerClass, "clean", methodType(void.class)); } final MethodHandle nonNullTest = lookup.findStatic(Objects.class, "nonNull", methodType(boolean.class, Object.class)) .asType(methodType(boolean.class, cleanerClass)); final MethodHandle noop = dropArguments(constant(Void.class, null).asType(methodType(void.class)), 0, cleanerClass); final MethodHandle unmapper = filterReturnValue(directBufferCleanerMethod, guardWithTest(nonNullTest, cleanMethod, noop)) .asType(methodType(void.class, ByteBuffer.class)); return (BufferCleaner) (ByteBufferIndexInput parent, ByteBuffer buffer) -> { if (directBufferClass.isInstance(buffer)) { final Throwable error = AccessController.doPrivileged((PrivilegedAction<Throwable>) () -> { try { unmapper.invokeExact(buffer); return null; } catch (Throwable t) { return t; } }); if (error != null) { throw new IOException("Unable to unmap the mapped buffer: " + parent.toString(), error); } } }; } catch (ReflectiveOperationException e) { return "Unmapping is not supported on this platform, because internal Java APIs are not compatible to this Lucene version: " + e; } catch (SecurityException e) { return "Unmapping is not supported, because not all required permissions are given to the Lucene JAR file: " + e + " [Please grant at least the following permissions: RuntimePermission(\"accessClassInPackage.sun.misc\"), " + "RuntimePermission(\"accessClassInPackage.jdk.internal.ref\"), and " + "ReflectPermission(\"suppressAccessChecks\")]"; } }
696766e3-9122-48f7-aa80-77576f2b660b
1
public static Logger getInstance(){ if(Logger.logger == null) Logger.logger = new Logger(); return Logger.logger; }
e03ab448-d87f-4562-9d6a-bf849ba7e583
5
static final boolean method2797(String string, byte i) { anInt4763++; if (string == null) return false; for (int i_1_ = 0; ((Class348_Sub40_Sub30.friendListLength ^ 0xffffffff) < (i_1_ ^ 0xffffffff)); i_1_++) { if (string.equalsIgnoreCase(Class83.friendListUsernames[i_1_])) return true; } if (string.equalsIgnoreCase(((Player) (Class132 .localPlayer)) .aString10544)) return true; if (i != -63) return false; return false; }
6b34dcfa-0472-41f2-93ca-061e97bb7465
8
public boolean hasAxe() { if(playerHasItem2(6739) || playerHasItem2(1351) || playerHasItem2(1349) || playerHasItem2(1353) || playerHasItem2(1355) || playerHasItem2(1357) || playerHasItem2(1359) || playerHasItem2(1361)) { return true; } return false; }
53ba3501-46fe-4949-a651-cd14af6814fa
5
public FenetreConnexion(final Portail p1) { setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setBounds(100, 100, 401, 348); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); textField = new JTextField(); textField.setBounds(143, 103, 183, 20); contentPane.add(textField); textField.setColumns(10); passField = new JPasswordField(); passField.setColumns(10); passField.setBounds(143, 156, 183, 20); contentPane.add(passField); JLabel lblLogin = new JLabel("Login :"); lblLogin.setBounds(45, 106, 54, 14); contentPane.add(lblLogin); JLabel lblMotDePasse = new JLabel("Mot de passe "); lblMotDePasse.setBounds(45, 159, 75, 14); contentPane.add(lblMotDePasse); JLabel lblVeuillezVousConnecter = new JLabel("Veuillez vous connecter"); lblVeuillezVousConnecter.setFont(new Font("Calibri", Font.BOLD, 14)); lblVeuillezVousConnecter.setBounds(117, 36, 209, 14); contentPane.add(lblVeuillezVousConnecter); JButton btnConnection = new JButton("Connection"); btnConnection.setBounds(143, 244, 101, 29); contentPane.add(btnConnection); final JLabel lblLoginOuMot = new JLabel("Login ou mot de passe incorrect"); lblLoginOuMot.setVisible(false); lblLoginOuMot.setBounds(96, 205, 209, 14); contentPane.add(lblLoginOuMot); // Action du boutton connection btnConnection.addActionListener(new ActionListener(){ @SuppressWarnings("deprecation") public void actionPerformed(ActionEvent e){ if ( textField.getText().equals("") || passField.getText().equals("")) { lblLoginOuMot.setVisible(true); } else { Iterator<Utilisateur> it = p1.ListUsers.iterator(); while (it.hasNext()) { Utilisateur u = it.next(); if ( u.getLogin().equals(textField.getText())) { if (u.getPass().equals(passField.getText())) { setVisible(false); p1.userConnected(u); p1.AfficheEnt(p1); } else lblLoginOuMot.setVisible(true); } } } } }); }
5f0dff59-0a99-4d7b-a5ed-ea40f6e0daad
5
private void checkCollisions() { for (Ball ball : balls) { if (ball.getBoundsInParent().intersects(leftPaddle.getBoundsInParent())) { ball.collision(); ball.move(); rightPaddle.computeOptimalPoint(balls); leftPaddle.computeOptimalPoint(balls); continue; } if (ball.getBoundsInParent().intersects(rightPaddle.getBoundsInParent())) { ball.collision(); ball.move(); rightPaddle.computeOptimalPoint(balls); leftPaddle.computeOptimalPoint(balls); continue; } if (ball.getBoundsInParent().getMaxX() > rightPaddle.getBoundsInParent().getMinX()) { gameEnd("Right"); // System.out.println(rightPaddle.expectedMove()); parallel.stop(); } else if (ball.getBoundsInParent().getMinX() < leftPaddle.getBoundsInParent().getMaxX()) { gameEnd("Left"); // System.out.println(leftPaddle.expectedMove()); parallel.stop(); } } return; }
bdb49143-85c4-4303-a000-4af4181b59f4
4
public void loadProperties(String fileName) throws FileNotFoundException { InputStream in = null; try { in = PropertiesReader.class.getClassLoader().getResourceAsStream(fileName); if(in == null ){ in = new FileInputStream(System.getProperty("user.dir")+ File.separator+fileName); } if(in != null){ properties.load(in); } }catch (FileNotFoundException e){ throw e; } catch (Exception e) { log.error(e); }finally { IOUtils.close(in); } }
972d6a43-f6c2-43eb-8823-f521c815a0d7
9
@TargetApi(Build.VERSION_CODES.GINGERBREAD) public static void main(String[] args) throws Exception { // 先使用hexedit 编辑package FileInputStream is = new FileInputStream("/tmp/AndroidManifest.xml"); byte[] data = IOUtils.toByteArray(is); Map<String, String> map = new HashMap<String, String>(); map.put("c.o.m...t.e.n.c.e.n.t...m.m...p.l.u.g.i.n...g.w.a.l.l.e.t...q.u.e.r.y.p.r.o.v.i.d.e.r", "c.o.m...t.e.n.c.e.n.t...m.n...p.l.u.g.i.n...g.w.a.l.l.e.t...q.u.e.r.y.p.r.o.v.i.d.e.r"); map.put("c.o.m...t.e.n.c.e.n.t...m.m...s.d.k...p.l.u.g.i.n...p.r.o.v.i.d.e.r", "c.o.m...t.e.n.c.e.n.t...m.n...s.d.k...p.l.u.g.i.n...p.r.o.v.i.d.e.r"); map.put("c.o.m...t.e.n.c.e.n.t...m.m...s.d.k...c.o.m.m...p.r.o.v.i.d.e.r", "c.o.m...t.e.n.c.e.n.t...m.n...s.d.k...c.o.m.m...p.r.o.v.i.d.e.r"); map.put("c.o.m...t.e.n.c.e.n.t...m.m...p.l.u.g.i.n...e.x.t...E.x.t.C.o.n.t.e.n.t.P.r.o.v.i.d.e.r.B.a.s.e", "c.o.m...t.e.n.c.e.n.t...m.n...p.l.u.g.i.n...e.x.t...E.x.t.C.o.n.t.e.n.t.P.r.o.v.i.d.e.r.B.a.s.e"); map.put("c.o.m...t.e.n.c.e.n.t...m.m...p.l.u.g.i.n...e.x.t...m.e.s.s.a.g.e", "c.o.m...t.e.n.c.e.n.t...m.n...p.l.u.g.i.n...e.x.t...m.e.s.s.a.g.e"); map.put("c.o.m...t.e.n.c.e.n.t...m.m...p.l.u.g.i.n...e.x.t...S.e.a.r.c.h.C.o.n.t.a.c.t", "c.o.m...t.e.n.c.e.n.t...m.n...p.l.u.g.i.n...e.x.t...S.e.a.r.c.h.C.o.n.t.a.c.t"); map.put("c.o.m...t.e.n.c.e.n.t...m.m...p.l.u.g.i.n...e.x.t...N.e.a.r.B.y", "c.o.m...t.e.n.c.e.n.t...m.n...p.l.u.g.i.n...e.x.t...N.e.a.r.B.y"); map.put("c.o.m...t.e.n.c.e.n.t...m.m...p.l.u.g.i.n...e.x.t...S.N.S", "c.o.m...t.e.n.c.e.n.t...m.n...p.l.u.g.i.n...e.x.t...S.N.S"); map.put("c.o.m...t.e.n.c.e.n.t...m.m...p.l.u.g.i.n...e.x.t...A.c.c.o.u.n.t.S.y.n.c", "c.o.m...t.e.n.c.e.n.t...m.n...p.l.u.g.i.n...e.x.t...A.c.c.o.u.n.t.S.y.n.c"); map.put("c.o.m...t.e.n.c.e.n.t...m.m...p.l.u.g.i.n...e.x.t...e.n.t.r.y", "c.o.m...t.e.n.c.e.n.t...m.n...p.l.u.g.i.n...e.x.t...e.n.t.r.y"); char first = 'c'; ByteArrayOutputStream bios = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bios); for (int i = 0; i < data.length; i++) { byte b = data[i]; dos.writeByte(b); if ((char)b == first) { for (Map.Entry<String, String> entry : map.entrySet()) { String from = entry.getKey(); String to = entry.getValue(); int len = from.length(); if (i + len < data.length - 1) { boolean found = true; for (int j = 1; j < len; j++) { if (from.charAt(j) != '.' && from.charAt(j) != (char)data[i + j]) { found = false; break; } } if (found) { for (int j = 1; j < len; j++) { dos.writeByte((int) (to.charAt(j))); } i += (len - 1); break; } } } } } IOUtils.write(bios.toByteArray(), new FileOutputStream("/tmp/weixin.xml")); }
c4299abf-1658-4a1d-9c4e-46722701c23a
9
private final void method550(byte[] bs, int[] is, int i, int i_0_, int i_1_, int i_2_, int i_3_, int i_4_, int i_5_, int i_6_, int i_7_, int i_8_, aa var_aa, int i_9_, int i_10_) { aa_Sub1 var_aa_Sub1 = (aa_Sub1) var_aa; int[] is_11_ = var_aa_Sub1.anIntArray5487; int[] is_12_ = var_aa_Sub1.anIntArray5488; int i_13_ = i_6_ - aPureJavaToolkit5579.anInt6767; int i_14_ = i_7_; if (i_10_ > i_14_) { i_14_ = i_10_; i_1_ += (i_10_ - i_7_) * aPureJavaToolkit5579.anInt6789; i_0_ += (i_10_ - i_7_) * i_8_; } int i_15_ = i_10_ + is_11_.length < i_7_ + i_3_ ? i_10_ + is_11_.length : i_7_ + i_3_; for (int i_16_ = i_14_; i_16_ < i_15_; i_16_++) { int i_17_ = is_11_[i_16_ - i_10_] + i_9_; int i_18_ = is_12_[i_16_ - i_10_]; int i_19_ = i_2_; if (i_13_ > i_17_) { int i_20_ = i_13_ - i_17_; if (i_20_ >= i_18_) { i_0_ += i_2_ + i_5_; i_1_ += i_2_ + i_4_; continue; } i_18_ -= i_20_; } else { int i_21_ = i_17_ - i_13_; if (i_21_ >= i_2_) { i_0_ += i_2_ + i_5_; i_1_ += i_2_ + i_4_; continue; } i_0_ += i_21_; i_19_ -= i_21_; i_1_ += i_21_; } int i_22_ = 0; if (i_19_ < i_18_) { i_18_ = i_19_; } else { i_22_ = i_19_ - i_18_; } for (int i_23_ = -i_18_; i_23_ < 0; i_23_++) { int i_24_ = bs[i_0_++] & 0xff; if (i_24_ != 0) { int i_25_ = ((i & 0xff00ff) * i_24_ & ~0xff00ff) + ((i & 0xff00) * i_24_ & 0xff0000) >> 8; i_24_ = 256 - i_24_; int i_26_ = is[i_1_]; is[i_1_++] = (((i_26_ & 0xff00ff) * i_24_ & ~0xff00ff) + ((i_26_ & 0xff00) * i_24_ & 0xff0000) >> 8) + i_25_; } else { i_1_++; } } i_0_ += i_22_ + i_5_; i_1_ += i_22_ + i_4_; } }
ce69f03b-eaa8-486f-b057-8d063600536c
3
public void transformBlockInitializer(StructuredBlock block) { StructuredBlock start = null; StructuredBlock tail = null; int lastField = -1; while (block instanceof SequentialBlock) { StructuredBlock ib = block.getSubBlocks()[0]; int field = transformOneField(lastField, ib); if (field < 0) clazzAnalyzer.addBlockInitializer(lastField + 1, ib); else lastField = field; block = block.getSubBlocks()[1]; } if (transformOneField(lastField, block) < 0) clazzAnalyzer.addBlockInitializer(lastField + 1, block); }
cb1fdde3-60c2-4381-9692-2b21d2f109e4
3
private int nextState(char c, int state) { int start = SCANNER_TABLE_INDEXES[state]; int end = SCANNER_TABLE_INDEXES[state+1]-1; while (start <= end) { int half = (start+end)/2; if (SCANNER_TABLE[half][0] == c) return SCANNER_TABLE[half][1]; else if (SCANNER_TABLE[half][0] < c) start = half+1; else //(SCANNER_TABLE[half][0] > c) end = half-1; } return -1; }
8e90ea25-fd1c-4c49-9e28-2a99eb80aa84
7
private boolean jj_3R_52() { if (jj_3R_92()) return true; Token xsp; xsp = jj_scanpos; if (jj_3R_93()) jj_scanpos = xsp; if (jj_scan_token(K_IN)) return true; if (jj_scan_token(91)) return true; xsp = jj_scanpos; if (jj_3R_94()) { jj_scanpos = xsp; if (jj_3R_95()) return true; } if (jj_scan_token(92)) return true; return false; }