method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
6a97fa2c-e0df-4c58-bfa4-116b0b4cbea6
2
public Double getDouble(String key) { Object val = get(key); if (val == null) return null; else if (val instanceof Double) return (Double)val; else return ((Integer)val).doubleValue(); }
db6b675e-3af0-46ed-ad25-94838a8605bd
9
public static Class<?> wrapperEquivalentOf(Class<?> aClass) { Iterator<Map.Entry<Class<?>, Class<?>>> it = objectToPrimitiveMap .entrySet().iterator(); while (it.hasNext()) { Map.Entry<Class<?>, Class<?>> entry = it.next(); if (aClass.equals(entry.getValue())) return (Class<?>) entry.getKey(); } return aClass; }
8c5c2f6e-c095-423d-a434-9a2c42686491
6
public double score(StringWrapper s0, StringWrapper t0) { SourcedStringWrapper s = (SourcedStringWrapper)s0; SourcedStringWrapper t = (SourcedStringWrapper)t0; checkTrainingHasHappened(s, t); UnitVector sBag = asUnitVector(s); UnitVector tBag = asUnitVector(t); List<Similarity> similarities = new ArrayList<Similarity>(sBag.size()); double sim = 0.0; int i = 0; for (Iterator<Token> ti = sBag.tokenIterator(); ti.hasNext(); i++) { Token tok = ti.next(); int j = 0; for (Iterator<Token> tj = tBag.tokenIterator(); tj.hasNext(); j++) { Token tokJ = tj.next(); double distItoJ = tokenDistance.score(tok.getValue(), tokJ.getValue()); if (distItoJ >= tokenMatchThreshold) { similarities.add(new Similarity(i, j, distItoJ * sBag.getWeight(tok) * tBag.getWeight(tokJ))); } } } /* * This could be O(sBag.size() * tBag.size() * log (sBag.size() * tBag.size())) in the worst case but usually * the threshold will make it much better and likely less than O(sBag.size() * tBag.size()) which is the current * complexity. */ Collections.sort(similarities, Collections.reverseOrder()); boolean[] sUsed = new boolean[sBag.size()]; boolean[] tUsed = new boolean[tBag.size()]; // enforce that each word is only used for one similarity, to make sure normalization works for (int k = 0; k < similarities.size(); k++) { Similarity similarity = similarities.get(k); if (sUsed[similarity.r1] || tUsed[similarity.r2]) continue; sim += similarity.sim; sUsed[similarity.r1] = true; tUsed[similarity.r2] = true; } return sim; }
6c4049f5-ad4f-403d-9788-46372d4da733
5
public void run() { try { while (isMultiplayerGame()) { int id = inputStream.readInt(); IPacket packet = PacketList.instance.getPacketFromID(id); if (packet != null){ if (!packet.isServerPacket() || packet.isClientPacket()){ eventHandler.onInvalidSidedPacketReceive(packet); GameApplication.engineLogger.severe("Not reading packet " + packet + " : tried to receive from invalid side"); return; } packet.readPacket(inputStream); packet.handlePacket(theGame); } } } catch (IOException e) { currentConnectedServer = null; eventHandler.onConnectionError(EnumConnectionError.CONNECTION_LOST, e); } }
16a6cd8c-6eb6-444d-856f-4fbca0bdc93e
4
private void connectToFtpServer() { FTPClient client = new FTPClient(); try { client.connect("ftp.site.com"); boolean login = client.login("username", "password"); if (login) { System.out.println("Connection established..."); // Try to logout and return the respective boolean value boolean logout = client.logout(); // If logout is true notify user if (logout) { System.out.println("Connection close..."); } } else { System.out.println("Connection fail..."); } } catch (IOException e) { e.printStackTrace(); } finally { try { client.disconnect(); } catch (IOException e) { e.printStackTrace(); } } }
b3b52b03-56f0-4d6d-9de9-2f1a41e0ec23
0
public AbstractPlay get(int number) { return plays.get(number); }
05e5c07d-3656-48d6-8e80-3cfce7ad1cc2
7
public void paintElement() { this.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { switch (sItem) { case rect: currentObject = new Rectangle(); break; case oval: currentObject = new Oval(); break; case polygon: drawPolygon(e); return; } currentObject.setStartX(e.getX()); currentObject.setStartY(e.getY()); } public void mouseReleased(MouseEvent e) { if (sItem == SelectedItem.oval || sItem == SelectedItem.rect) { currentObject.setEndX(e.getX()); currentObject.setEndY(e.getY()); repaint(); paintList.add(currentObject); currentObject = null; mainFrame.itemDrawn(sItem); } } }); this.addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(MouseEvent e) { if (sItem == SelectedItem.oval || sItem == SelectedItem.rect) { currentObject.setEndX(e.getX()); currentObject.setEndY(e.getY()); repaint(); } } }); }
70995691-3fe0-432c-973d-f4a8546304ff
4
public void move(Direction d) { int x = coord.getX(); int y = coord.getY(); switch(d) { case NORTH: coord.setY(y-1); break; case SOUTH: coord.setY(y+1); break; case EAST: coord.setX(x+1); break; case WEST: coord.setX(x-1); break; } setChanged(); notifyObservers(); }
694c8a98-34ed-4064-a3a0-b83ce8470156
1
public boolean InsertarAfecta(Afecta p){ if (p!=null) { cx.Insertar(p); return true; }else { return false; } }
1fd5287a-1b2f-4dd8-aa51-ff76341be1bd
1
public static String toHexString(String input) { try { byte[] bytes = input.getBytes(Torrent.BYTE_ENCODING); return Torrent.byteArrayToHexString(bytes); } catch (UnsupportedEncodingException uee) { return null; } }
afff9524-1f8b-4126-9af5-6df3d2c27f22
5
@Override public void act(){ Quest testQuest = player.questList.getQuest("TestQuest"); String speech; if (testQuest == null) { testQuest = new TestQuest(stateManager, player); player.questList.add(testQuest); testQuest.step = "Start"; } if (testQuest.step.equals("Start")) { speech = "You shouldn't go messing around with someone's well"; } else if (testQuest.step.equals("GetWater")) { if (player.inventory.contains("Bucket")) { speech = "You fill the bucket with water"; testQuest.step = "HasWater"; } else { speech = "You'll probably need a bucket"; } } else if (testQuest.step.equals("HasWater")) { speech = "You already have water"; } else { speech = "You don't need the well for anything now"; } gui.showAlert(name, speech); }
c65b2300-b899-41aa-9c26-694f6eb01ad2
7
public double GetCameraTime(int CameraIPIndex) { if (Parent.GetNoCameraParameter()) { return 0; } URLConnection conn = null; BufferedReader data = null; String line; String result; StringBuffer buf = new StringBuffer(); URL CommandURL = null; double Time = 0; // try to connect try { String command_url = "http://" + this.IP[CameraIPIndex] + "/camogmgui/camogm_interface.php?cmd=gettime"; try { CommandURL = new URL(command_url); } catch (MalformedURLException e) { System.out.println("Bad URL: " + command_url); } conn = CommandURL.openConnection(); conn.connect(); data = new BufferedReader(new InputStreamReader(conn.getInputStream())); buf.delete(0, buf.length()); while ((line = data.readLine()) != null) { buf.append(line + "\n"); } result = buf.toString(); data.close(); // try to extract data from XML structure try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new ByteArrayInputStream(result.getBytes())); doc.getDocumentElement().normalize(); NodeList nodeLst = doc.getElementsByTagName("camogm_interface"); for (int s = 0; s < nodeLst.getLength(); s++) { Node fstNode = nodeLst.item(s); if (fstNode.getNodeType() == Node.ELEMENT_NODE) { Element fstElmnt = (Element) fstNode; NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("gettime"); Element fstNmElmnt = (Element) fstNmElmntLst.item(0); NodeList fstNm = fstNmElmnt.getChildNodes(); String response = ((Node) fstNm.item(0)).getNodeValue(); Time = Double.parseDouble(response.replace(".", "")); // we get rid of the comma and by doing that actually mulitply with 10000 } } } catch (Exception e) { e.printStackTrace(); } } catch (IOException e) { Parent.WriteErrortoConsole("Getting Camera Time IO Error: " + e.getMessage()); } return Time; }
f1db38cd-71d6-44d2-8784-a86ca565b14b
9
@Override public ElementHandler createHandler(String name) { if ("material".equals(name)) { return new MaterialBuilder(context, new FinishCallback<Material>() { @Override public void handle(Material value) { SceneObjectsBuilder.this.context.putProperty(PropertyNames.MATERIAL, Material.class, value); } }); } else if ("plane".equals(name)) { return new DeferredElementHandler(new PlaneBuilder(context, new FinishCallback<Plane>() { @Override public void handle(Plane value) { SceneObjectsBuilder.this.sceneObjects.add(new SimpleSceneObject(value)); } })); } else if ("sphere".equals(name)) { return new DeferredElementHandler(new SphereBuilder(context, new FinishCallback<Sphere>() { @Override public void handle(Sphere value) { SceneObjectsBuilder.this.sceneObjects.add(new SimpleSceneObject(value)); } })); } else if ("triangle".equals(name)) { return new DeferredElementHandler(new TriangleBuilder(context, new FinishCallback<Triangle>() { @Override public void handle(Triangle value) { SceneObjectsBuilder.this.sceneObjects.add(new SimpleSceneObject(value)); } })); } else if ("cylinder".equals(name)) { return new DeferredElementHandler(new CylinderBuilder(context, new FinishCallback<Cylinder>() { @Override public void handle(Cylinder value) { SceneObjectsBuilder.this.sceneObjects.add(new SimpleSceneObject(value)); } })); } else if ("cone".equals(name)) { return new DeferredElementHandler(new ConeBuilder(context, new FinishCallback<Cone>() { @Override public void handle(Cone value) { SceneObjectsBuilder.this.sceneObjects.add(new SimpleSceneObject(value)); } })); } else if ("torus".equals(name)) { return new DeferredElementHandler(new TorusBuilder(context, new FinishCallback<Torus>() { @Override public void handle(Torus value) { SceneObjectsBuilder.this.sceneObjects.add(new SimpleSceneObject(value)); } })); } else if ("model".equals(name)) { return new DeferredElementHandler(new ModelBuilder(context, new FinishCallback<List<Triangle>>() { @Override public void handle(List<Triangle> value) { SceneObjectsBuilder.this.sceneObjects.add(new ModelSceneObject(value)); } })); } else if ("csg_operation".equals(name)) { // not needed to be deferred return new CSGOperationNodeBuilder(parentContext, new FinishCallback<CSGOperationNode>() { @Override public void handle(CSGOperationNode value) { SceneObjectsBuilder.this.sceneObjects.add(new CSGSceneObject(value)); } }); } return null; }
ac5e0073-d360-4270-abb3-16e6824a78fd
9
public long set(int desde, int hasta, long newValue) { if(flag) propagar(setValue); if(desde==cotaDesde&&hasta==cotaHasta) { propagar(newValue); } else { if(izq!=null&&izq.cotaDesde<=desde&&izq.cotaHasta>=hasta) { //CHANGE FUNCTION value=izq.set(desde, hasta, newValue)+der.get(der.cotaDesde, der.cotaHasta); } else if(der!=null&&der.cotaDesde<=desde&&der.cotaHasta>=hasta) { //CHANGE FUNCTION value=der.set(desde, hasta, newValue)+izq.get(izq.cotaDesde, izq.cotaHasta); } else { //CHANGE FUNCTION value=izq.set(desde, izq.cotaHasta, newValue)+der.set(der.cotaDesde, hasta, newValue); } } return value; }
67104f90-e8de-49fc-af97-71fa9b39224c
8
public int canCompleteCircuit(int[] gas, int[] cost) { if (gas == null || cost == null || gas.length == 0 || cost.length == 0 || gas.length != cost.length) { return -1; } //sum after reach every station int sum = 0; //start position, will be change later if possible int start = 0; //the total gas, if gas has remains int total = 0; for (int i = 0; i < gas.length; i++) { //if sum < 0, the previous start position can not be start position sum += gas[i] - cost[i]; //calculate the total usage of gas total += sum; if (sum < 0) { start = i + 1; sum = 0; } } // if (total < 0) { return -1; } return start; }
312a9177-ba62-4005-b500-c982a2418561
3
public char squareContentSprite(final int x, final int y) { char result; final Pawn content = getSquareContent(x,y); if (content == null) { if (isBonusSquare(x, y)) { result = '#'; } else result = '.'; } else { if (content.equals(currentPawn)) { result = 'c'; } else result = content.getLetter(); } return result; }
c43b9790-2316-4d74-8bb1-86f17fb74b0f
6
* @param e */ public static void ride(Player p, Entity e) { if (e instanceof Creature) { ((Creature) e).setTarget(null); } if (e.getType() == EntityType.ENDER_DRAGON) { EnderDragon dr = (EnderDragon) e; dr.setPassenger(p); p.sendMessage(RideThaMob.cprefix + Lang._(LangType.RIDE_DRAGON)); return; } if (e.getType() == EntityType.GIANT) { Giant g = (Giant) e; g.setPassenger(p); p.sendMessage(RideThaMob.cprefix + Lang._(LangType.RIDE_GIANT)); } if (e.getType() == EntityType.PLAYER) { Player o = (Player) e; if ((p.hasPermission("ridethamob.player.*")) || (p.hasPermission("ridethamob.player." + p.getName()))) { o.setPassenger(p); p.sendMessage(RideThaMob.cprefix + Lang._(LangType.RIDE_PLAYER, o.getDisplayName())); return; } p.sendMessage(RideThaMob.cprefix + Lang._(LangType.RIDE_PLAYER_NO_PERM, o.getDisplayName())); return; } e.setPassenger(p); p.sendMessage(RideThaMob.cprefix + Lang._(LangType.RIDE) + e.getType().name()); }
58d14d1e-c618-494e-b5f1-366c75f07b0f
1
public int hashCode() { if (cachedHash != 0xdeadbeef) return cachedHash; int[] bounds = new int[2]; this.nonTrivial(bounds); return cachedHash = buffer.substring(bounds[0], bounds[1]).hashCode(); }
68df5311-48c1-4ddb-aca2-ca61af4e096e
8
public static void main (String args[]) throws InterruptedException { int n = 50; int timeMS = 10000; boolean prio = true; for (int i = 0; i < args.length; i++) { if (args[i].equals("-n")) n = new Integer(args[++i]).intValue(); else if (args[i].equals("-p")) prio = args[++i].charAt(0) != '0'; else if (args[i].equals("-t")) timeMS = new Integer(args[++i]).intValue(); else if (args[i].equals("-v")) verbose_s = true; else if (args[i].equals("-h") || args[i].equals("--help")) help(); else { System.err.println("unrecognized option '" + args[i] + "'"); help(); return; } } System.out.println("running with " + n + " threads during " + timeMS + "ms with" + (prio? "": "out") + " priority on last thread."); System.out.println(""); test(new CounterNoLock(), n, timeMS, prio); test(new CounterAtomic(), n, timeMS, prio); test(new CounterLock(), n, timeMS, prio); test(new CounterSyncProc(), n, timeMS, prio); test(new CounterSyncThis(), n, timeMS, prio); test(new CounterSyncObj(), n, timeMS, prio); test(new CounterSemaphore(false), n, timeMS, prio); test(new CounterSemaphore(true), n, timeMS, prio); System.out.println(""); System.out.println("stopped"); }
2a677e69-69bc-4fdd-8090-7bee7597a8ca
9
public void Checkwhile(String cond){ if(new_flag==2){ current_register--; } new_flag=0; current_label++; TypeTable.put(current_register,current_element.E_type); if(cond.equals("TRUE")){ AddOperation("STOREI","1",CString("T",current_register),"dk"); // System.out.println(";STOREI "+"1 "+CString("T",current_register)); current_register++; TypeTable.put(current_register,current_element.E_type); AddOperation("STOREI","1",CString("T",current_register),"dk"); // System.out.println(";STOREI "+"1 "+CString("T",current_register)); AddOperation("NE",CString("T",current_register-1),CString("T",current_register), Integer.toString(current_label)); // System.out.println(";NE "+CString("r",current_register-1)+" "+CString("r",current_register)+" label"+current_label); current_register++; }else if(cond.equals("FALSE")){ AddOperation("STOREI","1",CString("T",current_register),"dk"); // System.out.println(";STOREI "+"1 "+CString("T",current_register)); current_register++; TypeTable.put(current_register,current_element.E_type); AddOperation("STOREI","1",CString("T",current_register),"dk"); // System.out.println(";STOREI "+"1 "+CString("T",current_register)); AddOperation("EQ",CString("T",current_register-1),CString("T",current_register), Integer.toString(current_label)); // System.out.println(";EQ "+CString("T",current_register-1)+" "+CString("T",current_register)+" label"+current_label); current_register++; }else if(cond.equals("!=")){ AddOperation("EQ",CString("T",current_register-1),CString("T",current_register), Integer.toString(current_label)); // System.out.println(";EQ "+CString("T",current_register-1)+" "+CString("T",current_register)+" label"+current_label); }else if(cond.equals(">=")){ AddOperation("LT",CString("T",current_register-1),CString("T",current_register), Integer.toString(current_label)); // System.out.println(";LT "+CString("T",current_register-1)+" "+CString("T",current_register)+" label"+current_label); }else if(cond.equals("<=")){ AddOperation("GT",CString("T",current_register-1),CString("T",current_register), Integer.toString(current_label)); // System.out.println(";GT "+CString("T",current_register-1)+" "+CString("T",current_register)+" label"+current_label); }else if(cond.equals("=")){ AddOperation("NE",CString("T",current_register-1),CString("T",current_register), Integer.toString(current_label)); // System.out.println(";NE "+CString("T",current_register-1)+" "+CString("T",current_register)+" label"+current_label); }else if(cond.equals(">")){ AddOperation("LE",CString("T",current_register-1),CString("T",current_register), Integer.toString(current_label)); // System.out.println(";LE "+CString("T",current_register-1)+" "+CString("T",current_register)+" label"+current_label); }else if(cond.equals("<")){ AddOperation("GE",CString("T",current_register-1),CString("T",current_register), Integer.toString(current_label)); // System.out.println(";GE "+CString("T",current_register-1)+" "+CString("T",current_register)+" label"+current_label); } AddOperation("JUMP",CString("label",dostack.peek()),"dk","dk"); //System.out.println(";JUMP "+"label"+dostack.peek()); AddOperation("LABEL",CString("label",current_label),"dk","dk"); //System.out.println(";LABEL "+"label"+current_label); current_label++; }
a1703396-62f5-40da-aaf5-2b9fab800a53
9
private void helper() { int N = r.nextInt(199) + 2; List<Vertex> G = new ArrayList<Vertex>(N); for (int i = 0; i < N; i++) { G.add(new Vertex(i)); } boolean[][] connected = new boolean[N][N]; int numEdges = r.nextInt(N * (N-1)+1); for (int i = 0; i < numEdges; i++) { int a, b; do { a = r.nextInt(N); b = r.nextInt(N); } while (a == b || connected[a][b]); G.get(a).getNeighbors().add(G.get(b)); connected[a][b] = true; } Set<Vertex> graph = new HashSet<Vertex>(G); TransitiveClosure.transitiveClosure(graph); TransitiveClosure.floydWarshall(connected); // verify int count = 0; for (Vertex a : graph) { for (Vertex b : a.getExtendedContacts()) { assertTrue(connected[a.getData()][b.getData()]); count++; } } for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (connected[i][j]) { count--; } } } assertEquals(0, count); }
90016d6b-cd25-41b0-ab53-8e1fcfbc04a9
3
public static String arrayToString(Double[][] array) { String result = ""; int n = array.length; result += n + "\n"; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { result += array[i][j]; if (j + 1 != n) { result += ","; } } result += "\n"; } return result; }
623b74c6-df3f-4bf1-b0aa-b22b7f794bb7
8
public Location getFirstSquareNeighborLocation(int row, int col, int dist, int id) { for (int x = row - dist; x <= row + dist; x++) { if (isInBounds(x)) { for (int y = col - dist; y <= col + dist; y++) { if (isInBounds(y) && thisTick[x][y] != null && !(x == row && y == col) && thisTick[x][y].id == id) { return new Location(x, y); } } } } return null; }
7c76aed5-21a8-48d7-a830-006d47ca58e2
4
public void reproduce(PokemonTeam parent1, PokemonTeam parent2, int rankFit) { ArrayList<Pokemon> totalPokes = new ArrayList<Pokemon>(); for (int y =0; y< rankFit; y ++) { PokemonTeam child = new PokemonTeam(); child.removeAll2(); ArrayList<String> circumvent = new ArrayList<String>(); ArrayList<String> pokeKeys = new ArrayList<String>(); for (int i = 0; i < 6; i++) { totalPokes.add(parent1.getMember(i)); totalPokes.add(parent2.getMember(i)); pokeKeys.add(parent1.getMember(i).showName()); pokeKeys.add(parent2.getMember(i).showName()); } for (int x = 0; x < 6; x++) { int randomPokeKey = (int) (Math.random() * pokeKeys.size()); String currentKey = pokeKeys.get(randomPokeKey); while (circumvent.contains(currentKey)) { randomPokeKey = (int) (Math.random() * pokeKeys.size()); currentKey = pokeKeys.get(randomPokeKey); } Pokemon member = totalPokes.get(randomPokeKey); circumvent.add(currentKey); child.getTeam().add(member); } children.add(child); } }
d76de5f9-c1d6-462b-99d4-aa9779dfa6bb
9
@Override public void keyReleased(KeyEvent keyEvent) { if (keyEvent.getKeyCode() == KeyEvent.VK_P) { bPausa = !bPausa; } if (keyEvent.getKeyCode() == KeyEvent.VK_I) { if (!bInicio) { bInicio = true; sonSelect.play(); sonIntro.stop(); bSonido = true; } if (iVidas < 1 || bVictoria) { sonGameOver.stop(); reload(); sonSelect.play(); bSonido = true; } } if (keyEvent.getKeyCode() == KeyEvent.VK_SPACE) { if (bInicio && !bActivo) { bActivo = true; } } if (keyEvent.getKeyCode() == KeyEvent.VK_V) { bVictoria = true; } }
003661c6-1961-436e-8746-5127b6373647
5
public void put(int key, int value) { HashPrinter.tryPut(key, value); /** Index that moves through array slots */ int runner = 0; int hash = (key % table.length); if (table[hash] == null) { table[hash] = new Node(key, value); HashPrinter.successfulInsertion(key, hash); size++; } else { /** Collision */ Node entry = table[hash]; while (entry != null && runner < table.length) { HashPrinter.collisionMessage(hash); runner++; hash = ((key + runner) % table.length); entry = table[hash]; HashPrinter.movingNextSlotByLinear(hash); } if (runner == table.length) { HashPrinter.arrayFull(key, value); } else { HashPrinter.successfulInsertion(key, hash); table[hash] = new Node(key, value); size++; } } if (size >= maxSize) { resize(); } }
bcd69bb4-c771-4b9a-991d-2851d542acad
7
private String techLevel(int t) { switch (t) { case 0: return "Pre-Agriculture"; case 1: return "Agriculture"; case 2: return "Medieval"; case 3: return "Renaissance"; case 4: return "Early-Industrial"; case 5: return "Industrial"; case 6: return "Post-Industrial"; default: return "Hi-Tech"; } }
2dcb0586-142f-4df4-a184-ce38212a9b1f
3
public void update(double dt, Snake[] snakes) { timer += dt; if (timer > PELLET_TIMER) { generatePellet(); timer -= PELLET_TIMER; } for (int i = bullets.size()-1; i >= 0; i --) { bullets.get(i).update(this, snakes, dt); if (bullets.get(i).isFinished()) { bullets.remove(i); } } }
da391a0b-b7e6-4d7e-85f0-99bd5671b65d
6
public final void skipWS() { byte ch; while (pos < length) { ch = src[pos]; if ((ch != 0x20) && (ch != 0x09) && (ch != 0x0A) && (ch != 0x0D) && (ch != 0x00)) { break; } pos++; } }
a6fc2593-dad2-4131-8493-a2c10591394c
5
protected String removeSurroundingSpaces(String html) { //remove spaces around provided tags if(removeSurroundingSpaces != null) { Pattern pattern; if(removeSurroundingSpaces.equalsIgnoreCase(BLOCK_TAGS_MIN)) { pattern = surroundingSpacesMinPattern; } else if(removeSurroundingSpaces.equalsIgnoreCase(BLOCK_TAGS_MAX)) { pattern = surroundingSpacesMaxPattern; } if(removeSurroundingSpaces.equalsIgnoreCase(ALL_TAGS)) { pattern = surroundingSpacesAllPattern; } else { pattern = Pattern.compile("\\s*(</?(?:" + removeSurroundingSpaces.replaceAll(",", "|") + ")(?:>|[\\s/][^>]*>))\\s*", Pattern.DOTALL | Pattern.CASE_INSENSITIVE); } Matcher matcher = pattern.matcher(html); StringBuffer sb = new StringBuffer(); while(matcher.find()) { matcher.appendReplacement(sb, "$1"); } matcher.appendTail(sb); html = sb.toString(); } return html; }
c8148ef4-521f-40eb-8e78-23a4fc9020ce
2
@Override public void onMessage(String channel, String message) { if (_callbacks.containsKey(channel)) { for (ClientEventCallback callback : _callbacks.get(channel)) { callback.setMessage(channel, message); _pool.execute(callback); } } }
f0cf06d4-9385-4e46-b20f-57db640608be
8
public static void main(String[] args) throws Exception { if (args.length < 1 || args.length > 2) { System.out.println("[ERROR] Incorrect number arguments"); return; } if (args[0].equals("ArrayQueue")) { if (args.length < 2 || args[1].equals("")) { System.out.println("[ERROR] Argument #2 not found"); return; } int count = Integer.parseInt(args[1]); Class<? extends Queue> clazz = ArrayQueue.class; Queue<Integer> object = (Queue<Integer>) clazz.getConstructor(int.class).newInstance(count); System.out.println("ArrayQueue: " + run(object, count) + " ms"); } else if (args[0].equals("CircleQueue")) { Class<? extends Queue> clazz = CircleQueue.class; Queue<Integer> object = (Queue<Integer>) clazz.newInstance(); System.out.println("CircleQueue: " + run(object, 1000000) + " ms"); } else { System.out.println("[ERROR] Class not found"); } }
ee23ba73-1764-4961-ad8d-04ca07e9c9cf
4
public Resource getClosest(Point p) { Resource resource = null; Resource closestResource = null; double closestDistance = 0; try { for (String key : resources.keySet()) { resource = (Resource) resources.get(key); double distance = p.distance(resource.getCenterPoint()); if ((distance < closestDistance || closestDistance == 0)) { closestResource = resource; closestDistance = distance; } } } catch (ConcurrentModificationException concEx) { //another thread was trying to modify placeables while iterating //we'll continue and the new item can be grabbed on the next update } return closestResource; }
44450a8a-350b-4e02-ba6a-a64a0703102d
7
private void actionOptimise() { Object[][] data = ((MyTableModel)(tableContainer.getTable().getModel())).getData(); if (data.length > 1 && mapScrollPane.isCreated()) { ArrayList<House> houses = new ArrayList<House>(); for (int i = 0; i < data.length - 1; i++) { System.out.println(data[i][2]); House house = new House((Integer)data[i][3],(Integer)data[i][4], (Integer)data[i][5],(Color)data[i][2]); Boolean rotate = (Boolean)data[i][6]; System.out.println(house); house.calcPossiblePos(mapScrollPane); if (!houses.contains(house)) { houses.add(house); if (rotate) { House rotatedHouse = house.rotate(); rotatedHouse.calcPossiblePos(mapScrollPane); if (!houses.contains(rotatedHouse)) { houses.add(rotatedHouse); } } } } for (House temp : houses) { System.out.println(temp.getColor()); } mapScrollPane.optimize(houses); } System.out.println(); }
988c1e00-b3b8-42bc-bb5d-43f90fd42eed
3
@Test() public void whiteBoxTestQuadTree() { /* WHITE BOX QUADTREE TEST. * * We want to create a QuadTree with the following parameters: * Length: 800. * Number of QuadTrees: 16 (See below for ASCII 'art'). * Number of Points in each: (Check ASCII). * Total number of points: 2012. * * Our implementation of QuadTree, splits the QuadTree after 500 points have been reached. * * This gives us a total of 16 QuadTrees (Due to the way we've split the points). * ________________________________ * |_1_|_0_| | | * | 0 |500| 500 | | * |-------|-------| 0 | * | 0 | 0 | | * |-------|-------|--------------| * | 500 | 0 | 0 | 200 | * |-------|-------|------|-------| * | 0 | 1 | 250 | 60 | * |_______|_______|______|_______| * We want to make sure that every step of the program text can be reached. We focus our attention to this, by trying to assert that they have been reached. * */ //Clear the QuadTree QuadTree.clearQuadTree(); //First create a list of edges and Point2D's, which to base our input on, and insert these into our QuadTree's constructor. List<Edge> edges = new ArrayList<>(); List<Point2D> points = new ArrayList<>(); points.clear(); //Since we want a really specific division of our QuadTree, we must add points manually. // createRandomPoints(xMin, yMin, xMax, yMax, Amount) <- This is how we define the boundries for the creation of points. //QT#1, QT#2, QT#3 ... QT#16. //Notice that the test specifically calls an area and the amount '0'. This equals to putting 0 inside that area. points.addAll(createRandomPoints(0, 0, 200, 200, 0)); points.addAll(createRandomPoints(200, 0, 400, 200, 1)); points.addAll(createRandomPoints(0, 200, 200, 400, 500)); points.addAll(createRandomPoints(200, 200, 400, 400, 0)); points.addAll(createRandomPoints(400, 0, 600, 200, 250)); points.addAll(createRandomPoints(600, 0, 600, 200, 60)); points.addAll(createRandomPoints(400, 200, 600, 400, 0)); points.addAll(createRandomPoints(600, 200, 800, 400, 200)); points.addAll(createRandomPoints(0, 400, 200, 600, 0)); points.addAll(createRandomPoints(200, 400, 400, 600, 0)); points.addAll(createRandomPoints(0, 600, 100, 700, 0)); points.addAll(createRandomPoints(100, 600, 200, 700, 500)); points.addAll(createRandomPoints(0, 700, 100, 800, 1)); points.addAll(createRandomPoints(100, 700, 200, 800, 0)); points.addAll(createRandomPoints(200, 600, 400, 800, 500)); points.addAll(createRandomPoints(400, 400, 800, 800, 0)); System.out.println("Points Size: " + points.size()); //Iterate over the points, and add them to the edges in preparation of starting up the QuadTree. for (Point2D point : points) { Node n1 = new Node(point); Node n2 = new Node(point); Edge e = new Edge(n1, n2, 1, "Test Edge ", 1, 1); e.setMidNode(); edges.add(e); } System.out.println("Edges size: " + edges.size()); //Create the QuadTree, remember length 800, for 800x800 length quadratic quadtree. QuadTree QT = new QuadTree(edges, 0, 0, 800); ArrayList<QuadTree> QTs = QT.getBottomTrees(); //Collect all Bottom QuadTree's and extract the number of edges inside them. Add to tempResults for each. double tempResults = 0; List<Edge> resultEdges = new ArrayList<>(); for (QuadTree qt : QTs) { //System.out.println("x : "+qt.getQuadTreeX()+ " y : "+qt.getQuadTreeY()); List<Edge> qtedges = qt.getHighwayEdges(); for (Edge edge : qtedges) { resultEdges.add(edge); tempResults++; } } /* * * Assertion of test parameters. * */ //Test to see if x = 0 for QuadTree. double expResult = 0; double result = QT.getQuadTreeX(); assertEquals(expResult, result, 0); //Test to see if y = 0 for QuadTree. expResult = 0; result = QT.getQuadTreeY(); assertEquals(expResult, result, 0); //Test to see if length = 800 for QuadTree. expResult = 800; result = QT.getQuadTreeLength(); assertEquals(expResult, result, 0); //Test to see if amount of edges = 2012 for QuadTree. expResult = 2012; result = resultEdges.size(); assertEquals(expResult, result, 0); //Test to see if all 16 QuadTrees are created. double numQTExp = 16; double numQTResult = QTs.size(); assertEquals(numQTExp, numQTResult, 0); /* * * End of assertion of parameters * */ /* * * Actual whitebox test of QuadTree constructor. * */ //Series of tests to check every single QuadTree expected to be created, it's number of points, and whether they respect the logical mathematic boundries, and logical placements. // Basically a test of /*1 + 2 + 3 + 4 + 5 */ (see QuadTree.java for markings). //QT#1 expResult = 0; result = QT.getSW().getSW().getEdges().size(); System.out.println("Result for QT 1 : " + result); assertEquals(expResult, result, 0); //QT#2 expResult = 1; result = QT.getSW().getSE().getEdges().size(); System.out.println("Result for QT 2 : " + result); assertEquals(expResult, result, 500); //QT#3 expResult = 500; result = QT.getSW().getNW().getEdges().size(); System.out.println("Result for QT 3 : " + result); assertEquals(expResult, result, 500); //QT#4 expResult = 0; result = QT.getSW().getNE().getEdges().size(); System.out.println("Result for QT 4 : " + result); assertEquals(expResult, result, 500); //QT#5 expResult = 250; result = QT.getSE().getSW().getEdges().size(); System.out.println("Result for QT 5 : " + result); assertEquals(expResult, result, 500); //QT#6 expResult = 60; result = QT.getSE().getSE().getEdges().size(); System.out.println("Result for QT 6 : " + result); assertEquals(expResult, result, 500); //QT#7 expResult = 0; result = QT.getSE().getNW().getEdges().size(); System.out.println("Result for QT 7 : " + result); assertEquals(expResult, result, 500); //QT#8 expResult = 200; result = QT.getSE().getNE().getEdges().size(); System.out.println("Result for QT 8 : " + result); assertEquals(expResult, result, 500); //QT#9 expResult = 0; result = QT.getNW().getSW().getEdges().size(); System.out.println("Result for QT 9 : " + result); assertEquals(expResult, result, 500); //QT#10 expResult = 0; result = QT.getNW().getSE().getEdges().size(); System.out.println("Result for QT 10 : " + result); assertEquals(expResult, result, 500); //QT#11 expResult = 0; result = QT.getNW().getNW().getSW().getEdges().size(); System.out.println("Result for QT 11 : " + result); assertEquals(expResult, result, 500); //QT#12 expResult = 500; result = QT.getNW().getNW().getSE().getEdges().size(); System.out.println("Result for QT 12 : " + result); assertEquals(expResult, result, 500); //QT#13 expResult = 1; result = QT.getNW().getNW().getNW().getEdges().size(); System.out.println("Result for QT 13 : " + result); assertEquals(expResult, result, 500); //QT#14 expResult = 0; result = QT.getNW().getNW().getNE().getEdges().size(); System.out.println("Result for QT 14 : " + result); assertEquals(expResult, result, 500); //QT#15 expResult = 500; result = QT.getNW().getNE().getEdges().size(); System.out.println("Result for QT 15 : " + result); assertEquals(expResult, result, 500); //QT#16 expResult = 0; result = QT.getNE().getEdges().size(); System.out.println("Result for QT 16 : " + result); assertEquals(expResult, result, 500); }
e1ba96e6-e699-4bfb-9f08-549ab3878397
8
public void locateAllSubTrees(Vertex v, double radius, double offSet) { if (placedVertices.contains(root)) { double angularSpan = (Double) v.getProp().obj; int numberOfDivides = 1; numberOfDivides = g.getOutDegree(v); if (numberOfDivides == 0) { return; } Iterator<Edge> iter = g.edgeIterator(v); int j = 0; int sum = 0; for (; iter.hasNext();) { Edge e = iter.next(); Vertex v1 = e.source.equals(v) ? e.target : e.source; if (!placedVertices.contains(v1)) { sum += g.getOutDegree(v1); } else { } } iter = g.edgeIterator(v); for (; iter.hasNext();) { Edge e = iter.next(); Vertex v1 = e.source.equals(v) ? e.target : e.source; if (!placedVertices.contains(v1)) { double x = 350 + radius * Math.cos((angularSpan * j / (numberOfDivides + 1) + offSet)); double y = 350 + radius * Math.sin((angularSpan * j / (numberOfDivides + 1) + offSet)); double newOffset = (angularSpan * j / numberOfDivides + offSet); Point2D.Double newPoint = new Point2D.Double(x, y); vertexPlaces.put(v1, newPoint); placedVertices.add(v1); BaseVertexProperties properties = new BaseVertexProperties(v1.getColor(), v1.getMark()); properties.obj = new Double((angularSpan / sum) * (g.getOutDegree(v))); v1.setProp(properties); locateAllSubTrees(v1, 2 * radius, newOffset); j++; } else { } } return; } else { double x = 350; double y = 350; Point2D.Double newPoint = new Point2D.Double(x, y); placedVertices.add(v); vertexPlaces.put(v, newPoint); locateAllSubTrees(v, radius, offSet); } }
e024721a-42ae-40f9-a441-e10ad422dd80
3
public int getPreferredColumnWidth(TreeColumn column) { Dimension size = column.calculatePreferredHeaderSize(this); boolean isFirst = column == mColumns.get(0); for (TreeRow row : new TreeRowViewIterator(this, mRoot.getChildren())) { int width = column.calculatePreferredWidth(row); if (isFirst) { width += row.getDepth() * INDENT; } if (width > size.width) { size.width = width; } } return size.width; }
4971b1dd-cd46-4662-bdb2-4a74e4eef714
5
public void store(String id) { Ident ident = Yaka.tabident.chercheIdent(id); if (ident != null) {// l'ident existe var_param_const if (ident.isVar()) {// ident est une variable int type = this.type.peek(); String t; t = this.typeToString(type); if (type == ident.getType()) {// teste si l'expression a le même type que l'ident à affecter int offset = ((IdVar) ident).getOffset(); int index = -1 * offset / 2 - 1; Yaka.yvm.istore(offset); Yaka.tabident.var.set(index, 1); } else if (ident.isParam()){//ident_param Erreur.message("L'identificateur '" + id + "' n'est pas une variable"); } else if (type != YakaConstants.ERREUR){// si le type en sommet de la pile est erreur, on écrit pas le msg d'erreur Erreur.message("La variable '" + id + "' doit être de type " + t); } } else {// ident est une constante Erreur.message("L'identificateur '" + id + "' n'est pas une variable"); } } else {// l'ident n'existe pas Erreur.message("La variable '" + id + "' n'existe pas"); } }
58c98567-66d3-42e5-8cbc-33cc2005ec67
8
@SuppressWarnings("unchecked") public static <K> ArrayList<K> getObjectArray(JSONArray jsonArray, Class<K> clazz) { K[] result = (K[]) Array.newInstance(clazz, jsonArray.length()); for (int i = 0; i < jsonArray.length(); i++) { try { result[i] = clazz.getConstructor(JSONObject.class).newInstance(jsonArray.getJSONObject(i)); } catch (InstantiationException e1) { LOG.error("InstantiationException occured in getObjectArray", e1); } catch (IllegalAccessException e2) { LOG.error("IllegalAccessException occured in getObjectArray", e2); } catch (IllegalArgumentException e3) { LOG.error("IllegalArgumentException occured in getObjectArray", e3); } catch (InvocationTargetException e4) { LOG.error("InvocationTargetException occured in getObjectArray", e4); } catch (NoSuchMethodException e5) { LOG.error("NoSuchMethodException occured in getObjectArray", e5); } catch (SecurityException e6) { LOG.error("SecurityException occured in getObjectArray", e6); } catch (JSONException e7) { LOG.error("JSONException occured in getObjectArray", e7); } } return new ArrayList<K>(Arrays.asList(result)); }
9c71ce8c-7eb7-4788-a9c3-994f466dd8cd
8
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; HandlerType that = (HandlerType) o; if (event != null ? !event.equals(that.event) : that.event != null) return false; if (eventType != that.eventType) return false; if (state != null ? !state.equals(that.state) : that.state != null) return false; return true; }
d340a6d7-709f-4c45-a452-051dbf2491d2
3
public boolean addCommentToSpecificPost(Comment comment) { { /* * function gets an POST ID of the specific comment we want to add and the user name * we make sure to update the number of comments we have i that specific post * we update also the number of posts this user have plus 1 * we save all to the data bases */ Session session = null; boolean succses = true; try { session = factory.openSession(); session.beginTransaction(); int id =comment.getPostId(); String userName = comment.getCreatedBy(); MainForum mf = (MainForum)session.load(MainForum.class, id); mf.setPost(mf.getPost() + 1); User u = (User)session.load(User.class, userName); u.setPosts(u.getPosts() +1); session.save(comment); session.save(mf); session.save(u); session.getTransaction().commit(); log.info("a comment was added a specific post in main forum"); } catch (HibernateException e) { if (session != null) { session.getTransaction().rollback(); succses = false; log.info("a comment was failed to added in main forum"); throw new ForumException(e); } } finally { if (session != null) { session.close(); } return succses; } } }
ea88d54d-dbaa-41f3-a7af-70a2361d1661
5
public static void maxHeapify(int[] A, int i, int heapSize){ int left = i*2+1; int right = left+1; int largest = i; if(left < heapSize && A[left] > A[i]){ largest = left; } if(right < heapSize && A[right] > A[largest]){ largest = right; } if(largest != i){ //exchange x and y A[i] = A[i]+A[largest]; A[largest] = A[i]-A[largest]; A[i] = A[i] - A[largest]; maxHeapify(A,largest,heapSize); } }
1017b25c-998b-49fb-ae83-c46a5de3c0d6
4
public static boolean canSell(String uid, String id, int amount) { if(checkUserExistance(uid)) { stocks = UserControl.getUserStock(uid); if(!stocks.isEmpty()) { if (stocks.containsKey(id)) { if (stocks.get(id) >= amount) { return true; } } } } return false; }
b2a018ee-bf44-4242-aa75-5e80355f71ac
4
public List<urlObj> parseH5Urls(selectObj selectObj, urlObj urlObj) throws IOException { Document doc = Jsoup.connect(urlObj.getUrl()).get(); Elements elements = doc.select(selectObj.getDocumentSelect()); List<urlObj> list = new ArrayList<urlObj>(); System.out.println("Fetching : " + urlObj.getUrl()); int i = 0; for (Element link : elements) { //mQueue.add(link.attr("abs:href")); if (!link.attr("abs:href").equals("") && link.attr("abs:href") != null) { if (link.attr("abs:href").contains(selectObj.getUrlContain())) { urlObj ob = new urlObj(); ob.setDepth(selectObj.getParseDepth()+1); ob.setUrl(link.attr("abs:href")); list.add(ob); // enQueueUrl(ob); System.out.println(" URL: " + (++i) + " " + link.attr("abs:href")); } } } return list; }
2cc92afa-7161-45bd-ab13-26b03a61aa10
1
public void subtractGold(int goldloss) { gold -= goldloss; if ( gold < 0) gold = 0; }
e6baf897-8afa-4f27-8e19-2f7c95896b9e
5
public void consultar(String chave) { int indice = chave.hashCode(); Nodo nodoAux = raiz; while (nodoAux.indice != indice) { if (indice > nodoAux.indice) { if (nodoAux.direita.indice == indice) { System.out.println("Pai: " +nodoAux.direita.pai.conteudo + "\r\n" + "Conteudo: "+ nodoAux.direita.conteudo); } nodoAux = nodoAux.direita; // System.out.println("Indice: " + String.valueOf(nodoAux.indice) +"\r\n" + "Conteudo: "+ nodoAux.conteudo); } if (indice < nodoAux.indice) { if (nodoAux.esquerda == null) { System.out.println("Pai: " +nodoAux.esquerda.pai.conteudo + "\r\n" + "Conteudo: "+ nodoAux.esquerda.conteudo); } nodoAux = nodoAux.esquerda; } } }
9d152881-7418-4945-b14e-d6a1673363aa
4
public boolean Chk_RivalRate(String str){ boolean bl = false; Integer num, len; try{ bl = util.isNumric(str); if (bl){ num = Integer.parseInt(str); len = str.length(); if((util.isRange(num, 0, 10000) && util.isRange(len, 0, 4))){ bl = true; }else{ bl = false; } } }catch(Exception e){ e.printStackTrace(); } return bl; }
89093b9d-1180-48b8-a19b-ec5928666e42
6
public static boolean CheckID (String s) { String [] tab=s.split (""); if(tab.length==12 && "7".equals(tab[1]) && "0".equals(tab[2]) && "5".equals(tab[3]) &&"0".equals(tab[10])&& "1".equals(tab[11])) { System.out.println("ID correct"); return true; } else { System.out.println("ID incorrect"); return false; } }
83203d11-8b19-4f5b-98da-731b961154f6
3
private void refreshTable() { if (modelInventory.getRowCount() > 0) { for (int i = modelInventory.getRowCount() - 1; i > -1; i--) { modelInventory.removeRow(i); } } try { populateTable(); } catch (Throwable e) { // TODO Auto-generated catch block e.printStackTrace(); } }
73834570-e840-44bb-a136-c3eb8bd7e478
9
@Override public void detectRelationships(Obituary obit) throws Exception { List<List<Term>> sentences = extractor.tagEntities(obit); for (List<Term> sentence : sentences) { sentence = EntityUtils.combineEntities(sentence); chunker.addBIOChunks(sentence); tagSentence(sentence); Tree tree = getTree(sentence); List<String> lines = new ArrayList<String>(); List<Term> terms = new ArrayList<Term>(); for (int i=0; i < sentence.size(); i++) { if (EntityUtils.isPerson(sentence.get(i))) { lines.add(encodeTerm(sentence, i, null, false, tree)); terms.add(sentence.get(i)); } } for (int i=0; i < lines.size(); i++) { String name = terms.get(i).getText().replaceAll("_", " "); Map<String,Double> prediction = model.getPredictions(lines, i); String maxType = null; double maxScore = 0.0d; for (String key : prediction.keySet()) { if (prediction.get(key) > maxScore) { maxScore = prediction.get(key); maxType = key; } } if (maxType.equals("PARENT")) obit.addParent(name); else if (maxType.equals("SPOUSE")) obit.addSpouse(name); else if (maxType.equals("CHILD")) obit.addChild(name); } } }
a46f13be-3891-4dbc-8996-70e0e9a78e13
6
private boolean HandleCreatureCommand(String s) { if (s.matches("^attack \\S+ with \\S+$")) { // attack (creature) with (item) String []words = s.split(" "); String creatureName = words[1]; String itemName = words[3]; if (! inventory.contains(itemName)) { System.out.println("Bad Command"); return true; } if (! currentRoom.GetCreatures().contains(creatureName)) { System.out.println("Bad Commmand"); return true; } Creature creature = creatures.get(creatureName); if (creature.AttackWith(itemName)) { // Ha Ha! Look at me ma'! System.out.println("You assault the " + creatureName + " with your " + itemName); // Print death message if (creature.GetAttackMessage() != null) { System.out.println(creature.GetAttackMessage()); } // Perform all actions Iterator<String> iter = creature.attackActions.iterator(); while (iter.hasNext()) { PerformAction(iter.next()); } } else { // Barnacles, the bloke's stronger than I thought System.out.println("It's not very effective."); } return true; } return false; }
3be8e661-85eb-430b-9a85-ef49856e383d
3
private static List<Shape> buscarParce(List<Shape> shapes){ List<Shape> shapeList = new ArrayList<Shape>(); for(Shape shape : shapes) if (shape != null && shape instanceof ShapeParcela) shapeList.add((ShapeParcela) shape); return shapeList; }
55b2744a-c9a4-447b-a742-a91d81ee786d
9
private DBObject _create( List<String> path ){ Class c = null; if ( _collection != null && _collection._objectClass != null){ if ( path == null || path.size() == 0 ){ c = _collection._objectClass; } else { StringBuilder buf = new StringBuilder(); for ( int i=0; i<path.size(); i++ ){ if ( i > 0 ) buf.append("."); buf.append( path.get(i) ); } c = _collection.getInternalClass( buf.toString() ); } } if ( c != null ){ try { return (DBObject)c.newInstance(); } catch ( InstantiationException ie ){ LOGGER.log( Level.FINE , "can't create a: " + c , ie ); throw new MongoInternalException( "can't instantiate a : " + c , ie ); } catch ( IllegalAccessException iae ){ LOGGER.log( Level.FINE , "can't create a: " + c , iae ); throw new MongoInternalException( "can't instantiate a : " + c , iae ); } } return new BasicDBObject(); }
e9611fed-b8e7-42c6-8535-c6e214677efc
8
public void print_t37convert81(){ for (int i=0; i<t37convert81.length ; i++){ if (i==4||i==9||i==15||i==22||i==28||i==33||i==37) System.out.println(); System.out.print(t37convert81[i]+"\t"); }System.out.println(); }
24782941-90f7-4646-a4b4-77145416b6d1
4
@Override public void doLogic() { if (inputList[0] == true || inputList[1] == true || inputList[2] == true || inputList[0] == true){ power = false; } else { power = true; } inputList[0] = false; inputList[1] = false; inputList[2] = false; inputList[3] = false; }
b3fa5277-24ae-4a68-9aea-a028ff36a6b1
8
public ArrayList<Spielfeld> schritte(){ ArrayList<Spielfeld> result = new ArrayList<>(); if(linkerN != null && linkerN != Rand) result.add(linkerN); if(rechterN != null && rechterN != Rand) result.add(rechterN); if(obererN != null && obererN != Rand) result.add(obererN); if(untererN != null && untererN != Rand) result.add(untererN); return result; }
3c8a7c35-d8f4-4e6e-8422-fe806ee14649
9
private boolean r_verb_suffix() { int among_var; int v_1; int v_2; int v_3; // setlimit, line 165 v_1 = limit - cursor; // tomark, line 165 if (cursor < I_pV) { return false; } cursor = I_pV; v_2 = limit_backward; limit_backward = cursor; cursor = limit - v_1; // (, line 165 // [, line 166 ket = cursor; // substring, line 166 among_var = find_among_b(a_5, 38); if (among_var == 0) { limit_backward = v_2; return false; } // ], line 166 bra = cursor; switch(among_var) { case 0: limit_backward = v_2; return false; case 1: // (, line 168 // call R2, line 168 if (!r_R2()) { limit_backward = v_2; return false; } // delete, line 168 slice_del(); break; case 2: // (, line 176 // delete, line 176 slice_del(); break; case 3: // (, line 181 // delete, line 181 slice_del(); // try, line 182 v_3 = limit - cursor; lab0: do { // (, line 182 // [, line 182 ket = cursor; // literal, line 182 if (!(eq_s_b(1, "e"))) { cursor = limit - v_3; break lab0; } // ], line 182 bra = cursor; // delete, line 182 slice_del(); } while (false); break; } limit_backward = v_2; return true; }
7636bad5-0aa2-403d-bb29-6d019be61917
8
@Override public void keyPressed(KeyEvent ke) { if(ke.getKeyChar() == 'c') { lastTool = curTool; curTool = 2; } else if(ke.getKeyChar() == 'l') { lastTool = curTool; curTool = 3; } else if(ke.getKeyChar() == 'f') { lastTool = curTool; curTool = 1; } else if(ke.getKeyChar() == 'd') { lastTool = curTool; curTool = 0; } if(ke.getKeyCode() == KeyEvent.VK_EQUALS) { scale *= 2; if(scale > 32) { scale = 32; } hp.setScale(scale); hp.repaint(); this.heightmapPane.revalidate(); } else if(ke.getKeyCode() == KeyEvent.VK_MINUS) { scale /= 2; if(scale < 1) { scale = 1; } hp.setScale(scale); hp.repaint(); this.heightmapPane.revalidate(); } this.heightmapPane.getHorizontalScrollBar().setUnitIncrement(scale); this.heightmapPane.getVerticalScrollBar().setUnitIncrement(scale); this.setTool(curTool); }
d4092047-6928-48ab-a041-9c14a763e747
7
@MCCommand(cmds = { "create" }, op = true, usage = PORT_CREATE) public boolean portCreate(Player p, String name, String[] args) { Port port = pc.getPort(name); if (port != null) { return sendMessage(p, "&4There is already a port with that name. Please pick a unique name."); } Selection sel = wep.getSelection(p); if (sel == null) return sendMessage(p, ChatColor.RED + "Please select the protection area first."); port = new Port(); port.setName(name); try { port.setSourceBox(p.getWorld(), sel.getMinimumPoint(), sel.getMaximumPoint()); } catch (Exception e) { return sendMessage(p, "&4Source must have corners in the same world"); } try { port.setDestination(p.getLocation()); } catch (Exception e) { return sendMessage(p, "&4Cant set destination to be within the source"); } List<String> portOptions = new ArrayList<String>(); for (int i = 2; i < args.length; i++) { String op = args[i]; if (!Port.checkOption(op)) { sendMessage(p, "Port Option " + args[i] + " is not a valid option"); sendValidOptions(p); return true; } portOptions.add(op); } for (String op : portOptions) { port.addOptions(op); } pc.addPort(port); sendMessage(p, ChatColor.AQUA + "The port " + port.getName() + " was created successfully. options=" + port.getOptions()); return true; }
bbcbfac1-478e-42c0-86bc-f73a103c14f8
4
public static boolean isBorderLegal(int width, int height) { if (width < 11 && width > 6 && height > 6 && height < 11) { return true; } else { return false; } }
2a69ce25-1caf-4520-b0f8-f22cfc06740f
4
@Override protected void setAttrs(Post model, PreparedStatement stmt) throws SQLException { if (model.getTitle() == null) { stmt.setNull(1, java.sql.Types.CHAR); } else { stmt.setString(1, model.getTitle()); } if (model.getPostedAtMillis() == null) { stmt.setNull(2, java.sql.Types.DATE); } else { stmt.setDate(2, new Date(model.getPostedAtMillis())); } if (model.getUserId() == null) { stmt.setNull(3, java.sql.Types.INTEGER); } else { stmt.setInt(3, model.getUserId()); } if (model.getUpdatedAt() == null) { stmt.setNull(4, java.sql.Types.DATE); } else { stmt.setTimestamp(4, new Timestamp(model.getUpdatedAt())); } stmt.setLong(5, model.getId()); }
0e2e57cb-8b96-4b60-a5ab-38d36bcc699b
9
public void run() { while (true) { // sempre esperando if (waiting) { try { int myColor; int itsColor = Piece.cNeutral; serverSocket = new ServerSocket(waitingPort); socket = serverSocket.accept(); client.writeMessage(3, "INFO: \"" + socket.getInetAddress() + ":" + socket.getPort() + "\" se conectou."); client.setGameStatus("Distribua suas peças!"); myColor = randomPlayerID(); client.getStrategoC().setColor(myColor); if (myColor == Piece.cRed) { itsColor = Piece.cBlue; } else if (myColor == Piece.cBlue) { itsColor = Piece.cRed; } dataOut = new DataOutputStream(socket.getOutputStream()); dataOut.writeUTF("COMB2" + itsColor); // criei meu client.getStrategoC().setColor(myColor); client.getStrategoC().setPlaying(true); dataOut = new DataOutputStream(socket.getOutputStream()); dataOut.writeUTF("COMB1" + client.getMyName()); if (myColor == Piece.cRed) { client.writeMessage(2, "INFO: Você foi sorteado como <font color=#ff0000>1º player</font>!"); } else if (myColor == Piece.cBlue) { client.writeMessage(2, "INFO: Você foi sorteado como <font color=#0000ff>2º player</font>!"); } else { client.writeMessage(2, "ERRO: Você foi sorteado como <font color=#339966>0º player</font>!"); } client.setPieceButtonsEnabled(true); running = true; } catch (IOException e) { client.writeMessage(1, "ERRO: Porta já usada."); client.setPanelConnectEnabled(true); running = false; } waiting = false; } while (running) { // fica inputando try { dataIn = new DataInputStream(socket.getInputStream()); String data = dataIn.readUTF(); receiveCOMBX(data); } catch (IOException e) { running = false; waiting = false; client.writeMessage(1, "ERRO: O adversário se desconectou."); //System.exit(0); } } } }
c8eaffbd-af1b-4223-b473-05204b34298f
1
public String logout() { if(session.containsKey(USER_OBJ)) session.remove(USER_OBJ); return SUCCESS; }
7fb0ab39-78ee-4b80-af67-e4fb06f2f8d4
9
public void actionPerformed(ActionEvent event) { // System.out.println(event); ArrayList<JTextField> fields = parent.getFields(); String msg = ""; //check the first text field if (!fields.get(0).getText().equals("")) { ButtonGroup bg = parent.getButtons(); Enumeration<AbstractButton> buttons = bg.getElements(); String customerType = ""; while(buttons.hasMoreElements()) { AbstractButton b = buttons.nextElement(); if (b.isSelected()) { customerType = b.getText(); } } String insertq = "insert into accounts (account_no,sticker_no,first_name,last_name,address1,"+ "city,state,zip,account_type,date_begin,date_end) values (?,?,?,?,?,?,?,?,?,?,?)"; System.out.println(insertq); try { PreparedStatement stmt = null; //AddRecord.MainWindow.getConnection Connection c = parent.getWindow().getConnection(); if (c != null) { stmt = c.prepareStatement(insertq); for(int i=0;i<fields.size();i++) { if(i == 0) stmt.setInt(i+1,Integer.parseInt(fields.get(i).getText())); else stmt.setString(i+1,fields.get(i).getText()); } //set the customer type int i=fields.size() +1; stmt.setString(i,customerType); i++; //set the begin date stmt.setString(i,parent.getBeginDate()); //set the end date, i++; stmt.setString(i,""); //execute the insert stmt.executeUpdate(); //update the status bar String statusMsg = "Account No.: "+ fields.get(0).getText() + " "; //account number statusMsg += "Name: " + fields.get(1).getText() + " "; //first name statusMsg += fields.get(2).getText(); //last name parent.setStatusMsg(statusMsg); //clear the text fields for(int j=0;j<fields.size();j++) { fields.get(j).setText(""); } } else { JOptionPane.showMessageDialog(parent.getParent(), "Please check your configuration settings!", "No Database Connection!", JOptionPane.ERROR_MESSAGE ); } } catch(SQLException exception) { JOptionPane.showMessageDialog(parent.getParent(), "query: " + insertq+"\n"+exception, "addrecordaction actionPerformed", JOptionPane.INFORMATION_MESSAGE ); } catch(NumberFormatException nfe) { System.out.println(nfe); JOptionPane.showMessageDialog(parent.getParent(), //nfe.toString() +"\n"+ "Numbers only\n", //this is with the full path nfe.getMessage()+"\n"+ "Numbers only\n", "Input Error!", JOptionPane.ERROR_MESSAGE ); } }//end if else { msg += "Account No."; // System.out.println("gotta have an account number"); msg = "Please fill out the following fields:\n" + msg; JOptionPane.showMessageDialog(parent.getParent(), msg, "Incomplete form", JOptionPane.QUESTION_MESSAGE ); } }//end actionPerformed
ff6b9a87-47a0-4245-90a2-ed3c15b04eb2
3
@SuppressWarnings("unchecked") @Override public void process(final Exchange exchange) throws Exception { final List<JUGSession> listOfSessions = new ArrayList<JUGSession>(); exchange.getIn().setBody(null); // Récupération de l'entityManager final EntityManager em = EntityManagerUtil.getEntityManager(); final ExpressionBuilder builder = new ExpressionBuilder(); final ReadAllQuery databaseQuery = new ReadAllQuery( Jugpresentation.class, builder); final Query query = ((JpaEntityManager) em.getDelegate()) .createQuery(databaseQuery); // exécution de la requête try { final List<Jugpresentation> jugPres = query.getResultList(); final DozerBeanMapper mapper = exchange.getContext().getRegistry() .lookup("mapper", DozerBeanMapper.class); for (final Jugpresentation jugP : jugPres) { em.refresh(jugP); // mapping Dozer listOfSessions.add(mapper.map(jugP, JUGSession.class)); } } catch (final NoResultException e) { // pas de résultat trouvé, c'est pas bien grave if (LOG.isInfoEnabled()) { LOG.info(e); } } final ListeDesSessionsResponse resp = new ListeDesSessionsResponse(); resp.setListeDesSessions(listOfSessions); exchange.getIn().setBody(resp); }
bb3d9e46-1133-42db-be83-4a35685be35d
1
public static void main(String[] args) throws Exception { if (args.length != 2) { System.err.println( "Usage: java RFS862_UdpClient <destination host> <destination port>"); System.exit(1); } //get the dest host + port from console String dest_host = args[0]; int dest_port = Integer.parseInt(args[1]); //input stream from the console BufferedReader inFromUserConsole = new BufferedReader(new InputStreamReader( System.in)); //new udp socket DatagramSocket clientSocket = new DatagramSocket(); InetAddress IPAddress = InetAddress.getByName(dest_host); //sizes of sent and received data byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; //the message from the client System.out.println("Please input a message:"); String sentence = inFromUserConsole.readLine(); sendData = sentence.getBytes(); //build the datagram package DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, dest_port); //send it to the server clientSocket.send(sendPacket); DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); //get data from the server clientSocket.receive(receivePacket); //cast the received message as string String modifiedSentence = new String(receivePacket.getData()); System.out.println(modifiedSentence); //close the client socket clientSocket.close(); }
ea4354a9-2302-45c7-bd47-8cd3565af947
4
public void update() { up = keys[KeyEvent.VK_UP] || keys[KeyEvent.VK_W]; down = keys[KeyEvent.VK_DOWN] || keys[KeyEvent.VK_S]; left = keys[KeyEvent.VK_LEFT] || keys[KeyEvent.VK_A]; right = keys[KeyEvent.VK_RIGHT] || keys[KeyEvent.VK_D]; C = keys[KeyEvent.VK_C]; R = keys[KeyEvent.VK_R]; N = keys[KeyEvent.VK_N]; Q = keys[KeyEvent.VK_Q]; faster = keys[KeyEvent.VK_P]; slower = keys[KeyEvent.VK_M]; O = keys[KeyEvent.VK_O]; escape = keys[KeyEvent.VK_ESCAPE]; enter = keys[KeyEvent.VK_ENTER]; }
05385383-411d-4554-b04c-7db42380c233
5
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PreparedStatementKey that = (PreparedStatementKey) o; if (!sql.equals(that.sql)) return false; if (!mappedStatement.equals(that.mappedStatement)) return false; return true; }
8b8e7cdf-9150-401b-8556-e143d6997e42
9
static protected void FillBuff() throws java.io.IOException { if (maxNextCharInd == available) { if (available == bufsize) { if (tokenBegin > 2048) { bufpos = maxNextCharInd = 0; available = tokenBegin; } else if (tokenBegin < 0) bufpos = maxNextCharInd = 0; else ExpandBuff(false); } else if (available > tokenBegin) available = bufsize; else if ((tokenBegin - available) < 2048) ExpandBuff(true); else available = tokenBegin; } int i; try { if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1) { inputStream.close(); throw new java.io.IOException(); } else maxNextCharInd += i; return; } catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; } }
9fda2426-e132-4f3d-ac7c-777e91cc003c
1
private boolean jj_2_11(int xla) { jj_la = xla; jj_lastpos = jj_scanpos = token; try { return !jj_3_11(); } catch(LookaheadSuccess ls) { return true; } finally { jj_save(10, xla); } }
53387cd2-74cc-4f0d-8b95-ac0f18687f91
9
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PosRecibeDePosEntityPK that = (PosRecibeDePosEntityPK) o; if (prpIdElemento != that.prpIdElemento) return false; if (prpMoaConsec != that.prpMoaConsec) return false; if (prpMoaTipo != null ? !prpMoaTipo.equals(that.prpMoaTipo) : that.prpMoaTipo != null) return false; if (prpPosId != null ? !prpPosId.equals(that.prpPosId) : that.prpPosId != null) return false; return true; }
e867e9a5-80af-4c22-ab87-839b96ddebb1
5
public int[] searchRange(int[] A, int target) { int i = 0; int j = A.length - 1; int[] results = {-1, -1}; //the idea is to put the lower bound in i while (i < j) { int mid = i + (j - i) / 2; if (target <= A[mid]) { j = mid; } else { i = mid + 1; } } if (A[i] == target) { results[0] = i; } else { return results; } i = 0; j = A.length; //the idea is to put the upper bound in j-1 while (i < j) { int mid = i + (j - i) / 2; if (target >= A[mid]) { i = mid + 1; } else { j = mid; } } results[1] = j - 1; return results; }
5a52e60d-1fea-402b-9d12-da51a5499213
2
private Mesh LoadMesh(String fileName) { String[] splitArray = fileName.split("\\."); String ext = splitArray[splitArray.length - 1]; if(!ext.equals("obj")) { System.err.println("Error: '" + ext + "' file format not supported for mesh data."); new Exception().printStackTrace(); System.exit(1); } OBJModel test = new OBJModel("./res/models/" + fileName); IndexedModel model = test.ToIndexedModel(); ArrayList<Vertex> vertices = new ArrayList<Vertex>(); for(int i = 0; i < model.GetPositions().size(); i++) { vertices.add(new Vertex(model.GetPositions().get(i), model.GetTexCoords().get(i), model.GetNormals().get(i), model.GetTangents().get(i))); } Vertex[] vertexData = new Vertex[vertices.size()]; vertices.toArray(vertexData); Integer[] indexData = new Integer[model.GetIndices().size()]; model.GetIndices().toArray(indexData); AddVertices(vertexData, Util.ToIntArray(indexData), false); return this; }
e24cca81-29d0-4ccc-ab2a-82d79a75696e
9
private void lex(TokenStream tokenStream) { ASTNode n = root; Token t = null; int index = 0; while (index < tokenStream.size()) { t = tokenStream.get(index); switch (t.type) { case Function: case Block: Type endType; if (t.type == Type.Block) endType = Type.BlockClose; else endType = Type.FunctionClose; ASTNode fn = new ASTNode(t, n); fn.args = new Vector<ASTNode>(); n.push(fn); for (;;) { Token arg = tokenStream.get(++index); if (arg.type == endType) break; fn.args.add(new ASTNode(arg, n)); } // Set up block as new parent if (t.type == Type.Block) n = fn; break; case EndBlock: // Compare block names (e.g. #each and /each) if (! n.t.tag.substring(1).equals(t.tag.substring(1))) { System.out.println(n.t.tag.length() + " " + t.tag.length()); System.out.println("Tag mismatch:" + n.t.tag + " " + t.tag); } n = n.parent; break; default: n.push(new ASTNode(t)); } index++; } }
4426a6a8-2005-446f-b478-74d2944adc39
7
@SuppressWarnings("deprecation") public void setSystemDefaultHeader(Request req, Response resp) { resp.setStatuCode(200); Date now = new Date(); resp.setHeader("Server", this.getServerName()); resp.setHeader("Content-Type", getMimeType(req)); resp.setHeader("Date", now.toGMTString()); resp.setHeader("Expires", new Date(now.getTime() + this.getExpiresTime() * SECOND).toGMTString()); //process keep alive if(this.isEnableKeepAlive() && _count.get() <= this.getMaxKeepAlive() && req.containsHeader("Connection") && req.getHeader("Connection").toLowerCase().equals("keep-alive")){ resp.setHeader("Connection", "Keep-Alive"); int timeout = this.getKeepAliveTimeout(); if(timeout == 0){ if(req.containsHeader("Keep-Alive")) { timeout = Integer.parseInt(req.getHeader("Keep-Alive")); } } try { client.setSoTimeout(timeout * SECOND); } catch(SocketException ex) { log.error(ex); } resp.setHeader("Keep-Alive", "timeout=" + timeout + ", max=" + (this.getMaxKeepAlive() - _count.get())); } else { resp.setHeader("Connection", "Close"); } }
6f76f293-fd70-4397-a787-e8c8e5285bed
3
public ArrayList<Integer> grayCode(int n) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. ArrayList<Integer> res = new ArrayList<Integer>(1 << n); res.add(0); if(n == 0) return res; res.add(1); for(int i = 2; i <= n; ++i){ int size = res.size(); for(int j = size - 1; j >= 0; --j){ int t = res.get(j); res.add(t | (1 << (i-1))); } } return res; }
e37d954a-9d3f-4858-9a2c-849da9e55e68
7
public void paint(Position p, int moves) { boolean valid = false; //System.out.println("painting "+p); if ( maze.getValueAt(p) == '.') { valid = true; maze.setValue(p, moves); } else if ((int)maze.getValueAt(p) > moves) { valid = true; maze.setValue(p, moves); } if ( valid ) { Position u, d, l, r; u = new Position(p.x, p.y-1); d = new Position(p.x, p.y+1); l = new Position(p.x-1, p.y); r = new Position(p.x+1, p.y); if ( maze.isValidPos2(u) ) paint (u, moves+1); if ( maze.isValidPos2(d) ) paint (d, moves+1); if ( maze.isValidPos2(l) ) paint (l, moves+1); if ( maze.isValidPos2(r) ) paint (r, moves+1); } }
cf364c96-51e1-46d5-9576-fe18ad8f4dc2
8
public static char convertToChar (String string) { int length; Character item; char ret; ret = 0; length = string.length (); if (0 < length) { if ('&' == string.charAt (0)) { string = string.substring (1); length--; } if (0 < length) { if (';' == string.charAt (length - 1)) string = string.substring (0, --length); if (0 < length) { if ('#' == string.charAt (0)) try { ret = (char)Integer.parseInt (string.substring (1)); } catch (NumberFormatException nfe) { /* failed conversion, return 0 */ } else { item = (Character)refChar.get (string); if (null != item) ret = item.charValue (); } } } } return (ret); }
3c9e1daf-f4c1-4617-8e4f-61e99877c72b
4
public Shape getSahpe(String shapeType){ if(shapeType==null){ return null; } if("CIRCLE".equalsIgnoreCase(shapeType)){ return new Circle(); }else if("RECTANGLE".equalsIgnoreCase(shapeType)){ return new Rectangle(); }else if("SQUARE".equalsIgnoreCase(shapeType)){ return new Square(); } return null; }
f81d1dbf-b38c-41fd-acc8-29c5561598ec
8
public ASNode route(ASNode source, String name) throws FileNotFoundException, IOException { ASNode cnode = source, nnbr = source; int routingHops = 0; int totalLatency = 0; int ovHops = 0; while (!cnode.prefix.isMatch(name)) { if (ovHops > Math.log(nodeStore.length) / (2 * Math.log(2))) { return cnode; } cnode.messageCount++; if (cnode.nbr.isEmpty()) { cnode = getRandomNode(); System.err.println("GOT RND NODE"); } double maxScore = Double.MIN_VALUE; //overlay nbrs for (ASNode nbr : cnode.nbr) { if (nbr.prefix.getMatchScore(name, cnode.prefix) > maxScore) { maxScore = nbr.prefix.getMatchScore(name, cnode.prefix); nnbr = nbr; } } if (maxScore == 0) { nnbr = nodeStore[cnode.provider]; } //underlay nbrs, k-random links // for (ASNode nbr : cnode.kLinks) { // if (nbr.prefix.getMatchScore(name, cnode.prefix) > maxScore) { // maxScore = nbr.prefix.getMatchScore(name, cnode.prefix); // nnbr = nbr; // } // } //no nbr with matching prefix // if (maxScore == 0) { // cnode = getRandomNode(); // } //compute hop and latency //Stats.hop.step(); totalLatency += AllPaths.getPathInfo(cnode.id, nnbr.id, TreeBuilder.treeSize).latency; routingHops += AllPaths.getPathInfo(cnode.id, nnbr.id, TreeBuilder.treeSize).hops; ovHops++; if (cnode == nnbr) { cnode = getRandomNode(); } else { cnode = nnbr; } } if (sim != null) { sim.addToData(totalLatency, routingHops, ovHops, source.id + "*" + cnode.id); } return cnode; }
fa9e85b9-4d29-44c5-a961-03a91623bf35
8
public BufferedImage parseUserSkin(BufferedImage par1BufferedImage) { if (par1BufferedImage == null) { return null; } imageWidth = 64; imageHeight = 32; BufferedImage bufferedimage = new BufferedImage(imageWidth, imageHeight, 2); Graphics g = bufferedimage.getGraphics(); g.drawImage(par1BufferedImage, 0, 0, null); g.dispose(); imageData = ((DataBufferInt)bufferedimage.getRaster().getDataBuffer()).getData(); func_78433_b(0, 0, 32, 16); func_78434_a(32, 0, 64, 32); func_78433_b(0, 16, 64, 32); boolean flag = false; for (int i = 32; i < 64; i++) { for (int k = 0; k < 16; k++) { int i1 = imageData[i + k * 64]; if ((i1 >> 24 & 0xff) < 128) { flag = true; } } } if (!flag) { for (int j = 32; j < 64; j++) { for (int l = 0; l < 16; l++) { int j1 = imageData[j + l * 64]; boolean flag1; if ((j1 >> 24 & 0xff) < 128) { flag1 = true; } } } } return bufferedimage; }
58ea7c76-2810-4523-8a22-9594f510d34a
2
@Override public void union(int p, int q) { int pRoot = find(p); // component of p int qRoot = find(q); // component of q // Do nothing if p and q belong to the same component if (pRoot == qRoot) return; // Take care to make smaller tree point to larger one thus keeping the // component-tree height relatively smaller if (height[pRoot] < height[qRoot]) { // Label component-id of pRoot as qRoot, thus effectively making the // component-id of all vertices whose actual component-id was pRoot // (by the virtue of being led to pRoot through their // component-id's) // now as qRoot id[pRoot] = qRoot; height[qRoot] = height[pRoot] + 1; sz[qRoot] += sz[pRoot]; } else { // vice-versa id[qRoot] = pRoot; height[pRoot] = height[qRoot] + 1; sz[pRoot] += sz[qRoot]; } componentCount--; }
f845d234-0b5d-47f5-8f2a-1488a0b8bd84
7
public static void main(String[] args) { // E A I final int MAXVOLUME[] = { 15, 10, 5 }; final int MAXJOUR[] = { 45, 20, 30}; String strNumero; char charCategorie; int iCategorie = 0; int iPossession; int iEmprunt; Boolean bResultat; //ramasser les données strNumero = JOptionPane.showInputDialog("Numéro de l'abonné:"); charCategorie = JOptionPane.showInputDialog("Code de la catégorie:").charAt(0); iPossession = Integer.parseInt(JOptionPane.showInputDialog("Nombre de livre en possession:")); iEmprunt = Integer.parseInt(JOptionPane.showInputDialog("Nombre de livre pour emprunter:")); //déterminer s'il peut prendre plus de livre switch(charCategorie) { case 'e': case 'E': iCategorie = 0; break; case 'a': case 'A': iCategorie = 1; break; case 'i': case 'I': iCategorie = 2; break; default: JOptionPane.showMessageDialog(null, "Mauvaise catégorie!"); System.exit(1); } bResultat = (iPossession+iEmprunt)<=MAXVOLUME[iCategorie]; //afficher la conclusion JOptionPane.showMessageDialog(null, "L'abonné #"+strNumero+" "+(bResultat ?"peut emprunter les volumes pour "+MAXJOUR[iCategorie]+" jours." :"ne peut pas emprunter de volumes pour le moment.")); System.exit(0); }
dd27e90d-9641-4967-8511-2a65e72d2726
9
private String balance(String input) { int tam = input.length(); char stack[] = new char[tam]; int top = 0; for ( int i = 0; i < tam; i++ ) { char c = input.charAt(i); if ( c == '(' || c == '[') { stack[top] = c; top++; } else if ( top == 0 ) { return "No"; } else { char topChar = stack[top - 1]; if ( ( c == ')' && topChar == '(' ) || ( c == ']' && topChar == '[' ) ) { top--; } else { return "No"; } } } if ( top == 0 ) { return "Yes"; } else { return "No"; } }
7ef6ac58-80e1-452d-ad73-d723f5253ac4
3
public void fillCustomerOrder(int orderid) { //System.out.println("FillCustomerOrder-------------------"); try { // Here you only need one statement I think. You are subtracting amount from stock number PreparedStatement stmt = connection.prepareStatement("select stock_number, amount from OrderedItem where order_id = ?"); stmt.setInt(1, orderid); ResultSet rs = stmt.executeQuery(); DepotItemModel depotItemModel = new DepotItemModel(connection); while (rs.next()) { /*System.out.println("you're the best"); PreparedStatement sstmt = connection.prepareStatement("select amount from OrderedItem where stock_number = ?"); sstmt.setString(1, rs.getString("stock_number")); ResultSet srs = sstmt.executeQuery(); while(srs.next()) {*/ if (depotItemModel.load(rs.getString("stock_number"))) { // depotItemModel.setStockNumber(rs.getString("stock_number")); /* System.out.println("sock number: " + depotItemModel.getStockNumber()); System.out.println("orderid: " + orderid + "; old quantity: " + depotItemModel.getQuantity() + "; amount:" + rs.getInt("amount"));*/ depotItemModel.setQuantity(depotItemModel.getQuantity() - rs.getInt("amount")); depotItemModel.update(); // System.out.println("new quantity (should be same as current quantity): " + depotItemModel.getQuantity()); //depotItemModel.printAll(); } } } catch (SQLException e) { e.printStackTrace(); } checkStockLevels(); // System.out.println("FillCustomerOrder END-------------------"); }
f47e861f-66ad-45bc-a142-abc2904717a7
4
public void removePathsContaining(final Block block) { for (int i = paths.size() - 1; i >= 0; i--) { final Block[] path = (Block[]) paths.get(i); if ((path[0] == block) || (path[1] == block)) { if (FlowGraph.DEBUG) { System.out.println("removing path " + path[0] + " -> " + path[1]); } paths.remove(i); } } }
feb15b40-e62a-4049-9f19-d7af880cd25e
0
@Override public String toString(){ return expression; }
b6d8b178-060b-4709-8b01-f5b039addce5
0
PhysObject3D(Object3D obj, String name, SimpleVector velocity) { super(obj); setName(name); this.velocity = velocity; this.acceleration = new SimpleVector(); }
f1f2d778-4211-4d6e-95b9-39f662e1e8c6
5
AllImagesIterator(final String first, final String prefix, final boolean lexicographicalOrder, final Long minimumLength, final Long maximumLength, final String sha1) { super("aifrom", first /* can also be null */); getParams = paramValuesToMap("action", "query", "format", "xml", "list", "allimages", "ailimit", "max", "aiprop", "timestamp|user|comment|url|size|sha1|mime", "aidir", lexicographicalOrder ? "ascending" : "descending"); if ((prefix != null) && (prefix.length() > 0)) { getParams.put("aiprefix", prefix); } if (minimumLength != null) { getParams.put("aiminsize", minimumLength.toString()); } if (maximumLength != null) { getParams.put("aimaxsize", maximumLength.toString()); } getParams.put("aisha1", sha1); }
331febd2-7e25-4b7c-93d7-b41a230c4f37
0
public void die() { alive = false; }
f2dd05fe-890e-4120-9641-16cfe6769005
7
public byte[] decrypt(byte[] textEncrypted, String key){ byte[] decrypted = null; try{ //keygenerator.init(bits); // 192 and bits bits may not be available byte[] keyPadded = new byte[bits / 8]; for(int i = 0; i < bits / 8 && i < key.length(); i++){ keyPadded[i] = (byte)key.charAt(i); } /* Generate the secret key specs. */ SecretKeySpec mykey = new SecretKeySpec(keyPadded, "AES"); // Create the cipher desCipher = Cipher.getInstance("AES"); // Initialize the cipher for encryption desCipher.init(Cipher.DECRYPT_MODE, mykey); // Encrypt the text decrypted = desCipher.doFinal(textEncrypted); }catch(IllegalBlockSizeException e){ e.printStackTrace(); }catch(BadPaddingException e){ e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); System.out.println("error in desCipher.init"); //} } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchPaddingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return decrypted; }
b8218b6c-570b-4c36-84a7-5497894a76cc
9
public void dessinerObjet(Graphics g) { int size = 600; //size in pixels BufferedImage bufImg = new BufferedImage(size, size, BufferedImage.TYPE_4BYTE_ABGR); BufferedImage solo; try { solo = ImageIO.read(new File("carrenoir.jpeg")); Graphics horsEcran = bufImg.getGraphics(); for(int i = 0; i < this.largeur; i++) { for(int j = 0; j < this.hauteur; j++) { horsEcran.drawImage(solo, i * 20, j * 20, null); } } //pour dessiner des nourritures for(Nourriture nou : this.nourriture){ BufferedImage bufImgNourriture = ImageIO.read(new File(nou.graph)); for(int i = 0; i < this.largeur; i++) { for(int j = 0; j < this.hauteur; j++) { horsEcran.drawImage(bufImgNourriture, i*20, j*20, null); } } } //pour dessiner des neuneus for(Neuneu ne : this.population){ BufferedImage imgNeuneu = ImageIO.read(new File(ne.graph)); for(int i = 0; i < this.largeur; i++) { for(int j = 0; j < this.hauteur; j++) { horsEcran.drawImage(imgNeuneu, i * 20, j * 20, null); } } } g.drawImage(bufImg, 0, 0, null); } catch (IOException e) { System.out.println("Exception:(image!!) " + e.getMessage()); e.printStackTrace(); } }
65a5a338-04e4-4445-9eb2-2223051ee306
9
public double getBECharge(int reactor_type, int tech_number, double capacity, int DDFlag, int year) { double cumMass = getBECumMass(reactor_type, tech_number, capacity, DDFlag, year); double tempCost = 0.; double charge = 0.; double tech_capacity = 0.; int i, j; // TODO why is SFReprocessed 0? /* for (i = 0; i < 9; i++) { for (j = 0; j < END_YEAR - START_YEAR + 1; j++) { if (SFReprocessed[i][j] > 0) System.out.print("working here \n"); } } */ // for CapacityAdditions, specifiedTierCap, YearCapacitySpecified tech_number is tech_number + FRONTENDMASS.length // CapacityAdditions[tech_number][tier] == 0 if a capacity isn't specified --> if not specified, should use default unit cost // if the capacity is specified, calculate unit costs dynamically // specifiedTierCap[tech_number][tier][number] --> number indexes over the number of capacity additions // YearCapacitySpecified[tech_number][tier][number] --> number indexes over number of capacity additions if (CapacityAdditions[FRONTENDTECH.length + tech_number][BELONGS_TO_TIER[reactor_type]] == 0 || modUnitCostsBE[reactor_type][tech_number][0] == 0) { // take default costs if no capacity additions are specified tempCost = unitCostsBE[reactor_type][tech_number]; if (DDFlag == 0) { charge = tempCost*capacity*BACKENDMASS[reactor_type][tech_number]*capacityToMass(reactor_type); } else { charge = tempCost*capacity*BACKENDMASS_DD[tech_number]*capacityToMass(reactor_type); } } else { // calculate unit costs dynamically if capacity additions are specified // determine the tech_capacity for this year for (i = 0; i < CapacityAdditions[FRONTENDTECH.length + tech_number][BELONGS_TO_TIER[reactor_type]]; i++) { if (year >= YearCapacitySpecified[FRONTENDTECH.length + tech_number][BELONGS_TO_TIER[reactor_type]][i] - START_YEAR) { tech_capacity = specifiedTierCap[FRONTENDTECH.length + tech_number][BELONGS_TO_TIER[reactor_type]][i]; } } // TODO still need to finalize this function for growth in technology capacity double facilities = tech_capacity/BEPLANTSIZE[tech_number]; //if (tech_number == 2) {System.out.print("year " + year + " tech capacity " + tech_capacity + " capacity " + capacity + " tier " + BELONGS_TO_TIER[reactor_type] + " cumMass " + cumMass + "\n");} if (cumMass > 0) {System.out.print("Year " + year + "\n");} // this doesn't work if the technology capacity isn't limiting if (tech_capacity == 0) { tempCost = 0; } else { if (cumMass == 0) { //System.out.print("year " + year + " tech capacity " + tech_capacity + " tier " + BELONGS_TO_TIER[reactor_type] + " cumMass " + cumMass + "\n"); tempCost = (modUnitCostsBE[reactor_type][tech_number][0] + modUnitCostsBE[reactor_type][tech_number][1]) * facilities; charge = tempCost/countSameTier(reactor_type, year); } else { //System.out.print("working \n"); tempCost = ( (modUnitCostsBE[reactor_type][tech_number][0] + modUnitCostsBE[reactor_type][tech_number][1]) * facilities) / cumMass; tempCost += modUnitCostsBE[reactor_type][tech_number][2]; if (DDFlag == 0) { charge = tempCost*capacity*BACKENDMASS[reactor_type][tech_number]*capacityToMass(reactor_type); } else { charge = tempCost*capacity*BACKENDMASS_DD[tech_number]*capacityToMass(reactor_type); } } } } return(charge); }
e1a77356-51dd-4610-8828-2d2e29723c4f
9
public synchronized int[] baseNumberCds2Pos() { if (cds2pos != null) return cds2pos; calcCdsStartEnd(); cds2pos = new int[cds().length()]; for (int i = 0; i < cds2pos.length; i++) cds2pos[i] = -1; int cdsMin = Math.min(cdsStart, cdsEnd); int cdsMax = Math.max(cdsStart, cdsEnd); // For each exon, add CDS position to array int cdsBaseNum = 0; for (Exon exon : sortedStrand()) { int min = isStrandPlus() ? exon.getStart() : exon.getEnd(); int step = isStrandPlus() ? 1 : -1; for (int pos = min; exon.intersects(pos) && cdsBaseNum < cds2pos.length; pos += step) if ((cdsMin <= pos) && (pos <= cdsMax)) cds2pos[cdsBaseNum++] = pos; } return cds2pos; }
ad62748b-10d7-4f1f-82dd-a6e84fed44db
8
public static void main( String [ ] args ) { PairingHeap<Integer> h = new PairingHeap<>( ); int numItems = 10000; int i = 37; int j; System.out.println( "Checking; no bad output is good" ); for( i = 37; i != 0; i = ( i + 37 ) % numItems ) h.insert( i ); for( i = 1; i < numItems; i++ ) if( h.deleteMin( ) != i ) System.out.println( "Oops! " + i ); ArrayList<PairingHeap.Position<Integer>> p = new ArrayList<>( ); for( i = 0; i < numItems; i++ ) p.add( null ); for( i = 0, j = numItems / 2; i < numItems; i++, j =(j+71)%numItems ) p.set( j, h.insert( j + numItems ) ); for( i = 0, j = numItems / 2; i < numItems; i++, j =(j+53)%numItems ) h.decreaseKey( p.get( j ), p.get( j ).getValue( ) - numItems ); i = -1; while( !h.isEmpty( ) ) if( h.deleteMin( ) != ++i ) System.out.println( "Oops! " + i + " " ); System.out.println( "Check completed" ); }
2ff5c4f2-7f8b-41eb-8787-184b30214f39
0
public SaveAction(Environment environment) { super(environment); putValue(NAME, "Save"); putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_S, MAIN_MENU_MASK)); this.environment = environment; }
85ca2bd7-814c-4c57-a5ec-34dd51843bce
4
public HashMap<String, List<Integer>> fillHashMap(HashMap<String, List<Integer>> allKMers, String pathToFile) throws IOException { LinkedList<Character> helpList = new LinkedList<Character>(); FileReader fr; fr = new FileReader(pathToFile); BufferedReader br = new BufferedReader(fr); int c = 0; int count = 0; int secondCount = 0; while ((c = br.read()) != -1) { char character = (char) c; if (count < this.k) { helpList.addLast(character); count++; } else { if (allKMers.get(listToString(helpList)) != null) { String s = listToString(helpList); List<Integer> helpIntList = allKMers.get(listToString(helpList)); helpIntList.add(secondCount); allKMers.remove(s); allKMers.put(s, helpIntList); secondCount++; helpList.removeFirst(); helpList.addLast(character); } else { List<Integer> helpIntList = new ArrayList<Integer>(); helpIntList.add(secondCount); allKMers.put(listToString(helpList), helpIntList); secondCount++; helpList.removeFirst(); helpList.addLast(character); } } } if (allKMers.get(listToString(helpList)) != null) { String s = listToString(helpList); List<Integer> helpIntList = allKMers.get(listToString(helpList)); helpIntList.add(secondCount); allKMers.remove(s); allKMers.put(s, helpIntList); } else { List<Integer> helpIntList = new ArrayList<Integer>(); helpIntList.add(secondCount); allKMers.put(listToString(helpList), helpIntList); } return allKMers; }
8e593094-616d-49c8-8bce-2d95db7e70eb
0
public final double getLineWidth() { return lineWidth; }
b7125325-f473-4b22-a89c-3b8f28fbf70c
7
private void beginServing() { if (m_ServletMap.size() > 0) { do { // System.out.println("========================="); // System.out.println("SERVER PULSE"); // System.out.println("========================="); for (int i = 0; i < SERVLET_TYPE.values().length; i++) { SERVLET_TYPE servletType = SERVLET_TYPE.values()[i]; /* * In the event we want to do something before we have the * servlet respond. */ switch (servletType) { case CLIENT_RESPONDER_SERVLET: break; case REGISTRATION_SERVLET: break; case UNKOWN: break; default: break; } if (m_ServletMap.containsKey(servletType)) { // System.out.println("========================="); // System.out.println("contains key"); // System.out.println("========================="); /* Servlet call */ // m_ServletMap.get(servletType).checkResponses(); // if (!m_ServletMap.get(servletType).isExecuting()) { // // System.out.println("========================="); // System.out.println("Removing servlet"); // System.out.println("========================="); // // m_ServletMap.remove(servletType); // } } } /* Give some time for servlets to do their thing. */ // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } ThreadHelper.sleepThread(3000); } while (isExecuting()); } }
b8077222-e15b-471b-9b18-5d9a2d747a6a
2
public void draw(Graphics g) { g.setColor(Color.ORANGE); for (Meat meat : meats) { g.fillOval(meat.getX(), meat.getY(), 8, 8); } g.setColor(Color.black); for (Meat meat : meats) { g.drawOval(meat.getX(), meat.getY(), 8, 8); } }