method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
9158c89c-177d-4aff-a71f-291b46694479
2
@RequestMapping(value = "/projectForm") public ModelAndView showProjectForm(HttpServletRequest request) { //I need customers list, assignments list and worktypes list !!! ModelAndView modelAndView = new ModelAndView("projectForm"); String method = request.getParameter("action"); if (method.equals("add")) { modelAndView.addObject("command", new Project()); } else if (method.equals("edit")) { String projectId = request.getParameter("id"); Project project = getProjectsDAO().getById(Integer.parseInt(projectId)); modelAndView.addObject("command", project); } modelAndView.addObject("customersList", getCustomersDAO().getAll()); return modelAndView; }
46818e07-0c51-4f98-8997-cfce7f3e4277
0
public JSONStringer() { super(new StringWriter()); }
e0f770f9-a723-4964-91cf-5b736eda5e3a
3
public Set<HTTPHeaderLine> getAll( String name ) throws NullPointerException { if( name == null ) throw new NullPointerException( "Cannot retrieve header lines if the passed key (name) is null." ); // Get the set widht the elements Set<HTTPHeaderLine> set = this.map.get( name ); // make a copy Set<HTTPHeaderLine> result = new TreeSet<HTTPHeaderLine>(); if( set == null ) return result; Iterator<HTTPHeaderLine> iter = set.iterator(); while( iter.hasNext() ) { // Hint: HTTPHeaderLines are immutable -> no need to clone result.add( iter.next() ); } return result; }
61775109-e086-4e52-b11c-43f3ddcadd3f
1
public void defineModules(String... moduleNames) { fragments.clear(); for (String moduleName : moduleNames) { fragments.add(moduleName); } }
d00dfec1-9f62-4643-b395-893220ac0053
8
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line = ""; StringBuilder out = new StringBuilder(); int times = 1; int[] a = new int[10001]; while ((line = in.readLine()) != null && line.length() != 0) { int[] v = readInts(line); if (v[0] == 0 && v[1] == 0) break; Arrays.fill(a, Integer.MAX_VALUE); ArrayList<Integer> listOfNumbers = new ArrayList<Integer>(v[0]); for (int i = 0; i < v[0]; i++) { int n = Integer.parseInt(in.readLine().trim()); listOfNumbers.add(n); } Collections.sort(listOfNumbers); for (int i = 0; i < listOfNumbers.size(); i++) { int n = listOfNumbers.get(i); a[n] = Math.min(a[n], i + 1); } out.append("CASE# " + times++ + ":\n"); for (int i = 0; i < v[1]; i++) { int n = Integer.parseInt(in.readLine().trim()); if (a[n] == Integer.MAX_VALUE) out.append(n + " not found\n"); else out.append(n + " found at " + a[n] + "\n"); } } System.out.print(out); }
36c1670a-6c1e-4ec6-bb8d-5186c3c824e5
2
protected void updateAge() { age++; if (age > maxAge && maxAge != 0) { isAlive = false; } }
8c41bb2a-2079-42d0-863a-470ee8e21f30
8
public static void keyTyped(KeyEvent keyEvent) { Iterator<PComponent> it = components.iterator(); while(it.hasNext()) { PComponent comp = it.next(); if(comp == null) continue; if (shouldHandleKeys) { if (comp.shouldHandleKeys()) comp.keyTyped(keyEvent); } else { if (comp instanceof PFrame) { for (PComponent component : ((PFrame) comp).getComponents()) if (component.forceKeys()) component.keyTyped(keyEvent); } else if (comp.forceKeys()) comp.keyTyped(keyEvent); } } }
5beefd8b-6009-45e0-b0b0-391a0e6004f1
1
public void add( V val,K key){ if (root == null) { root = new BinaryNode<K,V>(val,key,null,null); } else{ root.insert(val,key); } }
32724464-b33d-429a-9191-b508a1d600e9
8
public static int maxSubArray(int[] a){ if (a == null || a.length <0)return 0; int sum = 0; int max = 0; int num = 0; for (int i = 0; i < a.length; i++){ sum += a[i]; //如果sum小于0,则将其置为0,否则负值与后边的数相加会肯定会使总的和变小 if (sum < 0) sum = 0; if (sum > max) max = sum; num++; } System.out.println(num); if (max == 0){ int maxNum = a[0]; for (int j : a){ if (j > maxNum){ maxNum = j; } } return maxNum; } return max; }
72e88bbc-793a-408d-b574-e81bd8521ee4
4
private String wrapText(String text) { int spaceSpace = GenericLabel.getStringWidth(" "); int spaceAvailable = getWidth(); int spaceRemaining = spaceAvailable; String[] words = text.split(" "); String result = ""; for (int i = 0; i < words.length; i++) { int wordSpace = GenericLabel.getStringWidth(words[i]); if (!result.isEmpty() && wordSpace > spaceRemaining) { result += "\n"; spaceRemaining = spaceAvailable; } result += words[i]; spaceRemaining -= wordSpace; if (spaceSpace > spaceRemaining) { result += "\n"; spaceRemaining = spaceAvailable; } else { result += " "; spaceRemaining -= spaceSpace; } } return result; }
c104179b-c23d-43d7-814f-ef736c335967
4
private Object handleLdsOrdinance(Object tos, boolean isPersonalOrdinance, String tagName) { if ((tos instanceof Person && isPersonalOrdinance) || (tos instanceof Family && !isPersonalOrdinance)) { LdsOrdinance ldsOrdinance = new LdsOrdinance(); ((PersonFamilyCommonContainer)tos).addLdsOrdinance(ldsOrdinance); ldsOrdinance.setTag(tagName); return ldsOrdinance; } return null; }
8b4fec8d-1fd0-42bc-b8c9-d1385b9e1c22
7
public boolean start() { synchronized (optOutLock) { // Did we opt out? if (isOptOut()) { return false; } // Is metrics already running? if (task != null) { return true; } // Begin hitting the server with glorious data task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() { private boolean firstPost = true; public void run() { try { // This has to be synchronized or it can collide with the disable method. synchronized (optOutLock) { // Disable Task, if it is running and the server owner decided to opt-out if (isOptOut() && task != null) { task.cancel(); task = null; // Tell all plotters to stop gathering information. for (Graph graph : graphs) { graph.onOptOut(); } } } // We use the inverse of firstPost because if it is the first time we are posting, // it is not a interval ping, so it evaluates to FALSE // Each time thereafter it will evaluate to TRUE, i.e PING! postPlugin(!firstPost); // After the first post we set firstPost to false // Each post thereafter will be a ping firstPost = false; } catch (IOException e) { if (debug) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage()); } } } }, 0, PING_INTERVAL * 1200); return true; } }
b840ea94-4589-4e07-b2ef-fd57b57d5689
3
private String getModelFileData(){ String modelData = null; FileInputStream fis = null; BufferedReader br = null; try{ fis = new FileInputStream(modelDataFileName); if(fis != null){ System.out.println("aaaaaaaaa"); } br = new BufferedReader(new InputStreamReader(fis , "UTF-8")); modelData =fileReader(br); }catch ( FileNotFoundException e) { e.printStackTrace( ); }catch ( UnsupportedEncodingException e ){ e.printStackTrace( ); } return modelData; }
6827dcb9-52b1-4b3f-915f-9cb5a8513c38
1
public void deleteElement(String value) { int codeValue = hashCode.hashCounter(value, length); if (exists(value)) { hashTable[codeValue].deleteElement(value); } }
d1da4602-7520-420d-be12-bf40a4cef87c
5
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Student other = (Student) obj; if (!Objects.equals(this.group, other.group)) { return false; } if (!Objects.equals(this.getName(), other.getName())){ return false; } if (!Objects.equals(this.getAge(), other.getAge())){ return false; } return true; }
200c28db-741d-4e17-a8ef-d4f7f4c0776f
4
protected final void addItemToPlayersInventory(Player player) throws InvalidActionException { if (player == null) throw new IllegalArgumentException("The given player is invalid!"); if (!(this instanceof Pickupable)) throw new InvalidActionException("The selected item can't be picked up!"); if (player.getRemainingActions() <= 0) throw new InvalidActionException("The player has no turns left!"); if (!getGrid().getElementsOnPosition(getGrid().getElementPosition(player)).contains(this)) throw new InvalidActionException("The item isn't positioned on the player's position!"); player.getInventory().add(this); getGrid().removeElement(this); player.decrementAction(); }
3e785b5c-3eb2-4da2-bf00-0e82d094d994
7
@Override public void run() { long currentTime = System.currentTimeMillis(); //generate report Map<String, StringBuilder> successLogMap = new HashMap<String, StringBuilder>(); Map<String, StringBuilder> failLogMap = new HashMap<String, StringBuilder>(); //collect log for (TestData data : datas) { AbstractApiData testData = (AbstractApiData) data; //ignore unexpected api data Object obj = testData.getMetadat(MisSupportApiData.OUTPUT_RESULT_MAP); if (obj == null) { logger.warn(String.format("Skip log gen. for api data with no result map![%s][%s]", testData.getClass(), testData.getBaseUrl() + testData.getParameters())); continue; } ResultMap resultMap = (ResultMap) obj; if ("ok".equals(resultMap.getStatus().toLowerCase().trim())) { if (! successLogMap.containsKey(testData.getBaseUrl())) { successLogMap.put(testData.getBaseUrl(), new StringBuilder()); } successLogMap.get(testData.getBaseUrl()).append(resultMap.getTestcaseName() + "," + resultMap.getStatus() + "\n"); } else { if (! failLogMap.containsKey(testData.getBaseUrl())) { failLogMap.put(testData.getBaseUrl(), new StringBuilder()); } failLogMap.get(testData.getBaseUrl()).append(resultMap.getTestcaseName() + "," + resultMap.getStatus() + "\n"); } } for (Entry<String, StringBuilder> row : successLogMap.entrySet()) { this.writeToPassLog(currentTime, row.getValue(), row.getKey()); } for (Entry<String, StringBuilder> row : failLogMap.entrySet()) { this.writeToFailLog(currentTime, row.getValue(), row.getKey()); } }
8046648e-ff26-4fc0-8526-527e6d3c5060
3
@Override public void updatePatient(Patient patient) throws Exception { // Get JDBC Connection Connection conn= JDBCManager.getConnection(); PreparedStatement stmt=null; String sql="Update Patient "+ "SET FirstName=?,LastName=?,Gender=?,Age=? "+ "WHERE HealthRecordNumber=?"; try { stmt=conn.prepareStatement(sql); //Extract patient informations and set to Prepared Statement stmt.setString(1, patient.getFirstName()); stmt.setString(2, patient.getLastName()); stmt.setString(3, patient.getGender()); stmt.setInt(4, patient.getAge()); stmt.setInt(5, patient.getHealthRecNo()); stmt.executeUpdate(); } catch (SQLException e) { throw e; } finally { // Closing the connections if(stmt!=null){ stmt.close(); } if(conn!=null){ conn.close(); } } }
50a5b0dd-60d6-427c-ada0-889fde549a97
7
public void keyReleased(KeyEvent e) { keyCode = e.getKeyCode(); if (keyCode == 38) { lastdir = 1; UP = false; } else if (keyCode == 40) { lastdir = 2; DOWN = false; } else if (keyCode == 37) { lastdir = 3; LEFT = false; } else if (keyCode == 39) { lastdir = 4; RIGHT = false; } else if (keyCode == 32) { tryinRun = false; } else if (keyCode == 90) { Z = false; } else if (keyCode == 88) { X = false; } keyCode = 0; }
61f56453-dc3e-4546-b441-5c0872c70450
8
public void setFieldValue(_Fields field, Object value) { switch (field) { case ID: if (value == null) { unsetId(); } else { setId((Integer)value); } break; case NOME: if (value == null) { unsetNome(); } else { setNome((String)value); } break; case EMAIL: if (value == null) { unsetEmail(); } else { setEmail((String)value); } break; case DATA: if (value == null) { unsetData(); } else { setData((String)value); } break; } }
39a797ac-a857-4999-8ded-b79eaac794d1
6
private synchronized void auto_reconnect(){ System.out.println("Attempting Auto-Reconnect..."); //Clean and desrtoy anything that may be left try{mysql_connection.close(); mysql_connection = null;}catch(SQLException e){} //On a sucesufull connection stop retrying boolean connected = false; //Attempt to reconnect up to the number of auto_reconnect_retry int retries_left = auto_reconnect_retry; while(retries_left > 0 && !connected){ retries_left--; System.out.println("Auto-Reconnect Attempt #" + (auto_reconnect_retry - retries_left) + " of " + auto_reconnect_retry); try{ wait(auto_reconnect_time); connected = reconnect(hostname_local_cache, username_local_cache, password_local_cache, database_local_cache); } catch(InterruptedException i){ System.err.println("Reconnect Canceled!"); } catch(SQLTransientConnectionException e){ System.err.println("AUTO RECONNECT: " + e.getMessage()); } catch(Exception e){ System.err.println("Unkown faliure: " + e.getLocalizedMessage()); } } }
5cf2f084-ea1b-43fb-b687-75a5c18b3ba3
4
private JSONObject readObject() throws JSONException { JSONObject jsonobject = new JSONObject(); while (true) { if (probe) { log("\n"); } String name = readName(); jsonobject.put(name, !bit() ? readString() : readValue()); if (!bit()) { return jsonobject; } } }
3812491f-f254-4b88-8307-088930cc26d0
9
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; IpAndMask other = (IpAndMask) obj; if (ip == null) { if (other.ip != null) return false; } else if (!ip.equals(other.ip)) return false; if (mask == null) { if (other.mask != null) return false; } else if (!mask.equals(other.mask)) return false; return true; }
467fea57-15a2-414e-948b-aa92fe251e7c
6
public Type intersection(Type type) { if (this == tError || type == tError) return tError; if (this == tUnknown) return type; if (type == tUnknown || this == type) return this; /* * We have two different singleton sets now. */ if ((GlobalOptions.debuggingFlags & GlobalOptions.DEBUG_TYPES) != 0) GlobalOptions.err.println("intersecting " + this + " and " + type + " to <error>"); return tError; }
52bc151b-b06f-4665-8c61-750fff79ac87
3
public void omniSend(Message m){ rover = head; while(rover != null){ if(rover.status == 1){ rover.sendMessage(m); if(m.header.equals("APPEND GIRL")){ Girl xxx = getGirl(randlist[conn.currgirl]); System.out.print(xxx.name + " "); } System.out.println(m.header + " : " + conn.name + " - " + rover.name); } rover = rover.next; } }
a17c1211-92d4-4b83-9318-94e708ecf60a
4
public void run() { logger.finer("Receiving packets..."); isReceiving = true; while(isReceiving) { byte[] bytes = new byte[Packet.MAXIMUM_PACKET_SIZE]; DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length); try { socket.receive(datagramPacket); try { Packet packet = Packet.parsePacket(datagramPacket.getData(), datagramPacket.getLength()); logger.finest("Received packet"); receiver.receivePacket(packet, datagramPacket.getAddress().getHostAddress(), datagramPacket.getPort()); } catch (MalformedPacketException e) { //it might be valuable to inform the server that it's receiving invalid packets from a client receiver.receivePacket(null, datagramPacket.getAddress().getHostAddress(), datagramPacket.getPort()); } } catch (IOException e) { //if the packet is having trouble receiving, the best thing to // do is keep trying. If the problem persists the connection // will time out if(logger.isLoggable(Level.FINEST)) logger.finest("IOException while receiving packets: " + e.getMessage()); } } }
92705376-5be5-4881-8753-8dc736876954
0
public int getV(){ return velocity; }
2fd04848-8321-46ee-8995-882af2a1e373
8
private void listAmount() { System.out.println("files to process: " + listImg.size()); System.out.println("start convert names... " ); for (int i = 0; i < listImg.size() ; i++) { String oldName = listImg.get(i); Utils.percentCounter(i,listImg.size()); //System.out.println(oldName); String s = (oldName.replaceAll(srcDrive+":\\\\P.*\\\\", "").toLowerCase()); String newName; if( oldName.toLowerCase().contains(".mp4") ||oldName.toLowerCase().contains(".avi") ||oldName.toLowerCase().contains(".wmv") ||oldName.toLowerCase().contains(".mov") ||oldName.toLowerCase().contains(".mpg") ||oldName.toLowerCase().contains(".mpeg")){ newName = (ImageData.getMovieInfo(oldName)).replace("-", "") + "_" + s; }else { newName = (ImageData.getImageInfo(oldName)).replace("-", "") + "_" + s; } newName = newName.replace(" ", "_"); //System.out.println(newName); if (Collections.frequency(listImgNew, newName)>0) { newName = newName.replace(".jpg","_"+Integer.toString(Collections.frequency(listImgNew, newName))+".jpg"); } listImg.set(i, newName + ";" + oldName); listImgNew.add(newName); } }
b8eff8c5-648d-4744-93e0-80b1f0e79c67
2
void printMap() { for (int i = 0; i < _map.length; i++) { double[] row = _map[i]; for (int j = 0; j < row.length; j++) { System.out.print(_map[i][j] + "\t"); } System.out.print("\n"); } }
851470ae-059b-4f4c-9860-e40f8cba2a98
9
private void handleIOSERDES(){ // Remove ISERDES/OSERDES for(Instance inst : design.getInstances()){ if(inst.getType().equals(PrimitiveType.ISERDES) || inst.getType().equals(PrimitiveType.OSERDES)){ instancesToRemove.add(inst); } boolean foundBadInstance = false; if(inst.getName().contains("XDL_DUMMY_CLB")){ for(Attribute attr : inst.getAttributes()){ if(attr.getPhysicalName().equals("_NO_USER_LOGIC")){ foundBadInstance = true; break; } } if(!foundBadInstance){ inst.getAttributes().clear(); if(design.getExactFamilyName().contains("virtex4")){ inst.getAttributes().add(new Attribute("G","","#LUT:D=0")); inst.getAttributes().add(new Attribute("YUSED","","0")); }else if(design.getExactFamilyName().contains("virtex5")){ //TODO V5 inst.getAttributes().add(new Attribute("D6LUT","","#LUT:O6=0")); inst.getAttributes().add(new Attribute("DUSED","","0")); } } } } }
4cdc25e3-ac33-45ee-9fb6-e2f7e2516ced
2
public void setPosition(int x){ System.out.println(time); if(x < startX){ x = startX; }else if(x > startX + distance){ x = startX + distance; } rect.x = x; this.time = (x - startX) * endTime / distance; System.out.println(time); }
d34def7a-2d0a-4385-b3c0-179ea49f385f
4
public void draw(Graphics g) { g.setColor(new Color(255, 255, 250, 50)); g.fillOval(x + 1, y + 1, size, size); g.setColor(color); g.fillOval(x, y, size, size); g.setColor(new Color(255, 255, 255, 50)); g.fillOval(x + 2, y + 2, size - 4, size - 10); g.setColor(new Color(255, 255, 255, 60)); g.fillOval(x + 8, y + 5, size - 16, size - 30); if (highlighted) { for (int i = 0; i < 4; i++) { g.setColor(new Color(color.getRed(), color.getGreen(), color .getBlue(), 255 - (i * 60))); g.drawOval(x - i, y - i, size + (2 * i), size + (2 * i)); } } if (selected) { for (int i = 0; i < 10; i++) { g.setColor(new Color(color.getRed(), color.getGreen(), color .getBlue(), 255 - (i * 25))); g.drawOval(x - i, y - i, size + (2 * i), size + (2 * i)); } } }
ab4ba08a-8445-4b32-ace0-aaa15987f524
1
public MenuRenderer() { try { Background = ImageIO.read(new File(Main.loc + "/Textures/Menu/Background.png")); Button1 = ImageIO.read(new File(Main.loc + "/Textures/Menu/Button1.png")); Button2 = ImageIO.read(new File(Main.loc + "/Textures/Menu/Button2.png")); } catch (Exception e1) { //JOptionPane.showMessageDialog(null, e1.getStackTrace(), "UNABLE TO LOAD IMAGES",JOptionPane.ERROR_MESSAGE); } }
14317a59-fefa-4390-917c-b8cd1f45eb67
8
@Override public boolean okMessage(final Environmental myHost, final CMMsg msg) { if(!(myHost instanceof MOB)) return super.okMessage(myHost,msg); final MOB myChar=(MOB)myHost; if(!super.okMessage(myChar, msg)) return false; if(msg.amISource(myChar) &&(!myChar.isMonster()) &&(msg.sourceMinor()==CMMsg.TYP_DEATH) &&(myChar.baseCharStats().getClassLevel(this)>=30) &&(!myChar.baseCharStats().getMyRace().ID().equals("Lich"))) { final Race newRace=CMClass.getRace("Lich"); if(newRace!=null) { myChar.tell(L("The dark powers are transforming you into a @x1!!",newRace.name())); myChar.baseCharStats().setMyRace(newRace); myChar.recoverCharStats(); } } return true; }
605bf0a9-9e2b-45ca-90bc-01f9a0ef2c61
1
private static double rombergGradoN(double extremoIzq, double extremoDer, Funcion fun, double k, double n){ if (n == 0){ //Si el grado es 0, significa que tengo que calcular trapecio, por lo que me devuelve T(h/2^k) return trapecio(extremoIzq, extremoDer, fun, k); } else { //Devuelve Rn(h/2^k) = ((4^n * Rn-1(h/2^k+1)) - Rn-1(h/2^k)) / ((4^n) - 1) return ((Math.pow(4,n) * rombergGradoN(extremoIzq, extremoDer, fun, k + 1, n - 1)) - rombergGradoN(extremoIzq, extremoDer, fun, k, n - 1)) / (Math.pow(4, n) - 1); } }
da177e93-7545-4bb9-b392-21d9998589d3
5
public void actionPerformed(ActionEvent e) { String action = e.getActionCommand(); String str, textFinal, text; if (action.equals("SAVEMLD")) { String fileName = chooseFile(); if (fileName == null) return; try { PrintStream out = new PrintStream(new FileOutputStream( fileName)); textFinal = ""; text = mldCommand.getRequests(); for (StringTokenizer st = new StringTokenizer(text, ";", true); st.hasMoreElements();) { str = st.nextToken(); str = str.replaceAll("<u>", ""); str = str.replaceAll("</u>", ""); if (str.equals(";")) textFinal += Utilities.retourLigne() ; else textFinal += str; } out.print(textFinal); out.close(); } catch (IOException err) { Object[] messageArguments = { fileName } ; GUIUtilities.error(Utilities.getLangueMessageFormatter (Constantes.MESSAGE_IMPOSSIBLE_SAVE_FICHIER, messageArguments) ) ; } } }
baeab499-edc7-4858-a723-d9a171e16607
2
private static boolean isValueAnArmstrongNumber(int input) { // convert user int value to a String object in order to use the charAt() method StringBuffer valueAsStr = new StringBuffer(String.valueOf(input)); int combinedTotal = 0; // determine the number of digits in the users input for(int i = 0; i < valueAsStr.length(); i++ ) { String number = Character.toString(valueAsStr.charAt(i)); // Using Math.pow (power of) work out the total of each individual part of the sum. Double toPower = Math.pow(Double.valueOf(number), valueAsStr.length()); // add individual values multiplied by one another to the combinedTotal combinedTotal += toPower.intValue(); } return (combinedTotal == input) ? true : false; }
27aa46a6-b3b4-45d9-8606-c98aadf6138a
1
public void setMonthlySalary(double monthly) { if(monthly < 0) { monthlySalary =0; } else monthlySalary = monthly; }
74dae50f-298a-44a8-b7cf-4879a8418020
7
public static void main(String[] args) throws Exception { int ponder = 5; if (args.length > 0) ponder = Integer.parseInt(args[0]); int size = 5; if (args.length > 1) size = Integer.parseInt(args[1]); ExecutorService exec = Executors.newCachedThreadPool(); Chopstick[] sticks = new Chopstick[size]; for (int i = 0; i < size; i ++) sticks[i] = new Chopstick(); for (int i = 0; i < size; i++) if (i < (size - 1)) exec.execute(new Philosopher(sticks[i], sticks[i+1], i, ponder)); else exec.execute(new Philosopher(sticks[0], sticks[i], i, ponder)); if (args.length == 3 && args[2].equals("timeout")) TimeUnit.SECONDS.sleep(5); else { System.out.println("Press Enter to quit"); System.in.read(); } exec.shutdownNow(); }
7b458976-9786-4f00-a8b6-5dc5a30546df
5
public void advance() throws ControllerException { try { switch (parser.ttype) { case StreamTokenizer.TT_NUMBER: tokenType = TYPE_INT_CONST; intValue = (int)parser.nval; currentToken = String.valueOf(intValue); break; case StreamTokenizer.TT_WORD: currentToken = parser.sval; Integer object = (Integer)keywords.get(currentToken); if (object != null) { tokenType = TYPE_KEYWORD; keyWordType = object.intValue(); } else { tokenType = TYPE_IDENTIFIER; identifier = currentToken; } break; default: symbol = (char)parser.ttype; // String quote if (symbol == '"') { currentToken = parser.sval; tokenType = TYPE_IDENTIFIER; identifier = currentToken; } else { tokenType = TYPE_SYMBOL; currentToken = String.valueOf(symbol); } break; } parser.nextToken(); } catch (IOException ioe) { throw new ControllerException("Error while reading script"); } }
8fbdd4d1-d530-44ff-bb2b-adeb3234141c
1
public int getID(Class<? extends APacket> p) { return PList.indexOf(p); }
ae1d95c1-dccd-4f2d-8fc8-bc69c143a053
0
public TaskThread() { // TODO Auto-generated constructor stub }
d3e90d0e-05a4-445c-a88b-be98cb3a0500
7
public void checkCollision() { if (snake.getPosition().equals(food.getPosition())) { snake.tail.add(new Point()); food.reset(); } for (int i = 0; i < snake.tail.size() - 1; i++) { if (snake.getPosition().equals(snake.tail.get(i))) { gameOver = true; } } if (snake.getPosition().getX() < 0 || snake.getPosition().getX() > this.getWidth() - 10 || snake.getPosition().getY() < 0 || snake.getPosition().getY() > this.getHeight() - 10) { gameOver = true; } }
4cf3599f-f9db-4750-81fe-732a13b26c4a
7
private int getTarget() { InfoDetail cil = null; int state; if (this.data != null) { for (InfoDetail o : this.data.getEnemies()) { if (o != null) { cil = o; } } if (cil == null) { state = -1; return state; } int dX = Math.abs(this.x - cil.getX()); int dY = Math.abs(this.y - cil.getY()); double distance = Math.sqrt(dX * dX + dY * dY); double angle = Math.toDegrees(Math.atan(dY / dX)); System.out.println(angle+"\n"); System.out.print(dX+": X"); System.out.print(dY+": Y"); if (cil.getX() >= this.x) { if (cil.getY() >= this.y) { angle =+ angle/2; } else { angle = 360 - angle; } } if (cil.getY() >= this.y) { angle = 180 - angle; } else { angle = 180 + angle; } state = ((int)angle); return state; } state = -1; return state; }
c403f6fa-e9b6-473d-a652-ae217222ce62
2
public static final boolean isJava(String fileName) { for (String file : JAVA) { if (file.equals(fileName)) { return true; } } return false; }
9fbc806c-dbfc-446b-9729-0c5765d30521
1
static long nextMonthDay(int index){ long start=startDay.getTime(); start+=index*milliSecondsOnyDay; Calendar calendar=new GregorianCalendar(TimeZone.getTimeZone("GMT")); calendar.setTime(new Date(start)); int thisMonthDay=calendar.get(Calendar.DAY_OF_MONTH); calendar.add(Calendar.MONTH,1); int nextMonthDay=calendar.get(Calendar.DAY_OF_MONTH); if(thisMonthDay!=nextMonthDay){ return -1; } return index+ (calendar.getTime().getTime()-start)/milliSecondsOnyDay; }
449ce2f4-3f8c-46b9-94e9-9305d5907871
7
@Override public void processPacket(final Client c, int packetType, int packetSize) { c.walkingToItem = false; c.pItemY = c.getInStream().readSignedWordBigEndian(); c.pItemId = c.getInStream().readUnsignedWord(); c.pItemX = c.getInStream().readSignedWordBigEndian(); if (Math.abs(c.getX() - c.pItemX) > 25 || Math.abs(c.getY() - c.pItemY) > 25) { c.resetWalkingQueue(); return; } c.getCombat().resetPlayerAttack(); if(c.getX() == c.pItemX && c.getY() == c.pItemY) { Server.itemHandler.removeGroundItem(c, c.pItemId, c.pItemX, c.pItemY, true); } else { c.walkingToItem = true; CycleEventHandler.getSingleton().addEvent(c, new CycleEvent() { @Override public void execute(CycleEventContainer container) { if(!c.walkingToItem) container.stop(); if(c.getX() == c.pItemX && c.getY() == c.pItemY) { Server.itemHandler.removeGroundItem(c, c.pItemId, c.pItemX, c.pItemY, true); container.stop(); } } @Override public void stop() { c.walkingToItem = false; } }, 1); } }
6b9988a8-a0ba-4991-9ba7-24005455a43d
6
private void find(ArrayList<Integer> current, HashMap<Integer, Boolean> diagonal1, HashMap<Integer, Boolean> diagonal2, ArrayList<String[]> result, int n) { if (current.size() == n) { result.add(getFormartStrings(current)); } else { //find available column int row = current.size(); for (Integer col : available(current, n)) { if ((diagonal1.get(row + col) == null || diagonal1.get(row + col) == false) && (diagonal2.get(row - col) == null || diagonal2.get(row - col) == false)) { current.add(col); diagonal1.put(row + col, true); diagonal2.put(row - col, true); find(current, diagonal1, diagonal2, result, n); current.remove(current.size() - 1); diagonal1.put(row + col, false); diagonal2.put(row - col, false); } } } }
263eb614-8770-4f47-903a-074cfb1225b6
2
public AcyclicLP(EdgeWeightedDigraph G, int s) { distTo = new double[G.V()]; for (int i = 0; i < G.V(); i++) distTo[i] = Double.NEGATIVE_INFINITY; distTo[s] = 0; edgeTo = new WeightedDirectedEdge[G.V()]; Topological topological = new Topological(G.digraph()); for (Integer v : topological.order()) relax(G, v); }
ee63f084-9a9a-4a6b-9511-e59e94bbf600
0
public Integer getErrorType() { return this.errorType; }
146729f6-728f-487d-82ab-3220256959f6
4
private void play() { Player[] pList = new Player[playerNumber]; ArrayList<Color> factions = Faction.allFactions(); ArrayList<PlayerInfo> infoList = new ArrayList<PlayerInfo>(infos.length); for(PlayerInfo info : infos) { infoList.add(info); } Random random = new Random(); int index = 0; while(infoList.size() != 0) { int next = random.nextInt(infoList.size()); pList[index] = infoList.remove(next) .getPlayer(chooseFaction(factions)); index++; } GameState temp = null; try { temp = new GameState(pList, new Board(), decks[deckSelect.getSelectedIndex()].newInstance(), bags[bagSelect.getSelectedIndex()].newInstance(), counters[counterSelect.getSelectedIndex()].newInstance()); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } final GameState state = temp; Thread gameThread = new Thread() { public void run () { Game.run(state, getSettings()); } }; gameThread.start(); Thread t = new Thread() { public void run () { SwingUtilities.invokeLater(new Runnable() { public void run () { frame.dispose(); settingsFrame.dispose(); } }); } }; t.start(); }
f46972cb-bb9f-483b-8038-9a4cfd4752c0
8
public String formatHTMLTable(StatCollector stat){ add("<!doctype HTML>"); add("<html>"); add("<body>"); add("<table border=1>"); add("<tr>Server statistic:"); // Total requests add("<tr><td>Total requests<td>"); add(stat.getRequests()); // Unique requests number add("<tr><td>Unique IP requests<td>"); add(stat.getUniqIPRequestsNumber()); //Unique requests table add("<tr><td>Unique IP requests details"); add("<td><table cellpadding=10 width=\"100%\">"); if(stat.getUniqIPRequests().size() > 0){ add("<tr><td>IP address<td>Requests number<td>Last request date"); } for(ProcessedRequest req:stat.getUniqIPRequests()){ add("<tr><td>"); add(req.getIPAddress()); add("<td>"); add(req.getRequestsNumber()); add("<td>"); add(req.getLastRequestDate()); } add("</table>"); //Redirections table add("<tr><td>Redirections table"); add("<td><table cellpadding=10>"); if(stat.getRedirects().keySet().size() > 0){ add("<tr><td>Redirect URL<td>Redirects number"); } for(String url:stat.getRedirects().keySet()){ add("<tr><td>"); add(url); add("<td>"); add(stat.getRedirects().get(url)); } add("</table>"); //Opened connections number add("<tr><td>Opened connections number<td>"); add(stat.getOpenedConnections()); //Last processed connections table add("<tr><td>Last processed connections"); add("<td><table cellpadding=10>"); List<ProcessedConnection> connections = stat.getProcessedConnections(); if(connections.size() > 0){ //print row with columns headers add("<tr>"); for(String colName:connections.get(0).getHeader()){ add("<td>"); add(colName); } //print cell values, skipping first row, that relates to current connection and is incomplete for(ProcessedConnection conn:connections.subList(1, connections.size())){ add("<tr>"); for(String cellValue:conn.getValues()){ add("<td>"); add(cellValue); } } } add("</table>"); //end add("</table>"); add("</body>"); add("</html>"); return sb.toString(); }
1bfcefec-d0af-4387-b55c-b8300ca21e69
8
public void saveGame() { File file = new File("Saved_Games.txt"); FileWriter writer; boolean flag = false; ArrayList<String> data = new ArrayList<String>(); ListIterator<String> iterator; String currentPuzzle = getCurrentPuzzle(); try { Scanner s = new Scanner(file); while(s.hasNextLine()) { data.add(s.nextLine()); } s.close(); iterator = data.listIterator(); while(iterator.hasNext()) { if(iterator.next().equals(user.getUsername())) { iterator.next(); iterator.set(difficulty); iterator.next(); iterator.set("16x16"); iterator.next(); iterator.set(String.valueOf(currentTime)); iterator.next(); iterator.set(String.valueOf(numberOfHints)); if(iterator.hasNext()) { iterator.next(); iterator.set(currentPuzzle); flag = true; break; } else { data.add(currentPuzzle); break; } } } if(flag == false) { data.add(user.getUsername()); data.add(difficulty); data.add("16x16"); data.add(String.valueOf(currentTime)); data.add(String.valueOf(numberOfHints)); data.add(currentPuzzle); } writer = new FileWriter("Saved_Games.txt"); iterator = data.listIterator(); while(iterator.hasNext()) { writer.write(iterator.next()); writer.write("\n"); } writer.close(); } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(null, "Could not find Saved_Games. Contact system administrator.", "Error", JOptionPane.ERROR_MESSAGE); } catch (IOException e) { JOptionPane.showMessageDialog(null, "Could not update Saved_Games. Contact system administrator.", "Error", JOptionPane.ERROR_MESSAGE); } setUserSavedGame("true"); user.setHasSavedGame(true); }
ceaf7e33-fe78-4281-bc19-c95a30df76fd
0
public TaskWithResult(int id) { this.id = id; }
82960d33-fe3b-47ae-800f-aa19950400f0
2
static public HashMap<String, String[]> loadDomain(){ try{ @SuppressWarnings("resource") BufferedReader csvFile = new BufferedReader(new FileReader("parserResult/authorDomain.csv")); String[] dataArray; String target; while((target = csvFile.readLine())!= null){ dataArray = target.split(","); domaindataresult.put(dataArray[0], dataArray); } }catch(IOException e){ } return domaindataresult; }
e387af63-65b5-4cbb-84f9-1d4064d26929
7
private int maximised_triangles() { int a; int b; HashMap<Integer,Integer> store = new HashMap<Integer,Integer>(); for(a = 1; a < 1000; a++) { for(b = 1; b < 1000; b++) { double c = Math.sqrt(IntMath.pow(a, 2) + IntMath.pow(b, 2)); if(Math.floor(c) == c) { int perimeter = a+b+(int)c; if(perimeter < 1000) { if(store.containsKey(perimeter)) { store.put(perimeter, store.get(perimeter) + 1); } else { store.put(perimeter, 1); } } } } } int max = 0; int max_perimeter = 0; for(int x : store.keySet()) { if(store.get(x) > max) { max = store.get(x); max_perimeter = x; } } return max_perimeter; }
4bdc17a7-536b-40be-89c4-48fdabe57b78
5
private static void EnemyMoveChoice(){ if(opponentHealth > 0){ Random rng = new Random(); int move = 1 + rng.nextInt(4); //move = 2; switch(move){ case 1: System.out.println("Zubat used Tackle!"); System.out.print("\n"); // line break playerHealth = DealDamage(playerHealth, tackle); break; case 2: System.out.println("Zubat used Lifeleech!"); System.out.print("\n"); // line break playerHealth = DealDamage(playerHealth, lifeLeech); opponentHealth = DealDamage(opponentHealth, -lifeLeech); break; case 3: System.out.println("Zubat used Supersonic!"); System.out.println("It missed!"); System.out.print("\n"); // line break break; case 4: System.out.println("Zubat used Bite!"); System.out.print("\n"); // line break playerHealth = DealDamage(playerHealth, tackle); break; default: System.out.println("Zubat is confused..."); System.out.print("\n"); // line break break; } } }
907db2a6-c90a-460a-b020-d856e61a2453
5
@EventHandler(priority = EventPriority.HIGH) public void registerAccount(PlayerJoinEvent event) { final Player player = event.getPlayer(); final User user = EdgeCoreAPI.userAPI().getUser(player.getName()); if (user == null) return; if (!Economy.isAllowAccounts()) return; try { if (Economy.isAutoCreateAccounts()) { if (economy.hasAccount(user)) return; economy.registerAccount(user.getUUID(), 500D, 0); player.sendMessage(lang.getColoredMessage(user.getLanguage(), "acc_apply_success").replace("[0]", economy.getAccount(user).getId() + "")); } else { Bukkit.getScheduler().runTaskTimer(EdgeConomy.getInstance(), new Runnable() { @Override public void run() { player.sendMessage(lang.getColoredMessage(user.getLanguage(), "registration_eco_accinfo")); } }, 20L * 5, 20L * 60 * 15); } } catch(Exception e) { e.printStackTrace(); player.sendMessage(lang.getColoredMessage(user.getLanguage(), "globalerror")); } }
2201afdb-1bda-4ad4-984e-5df4fbae71f2
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(PrefixSelectionTo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(PrefixSelectionTo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(PrefixSelectionTo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(PrefixSelectionTo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new PrefixSelectionTo().setVisible(true); } }); }
e65724f2-273a-4fb6-a920-b931ff78dc87
1
public void startBall() { _isBallStart = false; for (int i = 0; i < _gameField.balls().size(); i++) { _gameField.balls().get(i).setSpeed(0, -0.3); } }
4f44a368-8f7f-4708-a938-db2eac272421
7
public boolean canCastle(Castle castle) { if(!castle.isValid(this)) { return false; } Move kingMove = castle.getKingMove(); Move rookMove = castle.getRookMove(); if(get(kingMove.getFrom()).hasMoved() || get(rookMove.getFrom()).hasMoved()) { return false; } if(!isEmpty(kingMove.getTo()) || !isEmpty(rookMove.getTo())) { return false; } if(kingMove.getDirection() == Direction.KingCastleLeft && !isEmpty(new Position(kingMove.getFrom(), Direction.Left))) { return false; } // TODO Check if king.getTo or rook.getTo is menaced return true; }
0c6bab5a-506b-4a1a-8a32-ff7d829b1317
3
@Override public String processCommand(String[] arguments) throws SystemCommandException { String guid = facade.getCurrentUserGUID(); if (guid == null) throw new SystemCommandException("No current user set."); Date start = DateUtil.parseArgumentDate(arguments[1], arguments[2]); Date stop = DateUtil.parseArgumentDate(arguments[3], arguments[4]); String electorateID = arguments[0]; Date openNominations; if (arguments.length == 7) openNominations = DateUtil.parseArgumentDate(arguments[5], arguments[6]); else openNominations = null; try { facade.editElection(openNominations, start, stop, electorateID); } catch (RuntimeException e) { throw new SystemCommandException(e.getMessage()); } return "Edited election details."; }
56547681-760d-4a0d-afd7-4009b2129791
9
public NamiBeitragConfiguration(File configFile) throws ConfigFormatException { // Lese Konfigurationsdatei ein (inkl. Validierung) Document doc; try { XMLReaderJDOMFactory schemafac = new XMLReaderXSDFactory(XSDFILE); SAXBuilder builder = new SAXBuilder(schemafac); log.info("Using Beitrag config file: " + configFile.getAbsolutePath()); if (!configFile.exists() || !configFile.canRead()) { throw new ConfigFormatException("Cannot read config file"); } doc = builder.build(configFile); } catch (JDOMException e) { throw new ConfigFormatException("Could not parse config file", e); } catch (IOException e) { throw new ConfigFormatException("Could not read config file", e); } // Parse Konfiguration aus XML Element namibeitragEl = doc.getRootElement(); if (namibeitragEl.getName() != "namibeitrag") { throw new ConfigFormatException("Wrong root element in config file"); } gruppierungsnummer = namibeitragEl .getAttributeValue("gruppierungsnummer"); // Datenbankverbindung aus XML lesen Element databaseEl = namibeitragEl.getChild("database"); databaseConfig = new Properties(); databaseConfig.setProperty("driver", databaseEl.getChildText("driver")); databaseConfig.setProperty("url", databaseEl.getChildText("url")); databaseConfig.setProperty("username", databaseEl.getChildText("username")); databaseConfig.setProperty("password", databaseEl.getChildText("password")); // Beitragssätze aus XML einlesen Element beitragssaetzeEl = namibeitragEl.getChild("beitragssaetze"); beitragssaetze = new HashMap<>(); for (Element satzEl : beitragssaetzeEl.getChildren("beitragssatz")) { String typStr = satzEl.getAttributeValue("typ"); Beitragsart typ = Beitragsart.fromString(typStr); String betragStr = satzEl.getAttributeValue("betrag"); BigDecimal betrag = new BigDecimal(betragStr); beitragssaetze.put(typ, betrag); } // SEPA-Parameter einlesen Element sepaEl = namibeitragEl.getChild("sepa"); sepaCreditorId = sepaEl.getChildText("creditorId"); sepaType = sepaEl.getChildText("lastschriftType"); if (sepaType == null || sepaType.isEmpty()) { sepaType = "CORE"; } sepaMRefPrefix = sepaEl.getChildText("mrefPrefix"); if (sepaMRefPrefix == null) { sepaMRefPrefix = ""; } hibiscusUrl = sepaEl.getChildText("hibiscusUrl"); hibiscusKontoId = sepaEl.getChildText("hibiscusKontoId"); pdfViewer = namibeitragEl.getChildText("pdfViewer"); letterOutputPath = namibeitragEl.getChildText("letterOutputPath"); }
97e7f143-2b0a-4957-9bd6-09da8adee7ce
5
public static void saveProperties(Properties props, File propertyFile, String headerText) { OutputStream out = null; try { out = new FileOutputStream(propertyFile); if (StringUtils.isNotBlank(headerText)) { props.store(out, headerText); } } catch (FileNotFoundException ex) { LOG.warn("Failed to find properties file", ex); } catch (IOException ex) { LOG.warn("Failed to read properties file", ex); } finally { if (out != null) { try { out.flush(); out.close(); } catch (IOException ex) { LOG.warn("Failed to close properties file", ex); } } } }
322933d7-8e02-4e84-86d7-6a4977cf724f
9
private String determinePixelSymbol(int intensity) { String result = null; if (intensity > 240) { result = " "; } else if (intensity > 200) { result = "."; } else if (intensity > 160) { result = "^"; } else if (intensity > 120) { result = "*"; } else if (intensity > 90) { result = "&"; } else if (intensity > 50) { result = "%"; } else if (intensity > 30) { result = "$"; } else if (intensity > 20) { result = "@"; } else if (intensity >= 0) { result = "#"; } return result; }
d75c9c43-7341-4dcf-9db9-5796c99023b1
0
@Override public void modifiedStateChanged(DocumentEvent e) {}
b7d90e69-3697-4aa0-be3a-0f8247089961
1
private void saveXMLFile(ArrayList<String[]> data) { String xml = createXMLString(data); File xmlfile = new File("ports.xml"); // OutputStreamWriter to enable forcing UTF-8 encoding. OutputStreamWriter writer = null; try { writer = new OutputStreamWriter(new FileOutputStream(xmlfile), Charset.forName("UTF-8").newEncoder()); writer.write(xml); writer.close(); } catch (IOException e) { logger.log(Level.SEVERE, "Error writing to ports.xml", e); } }
e18b3f1d-5de1-4413-84b9-c479590d3b87
2
private String collectionsAsString(List<String> list) { String str = "( "; Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { String s = iterator.next(); str += s; if (iterator.hasNext()) { str += " ,"; } } str += " )"; return str; }
05d34c26-6fa5-468c-bc0d-ad114da72200
2
public void updateStatus(String text) { if (text.length() + statusText.length() > MAX_STATUS_SIZE) { // Remove the last line statusText.delete(statusText.lastIndexOf("\n"),statusText.length()); } // Update the master text statusText.insert(0, text+"\n"); // And then add it to the text area if (statusPanel != null) { statusPanel.setText(statusText.toString()); } }
29b81134-1a1a-4fd9-bceb-dc748491eee3
1
public int getSize() throws IteratorException { int size = 0; if (list != null) { size = list.size(); } else { throw new IteratorException(); //No Data } return size; }
dfbef4bb-7c50-40d7-b79f-e4ca85b988b9
7
public JSONNode addArrayElement(Object value) { NodeType type; if (getNodeType() != NodeType.ARRAY) return null; type = null; if (value != null) { if (value instanceof Boolean) type = NodeType.PRIMITIVE; else if (value instanceof Integer) type = NodeType.PRIMITIVE; else if (value instanceof Double) type = NodeType.PRIMITIVE; else if (value instanceof String) type = NodeType.PRIMITIVE; else if (value.getClass().isArray()) type = NodeType.ARRAY; else type = NodeType.OBJECT; } return add(null, value, type); }
2fdf264e-c27d-49f2-91e9-81320f021b1b
1
public static void addPreLive(final String name) { if (CallGraph.preLive == null) { CallGraph.init(); } CallGraph.preLive.add(name); }
4b579eeb-03d9-442f-b52a-f021383182f7
9
private void zoom(double upperLeftX2, double upperLeftY2, double utmWidth2, double utmHeight2, boolean zoomIn, double x1utm2, double x2utm2, double y1utm2, double y2utm2) { if(zoomIn) { if(x1utm2 > x2utm2) { //If x1 > x2 then switch double temp = x1utm2; x1utm2 = x2utm2; x2utm2 = temp; } if(y1utm2 > y2utm2) { //If y1 > y1 then switch double temp = y1utm2; y1utm2 = y2utm2; y2utm2 = temp; } if(utmWidth == 1500 || utmHeight == 1500) { repaint(); return; } if(x2utm2-x1utm2 < 1500 || y2utm2-y1utm2 < 1500) { //You can't zoom more than this (1500m in either width or height) utmWidth = 1500; utmHeight = 1500; } else { utmWidth = x2utm2-x1utm2; utmHeight = y2utm2-y1utm2; } upperLeftX += x1utm2; upperLeftY -= y1utm2; } else { upperLeftX = upperLeftX2; upperLeftY = upperLeftY2; utmWidth = utmWidth2; utmHeight = utmHeight2; } if(utmWidth/utmHeight < preferredRatio) { this.utmWidth = utmHeight * preferredRatio; } else if(utmWidth/utmHeight > preferredRatio) { this.utmHeight = utmWidth / preferredRatio; } utmWidthRelation = utmWidth/1000; utmHeightRelation = utmHeight/1000; calculateZoomLvl(); calculateFactor(); //A new query with the new interval is made and all the nodes in this interval is redrawn with the new factor queryQT(new Interval<Double>(upperLeftX, upperLeftX+utmWidth), new Interval<Double>(upperLeftY, upperLeftY-utmHeight)); edges = qt.getEdges(); drawGraph(edges, width, height); repaint(); }
0f4e0933-c4e2-4f64-be1c-4d0e63cfff2e
2
public String getCreditByUID(Statement statement,String UID)//根据用户名获取信用度 { String result = null; sql = "select credit from Users where UID = '" + UID +"'"; try { ResultSet rs = statement.executeQuery(sql); while (rs.next()) { result = rs.getString("credit"); } } catch (SQLException e) { System.out.println("Error! (from src/Fetch/Users.getCreditByUID())"); // TODO Auto-generated catch block e.printStackTrace(); } return result; }
1836bf1e-003f-42db-b0ce-9ebab41526c8
7
private void addIgnore(long l) { try { if(l == 0L) return; if(ignoreCount >= 100) { pushMessage("Your ignore list is full. Max of 100 hit", 0, ""); return; } String s = TextClass.fixName(TextClass.nameForLong(l)); for(int j = 0; j < ignoreCount; j++) if(ignoreListAsLongs[j] == l) { pushMessage(s + " is already on your ignore list", 0, ""); return; } for(int k = 0; k < friendsCount; k++) if(friendsListAsLongs[k] == l) { pushMessage("Please remove " + s + " from your friend list first", 0, ""); return; } ignoreListAsLongs[ignoreCount++] = l; needDrawTabArea = true; stream.createFrame(133); stream.writeQWord(l); return; } catch(RuntimeException runtimeexception) { signlink.reporterror("45688, " + l + ", " + 4 + ", " + runtimeexception.toString()); } throw new RuntimeException(); }
7880d215-6e52-4340-bccd-e1fb3bce1cdd
3
@Override public GameState doAction(GameState state, Card card, int time) { if(time == Time.DAY) { state = beggarDayAction(state, card); } else if(time == Time.DUSK) { PickTreasure temp = new PickTreasure(); state = temp.doAction(state, card, time); } else if(time == Time.NIGHT) { //Do nothing } return state; }
155e4c59-6799-4dde-ae6a-94894283ed17
0
public Person3(String pname){ name = pname; }
5c39f42a-37b4-4a25-8bfc-927abeacd6a3
1
private void printRow(String header, String[] cells) { printCell(header); for (String cell : cells) { printCell(cell); } System.out.println(); }
cddf89e5-8ff6-4b4c-a52d-43d6d26983c0
1
private int readCodeBit() throws IOException { int temp = input.read(); // read one digit after freq in inputBitstream if (temp != -1) return temp; else // Treat end of stream as an infinite number of trailing zeros return 0; }
2965ae17-6649-424b-9cbf-003be582b783
6
public static String unescape(String string) { int length = string.length(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; ++i) { char c = string.charAt(i); if (c == '+') { c = ' '; } else if (c == '%' && i + 2 < length) { int d = JSONTokener.dehexchar(string.charAt(i + 1)); int e = JSONTokener.dehexchar(string.charAt(i + 2)); if (d >= 0 && e >= 0) { c = (char)(d * 16 + e); i += 2; } } sb.append(c); } return sb.toString(); }
e65a3606-05f1-4f02-8674-a1a1150a795d
5
protected void searchByName(String mask) { if (mask.isEmpty()) { searchFromIdx = 0; return; } try { Pattern p = Pattern.compile(mask); ArrayList<CourseRec> all = courseModel.getFilteredCourses(); for (int i = searchFromIdx; i < all.size(); i++) { CourseRec cr = all.get(i); if (p.matcher(cr.getName()).find()) { selectCourse(cr); searchFromIdx = i; return; } } // If not found, restart from the top. This goes recursively once. if (searchFromIdx > 0) { searchFromIdx = 0; searchByName(mask); } } catch (Exception e) { } }
0f41def3-8be2-4278-a4e2-1b8ef4e07c4a
5
private boolean isCrossWin(){ if(model.getField().getCell(1, 1)==Field.DEFAULT_VALUE) return false; if( (model.getField().getCell(1, 1) == model.getField().getCell(0, 0) && model.getField().getCell(1, 1) == model.getField().getCell(2, 2)) || (model.getField().getCell(1, 1) == model.getField().getCell(2, 0) && model.getField().getCell(1, 1) == model.getField().getCell(0, 2)) ) return true; else return false; }
910b9ab8-7ac9-4943-b3de-146fe5937cdb
0
@Override public String toString(){ return "id= "+this.getId()+", "+this.getName()+"\n"+getTime()+"\n"+"Ребро: "+this.getEdge()+"\n"+"Высота: "+this.getHig()+"\n"+"Сумма рёбер: "+this.getSum()+"\n"+" Площадь грани: "+this.getArea_surf()+"\n"+"S=: "+this.getArea()+" V=: "+this.getVolume()+"\n"; }
f1e2b604-6499-4d76-a7cf-d8862c91eb0f
2
public static String[] concatenateStringArrays(String[] array1, String[] array2) { if (SpringObjectUtils.isEmpty(array1)) { return array2; } if (SpringObjectUtils.isEmpty(array2)) { return array1; } String[] newArr = new String[array1.length + array2.length]; System.arraycopy(array1, 0, newArr, 0, array1.length); System.arraycopy(array2, 0, newArr, array1.length, array2.length); return newArr; }
71aeb2ed-a631-47a5-be5d-9c21da6da600
4
public Matrix plus(Matrix B) { Matrix A = this; if (B.M != A.M || B.N != A.N) { throw new RuntimeException("Illegal matrix dimensions."); } Matrix C = new Matrix(M, N); for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { C.data[i][j] = A.data[i][j] + B.data[i][j]; } } return C; }
b91712ed-02ab-4537-88da-8a87af596b22
6
public static void main(String[] args) throws Exception { int ponder = 5; if (args.length > 0) ponder = Integer.parseInt(args[0]); int size = 3; if (args.length > 1) size = Integer.parseInt(args[1]); ExecutorService exec = Executors.newCachedThreadPool(); Chopstick[] sticks = new Chopstick[size]; for (int i = 0; i < size; i++) sticks[i] = new Chopstick(); for (int i = 0; i < size; i++) exec.execute(new Philosopher(sticks[i], sticks[(i + 1) % size], i, ponder)); if (args.length == 3 && args[2].equals("timeout")) TimeUnit.SECONDS.sleep(5); else { System.out.println("Press 'Enter' to quit"); System.in.read(); } exec.shutdownNow(); }
41cf69f5-90a3-4f0a-b026-1ea992eb9fb9
0
public List<ParkBoy> getBoyList() { return boyList; }
8881b603-daa3-48b8-829e-1903fdbc54cc
5
public void hits() { if (getState() != STATE_HIT) { setCanHitEnemy(false); setSpeed(0f); setState(STATE_HIT); switch (getFacing()) { case Entity.UP: moveY(-50); break; case Entity.DOWN: moveY(50); break; case Entity.LEFT: moveX(-50); break; case Entity.RIGHT: moveX(50); break; } } }
882e2462-238e-488c-8254-1a8ed299967c
3
public void cliqueDeclin() { if( etape == 0 && joueurEnCours.getPeupleDeclin() == null && Game.getInstance().askConf("Confirmer le passage en déclin ?") ){ //joueurEnCours.getPeuple().decliner(); //joueurSuivant(); tempEnDeclin = true; setEtape(2); miseEnMain(); Game.getInstance().showTemp(joueurEnCours.getNom() + " se redéploie."); } Game.getInstance().majInfos(); }
4347b1cf-d2ce-4770-b3ff-c69daf68d879
5
public void run() { edge.addElement(GridCell.getStartCell()); int attempts =0;// variable to count how many attempts int state=NOT_FOUND; while(state==NOT_FOUND && attempts<maxSteps)//while a path hasnt been found and the whole grid hasnt been checked { attempts++; state = step();//sets state to output of step try { Thread.sleep(speed*10);//sleep } catch(InterruptedException e){} } if(state==FOUND)//if a path has been found { try { Path.setPath(map);//runs the find path method in the path class } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { System.out.println("No Path Found"); JOptionPane.showMessageDialog(null,"No Path Can Be Found"); AStar.running=false;// sets the booleans to false to let the searches run again Dijkstra.running=false; GridCell.startmove=false; } }
c06b541a-44f2-4d69-850f-0d822fbc2bbf
8
public LocalLog(String className) { // get the last part of the class name this.className = LoggerFactory.getSimpleClassName(className); Level level = null; if (classLevels != null) { for (PatternLevel patternLevel : classLevels) { if (patternLevel.pattern.matcher(className).matches()) { // if level has not been set or the level is lower... if (level == null || patternLevel.level.ordinal() < level.ordinal()) { level = patternLevel.level; } } } } if (level == null) { // see if we have a level set String levelName = System.getProperty(LOCAL_LOG_LEVEL_PROPERTY); if (levelName == null) { level = DEFAULT_LEVEL; } else { Level matchedLevel; try { matchedLevel = Level.valueOf(levelName.toUpperCase()); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Level '" + levelName + "' was not found", e); } level = matchedLevel; } } this.level = level; }
92343c05-c8ca-4bf0-abf8-395f265fe5d9
4
@Test public void testGetDefaults() { List<String> keys = new ArrayList<String>(); List<String> args = Arrays.asList("get"); String scriptResult = ""; try { scriptResult = (String) _luaScript.callScript("config.lua", keys, args); } catch (LuaScriptException e1) { System.out.println("Exception: " + e1.getMessage()); fail(e1.getMessage()); } Map<String, Object> result = JsonHelper.parseMap(scriptResult); for (String key : result.keySet()) { if (key.equals("application")) { assertEquals("qless", result.get(key)); } if (key.equals("heartbeat")) { assertEquals(60, result.get(key)); } } }
02f52212-2d40-4489-9c39-d2d93be4b0ef
4
public static boolean isOpp(ChipColor color1, ChipColor color2) { if((color1 == BLACK && color2 == WHITE) || (color1 == WHITE && color2 == BLACK)) return true; else return false; }
05ae097d-f144-45da-a8db-d2fd1253a2c3
4
public void savePlayerMap(boolean resetValues) { if (resetValues) { for (Player Player : PlayerMap.values()) { resetPlayerData(Player); } } checkFile(); try { FileOutputStream fos = new FileOutputStream(getFile()); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(PlayerMap); oos.close(); fos.close(); } catch (IOException e) { Bukkit.broadcastMessage("D4 PeaceKeeper has encountered an error: " + e.getMessage()); } try { printPlayerData(); } catch (IOException e) { Bukkit.broadcastMessage("D5 PeaceKeeper has encountered an error: " + e.getMessage()); } }
d7cbf4e4-1847-425e-8e2c-982c92e16189
6
public void maxHeapify(int[] A, int len, int n) { while (n <= len / 2) { int max = n; int left = n << 1; if (left <= len && A[max] < A[left]) { max = left; } int right = (n << 1) + 1; if (right <= len && A[max] < A[right]) { max = right; } if (n == max) { return; } swap(A, max, n); n = max; } }
e61f5771-cce3-45cf-9c01-5338ad6fb4a1
9
public Shape select(int qx, int qy) { for (int i = shapes.size() - 1; i >= 0; i--) { Shape shape = shapes.get(i); if (shape instanceof Square) { if (testInSquare((Square) shape, qx, qy)) { System.out.println("Square selected!"); return shape; } } else if (shape instanceof Circle) { if (testInCircle((Circle)shape, qx, qy)) { System.out.println("Circle selected!"); return shape; } } else if (shape instanceof Rectangle) { if (testInRectangle((Rectangle)shape, qx, qy)) { System.out.println("Rectangle selected!"); return shape; } } else if (shape instanceof Ellipse) { if (testInEllipse((Ellipse)shape, qx, qy)) { System.out.println("Ellipse selected"); return shape; } } } return null; }
4a6056b1-75cc-4b94-bec7-8f7243ddf333
0
public VueComptesRendus getVue() { return vue; }
96850782-02f6-41de-84d3-8c767fdd5c63
0
protected void interrupted() { end(); }
1f788b31-5656-45a6-aefd-f334bee25f37
1
private void invokeInsn(final int opcode, final Type type, final Method method) { String owner = type.getSort() == Type.ARRAY ? type.getDescriptor() : type.getInternalName(); mv.visitMethodInsn(opcode, owner, method.getName(), method.getDescriptor()); }
fec41728-ce23-4dcb-962a-6a4eb4c5c94b
6
public String toString() { if (x!=0 && y>0) { return x+" + "+y+"i"; } if (x!=0 && y<0) { return x+" - "+(-y)+"i"; } if (y==0) { return String.valueOf(x); } if (x==0) { return y+"i"; } // shouldn't get here (unless Inf or NaN) return x+" + i*"+y; }