method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
3e959e8d-8b17-4ab7-9c75-3f3274f9bacf
6
public boolean check() { for (InputNode in : this.input) { if (!in.check()) { // System.out.println("Input Node " + in.getName() + " is not valid"); return false; } } for (InnerNode in : this.inner) { if (!in.check()) { // System.out.println("Inner Node " + in.getName() + " is not valid"); return false; } } for (OutputNode on : this.output) { if (!on.check()) { System.out.println("Output Node " + on.getName() + " is not valid"); return false; } } return true; }
34df034e-955d-4bd3-a2e3-0c969e754243
1
protected void onEntryRemove(Object key, ICacheable data){ if(null != mDiskLruCache){ mDiskLruCache.put(key, data); } }
daa9f210-4795-44d4-b93b-2c2ccde13b0e
4
public static final boolean isPrimitiveArray(Object array) { if (array != null) { Class<?> clazz = array.getClass(); if (clazz.isArray()) { String className = array.getClass().getName(); return className.length() == 2 && className.charAt(0) == '['; } } return false; }
febedf7c-19e5-43e8-87b5-0c5035defcb7
5
public static void main(String[] args) { QArrayCount<Integer> q = new QArrayCount<Integer>(); for (int i = 1; i <= 567; i++) q.enqueue(i); for (int i = 1; i <= 89; i++) q.dequeue(); for (int i = 8; i <= 9; i++) q.enqueue(i); for (int i = 1; i <= 43; i++) q.dequeue(); for (Integer i : q) System.out.println(i); System.out.println("Size: " + q.size()); }
83af6892-793d-48d3-ab0d-064f2ce0b5b2
2
public void setHmac(Key key){ Mac hmac = null; try { hmac = Mac.getInstance("HmacSHA256"); } catch (NoSuchAlgorithmException e) { // TODO vernuenftiges handling e.printStackTrace(); } try { hmac.init(key); } catch (InvalidKeyException e) { // TODO vernuenftiges handling e.printStackTrace(); } byte[] message = this.toString().getBytes(); hmac.update(message); byte[] hash = hmac.doFinal(); base64hash = Base64.encode(hash); }
f1c704bb-65af-4fe3-839f-946a2c853da4
2
@Override public Move chooseMove(State s) { // return if there are no moves available if (s.findMoves().size() == 0) return null; synchronized (s) { try { s.wait(); } catch (InterruptedException e) {} return Board.getMove(); } }
fbd5c856-4383-4b12-96f7-a7f5d86a4409
5
@Test public void testRandom () { System.err.println ("testRandom"); int numRects = 100000; int numRounds = 10; Random random = new Random (1234); // same random every time for (int round = 0; round < numRounds; round++) { tree = new PRTree<Rectangle2D> (converter, 10); List<Rectangle2D> rects = new ArrayList<Rectangle2D> (numRects); for (int i = 0; i < numRects; i++) { Rectangle2D r = new Rectangle2D.Double (getRandomRectangleSize (random), getRandomRectangleSize (random), getRandomRectangleSize (random), getRandomRectangleSize (random)); rects.add (r); } tree.load (rects); double x1 = getRandomRectangleSize (random); double y1 = getRandomRectangleSize (random); double x2 = getRandomRectangleSize (random); double y2 = getRandomRectangleSize (random); MBR query = new SimpleMBR (Math.min (x1, x2), Math.min (y1, y2), Math.max (x1, x2), Math.min (y1, y2)); int countSimple = 0; for (Rectangle2D r : rects) { if (query.intersects (r, converter)) countSimple++; } int countTree = 0; for (Rectangle2D r : tree.find (query)) countTree++; assertEquals (round + ": should find same number of rectangles", countSimple, countTree); } }
cadce98b-28e9-4bdf-acaf-af84e2719514
2
public void replenishmentOrder(String manu, String modNum, int q) { System.out.println("Sending replenishment order..."); Statement s = null; String updateRep = "UPDATE ProductDepot p SET p.replenishment = '" + q + "' WHERE p.manufacturer = '" + manu + "' AND p.model_number = '" + modNum + "'"; try { s = custConn.getConnection().createStatement(); int rst = s.executeUpdate(updateRep); } catch (Exception e) { System.out.println("Unable to update replenishment"); System.exit(1); } String update = "UPDATE ProductDepot p SET p.quantity = p.quantity + p.replenishment, p.replenishment = 0 WHERE p.manufacturer = '" + manu + "' AND p.model_number = '" + modNum + "'"; try { //Statement st = custConn.getConnection().createStatement(); int rst = s.executeUpdate(update); } catch (Exception e) { System.out.println("Error updating product quantity. Exiting"); System.exit(1); } System.out.println("ProductDepot replenished!"); }
d23cc4d8-3feb-4232-b9a7-74e938d1de8c
1
private String getDescription() { String desc = "@MongoBatchInsert(" + this.getParsedShell().getOriginalExpression() + ")"; if (!StringUtils.isEmpty(globalCollectionName)) { desc = ",@MongoCollection(" + globalCollectionName + ")"; } return desc; }
a11bb83b-0842-4842-9961-5c22b0da4f5a
3
@SuppressWarnings("unchecked") @Override public B get(A a) { B b = null; try { b = (B) getMethod.invoke(a, new Object[0]); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return b; }
1b5d7eb9-d4d8-4333-9bc3-60db86fa2ce9
2
@Override public int compareTo(CButton o) { final int compareTo = this.getText().compareTo(o.getText()); if (this != o && compareTo == 0) return this.name.compareTo(o.getText()); else return compareTo; }
69a64ecb-0365-4285-be64-ea78e278affb
0
private static void updateSecondProjectView() { getInstance().secondProjectTitleL.setText("Second Project: " + getInstance().secondProject.getProjectName()); getInstance().secondProjectScreensCBL.setListData(getScreenCheckBoxes( getInstance().secondProject, false)); getInstance().secondProjectScreensCBL.clearChecked(); getInstance().secondProjectScreensP.setViewportView(getInstance().secondProjectScreensCBL); getInstance().secondProjectAssetsCBL .setListData(getAssetCheckBoxes(getInstance().secondProject)); getInstance().secondProjectAssetsCBL.clearChecked(); getInstance().secondProjectAssetsP.setViewportView(getInstance().secondProjectAssetsCBL); getInstance().secondProjectDisplayP.repaint(); }
ae43a97b-5196-4b4e-bf0e-e83e4aa8fce6
7
private static void printConfiguration (int indent, Configuration c) { String temp; // atypical: should always be able to read configuration if (c == null) { indentLine (indent, "<!-- null configuration -->"); return; } indentLine (indent, "<config value='" + c.getConfigurationValue () + "' total-length='" + c.getTotalLength () + "' attributes='" + Integer.toHexString (c.getAttributes ()) + "'"); temp = c.getConfiguration (defaultLanguage); if (temp != null) indentLine (indent + 4, "description='" + temp + "'"); indentLine (indent + 4, "max-power='" + (2 * c.getMaxPower ()) + " mA.' interfaces='" + c.getNumInterfaces () + "'>"); indent += 2; maybePrintDescriptors (indent, c.nextDescriptor ()); for (int i = 0; i < c.getNumInterfaces (); i++) { try { Interface intf; // NOTE: assumes altsetting range is contiguous, [0..N] for (int j = 0; (intf = c.getInterface (i, j)) != null; j++) { // claimer of interface selects altsettings if (j == 0) { String claimer = intf.getClaimer (); if (claimer != null) indentLine (indent, "<!-- interface " + i + " is claimed by: " + claimer + " driver -->"); else indentLine (indent, "<!-- interface " + i + " is unclaimed -->"); } printInterface (indent, intf); } } catch (IOException e) { indentLine (indent, "<!-- CAN'T GET INTERFACE: "); e.printStackTrace (System.out); indentLine (indent, "-->"); } } indentLine (indent, "</config>"); }
12a96d83-d258-422d-aa88-5c179088cf06
2
private int sMax(int sMax) { if (radius <= 100) { return (int) Math.floor(0.65 * sMax); } else if (radius >= 800) { return sMax; } else { double result = 0.18 * Math.log1p(radius) - 0.2; return (int) Math.floor(result*sMax); } }
08d30ab2-273a-4d5e-b37a-fe685ed53aee
8
private static void mergePreferences( CommonPrefResource prefFile, Properties properties, MultiStatus status) { if (prefFile == null && properties == null) return; if (!prefFile.exists) return; InputStream input = null; // Added this code for testing /*try { input = prefFile.getInputStream(); BufferedReader bufferReader = new BufferedReader(new InputStreamReader(input)); String line = null; System.out.println("CommonPrefsHelper MERGE PREFERENCES: \n"); while((line = bufferReader.readLine()) != null) { System.err.println(line); } bufferReader.close(); } catch(IOException e) { }*/ // End try { input = prefFile.getInputStream(); //prefs.load(input); // Add this code for testing CommonPrefProjectPreference.read(input, properties); // End } catch (IOException e) { if (status != null) { status.add(new Status(Status.WARNING, StartupPlugin.PLUGIN_ID, "Failed loading preference file " + prefFile.getResourceName(), e)); } } catch (BackingStoreException e) { } finally { if (input != null) { try { input.close(); } catch (IOException e) { } } } }
5cb2a5d0-3325-4631-a5cc-5c1a54102288
6
@Override public ItemStack transferStackInSlot(EntityPlayer player, int slot) { ItemStack stack = null; Slot slotObject = (Slot) inventorySlots.get(slot); // null checks and checks if the item can be stacked (maxStackSize > 1) if (slotObject != null && slotObject.getHasStack()) { ItemStack stackInSlot = slotObject.getStack(); stack = stackInSlot.copy(); // merges the item into player inventory since its in the tileEntity if (slot < SLOT_COUNT) { if (!this.mergeItemStack(stackInSlot, 0, 35, true)) { return null; } } // places it into the tileEntity is possible since its in the player // inventory // else if (!this.mergeItemStack(stackInSlot, 0, SLOT_COUNT, false)) // { // return null; // } if (stackInSlot.stackSize == 0) { slotObject.putStack(null); } else { slotObject.onSlotChanged(); } if (stackInSlot.stackSize == stack.stackSize) { return null; } slotObject.onPickupFromSlot(player, stackInSlot); } return stack; }
ae7d0b15-3d61-4b67-b382-538962f2c59a
1
@Override protected boolean doDelete(final String key) { try { return cache.remove(key); } catch (Throwable e) { CacheErrorHandler.handleError(e); return false; } }
0386a2b1-7b32-4d98-bb30-e3dfe2dc932e
8
public List<Integer> analyze() { List<Integer> features = new ArrayList<Integer>(); try { // find min and max values: for (String chr : decompressorISS.getChromosomes()) { boolean lastBaseOverThreshold = true; CompressedCoverageIterator it = decompressorISS .getCoverageIterator(); while (it.hasNext()) { it.next(); GenomicPosition currentPos = it.getGenomicPosition(); if (currentPos.getChromosome() == chr) { CoverageHit hitQuery = decompressorISS .query(currentPos); float value = hitQuery.getInterpolatedCoverage(); if (lastBaseOverThreshold) { if (value <= ISS_THRESHOLD) { // found feature features.add((int) currentPos.get0Position()); lastBaseOverThreshold = false; } else { continue; } } else { if (value > ISS_THRESHOLD) { // found feature features.add((int) currentPos.get0Position()); lastBaseOverThreshold = true; } else { continue; } } } } } return features; } catch (Exception e) { e.printStackTrace(); } finally { try { decompressorISS.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return null; }
9072549d-e47a-4492-b028-307d7213d2c0
7
private boolean gameInitFromFile(File fin){ DataInputStream file; try{ file = new DataInputStream(new BufferedInputStream(new FileInputStream(fin))); }catch (FileNotFoundException ex){ return false; } try{ asteroids = new ArrayList<Asteroid>(); bullets = new ArrayList<Bullet>(); //write status score1 = file.readInt(); score2 = file.readInt(); level = file.readInt(); //write options gravExists = file.readBoolean(); gravVisible = file.readBoolean(); unlimitedLives = file.readBoolean(); numAsteroids = file.readInt(); startingLevel = file.readInt(); isSinglePlayer = file.readBoolean(); //write players int newX = file.readInt(); int newY = file.readInt(); double newAngle = file.readDouble(); double newVX = file.readDouble(); double newVY = file.readDouble(); double newVAngle = file.readDouble(); int newLives = file.readInt(); int status = file.readInt(); player1 = new Player(newX,newY,newAngle,newVX,newVY,newVAngle, newLives,0); if (status == 0){ player2 = null; }else{ newX = file.readInt(); newY = file.readInt(); newAngle = file.readDouble(); newVX = file.readDouble(); newVY = file.readDouble(); newVAngle = file.readDouble(); newLives = file.readInt(); player2 = new Player(newX,newY,newAngle,newVX,newVY,newVAngle,newLives,1); } status = file.readInt(); for (int i = 0; i < status; i++){ newX = file.readInt(); newY = file.readInt(); newAngle = file.readDouble(); newVX = file.readDouble(); newVY = file.readDouble(); newVAngle = file.readDouble(); Color newColor = new Color(file.readInt()); int newShooterID = file.readInt(); Bullet newBullet = new Bullet(newX,newY,newAngle,newVX,newVY,newVAngle,newColor, newShooterID); newBullet.setDist(file.readDouble()); bullets.add(newBullet); } status = file.readInt(); for (int i = 0; i < status; i++){ newX = file.readInt(); newY = file.readInt(); newAngle = file.readDouble(); newVX = file.readDouble(); newVY = file.readDouble(); newVAngle = file.readDouble(); int newType = file.readInt(); asteroids.add(new Asteroid(newX, newY, newAngle, newVX, newVY, newVAngle, newType)); } status = file.readInt(); if (status == 0){ rogueSpaceship = null; }else{ newX = file.readInt(); newY = file.readInt(); newAngle = file.readDouble(); newVX = file.readDouble(); newVY = file.readDouble(); newVAngle = file.readDouble(); rogueSpaceship = new RogueSpaceship(newX,newY,newAngle,newVX,newVY,newVAngle); } status = file.readInt(); if (status == 0){ alienShip = null; }else{ newX = file.readInt(); newY = file.readInt(); newAngle = file.readInt(); newVX = file.readDouble(); newVY = file.readDouble(); newVAngle = file.readDouble(); newLives = file.readInt(); alienShip = new AlienShip(newX,newY,newAngle,newVX,newVY,newVAngle); } file.close(); }catch (IOException ex){ return false; } return true; }
a58cbf0a-6c73-4aab-853b-b5c20bb54565
1
public void createObj(){ for(int i=0; i<1100000;i++){ TestGarbageCollector t = new TestGarbageCollector(); } System.out.println(Runtime.getRuntime().freeMemory()/1024+"MB"); }
0571ac72-b38e-425a-9481-bd4035c5181e
4
public double characterEnergy() { if (P2character.equals("White")) { return whiteKnight.characterEnergy(); } else if (P2character.equals("Bond")) { return jamesBond.characterEnergy(); } else if (P2character.equals("Ninja")) { return redNinja.characterEnergy(); } else if (P2character.equals("Mage")) { return purpleMage.characterEnergy(); } return markGreen.characterEnergy(); }
4f228e9a-d23c-4224-b60c-a1657920e8a6
2
public TreeNode nodeAtPoint(Point2D point, Dimension2D size) { Iterator it = nodeToPoint.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); Point2D p = scalePoint((Point2D) entry.getValue(), size); TreeNode node = (TreeNode) entry.getKey(); if (nodeDrawer.onNode(node, point.getX() - p.getX(), point.getY() - p.getY())) return node; } return null; }
e7d261b3-f227-4336-9cc7-bc950133ed16
6
public void updateFiles() throws ClassNotFoundException, IOException{ boolean found=false; File dropins = new File("./dropins/plugins/"); File [] names = dropins.listFiles(new PluginFilter(dropins)); if(names.length==0){ return; } Collection<File> pluginstmp = new ArrayList<File>(); for(File plugin : names){ pluginstmp.add(plugin); if(!this.plugins.contains(plugin)){ // something has been added found=true; } } for(File f : this.plugins){ if(!pluginstmp.contains(f)) found=true; // something has been removed } this.plugins.clear(); this.plugins.addAll(pluginstmp); if(found) this.somethingHappens(); }
10d5a2b6-1389-49de-a942-0d6fd100f718
7
public void damageTile(int x, int y, int damage) { if (x < 0 || x >= width || y < 0 || y >= height) { return; } if (getTile(tiles[x + y * width][0]).isSolid() && getTile(tiles[x + y * width][0]).canBeDamaged()) { tiles[x + y * width][1] += damage; if (getTile(tiles[x + y * width][0]).getMaxDamage() <= tiles[x + y * width][1]) { changeTileAt(x, y, Tile.GRASS); } } }
877e5fdb-243d-4412-bfc3-e47c4c67e6e3
7
public static byte[] unencodedSeptetsToEncodedSeptets(byte[] septetBytes) { byte[] txtBytes; byte[] txtSeptets; int txtBytesLen; BitSet bits; int i, j; txtBytes = septetBytes; txtBytesLen = txtBytes.length; bits = new BitSet(); for (i = 0; i < txtBytesLen; i++) for (j = 0; j < 7; j++) if ((txtBytes[i] & (1 << j)) != 0) bits.set((i * 7) + j); // big diff here int encodedSeptetByteArrayLength = txtBytesLen * 7 / 8 + ((txtBytesLen * 7 % 8 != 0) ? 1 : 0); txtSeptets = new byte[encodedSeptetByteArrayLength]; for (i = 0; i < encodedSeptetByteArrayLength; i++) { for (j = 0; j < 8; j++) { txtSeptets[i] |= (byte) ((bits.get((i * 8) + j) ? 1 : 0) << j); } } return txtSeptets; }
5a81823c-9b7c-4c79-b74a-31b90706a134
6
@Override public String onFactionCall(L2Npc npc, L2Npc caller, L2PcInstance attacker, boolean isPet) { if (attacker == null) return null; L2Character originalAttackTarget = (isPet ? attacker.getPet() : attacker); if (attacker.isInParty() && attacker.getParty().isInDimensionalRift()) { byte riftType = attacker.getParty().getDimensionalRift().getType(); byte riftRoom = attacker.getParty().getDimensionalRift().getCurrentRoom(); if (caller instanceof L2RiftInvaderInstance && !DimensionalRiftManager.getInstance().getRoom(riftType, riftRoom).checkIfInZone(npc.getX(), npc.getY(), npc.getZ())) return null; } // When a faction member calls for help, attack the caller's attacker. npc.getAI().notifyEvent(CtrlEvent.EVT_AGGRESSION, originalAttackTarget, 1); return null; }
dcbde9be-7238-4c3c-bbcf-918f39b00f65
3
private void click() { if(curPage == 0) { if(options.get(curPage)[curOption].getTitle().equals("Resume")) { game.enterState(Game.IN_GAME_STATE_ID, new FadeOutTransition(), new FadeInTransition()); } else if(options.get(curPage)[curOption].getTitle().equals("Exit to Main Menu")) { game.enterState(Game.MAIN_MENU_STATE_ID, new FadeOutTransition(), new FadeInTransition()); } } }
b1916827-fe4b-432f-96af-bff542edffc3
7
@Override public String toString() { String[][] board = new String[8][8]; Iterator<Piece> it = this.whitePieces.iterator(); while (it.hasNext()) { Piece next = it.next(); Point p = next.getPosition(); if (next.isKing()) board[p.x][p.y] = "W"; else board[p.x][p.y] = "w"; } // end while it = this.blackPieces.iterator(); while (it.hasNext()) { Piece next = it.next(); Point p = next.getPosition(); if (next.isKing()) board[p.x][p.y] = "B"; else board[p.x][p.y] = "b"; } // end while String result = " 0 1 2 3 4 5 6 7\n"; for (int row = 0; row < 8; row++) { result += Integer.toString(row) + " "; for (int col = 0; col < 8; col++) { String cell = " "; if (board[row][col] != null) cell = board[row][col]; result += cell + " "; } // end for result += "\n"; } // end for return result; } // end toString()
2a9d82b0-6c71-4d6a-bfb4-06f41f96ea58
7
public static Object kettleCast(Object value) { if (value == null) { return value; } Class<?> c = value.getClass(); if (c == Integer.class || c == int.class) { return ((Integer) value).longValue(); } if (c == Float.class || c == float.class) { return ((Float) value).doubleValue(); } if (c == BigInteger.class) { return new BigDecimal((char[]) value); } return value; }
39c9a514-a043-422c-9efd-1b8031b3166e
9
public double lorentzInnerProduct(Matrix matrix2, boolean isRowVector) { // Can only operate on a "vector" (nx1 matrix) if ((!isRowVector && ((numCols > 1) || (matrix2.numCols > 1))) || (isRowVector && ((numRows > 1) || (matrix2.numRows > 1)))) return Double.NaN; double result = 0.0; for (int i = 0; i < 3; ++i) result += (isRowVector ? (data[0][i] * matrix2.data[0][i]) : (data[i][0] * matrix2.data[i][0])); result -= (isRowVector ? (data[0][3] * matrix2.data[0][3]) : (data[3][0] * matrix2.data[3][0])); return result; }
76431ba3-57df-432d-a352-2ac636f9e65d
7
public List<ZoneResource> listZoneRecords(final Zone zone) { Set<ZoneResource> zoneResources = new HashSet<ZoneResource>(); boolean readMore = true; Map<String, String> query = new HashMap<String, String>(); while (readMore) { String result = pilot.executeResourceRecordSetGet(zone.getExistentZoneId(), query); XMLTag xml = XMLDoc.from(result, true); log.trace("List Zone Records:\n{}", xml); if (xml.hasTag("Error")) { throw parseErrorResponse(xml); } if (xml.getText("//IsTruncated").equals("false")) { readMore = false; } String lastName = ""; for (XMLTag record : xml.getChilds("//ResourceRecordSet")) { String name = record.getText("Name"); String type = record.getText("Type"); String weight = null; String setIdentifier = null; if (record.hasTag("SetIdentifier")) { setIdentifier = record.getText("SetIdentifier"); weight = record.getText("Weight"); } String ttl = null; String aliasZoneId = null; String aliasDnsName = null; List<String> values = new ArrayList<String>(); if (record.hasTag("AliasTarget")) { aliasZoneId = record.getText("AliasTarget/HostedZoneId"); aliasDnsName = record.getText("AliasTarget/DNSName"); } else { ttl = record.getText("TTL"); for (XMLTag resource : record.getChilds("ResourceRecords/ResourceRecord")) { values.add(resource.getText("Value")); } Collections.sort(values); } zoneResources.add((new ZoneResource(name, RecordType.valueOf(type), parseIntWithDefault(ttl, 0), values, setIdentifier, parseIntWithDefault(weight, 0), aliasZoneId, aliasDnsName))); lastName = name; } query.put("name", lastName); } List<ZoneResource> list = new ArrayList<ZoneResource>(); list.addAll(zoneResources); return list; }
934318e0-6061-46de-93d6-15ecacdf3653
3
private void btnAgregarEventoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarEventoActionPerformed //obtenemos lo necesario de la vista: int idCliente = obtenerClaveClienteSeleccionado(); int idEmpleado = obtenerClaveEmpleadoSeleccionado(); int idMesa = obtenerClaveMesaSeleccionada(); String fecha = obtenerFecha(); Object[] proveedores = obtenerProveedores(); float precioTotal = obtenerPrecio(); int idPaquete = obtenerTipoPaquete(); //creamos el controlador de eventos. try { ControladorEventos unControlador = new ControladorEventos(); boolean existe = unControlador.ExisteElEvento(idCliente, idMesa, fecha, idEmpleado); if(existe){ mostrarMensajeEnPantalla("Este evento ya existe"); }else{ boolean seAgregoEvento = unControlador.agregarEvento(idCliente, idEmpleado, idMesa, proveedores, idPaquete, precioTotal, fecha); if (seAgregoEvento) { mostrarMensajeEnPantalla("Evento Agregado"); } else { mostrarMensajeEnPantalla("Evento NO Agregado"); } } } catch (SQLException ex) { ex.printStackTrace(); mostrarMensajeEnPantalla("Error con la BD. " + ex.getLocalizedMessage()); } }//GEN-LAST:event_btnAgregarEventoActionPerformed
3c9264de-9451-4d15-8705-949267102c92
6
public List<Noeud> genererPlanDepuisXML() throws XmlParserException { File xml = this.fichierATraiter; ArrayList<Noeud> listeDesNoeuds=null; if (xml != null) { try { // creation d'un constructeur de documents a l'aide d'une fabrique DocumentBuilder constructeur = DocumentBuilderFactory.newInstance().newDocumentBuilder(); // lecture du contenu d'un fichier XML avec DOM Document document = constructeur.parse(xml); verifierSiValide(); Element racine = document.getDocumentElement(); if (racine.getNodeName().equals("Reseau")){ //Cr???ation et remplissage de la liste de noeuds listeDesNoeuds= new ArrayList<Noeud>(); construirePlanAPartirDeDOMXML(racine,listeDesNoeuds); } } catch (ParserConfigurationException pce) { String message= new String("Erreur de configuration du parseur DOM lors de l'appel a fabrique.newDocumentBuilder(); "); throw new XmlParserException(message,pce); } catch (SAXException se) { String message = new String("Erreur lors du parsing du document lors de l'appel a construteur.parse(xml)"); throw new XmlParserException(message,se); } catch (IOException ioe) { String message= new String("Erreur d'entree/sortie lors de l'appel a construteur.parse(xml)"); throw new XmlParserException(message,ioe); } catch (XmlParserException myEx) { throw myEx; } } return listeDesNoeuds; }
bcd2b7f3-d684-463c-a110-5ee195e3c5bb
2
public static long directorySize(File directory) { long length = 0; for (File file : directory.listFiles ()) { if (file.isFile ()) { length += file.length (); } else { length += directorySize (file); } } return length; }
f81e3e8d-54a5-4220-a500-1c353bce42a6
9
public TagParseResult clone() { ByteArrayOutputStream byteOut = null; ObjectOutputStream out = null; ByteArrayInputStream byteIn = null; ObjectInputStream in = null; try { byteOut = new ByteArrayOutputStream(); out = new ObjectOutputStream(byteOut); out.writeObject(this); byteIn = new ByteArrayInputStream(byteOut.toByteArray()); in = new ObjectInputStream(byteIn); return (TagParseResult) in.readObject(); } catch (Exception e) { System.out.println(e.toString()); e.printStackTrace(); return null; } finally { if (null != in) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != byteIn) { try { byteIn.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != out) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != byteOut) { try { byteOut.close(); } catch (IOException e) { e.printStackTrace(); } } } }
0ab2535a-37b3-437d-b9aa-589f462b1fc8
8
private void requestFriends(int startIndex) { HttpGet httpget = new HttpGet("http://m.facebook.com/" + user.getUserUIDString() + "?v=friends&startindex=" + startIndex); CloseableHttpResponse response = null; HttpEntity entity = null; String str = null; try { response = httpClient.execute(httpget, cont); try { entity = response.getEntity(); str = EntityUtils.toString(entity); } finally { EntityUtils.consume(response.getEntity()); response.close(); } } catch (ClientProtocolException ex) { // Handle protocol errors } catch (IOException ex) { // Handle I/O errors } String regex = "(<a href=\"/)([0-9a-zA-Z.]*)(\\?fref)"; Hashtable<String, String> allMatches = new Hashtable<String, String>(); Matcher m = Pattern.compile(regex).matcher(str); while (m.find()) { if (!allMatches.containsKey(m.group())) { allMatches.put(m.group(), m.group()); } } Collection<String> col = allMatches.values(); for (Iterator<String> i = col.iterator(); i.hasNext();) { String item = i.next(); item = item.replace("<a href=\"/", "").replace("?fref", ""); if (FacePath.DEBUG >= 4) { System.out.println("GLOFOT-found: " + item); } // dep queue.add(item); } if (this.allFriends) { String nextPageRegex = "(<a href=\"/" + user.getUserUIDString() + "\\?v=friends&amp;mutual&amp;startindex=)([0-9]*)(&amp;refid=17\"><span>See More Friends</span></a>)"; Matcher nextPageMatcher = Pattern.compile(nextPageRegex).matcher(str); String match = null; if (nextPageMatcher.find()) { match = nextPageMatcher.group(); match = match.replace( "<a href=\"/" + user.getUserUIDString() + "?v=friends&amp;mutual&amp;startindex=", "").replace( "&amp;refid=17\"><span>See More Friends</span></a>", ""); requestFriends(Integer.parseInt(match)); } } }
913ea201-3a04-4fd7-9199-0cd70ad065d8
8
protected void onPrivateMessage(String sender, String login, String hostname, String message) { if (sender.equals("geordi") || sender.equals("clang")) { sendMessage(MAINCHAN,message); return; } if (message.startsWith("?") && sender.equals("IsmAvatar")) this.sendRawLineViaQueue(message.substring(1)); if (message.startsWith("!")) message = message.substring(1); if (message.isEmpty()) return; String msg[] = message.split("\\s",2); if (msg[0].isEmpty()) return; command(sender,sender,msg[0].toLowerCase(),msg.length == 1 ? "" : msg[1]); }
e07cd8f3-9c58-4e8c-a8dd-09e5f0e76ac5
8
public static boolean processTripleMegaPhone(final MapleClient c, final List<String> message, final byte numlines, final boolean ear) { String tag = ""; String legend = ""; final List<String> messages = new LinkedList<String>(); String msg = "-"; for (byte i = 0; i < numlines; i++) { if (c.getPlayer().getPrefixShit() >= 2) { legend = c.getPlayer().getLegend(); msg = "[" + legend + "]" + message.get(i); } if (c.getPlayer().getPrefixShit() == 1 || c.getPlayer().getPrefixShit() == 2) { tag = Status.getName(c.getPlayer().getGMLevel()); msg = "<" + tag + ">" + message.get(i); } if (isIllegalWords(c.getPlayer(), msg)) { msg = "<Retard> [I Suck Dick]" + c.getPlayer().getName() + " : I'm a Cock Sucker. Ban me GM bahahaha. I tried to advertise"; } messages.add(msg); } try { c.getChannelServer().getWorldInterface().broadcastSmega(MaplePacketCreator.tripleSmega(messages, ear, c.getChannel()).getBytes()); for (int i = 1; i < messages.size(); i++) { if (messages.get(i) != null) { MainIRC.getInstance().sendIrcMessage(messages.get(i)); } } return true; } catch (RemoteException e) { System.out.println("RemoteException occured, triple megaphone"); return false; } }
44cef35b-8f4c-4aad-9f03-42397d437890
8
public void draw(Graphics2D g, int rotation) { if (!isFinished()) { setRotationAngle(getRotationAngle() + rotation); double xRotation = getXRotation(); double yRotation = getYRotation(); boolean canDraw = true; boolean leftTurn = false; for (Block block : blockArray) { if (rotation > 0) { // trig rotation stuff // since 90 degree rotation // sin(theta) = 1 and cos(theta) = 0 double newX = (yRotation - block.getYValue()) + xRotation; double newY = -xRotation + block.getXValue() + yRotation; block.setXValue(newX); block.setYValue(newY); } if (block.getXValue() < 0) canDraw = false; else if ((block.getXValue() + 40) > TetrisPanel.XFRAME) { canDraw = false; leftTurn = true; } block.draw(g); } if (!canDraw) { g.setColor(TetrisPanel.BACKGROUND); g.fillRect(0, 0, TetrisPanel.XFRAME, TetrisPanel.YFRAME); if (!leftTurn) doMoveRight(); else doMoveLeft(); draw(g, 0); } if (getRotationAngle() == 360) setRotationAngle(0); } }
0af277e4-b921-49d1-b66f-5448568b54c7
5
public synchronized boolean updateCrashedPeers(Set<Byte> crashedPeerOrds) { boolean somethingChanged = false; //DEBUG for (byte b : crashedPeerOrds) { System.out.println(String.format("MORTO: %s", b)); } if (crashedPeerOrds.contains(this.getOrd())) { gameTable.forceEndGame("La tua connessione è troppo lenta, sei stato buttato fuori il gioco!"); } for (int i=(getOrd()+1)%peers.size(); i!=getOrd(); i=(i+1)%peers.size()) { Peer p = peers.get(i); if (crashedPeerOrds.contains((byte)p.getOrd())) { //DEBUG System.out.println(String.format("Setto peer %s morto!", p.getOrd())); if (p.isActive()) somethingChanged = true; p.setActiveStatus(false); } } return somethingChanged; }
de0faaf8-83ad-465f-8453-c6048392f8a5
5
String readByteXByteSIBmsg() { //configurable buffer size int buffsize= 4 *1024; StringBuilder builder = new StringBuilder(); char[] buffer = new char[buffsize]; String msg = ""; int charRead =0; try { while ((charRead = in.read(buffer, 0, buffer.length)) != (-1)) { builder.append(buffer, 0 , charRead); // System.out.println("reading" + builder.toString()); } msg = builder.toString(); if(msg.contains("<SSAP_message>") && msg.contains( "</SSAP_message>") ) { //The first message is not an event but just the confirmation message!!! if(this.xmlTools.isSubscriptionConfirmed(msg)) { this.KP_ERROR_ID=this.ERR_Subscription_DONE; startEventHandlerThread(kpSocket,in,out); return msg; }//if(this.xmlTools.isSubscriptionConfirmed(ret)) else { /*flush all chars in the message instead:break;*/ deb_print("KpCore:readByteXByteSIBmsg:SSAP message recognized"); } }//if(tmp_msg.startsWith("<SSAP_message>") && tmp_msg.endsWith("</SSAP_message>")) deb_print("KpCore:readByteXByteSIBmsg:READ LOOP TERMINATED"); closeConnection(); }catch(Exception e) { err_print("KPICore:readByteXByteSIBmsg:Exception on EVENT HANDLER:RECEIVE:\n"+e); this.KP_ERROR_ID=this.ERR_SOCKET_TIMEOUT; } // return responseData.toString(); return msg; }
a94650e2-f59f-4388-b940-fe8f887080ee
4
double getAttack(Match match, Team team) { int countMatches = 0; int[] goals = new int[deep]; Match currentMatch = getPrevMatch(team, match); for (int i = 0; i < deep && currentMatch != null; i++, currentMatch = getPrevMatch( team, currentMatch), countMatches++) { goals[i] = getScoreForTeam(currentMatch, team); countMatches++; } if (countMatches < deep) return -1; double res = 0; for (int i = 0; i < goals.length; i++) { res += goals[i]; } return res / (deep); }
abf59f65-7554-4191-b169-2fc62df7aee3
5
@Override public String toString() { int i; StringBuilder sb = new StringBuilder(); if (this.getMarks() != null) { try { if (average() != 0) { sb.append(super.toString()); sb.append("\n\tPromotion: " + p.getName()); sb.append("\n\tId: ").append(id).append("\n\tMarks: "); for (i = 0; i < NB_EVALUATIONS; i++) { if (this.marks[i] != null) { sb.append(marks[i] + " "); } } sb.append("\n\tGrader(s): ").append(this.getGraders()); sb.append("\n\tAverage: ").append(this.average()) .append("\n"); } } catch (EmptyMarks e) { System.out.println(super.toString() + " doesn't have marks !"); } } return sb.toString(); }
e8bf845a-5ebf-416b-a3c0-a98088fc22b4
9
public synchronized String kick(String player) { player = player.toLowerCase().trim(); MiniServer bannedPlayer = null; System.out.println("1. " + player); System.out.println("2. " + host.getClientName().toLowerCase().trim()); if(player.equals(host.getClientName().toLowerCase().trim())) { try { host.sendMessageToClient("Don\'t ban yourself."); } catch (IOException e) { System.err.println("Couldn\'t cancel ban of host properly..."); e.printStackTrace(); } return ""; } for(int i=0; i<players.length; i++) { if(players[i] != null && players[i].getClientName().toLowerCase().equals(player)) { bannedPlayer = players[i]; players[i] = null; try { bannedPlayer.sendMessageToClient("You have been banned from the game."); bannedPlayer.receiveBan(); bannedPlayerList.add(bannedPlayer.getClientName().toLowerCase()); } catch (IOException e) { System.err.println("Couldn\'t ban player..."); e.printStackTrace(); } this.numPlayers--; //change host if host leaves: if(player == this.host.getClientName().toLowerCase()) { for(int j=1; j<players.length; j++) { if(players[i+j] != null) { this.host = players[i+j]; } } } renewRefreshMessage(); return ""; } } return "ERROR: couldn't find player to ban!"; }
00fec439-67fc-445e-909d-67c21445c9b5
6
public boolean almostEquals(Object obj) { if (this == obj) return true; if (getClass() != obj.getClass()) return false; Root other = (Root) obj; if (expr == null) { if (other.expr != null) return false; } else if (!expr.equals(other.expr)) return false; if (nthRoot != other.nthRoot) return false; return true; }
98af8376-cb35-46bc-a4fd-ffcabbfa2d15
7
@Override public boolean isReallyNeutral(FactionMember M) { if(M != null) { Faction F=null; Faction.FRange FR=null; for(final Enumeration<String> e=M.factions();e.hasMoreElements();) { F=CMLib.factions().getFaction(e.nextElement()); if(F!=null) { FR=CMLib.factions().getRange(F.factionID(),M.fetchFaction(F.factionID())); if(FR!=null) switch(FR.alignEquiv()) { case NEUTRAL: return true; case EVIL: return false; case GOOD: return false; default: continue; } } } } return true; }
2ae39519-96dc-4fa6-9971-e9b6f1f321d5
0
@Override public String introduceYourself() { return "DecisionQuest"; }
a2b9200c-c429-4422-8934-a14bf30d1714
9
public void newGame() { final int rows = this.mRows; final int cols = this.mCols; if (null == this.mCellsState) { this.mCellsState = new CellState[rows][cols]; } for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { this.mCellsState[i][j] = CellState.EMPTY; } } if (null == this.mGomokuPieces) { this.mGomokuPieces = new ArrayList<>(rows * cols); } ScreenManager.getInstance().getBaseGameActivity().getEngine().runOnUpdateThread(new Runnable() { @Override public void run() { GomokuBoard.this.mEntity.detachChildren(); } }); if (GameManager.getInstance().getCurrentGameMode() == GameMode.OFFLINE) { int depth = 0; if (GameManager.getInstance().getComputerLevel() == ComputerLevel.EASY) { depth = 8; } else if (GameManager.getInstance().getComputerLevel() == ComputerLevel.MEDIUM) { depth = 10; } else if (GameManager.getInstance().getComputerLevel() == ComputerLevel.HARD) { depth = 13; } if (null == this.mEvaluater) { this.mEvaluater = new Evaluater(this, depth); } } }
9d075aef-0644-41d2-9952-c2135e2ac409
9
private static boolean isKingInCheckAfterMoveRec(byte[][] board, byte piece, int hPos, int vPos, int skiphPos, int skipvPos, int tohPos, int tovPos, int hAdd, int vAdd) { hPos += hAdd; vPos += vAdd; if (hPos < 0 || hPos > 7 || vPos < 0 || vPos > 7 || (hPos == tohPos && vPos == tovPos)) { return false; } if (board[hPos][vPos] == EMPTY || (skiphPos == hPos && skipvPos == vPos)) { return isKingInCheckAfterMoveRec(board, piece, hPos, vPos, skiphPos, skipvPos, tohPos, tovPos, hAdd, vAdd); } return board[hPos][vPos] == piece; }
a0ff5153-254d-4e63-b340-d54f26c80d90
1
public void notifyWorldModelListeners() { for (final WorldModelListener listener : this.listenersWorld) { notifyWorldModelListener(listener); } }
914d80ec-3e9e-46cf-908e-ff02f67a7d69
0
*/ private GrammarTable initGrammarTable() { grammarTable = new GrammarTable(new GrammarTableModel(grammar) { public boolean isCellEditable(int r, int c) { return false; } }); return grammarTable; }
e3aea9b4-df47-4ffb-88a5-1f10a2380ef7
7
@Override public int[] next() { if (started == false) { this.current = new int[size]; for (int i = 0; i < size; i++) this.current[i] = i + 1; this.started = true; return this.current; } int[] new_digits = current.clone(); int n = new_digits.length - 1; int j = n - 1; while (current[j] > current[j + 1]) j--; int k = n; while (current[j] > current[k]) k--; int temp = new_digits[j]; new_digits[j] = new_digits[k]; new_digits[k] = temp; int r = n; int s = j + 1; while (r > s) { temp = new_digits[r]; new_digits[r] = new_digits[s]; new_digits[s] = temp; r--; s++; } int j1 = new_digits.length - 2; while (new_digits[j1] > new_digits[j1 + 1]) { if (j1 == 0) { this.exhausted = true; break; } j1--; } current = new_digits; return new_digits; }
1d5d6155-516c-4f06-b87c-10aadd8e57cc
3
public void tick() { snake.move(); for (int i = 0; i < food.getFood().size(); i++) { if (snake.getHead().getX() == food.getFood().get(i).getX() && snake.getHead().getY() == food.getFood().get(i).getY()) { food.ateMeat(i); snake.increase(); } } }
ca55d74d-ba31-48d4-9fe2-499fbd27b0b0
2
@Override public T validate(String fieldName, T value) throws ValidationException { if (value == null) { return null; } if (max.compareTo(value) <= 0) { throw new ValidationException(fieldName, value, "must be less than " + max); } return value; }
d01c9648-43e4-4687-945b-4e6016dca7e3
3
public static String half2Fullchange(String QJstr) throws Exception { StringBuffer outStrBuf = new StringBuffer(""); String Tstr = ""; byte[] b = null; for (int i = 0; i < QJstr.length(); i++) { Tstr = QJstr.substring(i, i + 1); if (Tstr.equals(" ")) { // 半角空格 outStrBuf.append(Tstr); continue; } b = Tstr.getBytes("unicode"); if (b[2] == 0) { // 半角? b[3] = (byte) (b[3] - 32); b[2] = -1; outStrBuf.append(new String(b, "unicode")); } else { outStrBuf.append(Tstr); } } return outStrBuf.toString(); }
067ebac6-2d1c-4d4f-8b39-dce4fcccca35
5
public static void engine() { if (World.world[World.PLAYER_POS_X][World.PLAYER_POS_Y] .equals(GlobalParams.paling)) { System.out.println("Забор не помеха? Ну-ну..."); World.PLAYER_POS_X = x; World.PLAYER_POS_Y = y; } if (World.world[World.PLAYER_POS_X][World.PLAYER_POS_Y] .equals(GlobalParams.wall)) { System.out.println("Вы уперлись носом в стену."); World.PLAYER_POS_X = x; World.PLAYER_POS_Y = y; } if (World.world[World.PLAYER_POS_X][World.PLAYER_POS_Y] .equals(GlobalParams.closeDoor)) { if (checkDoor == 0) { if (GlobalParams.keyToTheDoor != 0) { GlobalParams.keyToTheDoor -= 1; checkDoor = 1; World.world[World.PLAYER_POS_X][World.PLAYER_POS_Y] = "Открытая дверь"; System.out.println("Вы открыли дверь ключем"); checkDoor = 0; } else { System.out .println("Перед вам закрытая дверь. Но у вас нет ключа от неё."); World.PLAYER_POS_X = x; World.PLAYER_POS_Y = y; } } else { System.out.println("Дверь заперта. Используйте ключ."); World.PLAYER_POS_X = x; World.PLAYER_POS_Y = y; } } }
a7f51e74-39d4-4e68-a559-40c4cf75bc1d
7
public static void main(String[] args) throws Throwable{ BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) ); StringBuilder sb = new StringBuilder( ); int casos = Integer.parseInt( in.readLine( ) ); in.readLine( ); for (int t = 0; t < casos; t++) { lineas = new ArrayList<String>(); for (String line; (line = in.readLine( )) != null && !line.equals(""); ) { StringTokenizer st = new StringTokenizer( line ); if(st.countTokens() > 1 ){ m = new char[lineas.size()][lineas.get(0).length()]; mC = new boolean[lineas.size()][lineas.get(0).length()]; for(int i = 0; i < lineas.size(); i++) { String liniesita = lineas.get(i); for (int j = 0; j < liniesita.length(); j++) { m[i][j] = liniesita.charAt(j); } } int i = Integer.parseInt(st.nextToken()); int j = Integer.parseInt(st.nextToken()); sb.append( floodfill(i-1, j-1) +"\n") ; }else{ lineas.add(line); } } if( t < casos-1 ){ sb.append("\n"); } } System.out.print(new String(sb)); }
20ad58b7-0cab-412a-ba97-dbe166c93c58
4
private void smoothOver(Run start, Run end) { Run currentRun = start; while(currentRun != end.getNext()) { if(currentRun.next.getRunLength() == 0) remove(currentRun.getNext()); else if((currentRun.getRunType() == currentRun.getNext().getRunType()) && (currentRun.getHungerVal() == currentRun.getNext().getHungerVal())) { currentRun.setRunLength(currentRun.getRunLength() + currentRun.getNext().getRunLength()); remove(currentRun.getNext()); } else currentRun = currentRun.getNext(); } }
b18ff383-01ce-4c54-b2c0-adef75c5bb28
3
@Override public void deletePerson(Person person) throws SQLException { Connection dbConnection = null; PreparedStatement preparedStatement = null; String deletePerson = "DELETE FROM person WHERE name = '"+ person.getName() + "' AND surname = '" + person.getSurname()+"'"; try { dbConnection = PSQL.getConnection(); preparedStatement = dbConnection.prepareStatement(deletePerson); // execute delete SQL stetement preparedStatement.executeUpdate(); } catch (SQLException e) { System.out.println(e.getMessage()); } finally { if (preparedStatement != null) { preparedStatement.close(); } if (dbConnection != null) { dbConnection.close(); } } }
5528da3a-131e-411b-8cd3-d4ee8ba04a0c
1
private IdentificadorVariavelVetor completarIdVariavelVetor(Identificador id) throws SemanticError { int limiteSuperior = tipoConstante == Tipo.INTEIRO ? Integer.parseInt(valorConstante) : valorConstante.charAt(0); int tamanho = limiteSuperior - valorLimiteInferior + 1; int deslocamentoVetor = deslocamento; deslocamento += tamanho; return new IdentificadorVariavelVetor(id.getNome(), deslocamentoVetor, tipoElementos, tipoLimiteInferior, valorLimiteInferior, limiteSuperior); }
92af27d7-4c6a-40c9-8a30-ee685299de8c
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(VtnPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(VtnPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(VtnPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(VtnPrincipal.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 VtnPrincipal().setVisible(true); } }); }
2d3be795-2b40-469a-8e53-54d067a98725
4
@Override public void run() { BufferedReader reply = makeRequest(); if(reply == null) // Stop immediately if the request did not generate a response. return; /* Send the request to be interpreted and alert the user * about the response. */ if(parseXml(reply)) { if(mReply == REPLY_SUCCESS) { mUi.displayAlert(GSInsert.INSERT_SUCCESS_TITLE, GSInsert.INSERT_SUCCESS_MESSAGE, JOptionPane.INFORMATION_MESSAGE); System.out.println("Upload success."); } else if(mReply == REPLY_READ_ONLY) { mUi.displayAlert(GSInsert.RESPONSE_UNAUTHORIZED_TITLE, GSInsert.RESPONSE_UNAUTHORIZED_MESSAGE, JOptionPane.WARNING_MESSAGE); System.out.println("Upload unauthorized."); } else { mUi.displayAlert(GSInsert.INSERT_FAILURE_TITLE, GSInsert.INSERT_FAILURE_MESSAGE, JOptionPane.ERROR_MESSAGE); System.out.println("Upload failed."); } } else mUi.displayAlert(GSInsert.PARSE_ERROR_TITLE, GSInsert.PARSE_ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE); }
feb0b050-daf4-47cf-9119-9a0f0bc99f65
3
public void carregarProfessoresDeArquivo(String nomeArquivo) throws ProfessorJaExisteException, IOException { BufferedReader leitor = null; try { leitor = new BufferedReader(new FileReader(nomeArquivo)); String nomeProf = null; do { nomeProf = leitor.readLine(); // lê a próxima linha do arquivo, // nome do professor if (nomeProf != null) { String matriculaProf = leitor.readLine(); // Lê a próxima // linha do // arquivo, // matrícula do // professor this.cadastraProfessor(nomeProf, matriculaProf); } } while (nomeProf != null); // vai ser null quando chegar no fim do // arquivo } finally { if (leitor != null) { leitor.close(); } } }
317263ba-5497-4863-b347-1b1fd1990271
0
public void update(){ }
f10103ed-6897-4144-be2f-0d05357e8d12
9
public void keyReleased(KeyEvent e) { if(e.getKeyCode()==KeyEvent.VK_UP||e.getKeyCode()==KeyEvent.VK_W){ Up = false; } if(e.getKeyCode()==KeyEvent.VK_DOWN||e.getKeyCode()==KeyEvent.VK_S){ Down = false; } if(e.getKeyCode()==KeyEvent.VK_LEFT||e.getKeyCode()==KeyEvent.VK_A){ Left = false; } if(e.getKeyCode()==KeyEvent.VK_RIGHT||e.getKeyCode()==KeyEvent.VK_D){ Right = false; } if(e.getKeyCode()==KeyEvent.VK_R){ Restart = false; } }
3af5cf99-77db-4bdb-abb0-fafd7596a008
4
@Override public int compareTo(Element<T> o) { if(this.isHead()) return 1; if(this.isTail()) return -1; if(o.isHead()) return -1; if(o.isTail()) return 1; return (this.value).compareTo(o.value); }
2f1ee667-321d-4759-ac04-f6839fcb401d
5
public Building(double x, double y, double width, double height) { if (x == 0 && y == 0 && width == 0 && height == 0) { x = Board.getInstance().getWidth() - 1; y = Board.getRandom(200, 250); width = Board.getRandom(500, 1000); height = 300; } this.setRect(x, y, width, height); if (Board.getRandom(0,5) == 4) { this.setRotation(Board.getRandom(5,10)); } }
8f51136c-7df7-437a-a0ee-1ff1be663038
7
public void setup() { //CREATE WALKER OBJECT Walker walker = new Walker(BUFFER); // load program properties Config config = new Config("props/superD.properties"); //list of directories to scan List<File> rootDirs = new ArrayList<File>(); //Load in all directories to scan from properties file into rootDirs ArrayList try { if (this.getDel() == null) { this.setDel(config.getConfig("ROOT_DEL")); } if (this.getRoot() == null) { this.setRoot(config.getConfig("ROOT")); } List<String> rootDirListArr = Arrays.asList(this.getRoot().split(this.getDel())); for (int i=0; i < rootDirListArr.size(); i++){ rootDirs.add(new File(rootDirListArr.get(i))); } } catch (ConfigException e) { log.fatal("Failed to read config file!", e); } //Call Walker.walk() on all the directories in rootDirs try{ for (int i=0; i < rootDirs.size(); i++){ //make sure that it is a directory if (rootDirs.get(i).isDirectory()){ walker.walk(rootDirs.get(i)); } else { log.debug(rootDirs.get(i).toString() + " Appears to not be a directory; skipping to next in list"); } } //TODO replace generic Exception with specific exception(s) }catch(Exception e){ e.printStackTrace(); } }
f7e6a413-0839-454a-ab18-22c5cd3c7444
0
public ArrayList<DrawableItem> getItems() { return items; }
360495fc-5fa7-458f-b03a-22e9182dc260
6
private void saveSQL(PrintStream out) throws IOException { out.println("<br><br>"); out.println("<h3>Script SQL</h3>"); String name, str, text, textFinal, requete; List<String> keywords = sql.getKeywords(); List<String> types = sql.getTypes(); text = sql.getRequests(); for (StringTokenizer st = new StringTokenizer(text, " (),<>;", true); st .hasMoreElements();) { str = st.nextToken(); if (keywords.contains(str)) out.println("<b style=\"color: blue;\">" + str + "</b>"); else if (types.contains(str)) out.println("<b style=\"color: red;\">" + str + "</b>"); else if (str.equals("(") || str.equals(")")) out.println("<b>" + str + "</b>"); else if (str.equals(";")) out.println(";<br><br>"); else out.println(str); } }
06fe7388-9473-4dbf-bd6b-75ceec25ce6e
4
private void makeRoom(int numValues) { if (values == null) { values = new float[2 * numValues]; types = new int[2]; numVals = 0; numSeg = 0; return; } int newSize = numVals + numValues; if (newSize > values.length) { int nlen = values.length * 2; if (nlen < newSize) nlen = newSize; float[] nvals = new float[nlen]; System.arraycopy(values, 0, nvals, 0, numVals); values = nvals; } if (numSeg == types.length) { int[] ntypes = new int[types.length * 2]; System.arraycopy(types, 0, ntypes, 0, types.length); types = ntypes; } }
5c89e644-2128-4b43-a01d-1113ca1770d4
3
* @param text messages to be added about the meeting. * @throws IllegalArgumentException if the list of contacts is * empty, or any of the contacts does not exist * @throws NullPointerException if any of the arguments is null */ public void addNewPastMeeting(Set<Contact> contacts, Calendar date, String text) throws NullPointerException { now.setTime(new Date()); if(date.after(now)) { throw new IllegalArgumentException("date should not be in the future"); } for(Contact contact : contacts) { if(!isContactValid(contact)) { throw new IllegalArgumentException("contact id " + contact.getId() + " is invalid"); } } MeetingImpl pm = new PastMeetingImpl(contacts, date); ((PastMeetingImpl)pm).addNotes(text); meetingList.add(pm); meetingSet.add(pm); }
5fe04eaa-6efd-4a7c-b575-85a638b43bd6
3
public static void setSkin(Plugin plugin, final Player p, final String toSkin) { new BukkitRunnable() { @Override public void run() { try { Packet packet = new PacketPlayOutNamedEntitySpawn(((CraftPlayer) p).getHandle()); Field gameProfileField = PacketPlayOutNamedEntitySpawn.class.getDeclaredField("b"); gameProfileField.setAccessible(true); @SuppressWarnings("deprecation") GameProfile profile = new GameProfile(Bukkit.getOfflinePlayer(p.getName()).getUniqueId(), p.getName()); fixSkin(profile, toSkin); gameProfileField.set(packet, profile); for (Player pl : Bukkit.getOnlinePlayers()) { if (pl.equals(p)) { continue; } ((CraftPlayer) pl).getHandle().playerConnection.sendPacket(packet); } } catch (Exception e) { e.printStackTrace(); } } }.runTaskAsynchronously(plugin); }
b734b0ad-27d5-4aa6-b6bc-6ab02d4cd975
2
private void setUpLogin() { setUpRegister(); login = new JPanel(); // Controls final JTextField username = new PlaceholderTextField("username"); final JPasswordField password = new PlaceholderPasswordField("password"); JButton submit = new JButton("Login"); JButton register = new JButton("Register"); JPanel centreBox = new JPanel(); centreBox.setPreferredSize(new Dimension(200, 110)); centreBox.setMinimumSize(new Dimension(200, 110)); centreBox.setMaximumSize(new Dimension(200, 110)); /* * Add button listeners */ submit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // Send request with username and password AuthenticateRequest rq = new AuthenticateRequest(); userId = username.getText(); char[] pw = password.getPassword(); password.setText(""); byte[] hash; PasswordHasher ph = new PasswordHasher(); hash = ph.preHash(userId, new String(pw)); // Clear password array for extra security Arrays.fill(pw, '\0'); rq.setSenderId(userId); rq.setPassword(hash); boolean success = Comms.sendMessage(rq); if (success) { // Receive response and handle try { AuthenticateResponse re = (AuthenticateResponse) Comms.receiveMessage(); handle(re); } catch (ClassCastException ex) { Alerter.getHandler().severe("Authentication failure", "Response from server was malformed. Please try again."); } } } }); register.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showRegister(); } }); // Layout code login.setLayout(new BoxLayout(login, BoxLayout.X_AXIS)); login.add(Box.createHorizontalGlue()); login.add(centreBox); login.add(Box.createHorizontalGlue()); GroupLayout loginControlLayout = new GroupLayout(centreBox); loginControlLayout.setHorizontalGroup(loginControlLayout.createSequentialGroup() .addContainerGap() .addGroup(loginControlLayout.createParallelGroup() .addComponent(username) .addComponent(password) .addGroup(loginControlLayout.createSequentialGroup() .addComponent(submit, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE, Short.MAX_VALUE) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(register, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE, Short.MAX_VALUE) ) ) .addContainerGap() ); loginControlLayout.setVerticalGroup(loginControlLayout.createSequentialGroup() .addComponent(username) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(password) .addPreferredGap(ComponentPlacement.UNRELATED) .addGroup(loginControlLayout.createParallelGroup() .addComponent(submit) .addComponent(register) ) ); centreBox.setLayout(loginControlLayout); }
f57d9e3b-ec67-4d89-a64d-2c586a0b0de6
8
public void wdgmsg(Widget sender, String msg, Object... args) { int ep; if((ep = epoints.indexOf(sender)) != -1) { if(msg == "drop") { wdgmsg("drop", ep); return; } else if(msg == "xfer") { return; } } if((ep = equed.indexOf(sender)) != -1) { if(msg == "take") wdgmsg("take", ep, args[0]); else if(msg == "itemact") wdgmsg("itemact", ep); else if(msg == "transfer") wdgmsg("transfer", ep, args[0]); else if(msg == "iact") wdgmsg("iact", ep, args[0]); return; } super.wdgmsg(sender, msg, args); }
9d9a4487-4ae1-4bb6-9315-158f0fa31693
0
public boolean doCheck() { return this.check; }
c95988d5-95e0-4557-a1e3-c722d6808dd0
4
public void WGOverridePwd(String sender, Command command) { if(command.arguments.length == 3) { User user; for(Game game : games.values()) { user = getUserByNick(game, command.arguments[1]); if(user != null) { user.setPassword(command.arguments[2]); if(game.autosave) { saveGame(game); } } } sendMessageWrapper(sender, null, "Password set for all users matching this nick."); } else { sendMessageWrapper(sender, null, "WGOVERRIDEPWD usage: !wgoverridepwd <user> <newpassword>"); } }
df5d807a-fc62-47b5-8829-720275db447b
6
protected void updateView(String machineFileName, String input, JTableExtender table) { ArrayList machines = this.getEnvironment().myObjects; Object current = null; if(machines != null) current = machines.get(0); else current = this.getEnvironment().getObject(); if(current instanceof Grammar && (table.getSelectedRow() < (table.getRowCount()-1))){ int spot = this.getMachineIndexBySelectedRow(table); Grammar cur = null; if(spot != -1) cur = (Grammar)machines.get(spot); else cur = (Grammar)this.getEnvironment().getObject(); CYKParsePane bp = new CYKParsePane((GrammarEnvironment)getEnvironment(), cur, myCNFGrammar, null); int column = 1; if(spot == -1) column = 0; bp.inputField.setText((String)table.getModel().getValueAt(table.getSelectedRow(), column)); //bp.inputField.setEnabled(false); bp.inputField.setEditable(false); JSplitPane split = SplitPaneFactory.createSplit(getEnvironment(), true, 0.5, bp, myPanel); MultiplePane mp = new MultiplePane(split); getEnvironment().add(mp, getComponentTitle(), new CriticalTag() { }); EnvironmentFrame frame = Universe.frameForEnvironment(getEnvironment()); String newTitle = cur.getFileName(); if(newTitle != "") frame.setTitle(newTitle); getEnvironment().remove(getEnvironment().getActive()); getEnvironment().add(mp, getComponentTitle(), new CriticalTag() { }); getEnvironment().setActive(mp); } }
4c4082c6-4ab2-47dc-bab4-ff84577a52ce
8
public static boolean isValid( RushHourCar car, ArrayList<RushHourCar> cars, int width, int height ) { ArrayList<Point> carBlocks = car.getBlocks(); for( Point carBlock : carBlocks ) { if( carBlock.x >= width || carBlock.x < 0 || carBlock.y >= height || carBlock.y < 0 ) { return false; } for( RushHourCar currentCar : cars ) { ArrayList<Point> currentCarBlocks = currentCar.getBlocks(); for( Point currentCarBlock : currentCarBlocks ) { if( carBlock.equals(currentCarBlock) ) { return false; } } } } return true; }
74523a04-c70d-498c-ad01-4bba7579fbbe
1
public static String reverse1(String s) { String rev = ""; int n = s.length(); for (int i = 0; i < n; i++) rev += s.charAt(n - i - 1); return rev; }
02974e89-4e5b-4d50-8ed7-f88759157b53
8
protected void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed if(JOptionPane.showConfirmDialog(rootPane,"Deseja Salvar os dados?") == 0){ /*if(txtNome.getText().isEmpty()){ JOptionPane.showMessageDialog(rootPane, "O campo nome não pode ser vazio"); }else if (txtCpf.getText().isEmpty()){ JOptionPane.showMessageDialog(rootPane, "O campo cpf não pode ser vazio"); }else if(txtRg.getText().isEmpty()){ JOptionPane.showMessageDialog(rootPane, "O campo Rg não pode ser vazio"); }else{*/ if(validaCampos()){ Cliente cliente = null; try { cliente = new Cliente(); cliente.setCpf(txtCpf.getText()); cliente.setDataNascimento(dataFormatada(txtDataNascimento.getText())); cliente.setEmails(this.listaEmails); cliente.setEnderecos(this.listaEnderecos); cliente.setNome(txtNome.getText()); cliente.setRg(txtRg.getText()); cliente.setTelefones(this.listaTelefones); cliente.setIdCliente(this.idCliente); cliente.setId(this.idPessoa); } catch (ErroValidacaoException ex) { //Logger.getLogger(frmCadastroCliente.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(rootPane, ex.getMessage()); cliente = null; }catch(Exception ex){ JOptionPane.showMessageDialog(rootPane, ex.getMessage()); cliente = null; } if(cliente != null){ ClienteDAO dao = new ClienteDAO(); try{ if(dao.Salvar(cliente)){ JOptionPane.showMessageDialog(rootPane, "Cliente Salvo com sucesso !"); this.listaEmails.clear(); this.listaEnderecos.clear(); this.listaTelefones.clear(); //criar limpar os campos limpaCampos(); this.tblEmail.repaint(); this.tblEndereco.repaint(); this.tblTelefones.repaint(); } }catch(ErroValidacaoException ex){ JOptionPane.showMessageDialog(rootPane, ex.getMessage()); }catch(Exception ex){ JOptionPane.showMessageDialog(rootPane, ex.getMessage()); } } }else{ JOptionPane.showMessageDialog(rootPane, "Todos os campos devem ser preenchidos !"); } } }//GEN-LAST:event_btnSalvarActionPerformed
3c69727f-7411-4bd6-889b-60e35531183b
4
public static Image gaussianNoise(Image original, double avg, double dev, double p) { if (original == null) return null; Image gaussian = original.shallowClone(); for (int x = 0; x < original.getWidth(); x++) { for (int y = 0; y < original.getHeight(); y++) { double rand = Math.random(); double noise = 0; if (rand < p) { noise = gaussianGenerator(avg, dev); } gaussian.setPixel(x, y, RED, original.getPixel(x, y, RED) + noise); gaussian.setPixel(x, y, GREEN, original.getPixel(x, y, GREEN) + noise); gaussian.setPixel(x, y, BLUE, original.getPixel(x, y, BLUE) + noise); } } return gaussian; }
b2d32705-809b-4fd3-af47-37542bcfdb16
0
public void setRatingId(int ratingId) { this.ratingId = ratingId; }
2919d32d-5872-457a-ba3b-c139b7ba958a
4
@Override public boolean handleCommandParametersCommand(String providedCommandLine, PrintStream outputStream, IServerStatusInterface targetServerInterface) { String[] commandParts = GenericUtilities.splitBySpace(providedCommandLine); if(commandParts.length == 2) { List<String> params = targetServerInterface.getCommandParameters(commandParts[1]); if(params == null) { outputStream.println("Command not supported:" + commandParts[1]); } else { if(params.size() == 0) { outputStream.println("Command has no parameters"); } else { for(String paramName:params) { outputStream.println("Parameter:"+paramName); } } } return true; } return false; }
197542f1-a411-42a4-aaa5-f4bd0e51f0b3
4
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Instructions other = (Instructions) obj; if (!Objects.equals(this.gameInstructions, other.gameInstructions)) { return false; } if (!Objects.equals(this.instructionType, other.instructionType)) { return false; } return true; }
a842f4b9-bdd8-40e3-870f-ac3608ba7365
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(janMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(janMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(janMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(janMenu.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 janMenu().setVisible(true); } }); }
96df465f-0a5a-40f4-a8ff-bcd2d95d7bfa
7
protected void onMouseClick(int mouseX, int mouseY, int mouseButton) { if (mouseButton == 0) { // Left-click for (Button button : buttons) { if (button.active && mouseX >= button.x && mouseY >= button.y && mouseX < button.x + button.width && mouseY < button.y + button.height) { onButtonClick(button); } } } }
acbd0037-ff56-44dd-af23-5d3873145109
8
private void jTableProductosMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTableProductosMousePressed // TODO add your handling code here: try { jButton1.setEnabled(true); jButton2.setEnabled(true); Cant = Integer.parseInt(JOptionPane.showInputDialog("Cantidad")); String idProd, nombreProd, newcant; int rows, index = 0; Double precio, total = 0.0; boolean flag = false; rows = jTableVentas.getRowCount(); String compare = (String) tmProd.getValueAt(jTableProductos.getSelectedRow(), 0); String compare2 = ""; int i = 1; if (rows == 0) { idProd = (String) tmProd.getValueAt(jTableProductos.getSelectedRow(), 0); nombreProd = (String) tmProd.getValueAt(jTableProductos.getSelectedRow(), 1); precio = (Double.parseDouble((String) tmProd.getValueAt(jTableProductos.getSelectedRow(), 3))) * Cant; tmVent.addRow(new Object[]{idProd, nombreProd, Cant, precio}); jTableVentas.setModel(tmVent); } else { int x = 0; z: while (i <= rows) { try { compare2 = (String) tmVent.getValueAt(x, 0); } catch (Exception e) { } if (compare.equals(compare2)) { flag = true; index = i; break z; } else { flag = false; } ++i; ++x; ++index; } if (flag) { if (index - 1 < rows) { index--; flag = false; int updatecant = (int) tmVent.getValueAt(index, 2) + Cant; precio = (Double.parseDouble((String) tmProd.getValueAt(jTableProductos.getSelectedRow(), 3))) * updatecant; tmVent.setValueAt(updatecant, index, 2); tmVent.setValueAt(precio, index, 3); } } else { idProd = (String) tmProd.getValueAt(jTableProductos.getSelectedRow(), 0); nombreProd = (String) tmProd.getValueAt(jTableProductos.getSelectedRow(), 1); precio = (Double.parseDouble((String) tmProd.getValueAt(jTableProductos.getSelectedRow(), 3))) * Cant; tmVent.addRow(new Object[]{idProd, nombreProd, Cant, precio}); } } int rows2 = jTableVentas.getRowCount(); for (int j = 0; j < rows2; j++) { total += (Double.parseDouble(tmVent.getValueAt(j, 3).toString())); } newcant = Integer.toString(Integer.parseInt((String) tmProd.getValueAt(jTableProductos.getSelectedRow(), 5)) - Cant); tmProd.setValueAt(newcant, jTableProductos.getSelectedRow(), 5); jLblPrecio.setText(total.toString()); } catch (HeadlessException | NumberFormatException e) { JOptionPane.showMessageDialog(this, e); } }//GEN-LAST:event_jTableProductosMousePressed
88333be0-f638-4fc5-91d3-fe662f800423
2
public static InputStream getInputFromJar(String path) throws IOException { if (path == null) { throw new IllegalArgumentException("The path can not be null"); } URL url = plugin.getClass().getClassLoader().getResource(path); if (url == null) { return null; } URLConnection connection = url.openConnection(); connection.setUseCaches(false); return connection.getInputStream(); }
6282e6be-dc70-4277-84b2-e6b6cf6ebd30
4
public static int fieldNum(String name) { int fieldNum = 0; if (name.equals("NMD.GENE")) return fieldNum; fieldNum++; if (name.equals("NMD.GENEID")) return fieldNum; fieldNum++; if (name.equals("NMD.NUMTR")) return fieldNum; fieldNum++; if (name.equals("NMD.PERC")) return fieldNum; fieldNum++; return -1; }
39e7a993-dc2c-4038-a578-f09e6a868ba1
8
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed if (txtNomUsager.getText().equals("") || txtPrenomUsager.getText().equals("") || txtNomOeuvre.getText().equals("")) { JOptionPane.showMessageDialog(null, "Tous les champs sont requis.", "Erreur", JOptionPane.ERROR_MESSAGE); } else { try { Date dateRetour = new SimpleDateFormat("dd/MM/yy", Locale.FRANCE).parse(txtDateRetour.getText()); int ret; if ( (ret = ihm.emprunterExemplaire(txtNomUsager.getText(), txtPrenomUsager.getText(), txtNomOeuvre.getText(), dateRetour)) < 0) { switch (ret){ case -1 :JOptionPane.showMessageDialog(null, "Oeuvre inconnue.", "Erreur", JOptionPane.ERROR_MESSAGE);break; case -2 :JOptionPane.showMessageDialog(null, "Il n'y a pas d'exemplaires disponibles", "Erreur", JOptionPane.ERROR_MESSAGE);break; case -3 :JOptionPane.showMessageDialog(null, "Usager inconnu.", "Erreur", JOptionPane.ERROR_MESSAGE);break; } } } catch (ParseException ex) { Logger.getLogger(RetraitExemplaire.class.getName()).log(Level.SEVERE, null, ex); } } }//GEN-LAST:event_jButton2ActionPerformed
9ada07f2-2fe9-4c35-907c-61ef73667843
9
private int requestEngineMove() { int move = Game.NULL_MOVE; int ponder = Game.NULL_MOVE; try { if (client.isPondering()) { client.send("stop"); while (client.isPondering()) client.receive(); } client.send(getPositionCommand(game)); client.send(getGoCommand(movetime)); while (client.isThinking()) client.receive(); move = client.getBestMove(); ponder = client.getPonderMove(); int length = game.length(); try { if (move != Game.NULL_MOVE) performMove(game, move); if (ponder != Game.NULL_MOVE) performMove(game, ponder); client.send(getPositionCommand(game)); client.send("go ponder"); } catch (Exception e) { } while (length < game.length()) game.unmakeMove(); } catch (Exception e) { writer.format("%s%n", e.getMessage()); } if (move != Game.NULL_MOVE) { writer.format( "My move is: %s%n", start.toAlgebraic(move) ); } return move; }
ac12e9ef-289d-4c08-90e6-8bbc0512d810
9
@Override public void task(int tId) { try { int nRow, nCol; int[][] mat; int[] vec; int[] product; File file; BufferedReader reader; PrintWriter printWriter; String line; String[] elements; //read the shared matrix file file = new File("fs/example/matrix.txt"); reader = new BufferedReader(new FileReader(file)); line = reader.readLine(); //the first line is dimension elements = line.split(" "); nRow = Integer.parseInt(elements[0]); nCol = Integer.parseInt(elements[1]); mat = new int[nRow][nCol]; for(int i=0; i<nRow; i++) { line = reader.readLine(); elements = line.split(" "); for(int j=0; j<nCol; j++) { mat[i][j] = Integer.parseInt(elements[j]); } } reader.close(); //read specific vector file based on task ID file = new File("fs/example/vector"+tId+".txt"); reader = new BufferedReader(new FileReader(file)); line = reader.readLine(); elements = line.split(" "); if(Integer.parseInt(elements[0]) != nCol || Integer.parseInt(elements[1]) != 1) throw new Exception("dimension error"); vec = new int[nCol]; for(int i=0; i<nCol; i++) { line = reader.readLine(); vec[i] = Integer.parseInt(line); } reader.close(); //calculate the produc product = new int[nRow]; for(int i=0; i<nRow; i++) { product[i] = 0; for(int j=0; j<nCol; j++) { product[i] += mat[i][j] * vec[j]; } } //write output file file = new File("fs/example/out"+tId+".txt"); printWriter = new PrintWriter(file); printWriter.println(nRow+" 1"); for(int i=0; i<nRow; i++) { printWriter.println(product[i]); } printWriter.close(); } catch(Exception e) { e.printStackTrace(); } }
8b7bdc3d-25f1-4710-a62b-46678e81f9ce
9
public void createBasis(double[][] A, double[] c, String[] I){ //Identifies how many artificial variables are needed //Finds an identity matrix in A //Indicates in which columns are the necessary columns to form a base B= new double[0][0]; int numArt=0; for (int i = 0; i < A.length; i++) { double[] Ii= new double[A.length]; Ii[i]=1; int pos=isColumn(Ii, A); if(pos==-1){ //Adds artificial variable String idAr="a"+numArt; nart++; numArt++; Ib=addToVector(idAr, Ib); //Depends on the initialization methodology if(true){ cb=addToVector(99999999, cb); } double[] column=Ii; if(B.length!=0){ B=addColumnToMatrix(column, B); } else{ B=new double[Ii.length][1]; for (int j = 0; j < Ii.length; j++) { B[j][0]=Ii[j]; } } if(Ub.length!=0){ Ub=addToVector(Double.MAX_VALUE, Ub); } else{ Ub= new double[1]; Ub[0]=Double.MAX_VALUE; } if(Lb.length!=0){ Lb=addToVector(0, Lb); } else{ Lb= new double[1]; Lb[0]=0; } } else{ String idAr=I[pos]; Ib=addToVector(idAr, Ib); if(B.length==0){ B=new double[Ii.length][1]; for (int j = 0; j < Ii.length; j++) { B[j][0]=Ii[j]; } } else{ B=addColumnToMatrix(Ii, B); } Ub=addToVector(U[pos], Ub); Lb=addToVector(L[pos], Lb); cb=addToVector(c[pos], cb); c=removeFromVector(pos, c); A=removeColumnFromMatrix(pos, A); I= removeFromVector(pos, I); U=removeFromVector(pos, U); L=removeFromVector(pos, L); } } cn=c; N=A; In=I; Un=U; Ln=L; setNBtoBounds(); }
1e22bb64-8129-44ad-9fd9-7e08ee2ea79c
3
public static String getSavePath(){ String os = System.getProperty("os.name").toUpperCase(); String path = null; String subFolder = "Operation5a"; if (os.contains("WIN")) path = System.getenv("APPDATA") + "/" + subFolder + "/"; else if (os.contains("MAC")) path = System.getProperty("user.home") + "/Library/Application Support/" + subFolder + "/"; else if (os.contains("NUX")){ path = System.getProperty("user.home") + "/" + subFolder + "/"; }else{ path = System.getProperty("user.dir") + "/" + subFolder + "/"; } File file = new File(path); file.mkdir(); return path; }
0df52e54-25ba-4b94-b2dd-fa043c4351cc
0
public static void main(String[] args) { new Enter("NetFlow"); }
15a80cac-c039-4c56-961b-a77c9b1223e6
3
public final static Opponent getByName(String name) throws NotFound { Opponent o = new Opponent(); o.setName(name); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("playerName", name)); try { JSONObject ob = Utils.getJSON("fights/searchCharacterJson/1", nvps); JSONArray arr = ob.getJSONArray("list"); for (int i = 0; i < arr.length(); i++) { JSONObject player = arr.getJSONObject(i); if (player.getString("name").equalsIgnoreCase(name)) { o.setAttack(player.getString("attack")); return o; } } } catch (JSONException e) { } throw new NotFound(); }
ff700a8c-e347-467e-9dae-495ba507027c
0
public void setEventDescription(String[] eventDescription) { this.eventDescription = eventDescription; }
fffabda2-d06c-4ddc-8ba8-e77f3599757c
4
private void jButton_passwordOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_passwordOKActionPerformed password = jPasswordField1.getPassword(); StringBuilder str1 = new StringBuilder(); for (int i = 0; i < password.length; i++) { str1.append(password[i]); } StringBuilder str = new StringBuilder(); char[] pwd2 = jPasswordField1.getPassword(); for (int i = 0; i < pwd2.length; i++) { str.append(pwd2[i]); } if (str.toString().equals(str1.toString())) { this.dispose(); }else{ count++; if(count == 3){ JOptionPane.showMessageDialog(null, "3 wrong password tries. Exiting......","Error",JOptionPane.ERROR_MESSAGE); System.exit(0); } JOptionPane.showMessageDialog(null, "Passwords dont match.","Error",JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jButton_passwordOKActionPerformed
f8fe5332-bee9-4d41-a74e-87312352dc9b
9
public ListNode addTwoNumbers(ListNode l1, ListNode l2) { if (l1 == null) { if (l2 == null) return null; return l2; } if (l2 == null) return l1; ListNode out = null; ListNode p1 = l1; ListNode p2 = l2; int carry = 0; ListNode idx = out; while (p1 != null || p2 != null) { int c1 = 0, c2 = 0; if (p1 != null) { c1 = p1.val; p1 = p1.next; } if (p2 != null) { c2 = p2.val; p2 = p2.next; } int t = c1 + c2 + carry; int v = t % 10; carry = t / 10; if (out == null) { out = new ListNode(v); idx = out; } else { ListNode cur = new ListNode(v); idx.next = cur; idx = cur; } } if (carry != 0) { ListNode cur = new ListNode(carry); idx.next = cur; } return out; }