method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
60bc07a4-1e34-4856-b66d-801744d71b16
9
public static void main(String[] args) throws IOException { FileSystem fs = FileSystem.get(new Configuration()); Path[] pages = FileUtil.stat2Paths(fs.listStatus(new Path(args[0]), new PathFilter(){ @Override public boolean accept(Path path) { return path.getName().endsWith(".html"); } })); FSDataOutputStream number = fs.create(PageIndexer.DEFAULT_PATH); for(int i = 0; i < pages.length; i++) { number.write(String.format("%s\t%d\n", pages[i].getName(), i).getBytes()); } number.flush(); number.close(); double[][] matrix = new double[pages.length][pages.length]; PageIndexer indexer = new PageIndexer(new Configuration(), PageIndexer.DEFAULT_PATH); Pattern link = Pattern.compile("<a *href=\"(.*?)\"", Pattern.MULTILINE); for(Path page : pages) { InputStream input = fs.open(page); byte[] data = new byte[input.available()]; input.read(data); input.close(); Matcher linkMatcher = link.matcher(new String(data)); int src = (int)indexer.queryNumber(new Text(page.getName())).get(); for(int i = 0; i < pages.length; i++) { matrix[src][i] = 0.0; } while(linkMatcher.find()) { int dest = (int)indexer.queryNumber(new Text(linkMatcher.group(1))).get(); matrix[src][dest] = 1; } double sum = 0; for(int i = 0; i < pages.length; i++) { sum += matrix[src][i]; } for(int i = 0; i < pages.length; i++) { matrix[src][i] /= sum; } } PageRankOutputFormat.init(); double d = 1; HTable t = new HTable(HBaseConfiguration.create(), PageRankOutputFormat.TABLE_NAME); do { for(int i = 0; i < pages.length; i++) { double sum = 0; for(int j = 0; j < pages.length; j++) { Get get = new Get(String.valueOf(j).getBytes()); Result r = t.get(get); double val = Double.parseDouble(new String(r.getValue( PageRankOutputFormat.COLUMN_NAME.getBytes(), "old".getBytes()))); sum += (matrix[j][i] * val); } Put put = new Put(String.valueOf(i).getBytes()); put.add(PageRankOutputFormat.COLUMN_NAME.getBytes(), "new".getBytes(), String.valueOf(sum).getBytes()); t.put(put); } d = PageRankOutputFormat.deltaVectorNorm(); t.flushCommits(); } while(d > 0.00001); t.close(); indexer.close(); fs.close(); }
cde95637-e140-4da6-b30d-6fae2562edc1
4
private Koordinate getMax(WarMachine warMachine, Koordinate koord, Ausrichtung ausrichtung) { switch (ausrichtung) { case XPLUS: return new Koordinate(koord.getX() + warMachine.getLaenge() - 1, koord.getY() + warMachine.getBreite() - 1); case XMINUS: return koord; case YPLUS: return new Koordinate(koord.getX(), koord.getY() + warMachine.getLaenge() - 1); case YMINUS: return new Koordinate(koord.getX() + warMachine.getBreite() - 1, koord.getY()); default: break; } return null; }
4d728a7c-62d4-4d22-8a73-ce57f06f10bb
3
public static int getMouseButtonCode(MouseEvent e) { switch (e.getButton()) { case MouseEvent.BUTTON1: return MOUSE_BUTTON_1; case MouseEvent.BUTTON2: return MOUSE_BUTTON_2; case MouseEvent.BUTTON3: return MOUSE_BUTTON_3; default: return -1; } }
abc78712-df69-47cc-bfa3-879213424867
9
public synchronized boolean equals(Object obj) { if (!(obj instanceof BatchFileFetchResult)) return false; BatchFileFetchResult other = (BatchFileFetchResult) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = super.equals(obj) && ((this.batchFiles==null && other.getBatchFiles()==null) || (this.batchFiles!=null && this.batchFiles.equals(other.getBatchFiles()))) && this.recordCount == other.getRecordCount(); __equalsCalc = null; return _equals; }
c45d8b0a-dc79-44e8-b238-f88d28f96be3
6
private boolean validarDatos() { //unicamente valido el numero de cuenta boolean valido = false; Validaciones val = new Validaciones(); if (jTextField1.getText().equals("") || jTextField2.getText().equals("")){ mensajeError("Ingrese un valor para Desde.. Hasta."); } else{ if (!val.isInt(jTextField1.getText()) || !val.isInt(jTextField2.getText())){ mensajeError("Ingrese un valor NUMERICO para Desde.. Hasta."); } else{ if ((Integer.parseInt(jTextField1.getText())>0) || (Integer.parseInt(jTextField1.getText())>0)){ valido = true; mensajeError(" "); } else{ mensajeError("Ingrese un valor POSITIVO para Desde.. Hasta."); } } } return valido; }
a9d540ff-7c75-4790-a55f-d1acac8d9194
3
private void createWheel(int n, boolean edges) { double d = canvas.getHeight() / 3 * Math.sqrt(n) / 5; createVertex(0.0, 0.0, getNewVertexID()); for (int i = 0; i < n; ++i) { createVertex(d * Math.sin(i * 2 * Math.PI / n), -d * Math.cos(i * 2 * Math.PI / n), getNewVertexID()); } if (edges) { for (int i = 0; i < n; ++i) { createEdge(vertices.get(i + 1), vertices.get((i + 1) % n + 1)); createEdge(vertices.get(0), vertices.get(i + 1)); } } type = GraphType.wheel; }
73291e5d-f5fd-47e3-9acc-9809ac417a4c
1
public Connection avaaYhteys() throws DAOPoikkeus { try { return DriverManager.getConnection( DBConnectionProperties.getInstance().getProperty("url"), DBConnectionProperties.getInstance().getProperty("username"), DBConnectionProperties.getInstance().getProperty("password")); } catch(Exception e) { throw new DAOPoikkeus("Tietokantayhteyden avaaminen epäonnistui.", e); } }
76a1bef6-624b-48d8-b87f-73f6e674ecde
5
public void start() { end = false; try { ServerSocket ss = new ServerSocket(port); while (!end) { //Accept socket and create a new ClientThread Socket s = ss.accept(); ClientThread ct = new ClientThread(s); clientList.add(ct); ct.start(); } try { //Attempt to close sockets/clients ss.close(); for (ClientThread c : clientList) { try { c.input.close(); c.output.close(); c.socket.close(); } catch (IOException e) { System.out.println("Exception closing clients: " + e); } } } catch (Exception e) { System.out.println("Exception closing socket: " + e); } } catch (IOException e) { System.out.println("Exception with socket: " + e); } }
5cc78529-a192-469d-9d4d-f35a54d3b87d
3
private BufferedImage decode() throws IOException { ImageReadParam readParam = null; if (getDecode() != null) { // we have to allocate our own buffered image so that we can // install our colour model which will do the desired decode readParam = new ImageReadParam(); SampleModel sm = cm.createCompatibleSampleModel (getWidth (), getHeight ()); final WritableRaster raster = Raster.createWritableRaster(sm, new Point(0, 0)); readParam.setDestination(new BufferedImage(cm, raster, true, null)); } final Iterator<ImageReader> jpegReaderIt = ImageIO.getImageReadersByFormatName("jpeg"); IIOException lastIioEx = null; while (jpegReaderIt.hasNext()) { try { final ImageReader jpegReader = jpegReaderIt.next(); jpegReader.setInput(ImageIO.createImageInputStream( new ByteBufferInputStream(jpegData)), true, false); return readImage(jpegReader, readParam); } catch (IIOException e) { // its most likely complaining about an unsupported image // type; hopefully the next image reader will be able to // understand it jpegData.reset(); lastIioEx = e; } } throw lastIioEx; }
d72d2556-342d-4345-b954-28a776f09624
3
public boolean equals(Object obj) { if (!(obj instanceof UUID)) return false; if (((UUID)obj).variant() != this.variant()) return false; UUID id = (UUID)obj; return (mostSigBits == id.mostSigBits && leastSigBits == id.leastSigBits); }
2ccedeb2-b411-4c84-a69a-74160f42828a
0
@Override public String introduceYourself() { return "TextQuest"; }
5128a8d3-c59a-4b8d-ba68-2acd82dc160c
4
private boolean check1(int i, int j) { int first = getMatrix(i, j); if (first == 0 || first == -1) { return false; } int second = getMatrix(i, j + 1); int third = getMatrix(i, j + 2); if (first == second && first == third) { return true; } return false; }
4cee75fe-9ecb-4519-9ed6-2a21eae67243
7
public Void doInBackground() { setProgress(0); ArrayList<Point2D> ser = new ArrayList<Point2D>(); int count = 0; int total = seqs.size()*(seqs.size()-1)/2; int step = total/10+1; int[] hist = new int[seqs.getMaxSeqLength()]; for (int i=0; i<seqs.size(); i++) { for(int j=i+1; j<seqs.size(); j++) { int difs = numDifs(seqs.get(i), seqs.get(j)); hist[difs]++; count++; } setProgress( (int)Math.round(100*(double)count/(double)total)); } int lowerCutoff = 0; while(lowerCutoff< hist.length && hist[lowerCutoff]==0) lowerCutoff++; int upperCutoff = hist.length-1; while(upperCutoff>lowerCutoff && hist[upperCutoff]==0) upperCutoff--; for(int i=lowerCutoff; i<=upperCutoff; i++) { ser.add(new Point2D.Double(i, hist[i])); } setProgress(Math.min(100, 100*count/total)); difCounts = new XYSeries(ser); return null; }
c9a02ea7-51a4-4aae-a7f7-4b6ec5f37adb
9
private String checkFieldAndReturnTransferType() { int fromProjectID = ((KeyValue) cmbFromProject.getSelectedItem()).getKey(); int toProjectID = ((KeyValue) cmbToProject.getSelectedItem()).getKey(); int fromDepartmentID = ((KeyValue) cmbFromDepartment.getSelectedItem()).getKey(); int toDepartmentID = ((KeyValue) cmbToDepartment.getSelectedItem()).getKey(); int fromLocationID = ((KeyValue) cmbFromLocation.getSelectedItem()).getKey(); int toLocationID = ((KeyValue) cmbToLocation.getSelectedItem()).getKey(); int[] check = {0, 0, 0}; if (fromProjectID != toProjectID) { check[0] = 1; } if (fromDepartmentID != toDepartmentID) { check[1] = 1; } if (fromLocationID != toLocationID) { check[2] = 1; } int sum = 0; for (int i = 0; i < check.length; i++) { sum += check[i]; } if (sum == 0) { //Error: No transfer ? return ""; } else if (sum == 1) { //Transfer only one if (check[0] == 1) { //Project return "Project Transfer"; } if (check[1] == 1) { //Department return "Department Transfer"; } if (check[2] == 1) { //Location return "Location Transfer"; } //Unexpected Error return ""; } else { //Custom transfer return "Custom Transfer"; } }
997f3997-ed0a-4500-82a9-5ac51e4edf8e
6
public Date getToOpenDate () { Date toOpenDate = null; for (ReceptionsFilter filter: filters) { if (filter instanceof OpenDateReceptionsFilter) { OpenDateReceptionsFilter openDateFilter = (OpenDateReceptionsFilter) filter; Date filterToOpenDate = openDateFilter.getToDate(); if (toOpenDate == null || (toOpenDate != null && filterToOpenDate != null && toOpenDate.getTime() > filterToOpenDate.getTime()) ) toOpenDate = filterToOpenDate; } } return toOpenDate; }
82e0a438-fdb0-47f6-954a-605a88a92815
9
public String nextToken() throws JSONException { char c; char q; StringBuffer sb = new StringBuffer(); do { c = next(); } while (Character.isWhitespace(c)); if (c == '"' || c == '\'') { q = c; for (;;) { c = next(); if (c < ' ') { throw syntaxError("Unterminated string."); } if (c == q) { return sb.toString(); } sb.append(c); } } for (;;) { if (c == 0 || Character.isWhitespace(c)) { return sb.toString(); } sb.append(c); c = next(); } }
2c676124-94b9-4d17-82dc-cdaec051f510
7
private final boolean cvc(int i) { if (i < 2 || !cons(i) || cons(i - 1) || !cons(i - 2)) return false; { int ch = b[i]; if (ch == 'w' || ch == 'x' || ch == 'y') return false; } return true; }
9858eda7-7f64-4145-9c0e-21173478923b
8
public static void rotateExpansionVector() { int eX = expansionVector.x, eY = expansionVector.y; if(eX == 1 && eY == 0) { eX = 0; eY = 1; } else if(eX == 0 && eY == 1) { eX = -1; eY = 0; } else if(eX == -1 && eY == 0) { eX = 0; eY = -1; } else if(eX == 0 && eY == -1) { eX = 1; eY = 0; } expansionVector = new Point(eX, eY); }
ecade30c-9ee3-445d-bc16-f3167b3d6ed2
4
public static boolean canUseReju(){ return ActionBar.getNode(0).canUse() && Equipment.containsOneOf(EquipShield.shieldId) && ActionBar.getAdrenaline() == 1000 && getHpPercent() <= Eat.HEAL_PERCENT && getHpPercent() > Eat.HEAL_PERCENT - 10; }
711fc9b7-dd37-4cd0-8d2b-e0bb7d66978c
5
@Override public void mousePressed(MouseEvent e) { if (_action != null) { if ((!isInBounds(e.getPoint())) || (_cards == null)) { return; } for (int i = _cards.size() - 1; i >= 0; i--) { if (_cards.get(i).isInBounds(e.getPoint())) { _selectedDCard = _cards.get(i); _cards.remove(i); _action.setSelectedCard(_selectedDCard); _dCompDraw.setComponent(_selectedDCard); return; } } } }
dcef64ee-827e-456f-89a6-7f6834d5de63
1
public InnerClassInfo[] getOuterClasses() { if ((status & OUTERCLASSES) == 0) loadInfo(OUTERCLASSES); return outerClasses; }
cf074961-5aec-4c16-97fb-5fe00d24d807
4
static void setEngineColor(String turn) throws IOException { switch (turn) { case "white": color = "white"; isForced = false; while (true) { if (Moves.computeMove() == 1) { break; } } break; case "black": isForced = false; color = "black"; break; } }
a9752869-5679-4d6d-87c6-87ee923f8ae4
9
public static void Filegen(String srcFilePath, String destFilePath,int rtpStreamPort) { int bytesRecieved = 0; int fileIndex=0; FileOutputStream fo=null; DataOutputStream dOut=null; long videoDuration = 0; File sourceVideo=new File(srcFilePath); VideoDetails video = Globals.GlobalData.videoLibrary.getVideoDetails(sourceVideo.getName()); File destFolder=new File(destFilePath); try { int counter=0; System.out.println(destFolder.getCanonicalPath()); if(!destFolder.exists()) { destFolder.mkdirs(); } File temp = new File(destFolder+"/temp"+fileIndex); fo = new FileOutputStream(temp); dOut = new DataOutputStream(fo); DatagramSocket clientSocket = new DatagramSocket(rtpStreamPort); byte[] receiveData = new byte[10000]; DatagramPacket dp=new DatagramPacket(receiveData,receiveData.length,InetAddress.getByName("localhost"),rtpStreamPort); clientSocket.setReceiveBufferSize(5000000); clientSocket.setSoTimeout(10000); ByteBuffer wrapped = ByteBuffer.wrap(receiveData); Short timeStamp=0; short prevTimeStamp = -1; long time=System.currentTimeMillis()/1000; long bytesInSegment = 0; while(true) { clientSocket.receive(dp); bytesRecieved+=dp.getLength(); bytesInSegment+=dp.getLength(); dOut.writeInt(dp.getLength()); timeStamp=wrapped.getShort(4); dOut.writeShort(timeStamp); dOut.write(receiveData,0,dp.getLength()); if(timeStamp!=prevTimeStamp) { long newtime=System.currentTimeMillis()/1000; if(newtime-time>=RTPFileGenerator.videoSegmentLength) { videoDuration+= newtime-time; dOut.close(); fo.close(); video.currentStreamingChunk = fileIndex; File actualFile = new File(destFolder+"/chunk"+fileIndex); temp.renameTo(actualFile); fileIndex++; counter=0; fo = new FileOutputStream(temp); dOut = new DataOutputStream(fo); Globals.log.message("Converting "+sourceVideo.getName()+" with SegmentDataRate : "+ (bytesInSegment/1024/5)+"KBps"+" Duration:"+videoDuration+" timeGap "+(newtime-time)); time=newtime; bytesInSegment = 0; } prevTimeStamp = timeStamp; } } } catch (Exception e) { e.printStackTrace(); } Globals.log.message("RTP file generation complete for "+srcFilePath); if(fo!=null&&dOut!=null) { try{ fo.close(); dOut.close(); File temp = new File(destFolder+"/temp"+fileIndex); File actualFile = new File(destFolder+"/chunk"+fileIndex); temp.renameTo(actualFile); }catch(Exception e){e.printStackTrace();} } try{ int averageDataRate = bytesRecieved/((fileIndex+1)*RTPFileGenerator.videoSegmentLength); fo = new FileOutputStream(destFolder+"/rtp.log"); dOut = new DataOutputStream(fo); PrintStream ps = new PrintStream(dOut); ps.print("AverageDataRate\r\n"); ps.print(averageDataRate+"\r\n"); ps.print("VideoDuration\r\n"); ps.print(videoDuration+"\r\n"); ps.print("NumberOfChunks\r\n"); ps.print(fileIndex+"\r\n"); ps.close(); dOut.close(); fo.close(); video.RTPEncodingAvaliable = true; video.avgBitRate = averageDataRate; video.numberOfChunks = fileIndex; video.streamingLive = false; video.currentStreamingChunk = -1; video.duration = (int) videoDuration; Globals.GlobalData.peerController.broadcastStreamDead(sourceVideo.getName()); } catch (Exception e) { e.printStackTrace(); } }
338d910e-34db-4aea-a0bf-f95168596838
0
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed // TODO add your handling code here: programmerThread.stop(); hidePanels(lastPane); world.worldDeleter(); world.initWorld(); //paint this.repaint(); }//GEN-LAST:event_jMenuItem1ActionPerformed
9dcb9b90-39ef-4165-9c31-22f54a120253
4
private void getLastLogin() { try { directory = new File("C:/PassGuard/"); lastLoginName = new File("C:/PassGuard/LatestLogin"); if (!directory.isDirectory()) { directory.mkdir(); } if (lastLoginName.isFile()) { reader = new BufferedReader(new FileReader(lastLoginName)); String line; if ((line = reader.readLine()) != null) { usernameField.setText(line); passwordField.requestFocus(); } } else { lastLoginName.createNewFile(); } } catch (IOException e) { e.printStackTrace(); } }
a338e704-0deb-487a-ba37-5941a7b54bab
0
public SkipWhileIterator(Iterable<T> source, Predicate<T> predicate) { this._source = source.iterator(); this._predicate = predicate; }
a2946924-1139-478a-8adc-f2dfdd47a733
5
private static void startPlugins() { List<IPlugin> pluginList = plugins.getPluginList(); for (IPlugin plugin : pluginList) { try { // if (plugin instanceof org.myjfinal.plugin.activerecord.ActiveRecordPlugin) { org.myjfinal.plugin.activerecord.ActiveRecordPlugin arp = (ActiveRecordPlugin) plugin; if (arp.getDevMode() == null) { arp.setDevMode(constants.getDevMode()); } } boolean success = plugin.start(); if (!success) { String message = "Plugin start error :" + plugin.getClass().getName(); log.error(message); throw new RuntimeException(message); } } catch(Exception e) { String message = "Plugin start error: " + plugin.getClass().getName() + ". \n" + e.getMessage(); log.error(message, e); throw new RuntimeException(message, e); } } }
2e9152d5-66d7-4e78-9810-14fdc60784ed
3
public void restorePlayerData() { p.getEquipment().clear();//clear equipment, without this it doesn't remove items p.getInventory().setContents(inventory); p.setExp(exp); p.getInventory().setBoots(boots); p.getInventory().setLeggings(leggins); p.getInventory().setChestplate(chestplate); p.getInventory().setHelmet(helmet); p.setExhaustion(exhausion); p.setFoodLevel(20); p.setHealth(p.getMaxHealth()); p.removePotionEffect(PotionEffectType.INVISIBILITY); p.addPotionEffects(potions); p.setGameMode(gm); p.setAllowFlight(flyAllowed); p.setFlying(fly); if(m.getSpawn() != null) { p.teleport(m.getSpawn().add(0, 1, 0));//Teleport player to dodgeball spawn } else if(m.mm.getGlobalSpawn() != null && m.mm.getGlobalSpawn().getWorldObj() != null) { p.teleport(m.mm.getGlobalSpawn().getLocation().add(0, 1, 0));//teleport player to dodgeball global spawn if exists } else { p.teleport(loc);//teleport player to saved location } }
a786287b-f011-4201-93a4-c0df5eca00b4
1
public void mergeContinueStack(VariableStack stack) { if (continueStack == null) continueStack = stack; else continueStack.merge(stack); }
7e105fda-a195-48d0-b832-27c9edd14506
7
private long fromVals(final int wordNumber, final int[] vals) { if(wordNumber * 32 > vals.length) { System.out.println("Wordnumber is too large for vals\t" + wordNumber + "\t" + vals.length); return -1; } int last = (wordNumber + 1) * 32; if(last > vals.length) { last = vals.length; } StringBuilder bytes = new StringBuilder(); for(int i = last -1; i >= wordNumber * 32; i--) { switch(vals[i] % 4) { case 0: bytes.append("00"); break; case 1: bytes.append("01"); break; case 2: bytes.append("10"); break; case 3: bytes.append("11"); break; } } return new BigInteger(bytes.toString(), 2).longValue(); }
275b61e9-27db-4dac-8d6b-95ec3f77c33c
4
private void bijnamenToevoegen(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { List<String> fouten = new ArrayList<>(); long docentNr = Long.parseLong(request.getParameter("docentNr")); String bijnaam = request.getParameter("bijnaam"); if (bijnaam == null || bijnaam.isEmpty()) { fouten.add("Bijnaam verplicht"); } else { try { docentService.bijnaamToevoegen(docentNr, bijnaam); } catch (DocentNietGevondenException ex) { fouten.add("Docent niet gevonden"); } } if (fouten.isEmpty()) { response.sendRedirect(response.encodeRedirectURL(String.format( REDIRECT_URL, request.getContextPath(), docentNr))); } else { request.setAttribute("docent", docentService.read(docentNr)); request.setAttribute("fouten", fouten); request.getRequestDispatcher(VIEW).forward(request, response); } }
a057b4e1-d11b-455c-8cc1-c58cade01615
1
@Override public Object applyFilters(PropertyContainer container, Object value) { for (int i = 0; i < filters.size(); i++) { PropertyFilter filter = (PropertyFilter) filters.get(i); value = filter.filter(container, value); } return value; }
dc580bbe-32e1-4156-8950-674f92bf2915
2
public ArrayList<Integer> spiralOrder(int[][] matrix) { ArrayList<Integer> result = new ArrayList<Integer>(); if (matrix.length == 0) return result; init(matrix.length, matrix[0].length); while (!closed) { result.add(matrix[index[0]][index[1]]); next(); } result.add(matrix[index[0]][index[1]]); return result; }
7858f95b-a9d2-419a-b73e-23f49cfe16ca
3
@Override protected void reactPressed(MouseEvent event) { ProgramState curr = StateMachine.getState(); if (curr != ProgramState.ARR_EDITING && curr != ProgramState.ARR_PLAYING) { if (isPressed) { isPressed = false; releaseImage(); StateMachine.resetLoopPressed(); } else { isPressed = true; pressImage(); StateMachine.setLoopPressed(); } } }
0c7987ec-e10a-4d0a-bb80-b163598f653b
9
@Override public E getEdge(D s, D e) { IndexVertex<D> vs = null ; IndexVertex<D> ve = null ; double weight = -1; Iterator<IndexVertex<D>> it = vset.iterator(); while ( it.hasNext()) { IndexVertex<D> iv = it.next(); if ( iv.getData().equals(s) ) { vs = iv; } if ( iv.getData().equals(e) ) { ve = iv; } if ( vs != null && ve != null ) { break; } } if ( vs == null ) { throw new VertexException("can not find vertex : " + s); } if ( ve == null ) { throw new VertexException("can not find vertex : " + e); } int is = vs.index(); int ie = ve.index(); if ( is < ie) { IndexVertex<D> tmp = vs; vs = ve; ve = tmp; } weight = graphFacade.getWeight(vs.index(), ve.index()); if ( weight < 0 ) { throw new EdgeException("cannot find edge between : " + s + " and " + e); } DefaultEdge<IVertex<D>> edge = new DefaultEdge<IVertex<D>>(vs, ve, weight); // cachedEdge.put(edge, edge); return (E) edge; }
7e2caeb1-81e2-4bb3-ab5f-6c7f89a02dad
4
public boolean loadClassDuration(OffRec off, boolean ignoreSSL) throws IOException { if (off.getKey() == null) return false; // https://www.edx.org/api/catalog/v2/courses/course-v1:DelftX+TP101x+3T2015 // "https://www.edx.org/api/catalog/v2/courses/course-v1:"; String newUrl = "https://www.edx.org/api/catalog/v2/courses/" + off.getKey(); URL url = new URL(newUrl); // All set up, we can get a resource through https now: URLConnection urlCon = url.openConnection(); // Tell the url connection object to use our socket factory which // bypasses security checks if (ignoreSSL) ((HttpsURLConnection) urlCon).setSSLSocketFactory(sslSocketFactory); InputStream stream = urlCon.getInputStream(); InputStreamReader reader = new InputStreamReader(stream); StringBuffer buffer = HttpHelper.readIntoBuffer(reader); stream.close(); Object data = JsonParser.parse(new StringReader(buffer.toString())); try { @SuppressWarnings("unchecked") String value = (String) ((Map<String, Object>) data).get("length"); value = value.trim(); int end = value.indexOf(' '); if (end >= 0) value = value.substring(0, end); int weeks = Integer.parseInt(value); off.setDuration(weeks); return true; } catch (Exception e) { System.out.println("Cannot get course length from " + newUrl + ": " + e); return false; } }
bb5ee44b-3d4a-4604-8985-6d3f428976f8
3
private ArrayList<MelhorPropostaCupom> ordenarPropostas(ArrayList<MelhorPropostaCupom> propostasAceitas){ ArrayList<MelhorPropostaCupom> propostasOrdenadas = new ArrayList<MelhorPropostaCupom>(); int count = propostasAceitas.size(); AID menorAID; while(propostasAceitas.size() > 0){ MelhorPropostaCupom melhorProposta = propostasAceitas.get(0); menorAID = melhorProposta.getVendedorAID(); Iterator<MelhorPropostaCupom> it = propostasAceitas.iterator(); while(it.hasNext()){ MelhorPropostaCupom tmp = it.next(); if(/*menorAID != null && */tmp.getVendedorAID().toString().compareTo(menorAID.toString()) < 0){ melhorProposta = tmp; menorAID = tmp.getVendedorAID(); } } propostasOrdenadas.add(melhorProposta); propostasAceitas.remove(melhorProposta); } return propostasOrdenadas; }
c97eb252-4106-4459-834b-620e7e089ba7
7
private static void checkColumnForMostWanted() throws Exception { HashMap<String, Double> outputVals = new HashMap<String, Double>(); BufferedReader reader = new BufferedReader(new FileReader(new File( ConfigReader.getChinaDir() + File.separator + "Kathryn_update_NCBI_MostWanted" + File.separator + "otusToMostWanted.txt"))); reader.readLine(); for(String s = reader.readLine(); s != null; s= reader.readLine()) { String[] splits = s.split("\t"); outputVals.put(splits[1], Double.parseDouble(splits[4])); } System.out.println("Got " + outputVals.size() + " prevelance "); reader.close(); reader = new BufferedReader(new FileReader(new File( ConfigReader.getChinaDir() + File.separator + "Kathryn_update_NCBI_MostWanted" + File.separator + "MW_all.txt"))); for(String s = reader.readLine(); s != null && s.trim().length() > 0 ; s = reader.readLine()) { String[] splits = s.split("\t"); if(outputVals.containsKey(splits[0])) { Double val = outputVals.get(splits[0]) ; if( val == null) throw new Exception("Logic error"); System.out.println(val + " " + Double.parseDouble(splits[64])); if( Math.abs(val - Double.parseDouble(splits[65]))>0.001) throw new Exception("Fail"); outputVals.remove(splits[0]); } } reader.close(); if(outputVals.size() != 0 ) throw new Exception("Fail"); System.out.println("Pass prevalance check"); }
629fc38b-5b78-4713-8726-44f267545904
0
public NodeList findNodes(String expr) throws XPathExpressionException { return (NodeList) evaluateXPath(expr, NODESET); }
095fedbf-6bae-4891-af59-2316dd832c3b
4
* The type of the patch, as a constant from OPT. */ public void storeUndo(UndoPatch undo, int patchType) { undo.opTag = patchType; while (patchIndex < undoPatches.size()) { undoPatches.remove(undoPatches.size() - 1); } if (!undoCanMerge || patchIndex == 0 || !undoCompatible(undoPatches.get(patchIndex - 1), undo)) { undoPatches.add(undo); undoCanMerge = true; patchIndex++; } else { undoMerge(undo, undoPatches.get(patchIndex - 1)); } }
a3f17dad-8e6f-4d4b-b5e9-95eddae44476
7
public static int position(Byte[] jeu, byte player){ int val=0; byte opponent=0; Byte empty = 0; if (player == 1) opponent = 2; else if (player == 2) opponent = 1; else System.out.println("erreur IA"); /* POSITION IA */ int [] tabIA = {0, 0,500, 1000, //vert positif 10, 10, 10, 500, 500, 20, 20, 20, 10, 10, 0, 35, 35, 35, 20, 20, 10, 0, 55, 55, 35, 35, 20, 10, 80, 80, 55, 35, 20, 1000000000, 80, 55, 35 }; /* 0, 1, 2, 3 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 15, 16, 17, 18, 19, 20, 21 22, 23, 24, 25, 26, 27 28, 29, 30, 31, 32, 33, 34, 35, 36 */ for (int i=0; i<37; i++){ if (jeu[i] == 2){ val += tabIA[i]; } } // if ((jeu[22] == player) && (jeu[28] != opponent)) val += 120; // if ((jeu[35] == player) && (jeu[34] != opponent)) val += 120; // // if (jeu[29] == player){ // if ((jeu[28] != opponent) || (jeu[34] != opponent)) // val += 50; // } // // if ((jeu[23] == player) && (jeu[22] != opponent)) val += 20; // if ((jeu[30] == player) && (jeu[35] != opponent)) val += 20; // // // if (((jeu[24] == player) && (jeu[18] == player)) || ((jeu[18] == player) && (jeu[12] == player))) // val += 30; // // // if ((jeu[28] == player || jeu[29] == player || jeu[34] == player) && jeu[33] == empty) //sur le point de gagner // val += 1500; // // if (jeu[15] == player || jeu[36] == player ) val += 100; ////////////////\\\\\\\\\\\\\\\\ //////// POSITION JOUEUR \\\\\\\\\ //////////////////\\\\\\\\\\\\\\\\\\ int [] tabJoueur = {35,55,80,1000000000, 20,35,55,80,80, 10,20,35,35,55,55, 0,10,20,20,35,35,35, 0,10,10,20,20,20, 500,500,10,10,10, 1000,500,0,0}; for (int i1=0; i1<37; i1++){ if (jeu[i1] == 1){ val -= tabJoueur[i1]; } } //Application des fonctions d'evaluations val -= frontalRougeGauche(jeu); //////////////////////////////////////////////////////// if(player==1) val=-val; return val; }
75d5b575-ee86-47b4-98a5-b4e7c60e996d
8
public static void findMaxSubArray(int[] inputArray) { int maxStartIndex = 0; int maxEndIndex = 0; int maxSum = Integer.MIN_VALUE; int cumulativeSum = 0; int maxStartIndexUntilNow = 0; for (int currentIndex = 0; currentIndex < inputArray.length; currentIndex++) { int eachArrayItem = inputArray[currentIndex]; cumulativeSum += eachArrayItem; if (cumulativeSum > maxSum) { maxSum = cumulativeSum; maxStartIndex = maxStartIndexUntilNow; maxEndIndex = currentIndex; } else if (cumulativeSum < 0) { maxStartIndexUntilNow = currentIndex + 1; cumulativeSum = 0; } } //System.out.println("Max sum : " + maxSum); // System.out.println("Max start index : " + maxStartIndex); // System.out.println("Max end index : " + maxEndIndex); int maxSum2 = 0; for (int currentIndex = 0; currentIndex < inputArray.length; currentIndex++) { if (inputArray[currentIndex] > 0) maxSum2 += inputArray[currentIndex]; } int max = Integer.MIN_VALUE; if (maxSum2 == 0) { for (int currentIndex = 0; currentIndex < inputArray.length; currentIndex++) { if (inputArray[currentIndex] > max) max = inputArray[currentIndex]; } maxSum2 = max; } //System.out.println("Max sum non contiguous : " + maxSum2); System.out.println(maxSum + " " + maxSum2); }
b36ad862-7f97-462a-bbef-2e6fa8e37667
5
public void run() { while (running == true) { if (socket.isClosed()) { listener.receiveMessage("DIS:", client); } String line; try { line = in.readLine(); if (line != null) listener.receiveMessage(line, client); } catch (SocketTimeoutException e) { continue; // Check if running is still true, and try another // read. } catch (IOException e) { listener.receiveMessage("DIS:", client); } } }
332b155c-b65f-4372-81bc-0d2110364bce
7
public static char[][] build_trans_block(int[] key_num,String key) { int col=key_num.length; int row=26/col; if(row*col!=26) { row+=1; } char[][] result=new char[row][col]; boolean[] filled=new boolean[26]; int cur_row=0; int cur_col=0; for(int i=0;i<key.length();i++) { char cur_c=key.toUpperCase().charAt(i); int pos=cur_c-'A'; if(filled[pos]) continue; result[cur_row][cur_col]=cur_c; filled[pos]=true; if(cur_col==col-1) { cur_row++; cur_col=0; } else { cur_col++; } } // int cur_row; // int cur_col=0; for(int i=0;i<26;i++) { if(!filled[i]) { result[cur_row][cur_col]=(char)('A'+i); filled[i]=true; if(cur_col==col-1) { cur_col=0; cur_row++; } else { cur_col++; } } } return result; }
77d872b1-13f1-42b4-897f-30b1561dd1ba
9
public void execute(String[] args) throws Exception { processArguments(args); String theAttr = (String)attributeNames.toArray()[0]; String theVal = (String)attributeNames.toArray()[1]; if (objectName == null) throw new CommandException("Missing object name"); log.debug("attribute names: " + attributeNames); if (attributeNames.size() != 2 ) { throw new CommandException("Wrong number of arguments"); } MBeanServerConnection server = getMBeanServer(); MBeanInfo info = server.getMBeanInfo(objectName); MBeanAttributeInfo[] attrs = info.getAttributes(); MBeanAttributeInfo attr=null; boolean found = false; for (int i=0;i < attrs.length ; i++ ) { if (attrs[i].getName().equals(theAttr) && attrs[i].isWritable()) { found=true; attr= attrs[i]; break; } } if (found == false) { throw new CommandException("No matching attribute found"); } else { Object oVal = convert(theVal,attr.getType()); Attribute at = new Attribute(theAttr,oVal); server.setAttribute(objectName,at); // read the attribute back from the server if (!context.isQuiet()) { PrintWriter out = context.getWriter(); Object nat = server.getAttribute(objectName,theAttr); if (nat==null) out.println("null"); else if (prefix) out.print(theAttr+"="); out.println(nat.toString()); } } closeServer(); }
799f299b-fa27-4a24-b2f8-f645ae6dcce7
7
public void stopKI() { // Set the State to KI stop switch (state) { case caculateKI: setState(State.stopCaculateKI); break; case caculateHelpKI: setState(State.stopCaculateHelpKI); break; case checkPossible: setState(State.stopCheckPossible); break; default: break; } ki.stop(); // waits until KI stopped while (ki.isKICalculating()) { } // Set a new State switch (state) { case stopCaculateKI: setState(State.playingHuman); break; case stopCaculateHelpKI: case stopCheckPossible: setState(State.playingHumanHelp); break; default: break; } }
53e1a2f3-becb-4856-b8ae-c013ecef741f
1
public Object getStat() throws Exception { Connection c = con.connect(); try { ResultSet set = c.prepareStatement(query).executeQuery(); if (set.next()) { return set.getObject(1); } else { return "<Empty Query Result>"; } } finally { c.close(); } }
5a755870-9234-4aed-9aa3-bb761d169726
4
public static Position getNextPosition(LineNumberReader reader) { try { String line = reader.readLine(); if(line == null) { throw new PositionFileException("The specified file contains not enough positions"); } try { String[] parts = line.split(","); if(parts.length < 3) { throw new PositionFileException("Illegal line: expected three doubles, separated by comma. Found \n" + line); } double x = Double.parseDouble(parts[0]); double y = Double.parseDouble(parts[1]); double z = Double.parseDouble(parts[2]); return new Position(x,y,z); } catch(NumberFormatException e) { throw new PositionFileException("Illegal line: expected three doubles, separated by comma. Found \n" + line); } } catch (IOException e) { throw new PositionFileException(e.getMessage()); } }
e58ec61b-9339-4395-8cf2-a1d455423777
1
public Wall[] getWalls(){ Wall[] wallsRes = new Wall[walls.size()]; for (int i = 0; i < walls.size(); i++){ wallsRes[i] = walls.get(i); } return wallsRes; }
bd8557fc-f0ca-4ee1-becc-150b03bbf1ac
7
public static int findNumThanks(String content) { if (content != null && !content.equals("")) if (content.contains("Thanks") || content.contains("thanks") || content.contains("Thank you") || content.contains("thank you") || content.contains("thx")) return 1; return 0; }
c16dde3d-b8ba-4e88-aa98-266725ef8d2e
1
private ArrayList<String> sortAlphanumeric(ArrayList<String> array) { ArrayList<String> sorted = new ArrayList<String>(); for (String s : array) { sorted.add(binarySearch(s, sorted), s); } return sorted; }
41417648-018a-46c3-a3a5-8e0ae54cabb7
2
@Inject public SchedulerProvider( SchedulerConfiguration schedulerConfiguration ) throws SchedulerException { StdSchedulerFactory schedulerFactory = new StdSchedulerFactory(); if ( schedulerConfiguration.getProperties() != null ) { schedulerFactory.initialize( schedulerConfiguration.getProperties() ); } this.scheduler = schedulerFactory.getScheduler(); if ( !schedulerConfiguration.startManually() ) { scheduler.start(); } }
ad27795f-4aa7-4872-ac27-91fe3faa65f3
4
public void addThread(ChatServerThread thread){ //replaces the first dead thread with this one, taking its id int count = threads.size(); boolean found = false; for (int i = 0; i<count; i++){ ChatServerThread thread2 = threads.get(i); if (thread2==null || !thread2.isAlive()){ thread.setID(i); // thread.setUserName(""+i); threads.remove(i); threads.add(i, thread); System.out.println("New thread added and ID set to "+i+"."); found = true; break; } } if (!found){ threads.add(thread); thread.setID(count); //thread.setUserName(""+count); System.out.println("New thread added and ID set to "+count+"."); } //thread.tell("Server Message", "You've joined the chat room "+name+"."); //tellEveryone( "Server Message", ""+thread.getUserName()+" joined the room."); //id -1 reserved for server messages }
9c4e9c58-202f-4906-99d9-61b823036720
9
public void displayInfo(){ String myPieces = ""; String needPieces = ""; for(int i=0; i < manager.myPieces.length; i++){ if(manager.myPieces[i]){ myPieces = myPieces + i + ", "; } else { needPieces = needPieces + i + ", "; } } myPiecesPanel.havePieces.setText(myPieces); neededPiecesPanel.needPieces.setText(needPieces); //if nothing is selected if(peersPanel.peerList.getSelectedIndex() == -1){ peerInfoPanel.connected.setText("<html><b>Connected:</b> </html>"); peerInfoPanel.areChoking.setText("<html><b>Choked:</b> </html>"); peerInfoPanel.areInterested.setText("<html><b>We're Interested:</b> </html>"); peerInfoPanel.isChoking.setText("<html><b>Is Choking:</b> </html>"); peerInfoPanel.isInterested.setText("<html><b>They're Interested:</b> </html>"); peerInfoPanel.theirPieces.setText("Pieces: "); return; } //when peer is selected Peer selectedPeer = peerMap.get(peersPanel.peerList.getSelectedValue()); if(selectedPeer.amConnected()){ peerInfoPanel.connected.setText("<html><b>Connected:</b> <font color=\"green\"> Yes </font></html>"); } else { peerInfoPanel.connected.setText("<html><b>Connected:</b> <font color=\"red\"> No </font></html>"); } if(selectedPeer.amChoking()){ peerInfoPanel.areChoking.setText("<html><b>Choked:</b> <font color=\"red\"> Choked </font></html>"); } else { peerInfoPanel.areChoking.setText("<html><b>Choked:</b> <font color=\"green\"> Unchoked </font></html>"); } if(selectedPeer.amInterested()){ peerInfoPanel.areInterested.setText("<html><b>We're Interested:</b> <font color=\"green\"> Interested </font></html>"); } else { peerInfoPanel.areInterested.setText("<html><b>We're Interested:</b> <font color=\"red\"> Uninterested </font></html>"); } if(selectedPeer.isChoking()){ peerInfoPanel.isChoking.setText("<html><b>Is Choking Us:</b> <font color=\"red\"> Being Choked </font></html>"); } else { peerInfoPanel.isChoking.setText("<html><b>Is Choking Us:</b> <font color=\"green\"> Unchoked </font></html>"); } if(selectedPeer.isInterested()){ peerInfoPanel.isInterested.setText("<html><b>Is Interested:</b> <font color=\"green\"> Interested </font></html>"); } else { peerInfoPanel.isInterested.setText("<html><b>Is Interested:</b> <font color=\"red\"> Uninterested </font></html>"); } String pieces = ""; for(int i=0; i < selectedPeer.availablePieces.size(); i++){ pieces = pieces + selectedPeer.availablePieces.get(i) + ", "; } peerInfoPanel.theirPieces.setText("Pieces: " + pieces); peerInfoPanel.uploadSpeed.setText("<html><b>Upload Speed:</b> " + selectedPeer.getUploadSpeed() + "</html>"); peerInfoPanel.downloadSpeed.setText("<html><b>Download Speed:</b> " + selectedPeer.getDownloadSpeed() + "</html>"); }
aa8787c2-b6a2-4a22-8f2f-bafe6133a520
5
private final String getChunk(String s, int slength, int marker) { StringBuilder chunk = new StringBuilder(); char c = s.charAt(marker); chunk.append(c); marker++; if (isDigit(c)) { while (marker < slength) { c = s.charAt(marker); if (!isDigit(c)) break; chunk.append(c); marker++; } } else { while (marker < slength) { c = s.charAt(marker); if (isDigit(c)) break; chunk.append(c); marker++; } } return chunk.toString(); }
53724ca5-424c-4661-9555-cff92ede97bd
5
protected void attemptFeedSheep(Player player, Sheep sheep) { /* Support for sheared state (setting), using that now. * If the sheep is sheared, then add to growing (if holding a food item and the sheep isn't growing already. Remove from naked list. * If not sheared, then add to naked list. */ if ( sheep.isSheared() ) { // Sheep is already sheered, adding to growing list if holding a food item and not growing already SheepFeed.debug("Sheep is already sheered"); if ( sheepFeedPlugin.isWoolGrowingSheep(sheep) ) { SheepFeed.debug("Sheep is already registered to grow wool"); return; } // check whether player has the right item in hand ItemStack heldItemStack = player.getItemInHand(); if ( !sheepFeedPlugin.config.isSheepFood(heldItemStack.getTypeId()) ) { // That's not sheep food! SheepFeed.debug("Sheep would not like that food"); return; } // not already scheduled to grow and correct food, remove one item and set growing schedule SheepFoodData foodData = sheepFeedPlugin.config.getFoodData(heldItemStack.getTypeId()); SheepFeed.debug(foodData.toString()); // check for permission if ( !this.sheepFeedPlugin.canFeed(player) ) { player.sendMessage("The sheep doesn't trust you and won't eat your "+ foodData.name +"."); } else { // remove the food item SheepFeed.debug(" amount of "+ heldItemStack.getType().toString() +" held: "+ heldItemStack.getAmount()); player.sendMessage("The sheep munches on the "+ foodData.name +" you fed it."); // reduce stack by one, but if it's the last item, remove the whole stack if ( heldItemStack.getAmount() == 1 ) { player.getInventory().clear(player.getInventory().getHeldItemSlot()); } else { heldItemStack.setAmount(heldItemStack.getAmount()-1); } // schedule growing of wool this.sheepFeedPlugin.scheduleWoolGrowth(sheep, foodData); } } }
f8f5af4b-bf83-4042-8daa-25cd9c0cf9c8
0
public static void main(String[] args) { String[][] test={{"JFK","SFO"},{"JFK","ATL"},{"SFO","ATL"},{"ATL","JFK"},{"ATL","SFO"}}; System.out.println(new OJ332().findItinerary(test)); }
f19a3d97-c5b7-44fb-9ef6-87158a96bee1
5
public boolean containsPoint(float pointX, float pointY) { // FIRST MOVE THE POINT TO LOCAL COORDINATES pointX = pointX - x; pointY = pointY - y; boolean inXRange = false; if ((pointX > aabbX) && (pointX < (aabbX + aabbWidth))) { inXRange = true; } boolean inYRange = false; if ((pointY > aabbY) && (pointY < (aabbY + aabbHeight))) { inYRange = true; } return inXRange && inYRange; }
069c2a77-7ba1-4c26-9529-98747983371b
6
public void stillGraphics(Client curPlr, int absX, int absY, int heightLevel, int id, int pause) { for(Player p : Server.getPlayerManager().getClientRegion((curPlr).currentRegion)){ if (p == null) continue; if (!p.isActive) continue; if (p.disconnected) continue; Client c = (Client) p; if (c == curPlr || c.withinDistance(absX, absY, heightLevel)) { c.getPA().sendStillGraphics(id, heightLevel, absY, absX, pause); } } }
9174a53c-14ef-4667-93ae-af6acc0f616a
0
public Item(String aDescription, int aPartNumber) { description = aDescription; partNumber = aPartNumber; }
ae5d504f-11c8-4e07-825f-16f3b26c8542
4
public static synchronized Address getInstance(String addressType) { int index = -1; if (addresses == null) { addresses = new ArrayList<>(); Address address = new Address(addressType); addresses.add(address); index = 0; } else { int counter = 0; for (Address address : addresses) { if (address.getAddressType().equals(addressType)) { index = counter; break; } counter++; } if (index == -1) { Address address = new Address(addressType); addresses.add(address); index = counter; } } return addresses.get(index); }
686f10aa-67e4-419c-b0ce-8cbd9c8850cc
4
private void getVariables() { for (int i = 0; i < exprBool.length(); i++) { char c = exprBool.charAt(i); if (c >= 'A' && c <= 'Z') { if (variables.indexOf(c) < 0) variables += c; } } }
5e987257-d242-473b-8927-2c4bf882e393
1
public static void main(String[] args) { /* Exceptions - Rules to Remember * A try block may be followed by multiple catch blocks, and the catch blocks may be followed by a single finally block * A try block may be followed by either a catch or a finally block or both. However, a finally block alone wouldn't suffice if code in the try block throws a checked exception. * The try, catch and finally block can't not exist independently. * The finally block can't appear before a catch block. * A finally block always executes, regardless of whether the code throws an exception. */ // invalid array index (maximum value is [3]) String[] students = {"Benjamin", "Joe", "Matthew"}; try { System.out.println(students[5].toString()); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("error thrown"); e.printStackTrace(); } finally { /* Exam Tip - The finally block will execute regardless of whether the try blocks throws an exception */ System.out.println("Finally Block is always executed"); } System.out.println("code has continued to run"); /* Why handle exceptions separately? For actual conditions you may have to verify whether you've completed the previous step before you can progress with the next step. If exception handlers are defined separately, any confusion with the steps that you need to accomplish to complete an action (or set of actions) has been clarified. Additionally, the code doesn't compromise the completion of a step before moving on to the next step, courtesy of teh appropriate exception handlers. If an exception is thrown, a catch statement can process the exception (printStackTrace() / log) and continue to process the remainder of the code, the application will not fall over (unless you tell it to). Do exceptions offer any other benefits? Apart from separating concerns between defining the regular program logic and the exception handling code, exceptions also can help pinpoint the offending code (code that throws an exception), together with the method in which it is defined, by providing a stack trace of the exception or error. What happens when an exception is thrown? * An exception is a Java object. * All types of exceptions subclass java.lang.Throwable. * When a piece of code hits an obstacle in the form of an exceptional condition, it creates an object of class java.lang.Throwable (at runtime an object of the most appropriate subtype will be created) and is then assigned a type. * This newly created object is then handed to the JVM, the JVM blows a siren in the form of this exception and looks for an appropriate code block that can "handle" this exception. */ }
a60e70cd-4705-4d87-b4ff-91db0a7df483
1
private void addOption(Element rootElement, String attrName, Serializable attrValue) { if (attrValue != null) { rootElement.setAttribute(attrName, attrValue.toString()); } }
8d18512e-fc63-4b45-8585-d976892a283f
2
@ Override public boolean equals(Object obj) { if (obj instanceof Coordinate2D) { Coordinate2D another = (Coordinate2D) obj; return (x == another.getX () && y == another.getY ()); } else return false; }
f3b2536d-62d3-4a59-b704-bdbcadb19f13
0
public void setConcurrent(){ this.concurrent = true; }
1665122e-f267-4a99-a2b5-fa574a493c5b
4
@Override public void removeEdgesTo(N to) { if(containsNode(to)) { for(N node : nodes.keySet()) { List<WeightedEdge<N, W>> edgesFrom = edgesFrom(node); for(WeightedEdge<N, W> edge : edgesFrom) { if(edge.to.equals(to)) { nodes.get(node).remove(edge); } } } } }
1fb5534e-1ab8-44be-841d-4c062ca672ad
7
public void test5() { if (b) ; else if (b) { if (b || (new Integer(i)).toString().contains("Whatever") && new Double(d).compareTo(new Double(5.0)) > 55 || !(i >> 2 > 0) && (new String()) instanceof Object) ; } else ; }
c3d33031-f30e-4810-ac61-c3c91461332b
1
private static int facSum(int n, int[] f){ int s = 0; for(char c : Integer.toString(n).toCharArray()){ s+=f[Integer.parseInt(""+c)]; } return s; }
dea523ff-2c19-4f85-8344-a24843f46156
4
public void load(){ Scanner sc; try { sc = new Scanner(new File("save.txt")).useDelimiter("\\s"); // Luetaan tiedostosta save.txt, käytetään erottimena " " pelaajat.removeAll(pelaajat); pelaajat.add(new Pelaaja(sc.nextLine())); pelaajat.add(new Pelaaja(sc.nextLine())); currentPelaaja=sc.nextInt(); sc.nextLine(); sc.nextLine(); while(true){ try{ pelaajat.get(0).getVihko().load(Jatsiyhdistelma.valueOf(sc.next()), sc.nextInt()); } catch(IllegalArgumentException e){ // Rivillä lukee "stop" break; } sc.nextLine(); } while(sc.hasNext()){ pelaajat.get(1).getVihko().load(Jatsiyhdistelma.valueOf(sc.next()), sc.nextInt()); sc.nextLine(); } sc.close(); } catch (FileNotFoundException e) { } }
05cfdb11-dbaf-464b-a767-15ec60a28e8a
0
@Override public YamlPermissionRcon getRcon() throws DataLoadFailedException { checkCache(PermissionType.GROUP, "rcon"); return (YamlPermissionRcon) cache.get(PermissionType.RCON).get("rcon"); }
2a142e7d-25c9-45d2-9c9c-fe03d00a49f2
2
private void push(JSONObject jo) throws JSONException { if (this.top >= maxdepth) { throw new JSONException("Nesting too deep."); } this.stack[this.top] = jo; this.mode = jo == null ? 'a' : 'k'; this.top += 1; }
29dd7c74-37d6-4a19-9cbc-3b9ae3176bfe
0
@After public void tearDown() throws Exception { this.cacheKey = null; this.cache = null; }
2ec77f87-fd8b-49df-96b3-453e0861c35d
5
public HashMap<String, String> getRow(String testcase,String ...sheetName) { HashMap<String,String> testData = new HashMap<String,String>(); String testSheetName; if (sheetName.length == 1){ testSheetName = sheetName[0]; }else{ testSheetName = getTestSheetName(testcase); } HSSFSheet testSheet = workBook.getSheet(testSheetName); String cellData; int totalRows = testSheet.getPhysicalNumberOfRows(); // Row starts from 1 as first row is header for (int row = 1; row < totalRows; row++) { // System.out.println(testSheet.getRow(row).getCell(0).toString()); if (testcase.equalsIgnoreCase(testSheet.getRow(row).getCell(0).toString())) { int totalCells = testSheet.getRow(row).getLastCellNum(); for(int cell=1; cell<totalCells; cell++){ //First column shows the scenario name. if(testSheet.getRow(row).getCell(cell) == null ){ cellData = ""; }else{ cellData = testSheet.getRow(row).getCell(cell).toString(); } String celllName = testSheet.getRow(0).getCell(cell).toString(); testData.put(celllName, cellData); } break; } } return testData; }
5984e254-2db8-4140-9dde-8675047e9ad8
7
public static Family getFamily() { String name = System.getProperty("os.name"); if(name.equalsIgnoreCase("freebsd")) return Family.FREEBSD; else if(name.equalsIgnoreCase("openbsd")) return Family.OPENBSD; else if(name.equalsIgnoreCase("mac os x")) return Family.OSX; else if(name.equalsIgnoreCase("solaris") || name.equalsIgnoreCase("sunos")) return Family.SOLARIS; else if(name.equalsIgnoreCase("linux")) return Family.LINUX; else if(name.toLowerCase().startsWith("windows")) return Family.WINDOWS; return Family.UNSUPPORTED; }
f8f401d1-b411-405b-9a00-79d3c67088fb
0
@Override public String toString(){ return "Hero : " + hero.toString() + "\n"; //"Weapon : " + weaponSlot.toString() + "\n"+ //"head armor : " + headArmorSlot.toString() + "\n" + //"Body armor : " + bodyArmorSlot.toString() + "\n"; }
07d8795e-08e6-4adb-99ad-5767bd216688
5
@Override public void incCount(E data) { if(head == null){ // We have an empty list - create the first node with data as its value head = new ListNode(data); }else { // We have a non-empty list - let's try to find a matching node ListNode current = head; // Is the head a match? If so, increment and return if(comparator.compare(data, current.value) ==0){ current.count++; return; } // Look for a node that matches data in the list while(current.next != null && comparator.compare(data, current.next.value) !=0){ current = current.next; } // There was no matching node - create a new one if(current.next == null){ ListNode temp = new ListNode(data); temp.next = head; this.head = temp; // Found a matching node - move it to the front and increment its count }else{ ListNode temp = current.next; current.next = temp.next; temp.next = head; head = temp; head.count++; } } }
0866e01e-aaa8-4657-9a74-e4a8c14f6408
6
public static boolean isCacheOld(String player) { PlayerCache checkPlayer = getPlayerCache(player); if(checkPlayer._playerJobs.isEmpty()) return true; if (Bukkit.getPlayer(player) != null) return false; boolean deletecache = false; Iterator<String> it = checkPlayer._playerJobs.iterator(); while (it.hasNext()) { String job = (String)it.next(); if(checkPlayer._joblevel.get(job) == 1) deletecache = true; if(checkPlayer._jobexp.get(job) > 0.0D) { deletecache = false; break; } } Date now = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(checkPlayer._dateModified); cal.add(5, _expired_timer); Date modified = cal.getTime(); if (modified.before(now)) deletecache = true; return deletecache; }
6200bfa2-b450-41f0-bb96-2d027262d510
8
private int checkNumber(int i) { int sum = 0; List<Integer> djelitelji = new ArrayList<Integer>(); for (Integer prim : primBrojevi) { if (i == prim) { return 1; } else { if (i % prim == 0) { sum++; djelitelji.add(prim); } } } if (sum == 1) { return 4; } else if (sum % 2 == 0 && checkOsnovni(i, djelitelji)) { return 2; } else if(sum % 2 == 1 && checkOsnovni(i, djelitelji)){ return 3; } return 5; }
8029a0c6-67d5-4839-a13b-64a127d8efaa
0
public String getRef() { return ref; }
e18457bd-7cb8-4eba-aef6-cbdc4871ac34
7
public void log(Clickstream clickstream) { if (clickstream == null) return; StringBuilder output = new StringBuilder(); String hostname = clickstream.getHostname(); HttpSession session = clickstream.getSession(); String initialReferrer = clickstream.getInitialReferrer(); Date start = clickstream.getStart(); Date lastRequest = clickstream.getLastRequest(); output.append("Clickstream for: ").append(hostname).append("\n"); output.append("Session ID: ").append((session == null ? "" : session.getId())).append("\n"); output.append("Initial Referrer: ").append(initialReferrer).append("\n"); output.append("Stream started: ").append(start).append("\n"); output.append("Last request: ").append(lastRequest).append("\n"); long streamLength = lastRequest.getTime() - start.getTime(); output.append("Stream length:"); if (streamLength > 3600000) { output.append(" ").append(streamLength / 3600000).append(" hours"); } else if (streamLength > 60000) { output.append(" ").append((streamLength / 60000) % 60).append(" minutes"); } else if (streamLength > 1000) { output.append(" ").append((streamLength / 1000) % 60).append(" seconds"); } output.append("\n"); int index = 0; for (Iterator<ClickstreamRequest> iterator = clickstream.getStream().iterator(); iterator.hasNext();) { output.append(++index).append(": "); output.append(iterator.next()); if (iterator.hasNext()) { output.append("\n"); } } log.info(output); }
581be5a9-4ab2-4724-964f-83bd664500be
1
@Override public Object getCellEditorValue() { if (isPushed) { doEditing(); } isPushed = false; return new String(label); }
3a610ec1-4bed-4426-ac5c-7a182749fe1e
8
public void populateSerialsJlist() { journalSerialListModel.clear(); conferenceSerialListModel.clear(); viewConferences.clear(); viewJournals.clear(); if (!model.getConferences().isEmpty()) { getAddConPaperButton().setEnabled(true); for (int i = 0; i < model.getConferences().size(); i++) { viewConferences.add(model.getConferences().get(i)); } } if(!model.getJournals().isEmpty()) { getAddJournalArticleButton().setEnabled(true); for(int i =0; i< model.getJournals().size();++i) { viewJournals.add(model.getJournals().get(i)); } } if(!viewConferences.isEmpty()) { for(int i=0; i< viewConferences.size();++i) { conferenceSerialListModel.addElement(viewConferences.get(i).getOrganization()); } } if(!viewJournals.isEmpty()) { for(int i=0; i< viewJournals.size();++i) { journalSerialListModel.addElement(viewJournals.get(i).getOrganization()); } } }
fd7f895c-8fbd-4fe4-ac7d-d90eb4c87587
3
public synchronized void cancel(Cancelable root) { root.cancelTask(); TreeNode rootNode = findNodeInTaskTrees(root); if (rootNode instanceof TreeNode) { List children = rootNode.getChildren(); TreeNode parentNode = rootNode.getParent(); for (Iterator iter = children.iterator(); iter.hasNext(); ) { TreeNode nextNode = ((Tree)(iter.next())).getRoot(); cancelRecursive(nextNode); } if (parentNode instanceof TreeNode) { Tree.removeFromParentChildren(rootNode); } else { removeFromTaskTrees(rootNode); } } }
740ebc21-6709-42e5-8b02-ae019f817678
9
public void enter(String plr,int num) throws InterruptedException, FileNotFoundException, UnsupportedEncodingException{ String gname; int found=0; int amt=0; int write=0; int cnt=0; String nme; while (found==0){ cnt=GosLink2.names.size(); for (int i=0;i<cnt;i++){ if(GosLink2.names.get(i)!=null){ nme=GosLink2.names.get(i); if (plr.equals(nme.substring(1))){ amt=Integer.parseInt(nme.substring(0,1)); if (amt<5){ amt=amt+1; GosLink2.names.remove(i); GosLink2.names.add(i,amt+plr); write=1; found=1; } else{found=2;} i=cnt+1200; } } } if (found==0){found=3;} } if (found==3){ GosLink2.names.add("1"+plr); write=1; found=1; } if (write==1){GosLink2.filewrt();} TN=GosLink2.TNH.get(num); gname=GosLink2.prps("muser"+num); String blah=num+",/"+plr+" Hello "+plr+". My name is "+gname+". I am a GosLink Bot. Please Telepath me @help for commands."; if (found==1){enters.add(blah);} }
fdd4920c-cb47-47e0-8fb9-240215e5f8a6
4
@Override public boolean verifier() throws SemantiqueException { if(gauche instanceof Identificateur && !gauche.verifier()){ GestionnaireSemantique.getInstance().add(new SemantiqueException("La declaration de la variable "+((Identificateur) gauche).getNom()+" a la ligne "+line+" est manquante")); }else gauche.verifier(); if(droite instanceof Identificateur && !droite.verifier()){ GestionnaireSemantique.getInstance().add(new SemantiqueException("La declaration de la variable "+((Identificateur) droite).getNom()+" a la ligne "+line+" est manquante")); }else droite.verifier(); return true; }
e1f1143a-8ef5-4bb5-b711-a9cd3d6b6a84
6
private Roster readRoster(ByteArrayInputStream inputStream) throws XmlException, IOException { final Roster roster = new Roster(); try { SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); saxParser.parse(inputStream, new DefaultHandler() { @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (qName.equalsIgnoreCase(DataConstants.ROSTER_TAG)) { roster.setBattleScribeVersion(attributes.getValue(DataConstants.BATTLESCRIBE_VERSION_ATTRIBUTE)); roster.setDescription(attributes.getValue(DataConstants.DESCRIPTION_ATTRIBUTE)); roster.setName(attributes.getValue(DataConstants.NAME_ATTRIBUTE)); roster.setPoints(Double.parseDouble(attributes.getValue(DataConstants.POINTS_ATTRIBUTE))); roster.setPointsLimit(Double.parseDouble(attributes.getValue(DataConstants.POINTS_LIMIT_ATTRIBUTE))); roster.setGameSystemId(attributes.getValue(DataConstants.GAME_SYSTEM_ID_ATTRIBUTE)); if (attributes.getIndex(DataConstants.GAME_SYSTEM_NAME_ATTRIBUTE) >= 0) { roster.setGameSystemName(attributes.getValue(DataConstants.GAME_SYSTEM_NAME_ATTRIBUTE)); } if (attributes.getIndex(DataConstants.GAME_SYSTEM_REVISION_ATTRIBUTE) >= 0) { roster.setGameSystemRevision( Integer.parseInt(attributes.getValue(DataConstants.GAME_SYSTEM_REVISION_ATTRIBUTE))); } throw new SAXParseCompleteException("DONE"); } } }); } catch (ParserConfigurationException e) { throw new IllegalStateException(e); } catch (SAXParseCompleteException e) { return roster; } catch (SAXException ex) { throw new XmlException(ex); } throw new XmlException("Invalid roster XML"); }
36c9ad9c-4123-46d3-8e61-5a928c00c678
0
@Override public Object getClock() { return (Object) this.clock; }
d20de29d-46b0-4e6c-a0c5-69e7524fefec
5
public static void main(String[] args){ boolean estMisAssertion = false; assert estMisAssertion = true; System.out.println("Lancement du programme Pair"); if (estMisAssertion) System.out.println("Veuillez patienter quelques instants ...\n"); FichierConfiguration fichierConf = new FichierConfiguration("configuration.txt"); System.out.println(fichierConf); File repertoire = new File("Download"); if ( ! repertoire.isDirectory() ) { System.out.println("Le Dossier Download est introuvable"); System.exit(1); } // *TODO* filtrer les fichiers cachés // use :"File[] listFiles(FileFilter filter)" File[] list = repertoire.listFiles(); Hashtable<String,Fichier> collection = new Hashtable<String,Fichier> (2*list.length, (float)0.75); for ( int i = 0; i < list.length ; i++) { // si ce n'est pas un fichier caché if ( list[i].exists() & list[i].getName().indexOf(".") != 0 ) { remplire(list[i], collection, fichierConf.getTaille()); } } // On dispose maintenant de la collection remplie sauver(collection); int localPort = 0; if (0 < args.length){ localPort = Integer.parseInt(args[0]); } Serveur th2 = new Serveur("String name", collection, fichierConf, localPort); th2.start(); /** / System.out.println("\nReprise du téléchargement des fichiers non complets"); RepriseTelechargement th6 = new RepriseTelechargement("th6", fichierConf, collection); th6.run(); System.out.println("Fin de la reprise des dl\n"); // */ System.out.println("\nProgramme utilisateur"); ThreadUtilisateur th4 = new ThreadUtilisateur("th4", fichierConf, collection); th4.run(); System.out.println("Fin du programme utilisateur"); sauver(collection); System.out.println("Fin du programme Pair"); System.exit(0); }
710a1d03-2e6c-4d6e-ba45-ef5b459193df
2
public String getTypeAlias(String typeSig) { String alias = (String) aliasesHash.get(typeSig); if (alias == null) { StringBuffer newSig = new StringBuffer(); int index = 0, nextindex; while ((nextindex = typeSig.indexOf('L', index)) != -1) { newSig.append(typeSig.substring(index, nextindex + 1)); index = typeSig.indexOf(';', nextindex); String typeAlias = getClassAlias(typeSig.substring( nextindex + 1, index).replace('/', '.')); newSig.append(typeAlias.replace('.', '/')); } alias = newSig.append(typeSig.substring(index)).toString().intern(); aliasesHash.put(typeSig, alias); } return alias; }
23487b5a-7346-4408-91ba-5c3a07c138b7
0
@Override public void fatalError(JoeException someException) { System.out.println(someException.getMessage()) ; this.errorOccurred = true; } // end method fatalError
c83b93fb-c018-4399-9c85-7e544b6148a7
5
protected void checkForHitLeft(Paddle paddle) { if (ballX <= (paddle.getX() + ballSize)) { if (ballY >= paddle.getY() - ballSize + 1 && ballY <= paddle.getY() + paddle.getLength() - 1) { hits1++; dx = right; dy = 0; // this is a direct hit int paddleCenter = paddle.getY() + paddle.getLength() / 2; int ballCenter = ballY + ballSize / 2; double offset = ballCenter - paddleCenter; double halfPaddle = paddle.getLength()/2; //set dx and dy dependent on region of paddle hit double angleDeg = 90.0 + 60.0 * (offset/halfPaddle); dx = +step * Math.sin(Math.toRadians(angleDeg)); if (offset < 0) { dy = -Math.sqrt(step*step - dx*dx); } else if (offset > 0) { dy = Math.sqrt(step*step - dx*dx); } } } }
0ebc3b1d-74bd-4e81-ab3a-a5a3db86ee0b
0
public String getName() { return name; }
79771669-dd17-4258-a155-f8b66d0a21db
6
@NotifyChange({"sessionChronometrages","finisOrNotCreated"}) public void initSession(){ //sessionChronometragePrincipale =new SessionChronometrage(course, voiture); //voiturePrincipale = voiture; if(course != null){ if(voiturePrincipale != null){ this.sessionChronometragePrincipale =null; for(SessionChronometrage sessionChrono : sessionChronometrages){ if(sessionChrono.getCourse() == course && sessionChrono.getVoiture() == voiturePrincipale ){ // une session existe afficher System.out.println("laaa"); sessionChronometragePrincipale = sessionChrono; finisOrNotCreated = sessionChronometragePrincipale.isFinished(); System.out.println("ici"+finisOrNotCreated); } /* if(sessionChronometragePrincipale == null){ sessionChronometragePrincipale = new SessionChronometrage(course, voiturePrincipale); } */ } if(this.sessionChronometragePrincipale == null){ finisOrNotCreated = false; System.out.println("ici"+finisOrNotCreated); } //sessionChronometrages.add(new SessionChronometrage(course, voiturePrincipale)); } } }
909237e6-65ca-4cfd-a30e-597d23d06ae8
8
private Object processMessage(Object obj, Throwable t) { StringBuilder str = new StringBuilder(); obj = str.append("会话ID:").append(ESBSessionUtils.getSessionID()).append(":").append(ESBSessionUtils.getServers().length) .append(":").append(obj); if (t != null && t instanceof ESBBaseCheckedException) { Category log = this.log; boolean find = false; while (true) { Object appender; for (Enumeration<?> allAppenders = log.getAllAppenders(); allAppenders.hasMoreElements();) { appender = allAppenders.nextElement(); if (appender instanceof ESBRollingFileAppender) { String logFileName = ((ESBRollingFileAppender) appender).getNextBackupFileName(); ((ESBBaseCheckedException) t).setLogStorage(logFileName); find = true; break; } } if (find || (log = log.getParent()) == null) { break; } } } return obj; }
822ac40d-6baa-44c8-aedd-9e619849f11a
3
public void delStep(int i){ if (steps.size()>i && !steps.isEmpty() && i > -1){ steps.remove(i); calcMashSchedule(); } }
45016a78-e418-49a2-99aa-05577ec65531
1
public boolean isInferenceComplete() { if (inferenceWorker != null) { return inferenceWorker.isDone(); } return true; }
db4be5fd-50d6-414c-a6a3-143ca255202b
3
@Override public boolean isDone(Game game) { boolean ended = super.isFinished(game); if(ended) return true; if(game.getNumSprites(itype) - game.getNumDisabledSprites(itype) >= limit && canEnd) { countScore(game); return true; } return false; }
5cf9c29b-1be4-4c80-b172-07e4905f0dad
8
private List<INode> mergeVirtualPlaces(ISubModel model) { List<INode> markToBeDeleted = new ArrayList<INode>(); /* Parcours des places susceptibles d'être liées (VIRTUAL) */ LOG.fine("Processing virtual places"); for (IPlace place : model.getPlaces()) { if (place.isTyped(IPlace.VIRTUAL)) { IPlace virtualPlace = place; LOG.finer(" Processing virtual place: " + virtualPlace.getName() + "(ref: " + virtualPlace.getTargetName() + ")"); markToBeDeleted.add(virtualPlace); // Tous les prédécesseurs de la place virtuelle doivent être liés à la cible de la référence for (INode pred : virtualPlace.getPrevious()) { for (IArc ancestorArc : model.getArcs(pred, virtualPlace)) { IArc link = model.createArc(pred, model.getTopModel().findNode(virtualPlace.getTargetName()), ancestorArc.getType()); link.setValuation(ancestorArc.getValuation()); LOG.finest(" Linking: " + pred.getName() + " -> " + model.getTopModel().findNode(virtualPlace.getTargetName())); } } // Tous les successeurs de la place référence doivent être liés à la cible de la référence for (INode succ : virtualPlace.getNext()) { for (IArc ancestorArc : model.getArcs(virtualPlace, succ)) { IArc link = model.createArc(model.getTopModel().findNode(virtualPlace.getTargetName()), succ, ancestorArc.getType()); link.setValuation(ancestorArc.getValuation()); LOG.finest(" Linking: " + model.getTopModel().findNode(virtualPlace.getTargetName()) + " -> " + succ.getName()); } } } // Suppression du type des places input / output if (place.isTyped(IPlace.INPUT) || place.isTyped(IPlace.OUTPUT)) { place.setType(IPlace.NORMAL); } } return markToBeDeleted; }
6e4bed97-ae47-4402-967d-2456acea580b
5
public void move() { x += dx; y += dy; if (x < 1) { x = 1; } if (y < 1) { y = 1; } //System.out.println("OLD-Mouse: " + this.oldMousePos[0] + " | " + this.oldMousePos[1] + " Neue Mouse-Pos " + this.mousePosition[0] + " | " + this.mousePosition[1] ); double newDegree = Vektor.getSchnittwinkel(x, y, this.oldMousePos[0], this.oldMousePos[1], x, y, this.mousePosition[0], this.mousePosition[1]); this.oldMousePos[0] = this.mousePosition[0]; this.oldMousePos[1] = this.mousePosition[1]; if(!Double.isNaN(newDegree)) { int steigung = 0; try { steigung = (this.oldMousePos[1]-this.mousePosition[1]) / (this.oldMousePos[0]-this.mousePosition[0]); } catch(ArithmeticException e) { steigung = 0; } //System.out.println("Steigung: " + steigung); if( steigung > 0) { degree += newDegree; //System.out.println("Ende: " + degree); } else { degree -= newDegree; } image = ImageRotate.rotateImage(this.orgImage, degree); } else { newDegree = 0; } }