method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
d9f630eb-cff5-452e-b7a7-e4d225172d1e
0
public void SetStartBusStop(int startBusStop) { //set the start bus stop this.startBustop = startBusStop; }
4405f8f0-4cbb-41cb-9424-ccd0516c2070
3
private InEdgeIteratorImpl(InternalNodeWrapper<N, E> to, ContextualReachability<N, E, ?> contextualReachability) { List<InternalNode<N, E>> reachableFromNodes = new ArrayList<InternalNode<N, E>>(); for (InternalNode<N, E> node : to.getReachableFrom()) { if (contextualReachability.isReachable(node)) { reachableFromNodes.add(node); } } reachableNodesIterator = reachableFromNodes.iterator(); }
d0d69374-2d56-4121-bb35-cf4f3a592bca
8
public svm_node[] getTemplatePixelsInSVMFormat(int x0, int y0, int x1, int y1) { int xDistance,yDistance; int startX,startY; int currentX,currentY; int Ox,Oy; double xRes,yRes; double offsetY; double scaleFactor; svm_node node; svm_node template[] = new svm_node[735]; /* template size is 21*35 samples */ /* distance between eyes on x and y axis */ xDistance = x1 - x0; yDistance = y1 - y0; /* distance between the eyes is 23 pixels from experiences * calculate the scale factor for each axis */ xRes = (double)xDistance / 23d; yRes = (double)yDistance / 23d; /* scale factor */ scaleFactor = Math.sqrt(Math.pow(xDistance, 2)+Math.pow(yDistance, 2)) / 23d; /* 6 from (35 -23)/2 and 8 because the eyes are on the 8 row from experiments */ Ox = x0 - (int)(6 * xRes) + (int)(8 * yRes); offsetY = (yDistance != 0) ? ((8 * yRes * xDistance) / yDistance) : (8 * scaleFactor); Oy = y0 -(int)offsetY; /* rotate the template to a horizontal position */ startX = Ox; startY = Oy; for (int y = 0; y < 21; y++) { currentX = startX; currentY = startY; for (int x = 0; x < 35; x++) { node = new svm_node(); node.index = y * 35 + x + 1; if ((currentX >= 0) && (currentX < width) && (currentY < height) && (currentY >= 0)) { /* convert data in svm format */ node.value = pixels[currentY * width + currentX] / 255d; } else { if (y == 0 ) { node.value = 128d/255d; } else { node.value = template[ (y - 1) * 35 + x].value; } } template[y * 35 + x] = node; currentX = startX + (int)((x + 1) * xRes); currentY = startY + (int)((x + 1) * yRes); } startX = Ox - (int)((y + 1) * yRes); startY = Oy + (int)((y + 1) * xRes); } return template; }
39c05989-629f-417b-bfef-646260cf8ebc
7
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Animal other = (Animal) obj; if (!Objects.equals(this.name, other.name)) { return false; } if (!Objects.equals(this.description, other.description)) { return false; } if (!Objects.equals(this.type, other.type)) { return false; } if (Double.doubleToLongBits(this.meat) != Double.doubleToLongBits(other.meat)) { return false; } if (Double.doubleToLongBits(this.hitpoints) != Double.doubleToLongBits(other.hitpoints)) { return false; } return true; }
c264d08a-b1f9-4c8e-aa36-7f9641bee584
8
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Machine other = (Machine) obj; if (IP == null) { if (other.IP != null) return false; } else if (!IP.equals(other.IP)) return false; if (id != other.id) return false; if (port != other.port) return false; return true; }
249e597e-6957-4b5a-a471-041e73d953a4
0
@Override public void initialize() throws Exception { this.buildTrain(); this.createPlanTickets(); }
4e43bc70-35cf-4185-964d-5cd7d8e78f23
0
public String getPath() { return this.key; }
c1c860d7-d7ee-4693-b222-89433e4405d7
5
public void actionPerformed(ActionEvent e) { String nick = GUIMain.userList.getSelectedValue().toString(); if (nick.startsWith("@")) { nick = nick.replace("@", ""); } else if (nick.startsWith("$")) { nick = nick.replace("$", ""); } else if (nick.startsWith("+")) { nick = nick.replace("+", ""); } else if (nick.startsWith("%")) { nick = nick.replace("%", ""); } else if (nick.startsWith("~")) { nick = nick.replace("~", ""); } Command.kick(nick); }
902a5fe6-919e-407e-a055-ec99182b9a05
7
public static void appendPoison(final Client c) { if (c.playerEquipment[c.playerShield] == 18340) { c.sendMessage("Your Anti-poison totem prevents you from being poisoned."); return; } if (System.currentTimeMillis() - c.lastPoisonSip > c.poisonImmune) { c.sendMessage("You have been poisoned."); c.isPoisoned = 1; c.updateRequired = true; c.appearanceUpdateRequired = true; c.poisonDamage = 70 + Misc.random(7); c.lastPoison = 3; final Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { public void run() { if (c.lastPoison == 0) { c.getCombat().appendHit(c, c.poisonDamage, 2, -1, false, 0); /*c.poisonMask = !c.getHitUpdateRequired() ? 1 : 2; c.handleHitMask(c.poisonDamage, 2, -1, 0, false); c.dealDamage(c.poisonDamage);*/ c.getPA().refreshSkill(3); c.poisonDamage--; } c.lastPoison = c.lastPoison == 0 ? 18 : c.lastPoison - 1; if (c.poisonDamage == 0 && c.isDead == false) { c.sendMessage("The poison has worn off."); timer.cancel(); c.updateRequired = true; c.appearanceUpdateRequired = true; c.isPoisoned = 0; } if (c.isDead == true) { c.poisonDamage = 0; c.isPoisoned = 0; timer.cancel(); } } }, 0, 1000); } }
ef1dae1c-a1da-49dd-a67d-56a34b4797c6
6
@Override public void ParseIn(Connection Main, Server Environment) { Environment.InitPacket(451, Main.ClientMessage); Environment.Append(0, Main.ClientMessage); Environment.Append(Integer.toString(4), Main.ClientMessage); List<Room> roomList = new ArrayList<Room>(); for(int FriendId : Main.Data.Friends) { Player pClient = Environment.ClientManager.GetClient(FriendId); if(pClient == null) continue; if((pClient.Flags & Server.plrOnline) == Server.plrOnline) // Is Online? { Room Room = Environment.RoomManager.GetRoom(pClient.CurrentRoom); if (Room == null) continue; roomList.add(Room); } } Environment.Append(roomList.size(), Main.ClientMessage); for(Room Room : roomList) { if(Room!=null) { Room.Serialize(Main.ClientMessage); } } Environment.Append(false, Main.ClientMessage); Environment.EndPacket(Main.Socket, Main.ClientMessage); }
f16d7f84-902b-42ed-abec-022d909a73d6
2
public void visitFieldExpr(final FieldExpr expr) { if (expr.object() != null) { expr.object().visit(this); } print("."); if (expr.field() != null) { print(expr.field().nameAndType().name()); } }
50112daf-d3d1-4df3-84c5-0f1681c82fb1
0
public void setBAsString(String b) { this.b = b; }
4485e812-a13a-4b40-a573-eaacbe55e3fc
7
public synchronized DataInputStream getChunkDataInputStream(int x, int z) { if (outOfBounds(x, z)) { debugln("READ", x, z, "out of bounds"); return null; } try { int offset = getOffset(x, z); if (offset == 0) { // debugln("READ", x, z, "miss"); return null; } int sectorNumber = offset >> 8; int numSectors = offset & 0xFF; if (sectorNumber + numSectors > sectorFree.size()) { debugln("READ", x, z, "invalid sector"); return null; } file.seek(sectorNumber * SECTOR_BYTES); int length = file.readInt(); if (length > SECTOR_BYTES * numSectors) { debugln("READ", x, z, "invalid length: " + length + " > 4096 * " + numSectors); return null; } byte version = file.readByte(); if (version == VERSION_GZIP) { byte[] data = new byte[length - 1]; file.read(data); DataInputStream ret = new DataInputStream(new BufferedInputStream(new GZIPInputStream(new ByteArrayInputStream(data)))); // debug("READ", x, z, " = found"); return ret; } else if (version == VERSION_DEFLATE) { byte[] data = new byte[length - 1]; file.read(data); DataInputStream ret = new DataInputStream(new BufferedInputStream(new InflaterInputStream(new ByteArrayInputStream(data)))); // debug("READ", x, z, " = found"); return ret; } debugln("READ", x, z, "unknown version " + version); return null; } catch (IOException e) { debugln("READ", x, z, "exception"); return null; } }
2e5a1774-f4a4-42da-8544-7c69b415fecb
1
public static LogFileInfo getLogFileInfo(HierarchicalConfiguration logFileData) { LogFileInfo logFileInfo = null; if (logFileData != null) { logFileInfo = new LogFileInfo(); logFileInfo.setRunId(logFileData.getLong(RUNID_TAG)); logFileInfo.setType(logFileData.getString(TYPE_TAG)); logFileInfo.setFileName(logFileData.getString(NAME_TAG)); logFileInfo.setFilePath(logFileData.getString(FILEPATH_TAG)); } return logFileInfo; }
ad1b03ba-ff46-4a53-962d-ed8d725edbca
6
@Override public boolean add(EmpleadoDTO em) { boolean valor = false; try { em.setId_usuario(getMaxidUsuario()+1); em.setActivo(true); em.setTiene_foto(true); conn = PaginaWebConnectionFactory.getInstance().getConnection(); String sql = "insert into usuario values(?,?,?,?,?,?,?,?,?,?)"; ps = conn.prepareStatement(sql); ps.setInt(1, em.getId_usuario()); ps.setString(2, em.getNom_usuario()); ps.setString(3, em.getPat_usuario()); ps.setString(4, em.getMat_usuario()); ps.setString(5, em.getArea()); ps.setString(6, em.getFecha_nacimiento()); ps.setString(7, em.getLogin()); ps.setBoolean(8, em.isActivo()); ps.setString(9, em.getCumple()); ps.setBoolean(10, em.isTiene_foto()); if (ps.executeUpdate() > 0){ valor = true; } } catch (SQLException e1) { e1.printStackTrace(); }finally{ try { if (conn != null) conn.close(); if (ps != null) ps.close(); if (rs != null) rs.close(); } catch (SQLException e) { e.printStackTrace(); } } return valor; }
0b1cb9c9-0fc7-4d03-b125-2b4b84ff9243
4
private static int loadTexture(String fileName) { String[] splitArray = fileName.split("\\."); String ext = splitArray[splitArray.length - 1]; try { BufferedImage image = ImageIO.read(new File("./res/textures/" + fileName)); boolean hasAlpha = image.getColorModel().hasAlpha(); int[] pixels = image.getRGB(0, 0, image.getWidth(), image.getHeight(), null, 0, image.getWidth()); ByteBuffer buffer = Util.createByteBuffer(image.getWidth() * image.getHeight() * 4); for (int y = 0; y < image.getHeight(); y++) { for (int x = 0; x < image.getWidth(); x++) { int pixel = pixels[y * image.getWidth() + x]; buffer.put((byte) ((pixel >> 16) & 0xFF)); buffer.put((byte) ((pixel >> 8) & 0xFF)); buffer.put((byte) ((pixel >> 0) & 0xFF)); if (hasAlpha) buffer.put((byte) ((pixel >> 24) & 0xFF)); else buffer.put((byte) (0xFF)); } } buffer.flip(); int texture = glGenTextures(); glBindTexture(GL_TEXTURE_2D, texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, image.getWidth(), image.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer); return texture; } catch(Exception e) { e.printStackTrace(); System.exit(1); } return 0; }
e791b1c1-179c-43d5-a3b3-2ab3bc138a4d
9
public static void divide(double basePercentage, int repetitions) { // The percentage of the training set has to be between 0 and 1 if (0 > basePercentage || basePercentage > 1) { System.err.println("The percentage of the training set has to be between 0 and 1."); return; } for (int i = 1; i <= repetitions; i++) { File baseFile = new File( "/Users/matthiasfelix/git/RecommenderSystem/RecommenderSystem/" + dataSet + basePercentage + "_set" + i + ".base"); File testFile = new File( "/Users/matthiasfelix/git/RecommenderSystem/RecommenderSystem/" + dataSet + basePercentage + "_set" + i + ".test"); FileWriter baseFileWriter; FileWriter testFileWriter; try { baseFileWriter = new FileWriter(baseFile); testFileWriter = new FileWriter(testFile); BufferedWriter baseBufferedWriter = new BufferedWriter(baseFileWriter); BufferedWriter testBufferedWriter = new BufferedWriter(testFileWriter); for (Integer user : userItemRatings.keySet()) { int N = userItemRatings.get(user).size(); int baseMax = Math.round((float) (N * basePercentage)); int testMax = N - baseMax; int baseSize = 0, testSize = 0; for (Map.Entry<Integer, Double> entry : userItemRatings.get(user).entrySet()) { String line = user + "\t" + entry.getKey() + "\t" + entry.getValue(); if (baseSize == baseMax) { testBufferedWriter.write(line + "\n"); } else if (testSize == testMax) { baseBufferedWriter.write(line + "\n"); } else { Random rnd = new Random(); if (rnd.nextDouble() < basePercentage) { baseBufferedWriter.write(line + "\n"); baseSize++; } else { testBufferedWriter.write(line + "\n"); testSize++; } } } } baseBufferedWriter.close(); testBufferedWriter.close(); } catch (IOException e) { e.printStackTrace(); } } }
902fd2ae-4398-476c-a50a-99c42027a724
3
@Override public boolean retainAll( final Collection<?> os ) { boolean result = false; final Iterator<T> iter = iterator(); while( iter.hasNext() ) { if( !os.contains( iter.next() ) ) { iter.remove(); result = true; } } return result; }
8906dec6-28b4-4277-866f-1f460319e83e
0
public int getS2() { return this.state2; }
15a9dddb-d662-4978-8cbb-6a7955be2f18
3
@Override public Class getColumnClass(int column) { Class returnValue; if ((column >= 0) && (column < getColumnCount())) { if (getValueAt(0, column) == null) { return String.class; } returnValue = getValueAt(0, column).getClass(); } else { returnValue = Object.class; } return returnValue; }
5a34e9e1-b6ed-4af7-848a-fce0a71ee55e
3
private void calculateEnabledState(JoeTree tree) { Document doc = tree.getDocument(); if (doc == Outliner.documents.getMostRecentDocumentTouched()) { Node node = tree.getEditingNode(); if (tree.getComponentFocus() == OutlineLayoutManager.ICON && tree.getNumberOfSelectedNodes() >= 2) { setEnabled(true); } else { setEnabled(false); } } }
ccc6a104-8a8a-449a-b849-0465acd70e66
7
private void parseZip(String s) { String x = s.trim(), zip = ""; int start = -2; int slut = 0; for (int i = 0; i < s.length(); i++) { if (Character.isDigit(s.charAt(i))) { //if current char is digit if (start == -2) { start = i; } slut = i; if (i+1 < s.length() && !Character.isDigit(s.charAt(i + 1))) { //if next char is not a digit slut = i + 1; break; } } } if ((slut + start) >= 0) { //if zip zip = x.substring(start, slut+1); address[3] = zip.trim(); x = x.substring(slut).trim(); } // at the end we set address[4] to either Sweden (in the case that zip = 0) else we find it using the postal. address[4] = Controller.getInstance().getPostal().get(address[3]); if(address[4] == null) address[4] = "Sweden"; }
658bcfb7-d3d3-4a9d-81de-26d39255a9f5
3
private int processCommentSymbol(final OutStream outStream, final Character currentChar) throws StreamException { outStream.writeSymbol(currentChar); switch (currentChar) { case '"': return MODE_STRING; case '\'': return MODE_CHAR; case '\\': return MODE_BACKSLASH; default: return MODE_REGULAR; } }
8caf485a-f86e-4af4-93ed-39eb9e3e7ce9
6
public void updateRight(){ if(right > 0){ for(int i=top; i<height+top; i++){ for(int j=originalWidth; j<originalWidth+right; j++){ drawDiamond(j, i); } } } else if(right < 0){ for(int i=top; i<height+top; i++){ for(int j=originalWidth-1; j>originalWidth+right-1; j--){ drawDiamond(j, i); } } } }
16f3b339-2b4c-42a9-9f20-dee98b97553a
6
int possibleMovesNum(Point[] grid, Pair pr) { int possible = 0; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { Point currentPoint = pointAtGridIndex(grid, i, j); if (currentPoint.value == 0) { continue; } for (Pair d : directionsForPair(pr)) { if (isValidBoardIndex(i + d.p, j + d.q)){ Point possiblePairing = pointAtGridIndex(grid, i + d.p, j + d.q); if (currentPoint.value == possiblePairing.value) { possible = possible + 2; } } } } } return possible; }
c9966214-733a-4335-86d6-0f237b4f46c9
3
public byte[] toByteArray() throws PacketEncodingException { ByteBuffer buffer = ByteBuffer.allocate(HEADER_SIZE + (message == null ? 0 : message.length())); buffer.putInt(protocolId); buffer.put(Packet.encodeConnectionId(connectionId)); buffer.putShort(Packet.encodeSequenceNumber(sequenceNumber)); buffer.putShort(Packet.encodeSequenceNumber(duplicateSequenceNumber)); buffer.putShort(Packet.encodeSequenceNumber(lastReceivedSequenceNumber)); buffer.putInt(receivedPacketHistory); buffer.put((isImmediateResponse ? Byte.MIN_VALUE : 0)); buffer.put(Packet.encodeMessageType(messageType)); if(message != null) buffer.put(message.getBytes()); return buffer.array(); }
050393c3-f24e-4c41-99c8-99bf6160ceb3
7
@Override public void endElement(String uri, String localName, String qName) throws SAXException { if (qName.equals("rowset") && !stack.isEmpty()) { EveAsset<EveAsset<?>> asset = stack.pop(); if (stack.isEmpty()) { response.add(asset); currentAsset = null; } } if (qName.equals("row") && stack.isEmpty() && currentAsset != null) { response.add(currentAsset); currentAsset = null; } super.endElement(uri, localName, qName); }
a752587c-2907-458e-ad54-878671c938bf
7
@Override public Object stringToValue(String text) throws ParseException { if ("".equals(text)) { getFormattedTextField().setBackground(Color.white); return null; } Object retVal = null; try { retVal = super.stringToValue(text); try { Double.parseDouble(text); if (!text.contains("f") && !text.contains("F") && !text.contains("d") && !text.contains("D")) { getFormattedTextField().setBackground(Color.white); } else { throw new NumberFormatException(); } } catch(NumberFormatException exe){ getFormattedTextField().setBackground(Color.red); } } catch(ParseException ex){ getFormattedTextField().setBackground(Color.red); throw ex; } return retVal; }
f2e20eb0-ae5f-4b3b-98ba-d9d8605c5332
0
public String getDay() { return day; }
908856e7-70f2-4e94-9e0b-58b29a7053b7
6
private int location(Value v, int position) throws Exception { if(isSpilled(v) || v.getColor() == -2) { int target = position == 1 ? t1 : t2; // if this is a special spill case if(v.getColor() < 0) { if(v instanceof Fetch) { int address = getFetchAddress((Fetch)v); emit(DLX.assemble(DLX.LDW, target, fp, address)); } else if (v instanceof Temporary) { return t2; } else { throw new Exception("No case to handle special spill"); } } else { int address = getSpillAddress(v); emit(DLX.assemble(DLX.LDW, target, fp, address)); } return target; } int reg = minAvail + v.getColor(); return reg; }
dfb588a0-cb01-4c37-9e4f-9d157a70bd81
0
public static void remove(Object object) { getController().rootPane.getChildren().remove(object); }
545c6825-5744-4b3a-80d8-cc8e27ab6944
9
public ValidationErrorList validate(){ Person person = doctor.getPerson(); ValidationErrorList errorList = new ValidationErrorList(); Validator instance = ESAPI.validator(); DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); if ( (instance.getValidInput("username", userAccount.getUsername(), "Name", 255, false, errorList) == null ) || (instance.getValidInput("password", userAccount.getPassword(), "Name", 255, false, errorList) == null ) || (instance.getValidInput("FirstName", person.getFirstName(), "Name", 255, false, errorList) == null ) || (instance.getValidInput("LastName", person.getLastName(), "Name", 255, false, errorList) == null ) || (instance.getValidInput("EmailID", person.getEmailId(), "Email", 255, false, errorList) == null ) || (instance.getValidInput("Address", person.getAddress(), "Address", 255, false, errorList) == null ) || (instance.getValidInput("Phone", person.getPhone(), "Phone", 15, false, errorList) == null ) || (instance.getValidInput("SSN", person.getSsn(), "Name", 15, false, errorList) == null ) || (instance.getValidDate("Dob", df.format(person.getDob()), DateFormat.getDateInstance(DateFormat.SHORT, Locale.US), false, errorList) == null) ) { logger.info("Doctor Validation Failed"); } return errorList; }
b415426e-8428-4e22-8f5c-389cd54990da
2
public List<MapName> getMapNameById(String lang, String id) { List<MapName> mapNames = new ArrayList<MapName>(); List<MapName> result = new ArrayList<MapName>(); mapNames = sendRequest(lang); for(MapName mapName : mapNames) { if(mapName.getId().equals(id)) { result.add(mapName); } } return result; }
91aa455f-40dd-431d-aaf6-64338ddc61b2
4
private void notifyListeners() { for (int j = 0; j < keys.length; j++) { if (keys[j].gotPressed()) { for (int i = 0; i < listeners.size(); i++) { if(!newListeners.contains(listeners.get(i))) { listeners.get(i).actionPerformed( new InputEvent(keys[j], InputEventType.PRESSED)); } else { newListeners.remove(listeners.get(i)); } } } } }
0ef4d9b5-6226-4178-81bd-e8a34ab7d250
0
public byte[] getBuf() { return buf; }
4bc3ec6b-0219-42e0-860a-99e1bfd25748
4
@Override public void deserialize(Buffer buf) { experienceCharacter = buf.readDouble(); if (experienceCharacter < 0) throw new RuntimeException("Forbidden value on experienceCharacter = " + experienceCharacter + ", it doesn't respect the following condition : experienceCharacter < 0"); experienceMount = buf.readDouble(); if (experienceMount < 0) throw new RuntimeException("Forbidden value on experienceMount = " + experienceMount + ", it doesn't respect the following condition : experienceMount < 0"); experienceGuild = buf.readDouble(); if (experienceGuild < 0) throw new RuntimeException("Forbidden value on experienceGuild = " + experienceGuild + ", it doesn't respect the following condition : experienceGuild < 0"); experienceIncarnation = buf.readDouble(); if (experienceIncarnation < 0) throw new RuntimeException("Forbidden value on experienceIncarnation = " + experienceIncarnation + ", it doesn't respect the following condition : experienceIncarnation < 0"); }
6221c10d-7738-4655-bcd2-399e60d5247f
2
@Override public boolean propertyIsDefault(String key) { if (propertyDefaultExists(key) && propertyExists(key)) { return propertyEquals(key, getPropertyDefault(key)); } else { return false; } }
b2b0c9c4-1347-40b3-ae21-bd23a4331113
6
private final String beginMultiLineCommentFilter( String line ) { //assert !inJavadocComment; //assert !inMultiLineComment; if ( line == null || line.equals( "" ) ) { return ""; } int index; //check to see if a multi-line comment starts on this line: if ( ( index = line.indexOf( "/*" ) ) > -1 && !isInsideString( line, index ) ) { String fromIndex = line.substring( index ); if ( fromIndex.startsWith( "/**" ) && !( fromIndex.startsWith( "/**/" ) ) ) { inJavadocComment = true; } else { inMultiLineComment = true; } //Return result of other filters + everything after the start //of the multiline comment. We need to pass the through the //to the ongoing multiLineComment filter again in case the comment //ends on the same line. return new StringBuilder( stringFilter( line.substring( 0, index ) ) ).append( ongoingMultiLineCommentFilter( fromIndex ) ).toString(); } //Otherwise, no useful multi-line comment information was found so //pass the line down to the next filter for processesing. else { return stringFilter( line ); } }
ce058681-e211-4d28-b5b7-1bc0662c929c
3
public void fusionWithMultiplyFullAlpha(CPLayer fusion, CPRect rc) { CPRect rect = new CPRect(0, 0, width, height); rect.clip(rc); for (int j = rect.top; j < rect.bottom; j++) { int off = rect.left + j * width; for (int i = rect.left; i < rect.right; i++, off++) { int color1 = data[off]; int alpha1 = (color1 >>> 24) * alpha / 100; int color2 = fusion.data[off]; int alpha2 = (color2 >>> 24) * fusion.alpha / 100; int newAlpha = alpha1 + alpha2 - alpha1 * alpha2 / 255; if (newAlpha > 0) { int alpha12 = alpha1 * alpha2 / 255; int alpha1n2 = alpha1 * (alpha2 ^ 0xff) / 255; int alphan12 = (alpha1 ^ 0xff) * alpha2 / 255; fusion.data[off] = newAlpha << 24 | (((color1 >>> 16 & 0xff) * alpha1n2) + ((color2 >>> 16 & 0xff) * alphan12) + (color1 >>> 16 & 0xff) * (color2 >>> 16 & 0xff) * alpha12 / 255) / newAlpha << 16 | (((color1 >>> 8 & 0xff) * alpha1n2) + ((color2 >>> 8 & 0xff) * alphan12) + (color1 >>> 8 & 0xff) * (color2 >>> 8 & 0xff) * alpha12 / 255) / newAlpha << 8 | (((color1 & 0xff) * alpha1n2) + ((color2 & 0xff) * alphan12) + (color1 & 0xff) * (color2 & 0xff) * alpha12 / 255) / newAlpha; } } } fusion.alpha = 100; }
3b175d30-a184-45f3-af9c-b98e81c38dd3
0
public ArrayList<String> getWorkPosition() { return WorkPosition; }
e85e256e-6af9-4cc6-a4cb-6486d0e2ad0e
4
@Override public void deserialize(Buffer buf) { super.deserialize(buf); objectGID = buf.readShort(); if (objectGID < 0) throw new RuntimeException("Forbidden value on objectGID = " + objectGID + ", it doesn't respect the following condition : objectGID < 0"); powerRate = buf.readShort(); overMax = buf.readBoolean(); int limit = buf.readUShort(); effects = new ObjectEffect[limit]; for (int i = 0; i < limit; i++) { effects[i] = ProtocolTypeManager.getInstance().build(buf.readShort()); effects[i].deserialize(buf); } objectUID = buf.readInt(); if (objectUID < 0) throw new RuntimeException("Forbidden value on objectUID = " + objectUID + ", it doesn't respect the following condition : objectUID < 0"); quantity = buf.readInt(); if (quantity < 0) throw new RuntimeException("Forbidden value on quantity = " + quantity + ", it doesn't respect the following condition : quantity < 0"); }
12e575fa-3951-45a9-823b-e87272658219
8
@Override public void handleMessage(Message msg) { String uri = (String) msg.obj; if (mLoadingManager.isOutdated(uri)) return; switch (msg.what) { case ACTION_ON_START: { Set<ResourceSpecs<T>> set = mLoadingManager.getSpecsList(uri); if (set == null) break; for (ResourceSpecs<T> specs : set) specs.onStart(); break; } case ACTION_ON_LOADED_FROM_MEMORY: case ACTION_ON_LOADED_FROM_DISK: case ACTION_ON_LOADED: { boolean fromMemory = (msg.what == ACTION_ON_LOADED_FROM_MEMORY); boolean fromDisk = (msg.what == ACTION_ON_LOADED_FROM_DISK); T res = mLoadingManager.getResult(uri); Set<ResourceSpecs<T>> set = mLoadingManager.remove(uri); for (ResourceSpecs<T> specs : set) specs.onLoaded(res, fromMemory, fromDisk); break; } } }
59c80e62-cef7-4652-9b81-efab88ce3ad3
7
public static HashMap<String,Integer> getEffectStats(HashSet<Integer> infPpl, HashSet<Integer> closedLocs) { HashMap<String,Integer> stats = new HashMap<String,Integer>(); int affCount = 0; int infConCount = 0; int totalConCount = 0; try { Connection con = dbConnect(); PreparedStatement getNumLocCon = con.prepareStatement( "SELECT contactCount,aggregatePop FROM "+locTbl+" WHERE locationID = ?"); PreparedStatement getNumPplLocCon = con.prepareStatement( "SELECT locationID FROM "+conTbl+" WHERE person1ID = ?"); Iterator<Integer> locs = closedLocs.iterator(); while (locs.hasNext()) { Integer loc = locs.next(); getNumLocCon.setInt(1, loc.intValue()); ResultSet getNumLocConQ = getNumLocCon.executeQuery(); if (getNumLocConQ.first()) { affCount += getNumLocConQ.getInt("aggregatePop"); totalConCount += getNumLocConQ.getInt("contactCount"); } else { System.out.println("Could not get stats on location:\t"+loc); } } Iterator<Integer> ppl = infPpl.iterator(); while (ppl.hasNext()) { HashMap<Integer,Integer> cons = new HashMap<Integer,Integer>(); Integer p = ppl.next(); getNumPplLocCon.setInt(1,p.intValue()); ResultSet getNumPplLocConQ = getNumPplLocCon.executeQuery(); while (getNumPplLocConQ.next()) { Integer loc = getNumPplLocConQ.getInt("locationID"); EpiSimUtil.incMapValue(cons, loc, 1); } locs = cons.keySet().iterator(); while (locs.hasNext()) { Integer loc = locs.next(); if (closedLocs.contains(loc)) infConCount += cons.get(loc).intValue(); } } con.close(); } catch (Exception e) { System.out.println(e); } stats.put("AFFECTED", new Integer(affCount)); stats.put("INF_CON", new Integer(infConCount)); stats.put("TOT_CON", new Integer(totalConCount)); return stats; }
c5fce383-f3fb-4d57-8b0b-55a46f43deda
9
public int compareTo( Object obj ) { if( obj == null ) { return( -1 ); } else if( obj instanceof GenKbGelCounterBuff ) { GenKbGelCounterBuff rhs = (GenKbGelCounterBuff)obj; int retval = super.compareTo( rhs ); if( retval != 0 ) { return( retval ); } { int cmp = getRequiredCounterName().compareTo( rhs.getRequiredCounterName() ); if( cmp != 0 ) { return( cmp ); } } return( 0 ); } else if( obj instanceof GenKbGelInstructionPKey ) { GenKbGelInstructionPKey rhs = (GenKbGelInstructionPKey)obj; if( getRequiredCartridgeId() < rhs.getRequiredCartridgeId() ) { return( -1 ); } else if( getRequiredCartridgeId() > rhs.getRequiredCartridgeId() ) { return( 1 ); } if( getRequiredGelInstId() < rhs.getRequiredGelInstId() ) { return( -1 ); } else if( getRequiredGelInstId() > rhs.getRequiredGelInstId() ) { return( 1 ); } return( 0 ); } else { int retval = super.compareTo( obj ); return( retval ); } }
b60308ba-7e18-49b5-beb6-412c9f8b2c12
6
protected static byte[] mintName(int ver, String node, String ns) throws UUIDException { /* * Generates a Version 3 or Version 5 UUID. These are derived from a * hash of a name and its namespace, in binary form. */ if (node.length() == 0) throw new UUIDException( "A name-string is required for Version 3 or 5 UUIDs."); // if the namespace UUID isn't binary, make it so byte[] binNs = makeBin(ns, 16); int version = 0; byte[] uuid = null; if (binNs == null) throw new UUIDException( "A binary namespace is required for Version 3 or 5 UUIDs."); switch (ver) { case MD5: version = version3; try { uuid = hash(new String(binNs, "ISO-8859-1") + node, "md5"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } break; case SHA1: version = version5; try { byte[] hashed = hash(new String(binNs, "ISO-8859-1") + node, "sha1"); uuid = new byte[16]; System.arraycopy(hashed, 0, uuid, 0, 16); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } break; } // set variant uuid[8] = (byte) (uuid[8] & clearVar | varRFC); // set version uuid[6] = (byte) (uuid[6] & clearVer | version); return (uuid); }
6caa28f7-0b6e-4919-a1f3-9b94795f63cd
4
public void clearMap(GameAction gameAction) { for (int i=0; i<keyActions.length; i++) { if (keyActions[i] == gameAction) { keyActions[i] = null; } } for (int i=0; i<mouseActions.length; i++) { if (mouseActions[i] == gameAction) { mouseActions[i] = null; } } gameAction.reset(); }
45c96160-3fda-4e3e-be18-148863f14558
1
private boolean jj_3_73() { if (jj_scan_token(AND)) return true; return false; }
349ef64f-029a-4fae-b20c-68c733e0cc70
2
protected String getMutatorName(Method m) { String name = m.getName(); if (name.startsWith("get")) { return "set" + name.substring(3); } else if (name.startsWith("is")) { return "set" + name.substring(2); } else { return null;// not valid, should not happen } }
19b9d48f-c2a7-46a6-bff8-920cc9c69b1e
5
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Telefone other = (Telefone) obj; if (this.id != other.id) { return false; } if (this.ddd != other.ddd) { return false; } if (this.numero != other.numero) { return false; } return true; }
14803b85-146f-48e8-a098-515f9b676c3a
2
@Override public boolean isOutOfBounds(final char character){ return character != NONE && (character < HangulJamo.MIN_VALUE || HangulJamo.MAX_VALUE < character); }
3a0717b0-c8fa-469e-b812-7f9b2e392dc0
1
private void readClassInfo(final DataInputStream in) throws IOException { thisClass = in.readUnsignedShort(); superClass = in.readUnsignedShort(); final int numInterfaces = in.readUnsignedShort(); interfaces = new int[numInterfaces]; for (int i = 0; i < numInterfaces; i++) { interfaces[i] = in.readUnsignedShort(); } }
5ca49658-0521-4005-a0fa-91a9bd8b0c2f
5
public Zone getZoneWithCardId(int id) throws NoZoneOpenException { int c; for(c = 0; c < 5; c++) { if(!this.monsterzones[c].isOpen()) { if(this.monsterzones[c].card.id == id) { return this.monsterzones[c]; } } else if(!this.magiczones[c].isOpen()) { if(this.magiczones[c].card.id == id) { return this.magiczones[c]; } } } throw new NoZoneOpenException(); }
8cb0ff4b-1f63-455c-ba86-041279615614
9
public static Point2D coordinates(final Rectangle2D rectangle, final RectangleAnchor anchor) { Point2D result = new Point2D.Double(); if (anchor == RectangleAnchor.CENTER) { result.setLocation(rectangle.getCenterX(), rectangle.getCenterY()); } else if (anchor == RectangleAnchor.TOP) { result.setLocation(rectangle.getCenterX(), rectangle.getMinY()); } else if (anchor == RectangleAnchor.BOTTOM) { result.setLocation(rectangle.getCenterX(), rectangle.getMaxY()); } else if (anchor == RectangleAnchor.LEFT) { result.setLocation(rectangle.getMinX(), rectangle.getCenterY()); } else if (anchor == RectangleAnchor.RIGHT) { result.setLocation(rectangle.getMaxX(), rectangle.getCenterY()); } else if (anchor == RectangleAnchor.TOP_LEFT) { result.setLocation(rectangle.getMinX(), rectangle.getMinY()); } else if (anchor == RectangleAnchor.TOP_RIGHT) { result.setLocation(rectangle.getMaxX(), rectangle.getMinY()); } else if (anchor == RectangleAnchor.BOTTOM_LEFT) { result.setLocation(rectangle.getMinX(), rectangle.getMaxY()); } else if (anchor == RectangleAnchor.BOTTOM_RIGHT) { result.setLocation(rectangle.getMaxX(), rectangle.getMaxY()); } return result; }
1e96501a-b97f-4f79-b1a6-c1c46164a2da
2
@Override public List<Direction> load(Criteria criteria, GenericLoadQuery loadGeneric, Connection conn) throws DaoQueryException { int pageSize = 50; List paramList = new ArrayList<>(); StringBuilder sb = new StringBuilder(WHERE); String queryStr = new QueryMapper() { @Override public String mapQuery() { Appender.append(DAO_ID_DIRECTION, DB_DIRECTION_ID_DIRECTION, criteria, paramList, sb, AND); Appender.append(DAO_ID_TOURTYPE, DB_DIRECTION_ID_TOURTYPE, criteria, paramList, sb, AND); Appender.append(DAO_ID_TRANSMODE, DB_DIRECTION_ID_TRANSMODE, criteria, paramList, sb, AND); Appender.append(DAO_DIRECTION_NAME, DB_DIRECTION_NAME, criteria, paramList, sb, AND); Appender.append(DAO_DIRECTION_STATUS, DB_DIRECTION_STATUS, criteria, paramList, sb, AND); Appender.append(DAO_DIRECTION_PICTURE, DB_DIRECTION_PICTURE, criteria, paramList, sb, AND); Appender.append(DAO_ID_DESCRIPTION, DB_DIRECTION_ID_DESCRIPTION, criteria, paramList, sb, AND); Appender.append(DAO_DIRECTION_TEXT, DB_DIRECTION_TEXT, criteria, paramList, sb, AND); if (paramList.isEmpty()) { return LOAD_QUERY; } else { return sb.insert(0, LOAD_QUERY).toString(); } } }.mapQuery(); try { return loadGeneric.sendQuery(queryStr, paramList.toArray(), pageSize, conn, (ResultSet rs, int rowNum) -> { Direction bean = new Direction(); bean.setIdDirection(rs.getInt(DB_DIRECTION_ID_DIRECTION)); bean.setName(rs.getString(DB_DIRECTION_NAME)); bean.setStatus(rs.getShort(DB_DIRECTION_STATUS)); bean.setPicture(rs.getString(DB_DIRECTION_PICTURE)); bean.setText(rs.getString(DB_DIRECTION_TEXT)); bean.setTransMode(new TransMode(rs.getInt(DB_DIRECTION_ID_TRANSMODE))); bean.setTourType(new TourType(rs.getInt(DB_DIRECTION_ID_TOURTYPE))); bean.setDescription(new Description(rs.getInt(DB_DIRECTION_ID_DESCRIPTION))); return bean; }); } catch (DaoException ex) { throw new DaoQueryException(ERR_DIRECTION_LOAD, ex); } }
78957f5a-32f2-4473-8dbc-b29ed8ef060e
0
public void setGivenBy(String givenBy) { this.givenBy = givenBy; }
45aa369f-c551-4cb1-97af-14048bd51ad2
0
private void initProgressBar(){ progressBar = new JProgressBar(); progressBar.setIndeterminate(true); progressBar.setBounds(INDENT_LEFT, getHeight()-50, getWidth()-INDENT_LEFT*2,20); progressBar.setVisible(true); add(progressBar); }
649f183b-d07c-4709-b618-e03537035382
6
public void update(int delta){ speedCounter += delta; if(speedCounter >= speed){ speedCounter = 0; } for(int i=0;i<entities.size();i++){ Entity e = entities.get(i); if(e instanceof Creature){ Creature c = (Creature)e; c.ai.update(delta); if(speedCounter == 0){ c.canAct = true; } if(c.health <= 0){ c.health = 0; kill(c); entities.remove(e); } updateInfoCounters(c,delta); if(c.canAct){ c.ai.move(this); //c.canAct = false; } } } }
9ad940e5-fe14-4aad-bad8-4f63bc294841
3
public void run() { try { if (MTServer.available.tryAcquire()){ PrintStream out = new PrintStream(clientSocket.getOutputStream(), true); Scanner in = new Scanner(clientSocket.getInputStream()); if (in.hasNextLine()){ out.println(in.nextLine().toUpperCase()); } in.close(); out.close(); clientSocket.close(); MTServer.available.release(); } }catch (IOException e) { e.printStackTrace(); } }
57870fc4-e20c-4510-ad78-9a6c4eb789f2
9
public static void handleExamine(final Player player, InputStream stream) { int npcIndex = stream.readUnsignedShort128(); boolean forceRun = stream.read128Byte() == 1; if(forceRun) player.setRun(forceRun); final NPC npc = World.getNPCs().get(npcIndex); if (npc == null || npc.hasFinished() || !player.getMapRegionsIds().contains(npc.getRegionId())) return; if (player.getRights() > 1) { player.getPackets().sendGameMessage( "NPC - [id=" + npc.getId() + ", loc=[" + npc.getX() + ", " + npc.getY() + ", " + npc.getPlane() + "]]."); } player.getPackets().sendNPCMessage(0, npc, "It's a " + npc.getDefinitions().name + "."); if(player.isSpawnsMode()) { try { if(NPCSpawns.removeSpawn(npc)) { player.getPackets().sendGameMessage("Removed spawn!"); return; } } catch (Throwable e) { e.printStackTrace(); } player.getPackets().sendGameMessage("Failed removing spawn!"); } if (Settings.DEBUG) Logger.log("NPCHandler", "examined npc: " + npcIndex+", "+npc.getId()); }
df10ef56-c8b8-400d-a9d9-b87090fa5d59
0
public void setCp(String cp) { this.cp = cp; }
256e2733-8f57-4f23-94b6-9806601ae432
4
private int method177(int arg0, int arg1, int arg3) { if (arg3 > 179) { arg1 /= 2; } if (arg3 > 192) { arg1 /= 2; } if (arg3 > 217) { arg1 /= 2; } if (arg3 > 243) { arg1 /= 2; } return (arg0 / 4 << 10) + (arg1 / 32 << 7) + arg3 / 2; }
82d6877d-6f04-4111-82e1-a32368576e32
8
private void setElementField(String str1, String str2, double x) { if (!(model instanceof MolecularModel)) return; MolecularModel m = (MolecularModel) model; int lb = str1.indexOf("["); int rb = str1.indexOf("]"); double z = parseMathExpression(str1.substring(lb + 1, rb)); if (Double.isNaN(z)) return; int i = (int) Math.round(z); if (i >= Element.NMAX || i < 0) { out(ScriptEvent.FAILED, "Element " + i + " doesn't exisit."); return; } String s = str2.toLowerCase().intern(); boolean b = true; if (s == "mass") m.getElement(i).setMass(x / M_CONVERTER); else if (s == "sigma") m.getElement(i).setSigma(x * IR_CONVERTER); else if (s == "epsilon") m.getElement(i).setEpsilon(x); else { out(ScriptEvent.FAILED, "Cannot set property: " + str2); b = false; } if (b) notifyChange(); }
3077b8fb-2f21-4ebd-98a5-3170f1a9c0ac
9
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Customer other = (Customer) obj; if (this.customerId != other.customerId) { return false; } if ((this.firstName == null) ? (other.firstName != null) : !this.firstName.equals(other.firstName)) { return false; } if ((this.lastName == null) ? (other.lastName != null) : !this.lastName.equals(other.lastName)) { return false; } if ((this.address == null) ? (other.address != null) : !this.address.equals(other.address)) { return false; } return true; }
b72f2212-e668-42dc-90ad-bf4b313172e3
9
public void handleCommand(DOMBuilder builder, Element parentElement, CommandToken token) throws SnuggleParseException { /* Get the token to which the limit is being applied to, which is precisely the * first argument. */ List<FlowToken> limitand = token.getArguments()[0].getContents(); /* Ha! */ /* Decide whether we should do a munder/mover in preference to the more common * msub/msup. This decision is made on whether the "limitand" has been flagged * as having a certain Interpretation. */ boolean isUnderOver = builder.getOutputContext()==OutputContext.MATHML_BLOCK && limitand.size()==1 && limitand.get(0).hasInterpretationType(InterpretationType.MATH_BIG_LIMIT_OWNER); BuiltinCommand command = token.getCommand(); String elementName; if (command.equals(CorePackageDefinitions.CMD_MSUB_OR_MUNDER)) { elementName = isUnderOver ? "munder" : "msub"; } else if (command.equals(CorePackageDefinitions.CMD_MSUP_OR_MOVER)) { elementName = isUnderOver ? "mover" : "msup"; } else if (command.equals(CorePackageDefinitions.CMD_MSUBSUP_OR_MUNDEROVER)) { elementName = isUnderOver ? "munderover" : "msubsup"; } else { throw new SnuggleLogicException("Unexpected limit command " + command); } /* And we can now just build up the MathML quite trivially */ Element result = builder.appendMathMLElement(parentElement, elementName); for (ArgumentContainerToken argument : token.getArguments()) { builder.handleMathTokensAsSingleElement(result, argument); } }
39e22d52-858c-4891-85d6-374663fe5a16
7
public void countAllLinksStatus() { for (String link : links) { HttpURLConnection httpURL; int code = 0; try { httpURL = (HttpURLConnection) new URL(link).openConnection(); httpURL.setRequestMethod("HEAD"); code = httpURL.getResponseCode(); } catch (IOException e) { System.out.println("ERROR! " + e); } if(code >= 200 && code < 300){ sortedLinksOK.add(link); } else if(code >= 300 && code < 400){ sortedLinksTO.add(link); } else if(code >= 400){ sortedLinksBAD.add(link); } } }
4c986d6f-16f8-4b06-a991-5ca6d40e89da
0
public PanelOptions getPanelOptions() { WindowPrincipale window = (WindowPrincipale) this.getParent().getParent().getParent().getParent().getParent(); return window.getPanelSettings(); }
cbd70b64-b84f-44a4-8292-4034f1568a5b
6
public void loadLevel(String filename) throws SlickException, IndexOutOfBoundsException{ Image level; mobs = new ArrayList<Entity>(); player = new Entity(charFactory.GetTile(0, 0, 5, 6, Player.class)); level = new Image(filename); if(level.getWidth() != TILE_COL || level.getHeight() != TILE_ROW){ throw new IndexOutOfBoundsException("Level size was wrong, got " + level.getWidth() + "x" + level.getHeight() + " expected " + TILE_COL + "x" + TILE_ROW); } for(int i = 0; i < TILE_COL; ++i){ for(int k = 0; k < TILE_ROW; ++k){ Color tempColor = level.getColor(i, k); int ARGBcolor = colorToARGB(tempColor); Sprite tile = tileTypes.get(ARGBcolor); if(tile != null){ tiles[i][k] = new Tile(tile); } else{ if(colorToARGB(new Color(255,125,255,255)) == ARGBcolor){ //- Player starting position player.getRect().setLocation(i*TILE_WIDTH, k*TILE_HEIGHT); } tiles[i][k] = new Tile(tileTypes.get(0)); } } } level.destroy(); }
689e0a72-2589-44e2-9e5e-539973e97241
6
@Override public ByteChunk getChunk( String urn, int maxSize ) { try { File f = _getFile( urn ); if( f == null || f.length() > maxSize ) return null; int size = (int)f.length(); byte[] data = new byte[size]; FileInputStream fis = new FileInputStream( f ); try { int r=0; for( int z; r < size && (z=fis.read(data, r, size-r)) > 0; r += z); if( r < size ) return null; return new SimpleByteChunk(data); } finally { fis.close(); } } catch( IOException e ) { return null; } }
cb3a9813-7425-4dcc-9cc1-e47d3ae4dd9c
6
public Tilaus haeTilauksenTiedot(int tilausID) throws DAOPoikkeus, SQLException { // Avataan ensiksi yhteys: Connection yhteys = avaaYhteys(); // Alustetaan tarvittavat oliot ja muuttujat. Asiakas asiakas = new Asiakas(); Tilaus tilaus = new Tilaus(); Tuote tuote = new Tuote(); Pizza pizza = new Pizza(); ArrayList<Tilausrivi> tilausrivit = new ArrayList<Tilausrivi>(); int asiakasID = 0; int tilauksenTuoteID = 0; ResultSet tulokset, fantasiaTulokset; // Esitellään kyselyt String tilausSQL = "SELECT asiakasID, kokonaisHinta, toimitustapaID, maksutapaID, pvm, lisatietoja FROM Tilaus WHERE tilausID = ?"; String asiakasSQL = "SELECT nimi, email, puhnro, osoite, postinro, postitmp FROM Asiakas WHERE asiakasID = ?"; String tilausriviSQL = "SELECT tilauksenTuoteID, tuoteID, kokoID, kplmaara, riviHinta, oregano, valkosipuli, laktoositon, gluteeniton FROM TilauksenTuote WHERE tilausID = ?"; String fantasiaSQL = "SELECT tayte1, tayte2, tayte3, tayte4 FROM TilauksenFantasia WHERE tilauksenTuoteID = ?"; // Alustetaan SQL-lauseet PreparedStatement tilausLause = yhteys.prepareStatement(tilausSQL); PreparedStatement asiakasLause = yhteys.prepareStatement(asiakasSQL); PreparedStatement tilausriviLause = yhteys.prepareStatement(tilausriviSQL); PreparedStatement fantasiaLause = yhteys.prepareStatement(fantasiaSQL); // Haetaan kamaa tietokannasta! try { // Haetaan ensin tilauksen tiedot ID:llä tilausLause.setInt(1, tilausID); // Suoritetaan lause tulokset = tilausLause.executeQuery(); while (tulokset.next()) { // asiakasID:tä tarvitaan seuraavassa haussa asiakasID = tulokset.getInt("asiakasID"); double kokonaisHinta = tulokset.getDouble("kokonaisHinta"); int toimitustapaId = tulokset.getInt("toimitustapaID"); int maksutapaId = tulokset.getInt("maksutapaID"); Date pvm = tulokset.getTimestamp("pvm"); String lisatiedot = tulokset.getString("lisatietoja"); // Luodaan tiedoista olio tilaus = new Tilaus(tilausID, asiakas, tilausrivit, kokonaisHinta, pvm, maksutapaId, toimitustapaId, lisatiedot); } // Meillä on tilaus, jossa ei ole vielä asiakasta eikä tilausrivejä. Haetaan seuraavaksi asiakas: asiakasLause.setInt(1, asiakasID); // Suoritetaan lause tulokset = asiakasLause.executeQuery(); while (tulokset.next()) { String nimi = tulokset.getString("nimi"); String email = tulokset.getString("email"); String puhnro = tulokset.getString("puhnro"); String osoite = tulokset.getString("osoite"); String postinro = tulokset.getString("postinro"); String postitmp = tulokset.getString("postitmp"); // Luodaan Asiakas-luokan olio ja pultataan se tilaukseen. asiakas = new Asiakas(nimi, email, puhnro, osoite, postinro, postitmp); tilaus.setAsiakas(asiakas); } // Tarvitaan vielä tilaukseen kuuluneet tuotteet. Haetaan tietokannasta tilausrivit. tilausriviLause.setInt(1, tilausID); // Suoritetaan lause tulokset = tilausriviLause.executeQuery(); while (tulokset.next()) { // tilauksenTuoteID:tä tarvitaan seuraavassa haussa tilauksenTuoteID = tulokset.getInt("tilauksenTuoteID"); int tuoteID = tulokset.getInt("tuoteID"); int kokoID = tulokset.getInt("kokoID"); int kplmaara = tulokset.getInt("kplmaara"); double riviHinta = tulokset.getDouble("riviHinta"); boolean oregano = tulokset.getBoolean("oregano"); boolean valkosipuli = tulokset.getBoolean("valkosipuli"); boolean laktoositon = tulokset.getBoolean("laktoositon"); boolean gluteeniton = tulokset.getBoolean("gluteeniton"); // Haetaan tuotteen tiedot ID:llä kannasta samalla TuoteDAO tDao = new TuoteDAO(); tuote = tDao.haeTuote(tuoteID); pizza = tDao.haePizza(tuoteID); // täytteiden vuoksi // Jos haettu tuote on Fantasiapizza, haetaan tietokannasta // vielä sinne tallennetut fantasian täytteet. if (tuote.getNimi().equals("Fantasia")) { fantasiaLause.setInt(1, tilauksenTuoteID); fantasiaTulokset = fantasiaLause.executeQuery(); while (fantasiaTulokset.next()) { int tayte1 = fantasiaTulokset.getInt("tayte1"); int tayte2 = fantasiaTulokset.getInt("tayte2"); int tayte3 = fantasiaTulokset.getInt("tayte3"); int tayte4 = fantasiaTulokset.getInt("tayte4"); TayteDAO tayteDao = new TayteDAO(); ArrayList<Tayte> fantasiataytteet = tayteDao.haeFantasiaTaytteet(tayte1, tayte2, tayte3, tayte4); pizza.setTaytteet(fantasiataytteet); } } // Luodaan Tilausrivi-luokan olio ja lisätään se listaan. Tilausrivi tilausrivi = new Tilausrivi(tuote, pizza, kokoID, kplmaara, riviHinta, oregano, valkosipuli, laktoositon, gluteeniton); tilausrivit.add(tilausrivi); } // Kun kaikki tilausrivit on haettu, pultataan ne kiinni tilaukseen. tilaus.setTilausrivit(tilausrivit); } catch(DAOPoikkeus e) { // Heitetään käyttäjälle virhe. throw new DAOPoikkeus("Tilaustietojen haku aiheutti virheen!", e); } finally { suljeYhteys(yhteys); } return tilaus; }
c9d8e01a-6e9a-4c07-859a-0209e19b7743
4
public Player(){ frame = new JFrame("GrooveJaar Player"); frame.setIconImage((new ImageUtil().getLogo())); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); JScrollPane scrollPane = new JScrollPane(); JButton btnRemove = new JButton("Delete"); btnRemove.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { int n = list.getSelectedIndex(); model.remove(n); player.removeQueue(n); } }); GroupLayout groupLayout = new GroupLayout(frame.getContentPane()); groupLayout.setHorizontalGroup( groupLayout.createParallelGroup(Alignment.TRAILING) .addGroup(groupLayout.createSequentialGroup() .addGroup(groupLayout.createParallelGroup(Alignment.TRAILING) .addComponent(player, GroupLayout.DEFAULT_SIZE, 401, Short.MAX_VALUE) .addGroup(groupLayout.createSequentialGroup() .addGap(10) .addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 391, Short.MAX_VALUE))) .addPreferredGap(ComponentPlacement.UNRELATED) .addComponent(btnRemove, GroupLayout.PREFERRED_SIZE, 63, GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); groupLayout.setVerticalGroup( groupLayout.createParallelGroup(Alignment.TRAILING) .addGroup(groupLayout.createSequentialGroup() .addGroup(groupLayout.createParallelGroup(Alignment.LEADING) .addGroup(groupLayout.createSequentialGroup() .addComponent(player, GroupLayout.PREFERRED_SIZE, 104, GroupLayout.PREFERRED_SIZE) .addGap(18) .addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 74, Short.MAX_VALUE)) .addGroup(groupLayout.createSequentialGroup() .addGap(173) .addComponent(btnRemove))) .addContainerGap()) ); list.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { if (arg0.getClickCount() == 2) { int index = list.locationToIndex(arg0.getPoint()); player.setIndex(index); if (player.isPlaying()||player.isPaused()) player.stop(); player.play(); } } }); list.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent arg0) { if (!arg0.getValueIsAdjusting()) // System.out.println("index:"+list.getSelectedIndex()+"="+model.get(list.getSelectedIndex())); player.setIndex(list.getSelectedIndex()); } }); scrollPane.setViewportView(list); list.setForeground(Color.BLACK); frame.getContentPane().setLayout(groupLayout); frame.setLocationRelativeTo(null); frame.pack(); frame.setVisible(false); }
858b8727-be3b-4afa-9feb-ffd5d7283799
3
public String bubbleSort2(String a) { char[] arr = a.toCharArray(); for (int i = arr.length - 1; i > 0; i--) { for (int j = 0; j < i; j++) { // notice if (arr[j] > arr[j + 1]) { swap(arr, j, j + 1); } } } return new String(arr); }
b4e80ad7-afe6-499e-8315-1fe29a887c96
8
public void readFile (String filename) throws IOException { BufferedReader in = new BufferedReader(new FileReader(filename)); for (String line = in.readLine(); line != null; line = in.readLine()) { if (line.trim().length() == 0) { continue; } String[] fields = line.split("\t"); String source = fields[0]; String[] types = fields[1].split(","); String[] labels = fields[2].split(","); ArrayList<Integer> indexedLabels = new ArrayList<Integer>(); for (String label : labels) { if (labelIndex.getId(label) == null) { labelIndex.put(label); } indexedLabels.add(labelIndex.getId(label)); } // We expect the document to be nicely tokenized, e.g. by Ucto String[] words = fields[3].split("\\s+"); ArrayList<Integer> tokens = new ArrayList<Integer>(); for (String word : words) { if (wordIndex.getId(word) == null) { wordIndex.put(word); } tokens.add(wordIndex.getId(word)); } ArrayList<Integer> indexedTypes = new ArrayList<Integer>(); for (String type : types) { if (typeIndex.getId(type) == null) { typeIndex.put(type); } indexedTypes.add(typeIndex.getId(type)); } documents.add(new Document(tokens, source, indexedTypes, indexedLabels)); } in.close(); }
3d0e95be-0848-43ff-90fd-87ee6f6c01b8
7
boolean addCluster(NodeCluster seed) { members.add(seed); seed.isSetMember = true; rawPull += seed.weightedTotal; pullWeight += seed.weightedDivisor; if (isRight) { freedom = Math.min(freedom, seed.rightNonzero); if (freedom == 0 || rawPull <= 0) return true; addIncomingClusters(seed); if (addOutgoingClusters(seed)) return true; } else { freedom = Math.min(freedom, seed.leftNonzero); if (freedom == 0 || rawPull >= 0) return true; addOutgoingClusters(seed); if (addIncomingClusters(seed)) return true; } return false; }
5e592ad9-8dab-4320-bdc8-3b49bd707544
9
@Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { JLabel label = (JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); String status = (String)value; Icon icon=null; //Icone per la colonna GPS if (column==IND_COLONNA_GPS ) { if(value.equals(VALORE_OK)) { icon = new ImageIcon(getClass().getResource("/adisys/server/img/spie/GPSOK.png")); } else if(value.equals(VALORE_KO)) { icon = new ImageIcon(getClass().getResource("/adisys/server/img/spie/GPSKO.png")); } else if(value.equals(VALORE_NULL)) { icon = new ImageIcon(getClass().getResource("/adisys/server/img/spie/GPSnull.png")); } else { icon = new ImageIcon(getClass().getResource("/adisys/server/img/spie/GPSerr.png")); } } else if (column==IND_COLONNA_ACC ) { //Icone per la colonna Accelerometro if(value.equals(VALORE_OK)) { icon = new ImageIcon(getClass().getResource("/adisys/server/img/spie/ACCOK.png")); } else if(value.equals(VALORE_KO)) { icon = new ImageIcon(getClass().getResource("/adisys/server/img/spie/ACCKO.png")); } else if(value.equals(VALORE_NULL)) { icon = new ImageIcon(getClass().getResource("/adisys/server/img/spie/ACCnull.png")); } else { icon = new ImageIcon(getClass().getResource("/adisys/server/img/spie/ACCerr.png")); } } if(icon == null){ label.setText(status); label.setIcon(null); } else { label.setText(""); label.setIcon(icon); } return label; }
95133f24-a01d-4260-b4e9-05b8b9fc0c51
5
private void getNextPosition() { // movement if(!facingRight) { dx -= moveSpeed; if(dx < - maxSpeed) { dx = -maxSpeed; } } else if(facingRight){ dx += moveSpeed; if(dx > maxSpeed) { dx = maxSpeed; } } if(falling) { dy += fallSpeed; } }
efd383e1-2cf5-43e4-abc4-c7e14d1c3aed
2
private String[] parseValues(String input, int column) { StringTokenizer st = new StringTokenizer(input); SortedSet values = new TreeSet(); while (st.hasMoreTokens()) { String token = st.nextToken(); token = parseValue(token, column); if (token == null) continue; values.add(token); } return (String[]) values.toArray(new String[0]); }
c4a12a3e-6f36-4b37-9729-c7cc5a5e2da0
9
public void HandleInput(GameTime gameTime) { InputHandler input = mGameWindow.GetInputHandler(); Level level = mGameState.GetLevel(); Vector2 mousePosition = new Vector2(input.GetMouseX(), input.GetMouseY()); mousePosition = mGameState.GetCamera().ScreenToWorld(mousePosition); mAngle = (float)Math.toDegrees(Math.atan2(mousePosition.Y - mPosition.Y, mousePosition.X - mPosition.X)) + 90; Vector2 direction = new Vector2(); if (input.IsKeyDown(Keyboard.KEY_W)) { direction.PlusEquals(mGameState.GetCamera().GetViewMatrix().Forwards()); } if (input.IsKeyDown(Keyboard.KEY_A)) { direction.PlusEquals(mGameState.GetCamera().GetViewMatrix().Left()); } if (input.IsKeyDown(Keyboard.KEY_S)) { direction.PlusEquals(mGameState.GetCamera().GetViewMatrix().Backwards()); } if (input.IsKeyDown(Keyboard.KEY_D)) { direction.PlusEquals(mGameState.GetCamera().GetViewMatrix().Right()); } mVelocity.PlusEquals(direction.GetNormalized().Times(ACCELERATION)); if (input.IsMouseHit(1)) { Light newLight = new Light(mCircleLightTexture, mousePosition, 0.5f, 2, 2); mLights.add(newLight); level.AddLight(newLight); } if (input.IsKeyHit(Keyboard.KEY_C)) { for (int i = 0; i < mLights.size(); i++) { level.RemoveLight(mLights.get(i)); } mLights.clear(); } if (input.IsKeyHit(Keyboard.KEY_T)) { mFlashLightOn = !mFlashLightOn; if (mFlashLightOn) { level.AddLight(mFlashlight); } else { level.RemoveLight(mFlashlight); } } }
2dc65d89-5634-4a92-bc7a-bef5a0d6bf26
1
private void movePosChildren(Vector2f vector2f){ for (GUI child:children){ child.setPosition(vector2f.add(child.getPosition().sub(getPosition()).getXY())); } }
c24d6d8c-38ba-4949-8f8b-cdea7abd0dc7
3
public static byte[] toByteArray(final Object obj) { final ByteArrayOutputStream baos = new ByteArrayOutputStream(512); ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(baos); oos.writeObject(obj); } catch (Exception ex) { throw new SerializationException(ex); } finally { try { if (oos != null) { oos.close(); } } catch (IOException ex) { // ignore close exception } } return baos.toByteArray(); }
d852aee6-85e7-4b1e-9e97-26d3b3b77b39
7
public GetInvoiceDetailsResponse(Map<String, String> map, String prefix) { if( map.containsKey(prefix + "responseEnvelope" + ".timestamp") ) { String newPrefix = prefix + "responseEnvelope" + '.'; this.responseEnvelope = new ResponseEnvelope(map, newPrefix); } if( map.containsKey(prefix + "invoice" + ".merchantEmail") ) { String newPrefix = prefix + "invoice" + '.'; this.invoice = new InvoiceType(map, newPrefix); } if( map.containsKey(prefix + "invoiceDetails" + ".createdDate") ) { String newPrefix = prefix + "invoiceDetails" + '.'; this.invoiceDetails = new InvoiceDetailsType(map, newPrefix); } if( map.containsKey(prefix + "paymentDetails" + ".viaPayPal") ) { String newPrefix = prefix + "paymentDetails" + '.'; this.paymentDetails = new PaymentDetailsType(map, newPrefix); } if( map.containsKey(prefix + "invoiceURL") ) { this.invoiceURL = map.get(prefix + "invoiceURL"); } for(int i=0; i<10; i++) { if( map.containsKey(prefix + "error" + '(' + i + ')'+ ".errorId") ) { String newPrefix = prefix + "error" + '(' + i + ')' + '.'; this.error.add(new ErrorData(map, newPrefix)); } } }
369b2aa5-9b2d-4cae-b947-46a7239b5a0d
5
@Override @EventHandler(ignoreCancelled = true) public void onPlayerInteract(final PlayerInteractEvent interaction) { super.onPlayerInteract(interaction); if (interaction.getAction() != Action.LEFT_CLICK_BLOCK) return; if (!Kiosk.SIGN_BLOCKS.contains(interaction.getClickedBlock().getTypeId())) return; final Sign state = (Sign) interaction.getClickedBlock().getState(); if (!this.hasTitle(state)) return; final Function function = this.getFunction(state); if (function == null) { Main.courier.send(interaction.getPlayer(), "unknownFunction", state.getLine(1)); interaction.setCancelled(true); return; } if (!function.canUse(interaction.getPlayer())) { Main.courier.submit(new Sender(interaction.getPlayer()), function.draftDenied()); interaction.setCancelled(true); return; } this.dispatch(interaction.getPlayer(), state); }
ff918e9f-6d3a-4b6f-8218-89245fd15e3f
6
public void updateTable(){ //add columns columns = new Vector(); columns.addElement("Alternatives"); objs = con.getObjPanel().getPrimitiveObjectives(); //do we really need this temp holder? for(int i=0; i<objs.size(); i++){ columns.add(objs.get(i).toString()); } //add data rows = new Vector(); for (int j=0; j<alts.size(); j++){ Vector data = new Vector(); HashMap temp = (HashMap)alts.get(j); data.add(temp.get("name")); for (int i=0; i<objs.size(); i++){ //for each primitive objective, find each alternative's value data.add(temp.get(objs.get(i).toString())); } rows.add(data); } //apply it to the JTable view tabModel.setDataVector(rows,columns); tabModel.fireTableStructureChanged(); colNames = table.getColumnModel().getColumn(0); DefaultTableCellRenderer dtcr = new DefaultTableCellRenderer(); dtcr.setBackground(new Color(238, 238, 238)); dtcr.setFont(new Font("Arial", Font.BOLD, 9)); colNames.setCellRenderer(dtcr); colNames.setMaxWidth(100); colNames.setPreferredWidth(100); colNames.setResizable(false); dtcr.setBorder(null); //determine data that can be entered by combo box //JComboBox[] cbox= new JComboBox[columns.size()]; for(int i=0; i<objs.size(); i++){ //set combobox if discrete TableColumn col = table.getColumnModel().getColumn(i+1); JObjective obj = (JObjective)objs.get(i); if (obj.getType() == JObjective.DISCRETE){ JComboBox cboCell; if (obj.domain.getElements() != null) cboCell = new JComboBox(obj.domain.getElements()); else cboCell = new JComboBox(); col.setCellEditor(new DefaultCellEditor(cboCell)); cboCell.setEditable(true); } //set formatted text field if not else { DecimalFormat df = new DecimalFormat("0.0"); JFormattedTextField txtCell = new JFormattedTextField(df); col.setCellEditor(new DefaultCellEditor(txtCell)); txtCell.setColumns(10); } } checkAlternativeCount(); }
de231da5-e35d-4f3b-a6ee-b8482db8a936
6
public static void main(String args[]) throws IOException { /* 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 { UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MainClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainClient.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 MainClient().setVisible(true); } }); //Prompt for the name of the computer where the server is running remoteAddress = JOptionPane.showInputDialog("Enter the name of the computer you want to connect to"); evaluateAddress(); while (!validAddress) { remoteAddress = JOptionPane.showInputDialog("You must enter a valid hostname"); evaluateAddress(); } //Prompt for username until at lest one character is entered username = JOptionPane.showInputDialog("Enter username:"); evaluateUsername(); while (username.equals("")) { username = JOptionPane.showInputDialog("You must choose a username!"); evaluateUsername(); } //Open a new socket to the server setMap(); connect(); login(); listen(); }
c6d51faa-0095-4ecf-b2ea-1acb3bf0357e
2
private static void processKeyEvents(){ if(Keyboard.getEventKeyState()){ if(Keyboard.getEventKey() == Keyboard.KEY_ESCAPE){ Game.setState(previousState); } } }
5447ae29-3da6-4ed5-9388-c2e513f41e69
6
protected String getPassword(final int times) { if(times <= 0) { throw new IllegalArgumentException("times cannot be lower than 1!"); } String[] pwInput = new String[times]; // ask password n times for(int i=0; i<times; i++) { PasswordDialog pwdDialog = new PasswordDialog(view); pwdDialog.showPasswordDialog(view); pwInput[i] = pwdDialog.getPassword(); if(pwdDialog.aborted()) { return null; } } // compare passwords and return null if they are not equal if(times > 1) { for(int i=1; i<times; i++) { if(pwInput[i].equals(pwInput[i-1]) == false) { displayError(bundle.getString("password_input_error"), bundle.getString("passwords_do_not_match")); return null; } } } // all passwords are equal, return the password return pwInput[0]; }
f2f84dd1-9130-47f7-9514-5ed7ccf4ccdf
9
public void testGetPhoneNumbers() throws InterruptedException{ driver.get(URL); Thread.sleep(3000); WebElement phone = driver.findElement(By.id("revPhone:firstField")); WebElement city = driver.findElement(By.id("revPhone:city")); WebElement search = driver.findElement(By.id("revPhone:search")); try { phone.clear(); phone.sendKeys("2479"); city.clear(); city.sendKeys("CHENNAI"); search.click(); Thread.sleep(3000); System.out.println("Wakeup from sleep"); WebElement searchResultsCount = driver.findElement(By.xpath("//*[@id='contentSrchResult']/div[1]/div[1]/span")); WebElement searchResultsPageCount =driver.findElement(By.xpath("//*[@id='second']/span")); WebElement firstButton = driver.findElement(By.id("j_id10:FIRSTPGLink")); WebElement nextButton = driver.findElement(By.id("j_id10:PGDOWNLink")); System.out.println("nextButton.isEnabled() --> "+nextButton.isEnabled()); String strPageCount = searchResultsPageCount.getText(); String[] splitStr = strPageCount.split("of"); System.out.println("First -- "+splitStr[0].trim() +"\n Second -- "+splitStr[1].trim()); String totPageCount = splitStr[1].trim(); Assert.assertTrue(firstButton.isDisplayed()); System.out.println("Total Count"+searchResultsCount.getText()); System.out.println("Total Page Count"+searchResultsPageCount.getText()); System.out.println("Is First Button displayed"+firstButton.isDisplayed()); Integer countPage; countPage = Integer.valueOf(totPageCount); System.out.println("Cout page ---- "+countPage); for(int k=0;k<countPage;k++){ System.out.println("--------------- Start Record "+k+" ----------------"); // Get Tables WebElement table = driver.findElement(By.id("second:myTab")); // get all the TR in the displayed table List<WebElement> allRows = table.findElements(By.tagName("tr")); // iterate now for(WebElement row : allRows){ List<WebElement> cell = row.findElements(By.tagName("td")); // iterate now int i=0; for(WebElement cellValue: cell){ if(i==0){ String textName = cellValue.getText(); System.out.println("Name is "+textName); /*List<WebElement> aLink = cellValue.findElements(By.tagName("a")); for(WebElement clickA : aLink){ clickA.click(); Thread.sleep(2000); System.out.println(driver.getPageSource()); WebElement backLink111 = driver.findElement(By.id("customerDetails:back")); backLink111.click(); } */ //getDetails(textName); } if(i==1){ System.out.println("Telephone number is "+cellValue.getText()); } if(i==2){ System.out.println("Address is "+cellValue.getText()); } if(i==3){ System.out.println("State is "+cellValue.getText()); } if(i>=3){ i=0; }else{ i++; } } } System.out.println("--------------- end of "+k+" Record ----------------"); nextButton.click(); Thread.sleep(1000); } } catch (RuntimeException e) { // TODO: handle exception System.out.println(e.getMessage()); } }
844a3dbf-0191-4604-8d78-7fd0fe2129fe
7
public boolean isTBonded(Atom a) { if (tbondList == null || tbondList.isEmpty()) return false; synchronized (tbondList) { for (TBond t : tbondList) { if (t.getAtom1() == a || t.getAtom2() == a || t.getAtom3() == a || t.getAtom4() == a) return true; } } return false; }
7b357e03-60e5-432e-bf64-d6b082f4b98b
4
@Override public void selectInterface(String interfaceName) { try { NetworkInterface selected = NetworkInterface.getByName(interfaceName); for ( int i = 0; i < selected.getInterfaceAddresses().size(); i++ ) { InetAddress bcast = selected.getInterfaceAddresses().get(i).getBroadcast(); if ( bcast != null ) { if ( bcast.getAddress().length == 4 ) { broadcastTarget = bcast; myAddress = selected.getInterfaceAddresses().get(i).getAddress(); } } } sock = new MulticastSocket(Config.DISCOVERPORT); start(); } catch (Exception e) { e.printStackTrace(); System.exit(0); } }
74519deb-c47e-4653-9c1c-ddb1636f6ac0
6
private String adjustUnitsInString(String input, float scale){ StringBuilder output = new StringBuilder(input); Matcher matcher = decimalPattern.matcher(input); while ( matcher.find() ){ String group1 = ( matcher.group(1) == null ) ? "" : matcher.group(1).trim(); String group3 = ( matcher.group(3) == null ) ? "" : matcher.group(3).trim(); //We only scale numbers that do not have any chars surrounding them if ( group1.isEmpty() && group3.isEmpty() ){ try{ float originalAmount = Float.parseFloat(matcher.group(2)); float newAmount = originalAmount * scale; DecimalFormat format = new DecimalFormat(); format.setMaximumFractionDigits(2); format.setMinimumFractionDigits(0); format.setGroupingUsed(false); String replacementAmount = format.format(newAmount); int offset = matcher.start() + matcher.group(1).length(); output.replace(offset, offset+matcher.group(2).length(), replacementAmount); } catch (NumberFormatException e){ //We cannot change the value so we ignore it., regex should prevent os from getting here in the first place. LOGGER.error("NumberFormatException thrown while converting '" + matcher.group(2) + "' to float, " + "this should have been caught in the regex. " + "Complete input string: '" + input); } } } return output.toString(); }
a7ed50e5-bc2a-4904-8d47-0ad7edc63352
4
public static void main(String[] args) { String line = ""; String message = ""; int c; try { while ((c = System.in.read()) >= 0) { switch (c) { case '\n': if (line.equals("go")) { PlanetWars pw = new PlanetWars(message); DoTurn(pw); pw.FinishTurn(); message = ""; } else { message += line + "\n"; } line = ""; break; default: line += (char) c; break; } } } catch (Exception e) { StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); String stackTrace = writer.toString(); System.err.println(stackTrace); System.exit(1); //just stop now. we've got a problem } }
2f39cbc3-64eb-4fbf-9e3d-c5e25ad9725b
3
public void permuteRec(int level, int[] num, List<ArrayList<Integer>> res, Deque<Integer> stk, boolean[] visited){ if(level == num.length){ res.add(new ArrayList<Integer>(stk)); return; } for(int i = 0; i < num.length; ++i){ if(!visited[i]){ stk.addLast(num[i]); visited[i] = true; permuteRec(level + 1, num, res, stk, visited); visited[i] = false; stk.removeLast(); } } }
a593232b-1136-4a67-8c2a-fdb2786e6f36
1
public void usingEntrySetAndIterator(Map<Integer, String> map){ Iterator<Map.Entry<Integer, String>> itrtr = map.entrySet().iterator(); while (itrtr.hasNext()) { Map.Entry<Integer, String> entry = itrtr.next(); System.out.println("Key: "+entry.getKey()+" Value: "+entry.getValue()); } }
f312fe1f-233e-4e2a-92cc-63a64f244ef2
7
public int largestRectangleArea(int[] height){ if(height==null || height.length==0) return 0; if(height.length==1) return height[0]; Stack<Integer> stack=new Stack<Integer>(); stack.push(-1); int max=0; for(int i=0;i<height.length;i++){ int curHeight=height[i]; int peekIndex=stack.peek(); while(peekIndex!=-1 && height[peekIndex]>curHeight){ //Meet smaller value, can calculate stack.pop(); int newPeek=stack.peek(); //Next peek till current pop are all larger than current pop max=Math.max(max, height[peekIndex]*(i-newPeek-1)); peekIndex=newPeek; } stack.push(i); } while(stack.peek()!=-1){ int top=stack.pop(); max=Math.max(max, height[top]*(height.length-1-stack.peek())); } return max; }
f2fac149-e011-41fb-8d2c-092de9c6cb50
6
@Override public String execute(HttpServletRequest request) throws SQLException, ClassNotFoundException { String tableName = request.getParameter("TableName"); System.out.println(tableName); if (tableName != null && tableName != "") { try { Class.forName("org.h2.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } // Connection connectionn = DriverManager.getConnection("jdbc:h2:tcp://localhost/F:/Видео Epam/db/FPDB", "Rody", "1"); Connection connection = ConnectionPool.getConnectionFromPool("jdbc:h2:tcp://localhost/F:/Видео Epam/db/FPDB","Rody","1"); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("SELECT * FROM " + tableName); ResultSetMetaData resultSetMD = resultSet.getMetaData(); List<List> result = new ArrayList<>(); List<Element> titlesOfColumns = new ArrayList<>(); boolean f = true; while (resultSet.next()) { List<Element> row = new ArrayList<>(); int i = 1; while(i <= resultSetMD.getColumnCount()){ if (f) titlesOfColumns.add(new Element(FirsUpperSymbol(resultSetMD.getColumnName(i).toLowerCase()))); row.add(new Element(resultSet.getString(i))); i++; } f = false; result.add(row); } request.setAttribute("titlesOfColumns", titlesOfColumns); request.setAttribute("result", result); connection.close(); } return "/WEB-INF/result.jsp"; }
4f729bdb-70ea-4240-ae44-c7b9d1e02964
5
protected void doDataIn(PeerMessage pm){ if(pm.type == PeerMessage.Type.CHOKE){ this.peer_choking = true; //Drop our requests. They aint gana get done. System.out.println(toString()+" choked us."); }else if(pm.type == PeerMessage.Type.UNCHOKE){ System.out.println(toString()+" unchoked us."); this.peer_choking = false; }else if(pm.type == PeerMessage.Type.INTERESTED){ System.out.println(toString()+" intrested in us."); this.peer_interested = true; }else if(pm.type == PeerMessage.Type.NOT_INTERESTED){ System.out.println(toString()+" not intrested in us."); this.peer_interested = false; }else if(pm.type == PeerMessage.Type.EXTENSION){ doExtension(pm.extensionID,pm.extension); } }
6aa20475-f759-4f9a-b443-70a4d54d41fe
5
public static void findTwoLargest(int[] a) { int largest = a[0]; int nextLargest = a[0]; for (int i = 0 ; i < a.length ; i++) { if (a[i] > largest) { largest = a[i]; } } for (int i = 0 ; i < a.length ; i++) { if (a[i] > nextLargest && a[i] < largest) { nextLargest = a[i]; } } System.out.println("Largest: " + largest + " Second Largest: " + nextLargest); }
a7edca12-75ac-4a80-9815-8cb00c2076ea
3
private boolean validPixel(int x, int y) { boolean validX = x >= -this.getWidth() / 2 && x <= this.getWidth() / 2; boolean validY = y >= -this.getHeight() / 2 && y <= this.getHeight() / 2; return validX && validY; }
76a5fb9b-1f1b-4659-afa3-8e1043796289
9
public static void setSkin(final String skinName, final JFrame frame) { try { if (skinName.equals("seaGlass")) { UIManager.setLookAndFeel(new SeaGlassLookAndFeel()); } else if (skinName.equals("syntheticaStandard")) { UIManager.setLookAndFeel(new SyntheticaStandardLookAndFeel()); } else if (skinName.equals("syntheticaBlueLight")) { UIManager.setLookAndFeel(new SyntheticaBlueLightLookAndFeel()); } else if (skinName.equals("syntheticaAluOxide")) { UIManager.setLookAndFeel(new SyntheticaAluOxideLookAndFeel()); } else if (skinName.equals("syntheticaWhiteVision")) { UIManager.setLookAndFeel(new SyntheticaWhiteVisionLookAndFeel()); } else if (skinName.equals("syntheticaBlackEye")) { UIManager.setLookAndFeel(new SyntheticaBlackEyeLookAndFeel()); } else if (skinName.equals("syntheticaBlackMoon")) { UIManager.setLookAndFeel(new SyntheticaBlackMoonLookAndFeel()); } else if (skinName.equals("syntheticaBlackStar")) { UIManager.setLookAndFeel(new SyntheticaBlackStarLookAndFeel()); } SwingUtilities.updateComponentTreeUI(frame); frame.pack(); } catch (ParseException | UnsupportedLookAndFeelException e) { JOptionPane.showMessageDialog(null, "Error with look and feel: " + e.getMessage()); logger.log(Level.ERROR, e.getMessage()); } }
d852d83c-44f6-4bdd-b85d-6c7ce84a9e58
2
public void run() { Scanner in = new Scanner( System.in ); while (in.hasNextLine()) { String line = in.nextLine(); if (line.equalsIgnoreCase( QUIT )) { finished = true; break; } else { messages.add( line ); } } finished = true; }
bcc77f71-7e74-4a43-b63b-5423428f43ef
8
public static void showEditor(String skinFilename) { Path skinPath; if (!skinFilename.endsWith(Constants.SKINFILE_SUFFIX)) { skinPath = Constants.PROGRAM_SKINS_PATH.resolve(skinFilename + Constants.SKINFILE_SUFFIX); } else { skinPath = Constants.PROGRAM_SKINS_PATH.resolve(skinFilename); } if ((skinFilename != null) && !skinFilename.equals("") && FileUtil.control(skinPath) && (model != null)) { Skin skin = model.loadSkin(skinPath); if (skin != null) { if (editor != null) { editor.dispose(); editor = null; } if (chooser != null) { chooser.dispose(); chooser = null; } editor = new Editor(skin); } else { handleUnhandableProblem("Main.showEditor", "Skin load failed!"); } } else { throw new InvalidParameterException(); } }