method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
dab0cb31-1559-45f0-8b33-0730a2bd4905
2
public void setRef5(String ref) { if (ref != null && ref.length() > 256) throw new IllegalArgumentException("Ref cannot be longer than 256 characters!"); this.ref5 = ref; }
511b245e-2e55-49ff-80b8-6f0f76eab6fb
9
public static void complementaryGraph(mxAnalysisGraph aGraph) { ArrayList<ArrayList<mxCell>> oldConnections = new ArrayList<ArrayList<mxCell>>(); mxGraph graph = aGraph.getGraph(); Object parent = graph.getDefaultParent(); //replicate the edge connections in oldConnections Object[] vertices = aGraph.getChildVertices(parent); int vertexCount = vertices.length; for (int i = 0; i < vertexCount; i++) { mxCell currVertex = (mxCell) vertices[i]; int edgeCount = currVertex.getEdgeCount(); mxCell currEdge = new mxCell(); ArrayList<mxCell> neighborVertexes = new ArrayList<mxCell>(); for (int j = 0; j < edgeCount; j++) { currEdge = (mxCell) currVertex.getEdgeAt(j); mxCell source = (mxCell) currEdge.getSource(); mxCell destination = (mxCell) currEdge.getTarget(); if (!source.equals(currVertex)) { neighborVertexes.add(j, source); } else { neighborVertexes.add(j, destination); } } oldConnections.add(i, neighborVertexes); } //delete all edges and make a complementary model Object[] edges = aGraph.getChildEdges(parent); graph.removeCells(edges); for (int i = 0; i < vertexCount; i++) { ArrayList<mxCell> oldNeighbors = new ArrayList<mxCell>(); oldNeighbors = oldConnections.get(i); mxCell currVertex = (mxCell) vertices[i]; for (int j = 0; j < vertexCount; j++) { mxCell targetVertex = (mxCell) vertices[j]; boolean shouldConnect = true; // the decision if the two current vertexes should be connected if (oldNeighbors.contains(targetVertex)) { shouldConnect = false; } else if (targetVertex.equals(currVertex)) { shouldConnect = false; } else if (areConnected(aGraph, currVertex, targetVertex)) { shouldConnect = false; } if (shouldConnect) { graph.insertEdge(parent, null, null, currVertex, targetVertex); } } } };
90a3e5dd-1a0c-4201-85c9-59ed5da1d45e
0
public void setAuther(String auther) { this.auther = auther; }
3e7cf548-32b7-4f28-b507-b834bb553ab9
5
public void run(){ System.out.println("DownloadQueueProcessor Running"); while(parent.getRunning()){ //make sure program is still running while(parent.queue.isEmpty()){ try { Thread.sleep(TIME_SLEEP_IF_EMPTY); //if DL Queue is empty, pause for half a second before trying again } catch (InterruptedException e) { e.printStackTrace(); } } if(!parent.queue.isEmpty()){ String picToDL = parent.queue.deQueue(); //if(picToDL != null) picDownloader.download(picToDL); } try { Thread.sleep(TIME_PAUSE); //Allow thread to rest some time, before checking again. } catch (InterruptedException e) { e.printStackTrace(); } } }
d29b0039-47c0-495d-a518-8c94d0e9257f
0
public void setData(int newData) { data = newData; }
ebbaf58d-c5c4-490a-8679-add8afb82f5a
7
private void wilidingBattleResolution() { if(playerChoices.getWildingsCard().equals("PreemptiveRaid") && ((BiddingAgainstWild)model.getBidding()).victory()){ Family winFamily=model.getBidding().getTrack()[0]; model.preemptiveRaid(winFamily); if(getSeatNum()!=winFamily.getPlayer()){ playerChoices.bidding(); } }else{ model.wildingsResolution(playerChoices.getWildingsCard(), playerChoices); if(model.getPhase()!=ModelState.WILDLINGSRESOLUTION && model.getPhase()!=ModelState.SUPPLY_TO_LOW){//case when the wildings resolution is directly solve playerChoices.blank(); if(model.getWesterosPhase()==3){ model.nextPhase(); }else if(getSeatNum()==0){ /*case when the wildings where attacking beacause of the 12 power*/ String card = model.choseCard(); playerChoices.westerosCard(card); sendProperty("WesterosCard",card); } } } }
af5e45fc-95d7-4225-94ae-c1cf6fd7fcf5
0
public void setPrenom(String prenom) { this.prenom = prenom; }
505b5b22-8c6d-4cac-84e4-609baa4aa8f9
0
CarItf deserializeFromJson(String json) { AutoBean<CarItf> bean = AutoBeanCodex.decode(factory, CarItf.class, json); return bean.as(); }
257f5a28-b234-47a7-be0a-ba7f460ec28f
5
@Override public void importScan(NessusClientData scan) { PreparedStatement pstmt = null; try { String scanUuid = UUID.randomUUID().toString(); pstmt = connection.prepareStatement("INSERT INTO scans (UUID, NAME) VALUES(?,?)"); pstmt.setString(1, scanUuid); pstmt.setString(2, scan.getPolicy().getName()); pstmt.executeUpdate(); pstmt.close(); log.finest(String.format("Successfully added scan record: %s", scanUuid)); for(ReportHost host : scan.getReport().getReportHosts()) { String hostUuid = UUID.randomUUID().toString(); pstmt = connection.prepareStatement("INSERT INTO hosts (UUID, SCAN_UUID, HOSTNAME, IP) VALUES(?,?,?,?)"); pstmt.setString(1, hostUuid); pstmt.setString(2, scanUuid); pstmt.setString(3, host.getName()); pstmt.setString(4, host.getAddress()); pstmt.executeUpdate(); pstmt.close(); log.finest(String.format("Successfully added host '%s' to scan '%s'.", host.getName(), scanUuid)); for(ReportItem item : host.getReportItems()) { String vulnUuid = UUID.randomUUID().toString(); pstmt = connection.prepareStatement("INSERT INTO vulns (UUID, SCAN_UUID, HOST_UUID, DESCRIPTION, CRITICALITY, SEVERITY, SOLUTION, SYNOPSIS, PLUGIN_NAME, PLUGIN_FAMILY) VALUES(?,?,?,?,?,?,?,?,?,?)"); pstmt.setString(1, vulnUuid); pstmt.setString(2, scanUuid); pstmt.setString(3, hostUuid); pstmt.setString(4, item.getDescription()); pstmt.setString(5, item.getRiskFactor()); pstmt.setInt(6, item.getSeverity()); pstmt.setString(7, item.getPluginName()); pstmt.setString(8, item.getPluginFamily()); pstmt.executeUpdate(); pstmt.close(); log.finest(String.format("Successfully added vulnerability record '%s' for host '%s' and scan '%s'.", vulnUuid, host.getName(), scanUuid)); } } }catch(SQLException e) { log.warning(String.format("Could not import scan: %s", e.getMessage())); }finally{ if(pstmt != null) { try { pstmt.close(); }catch(SQLException e) {} } } }
b57233bf-6350-4557-935c-ffb3e12f759c
1
private String getLastResponse() throws Exception { if ( !formValues.containsKey(LAST_RESPONSE_KEY) ) throw new Exception("Last response was not found."); return formValues.get(LAST_RESPONSE_KEY); }
52867002-ff50-469c-919c-ce8d28a63314
0
public FSAAction(String string, Icon icon) { super(string, icon); }
de6ec309-db5a-442c-af2b-1648c139104a
0
private void startButtonclick() { view.startServer.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { view.startServer.setEnabled(false); server.startServer(view.portText.getText()); } }); }
c5fdf87e-cc2b-41c7-99c5-73c53b2e69b3
3
private synchronized void checkGridletCompletion() { ResGridlet obj = null; int i = 0; // NOTE: This one should stay as it is since gridletFinish() // will modify the content of this list if a Gridlet has finished. // Can't use iterator since it will cause an exception while ( i < gridletInExecList_.size() ) { obj = (ResGridlet) gridletInExecList_.get(i); if (obj.getRemainingGridletLength() == 0.0) { gridletInExecList_.remove(obj); gridletFinish(obj, Gridlet.SUCCESS); continue; } i++; } // if there are still Gridlets left in the execution // then send this into itself for an hourly interrupt // NOTE: Setting the internal event time too low will make the // simulation more realistic, BUT will take longer time to // run this simulation. Also, size of sim_trace will be HUGE! if (gridletInExecList_.size() > 0) { super.sendInternalEvent(60.0*60.0); } }
64c6af55-1251-4d59-9131-a009ba56ec1e
2
private void leerCoches(){ ArrayList<String> list = disco.leerArchivo("coches/coches"); String[] aux; for(int i=0; i<list.size(); ++i){ aux = list.get(i).split("\t"); if(!cjtClientes.containsKey(aux[5])) aux[5]="-NA-"; else cjtClientes.get(aux[5]).addCoche(aux[0]); cjtCoches.put(aux[0],new Coche(aux[0],aux[1],aux[2],aux[3], aux[4],aux[5])); } }
29ef631b-8c99-4de5-9abe-f7a3e6712d74
4
public String execute( String input ) { try { return (String) ( this.proMethod.invoke( this.executor.newInstance(), input)); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } return null; }
750c354e-3ac3-4a93-803a-15ca3c3bd44b
0
public Object peek() { return getFirst(); }
5ce69f1e-3ff8-4cb8-81aa-49eee1e9832f
9
private static boolean isEmptyOrWhitespace(final String target) { if (target == null) { return true; } final int targetLen = target.length(); if (targetLen == 0) { return true; } final char c0 = target.charAt(0); if ((c0 >= 'a' && c0 <= 'z') || (c0 >= 'A' && c0 <= 'Z')) { // Fail fast, by quickly checking first char without executing Character.isWhitespace(...) return false; } for (int i = 0; i < targetLen; i++) { final char c = target.charAt(i); if (c != ' ' && !Character.isWhitespace(c)) { return false; } } return true; }
0f2ddd0a-120f-4115-a014-090571364a81
5
public void asignarColumnaLetrasA(String nombreRespuesta, int numeroRespuesta){ switch(numeroRespuesta){ case 0: _jlbl1.setText(nombreRespuesta); break; case 1: _jlbl2.setText(nombreRespuesta); break; case 2: _jlbl3.setText(nombreRespuesta); break; case 3: _jlbl4.setText(nombreRespuesta); break; case 4: _jlbl5.setText(nombreRespuesta); break; } }
7621232a-c5a9-4824-a51a-8d5c9ac94c34
1
@Override public long spawnBoss(String bossData) { super.spawnBoss(bossData); GameActor a = Application.get().getLogic().createActor(bossData); PhysicsComponent pc = (PhysicsComponent)a.getComponent("PhysicsComponent"); pc.setLocation(x + 100, y + Display.getHeight() + 200); pc.setAngleRad(MathUtil.getOppositeAngleRad(upAngle)); pc.setTargetAngle(pc.getAngleRad()); AIComponent aic = (AIComponent)a.getComponent("AIComponent"); BaseAI ai = aic.getAI(); if(ai instanceof EnemyBossAI) { EnemyBossAI ebai = (EnemyBossAI)ai; ebai.setSector(ID); } return a.getID(); }
94f5b55f-0bfa-4b00-a8a8-9df487d60ec6
7
public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = ""; StringBuilder out = new StringBuilder(); HashMap<String, String> map = new HashMap<String, String>(); d: do { line = br.readLine(); if (line.length() == 0) break d; String[] w = line.split(" "); map.put(w[1], w[0]); } while (line.length() != 0); d: do { line = br.readLine(); if (line == null || line.length() == 0) break d; if(!map.containsKey(line)) out.append("eh").append("\n"); else out.append(map.get(line)).append("\n"); } while (line != null && line.length() != 0); System.out.print(out); }
65f0b14e-7682-400b-bd96-acf969367bc1
9
private FlowToken readNextTokenTextMode() throws SnuggleParseException { /* Look at first character to decide what type of token we're going to read. * * NB: If adding any trigger characters to the switch below, then you'll need to add * them to {@link #readNextSimpleTextParaMode()} as well to ensure that they terminate * regions of plain text as well. */ int c = workingDocument.charAt(position); switch(c) { case -1: return null; case '\\': /* This is \command, \verb or an environment control */ return readSlashToken(); case '$': /* Math mode $ or $$ */ return readDollarMath(); case '{': /* Start of a region in braces */ return readBraceRegion(); case '%': /* Start of a comment. This should have been caught earlier */ throw new SnuggleLogicException("Comment should be have been skipped before getting here!"); case '&': /* 'Tab' character */ return new SimpleToken(workingDocument.freezeSlice(position, position+1), TokenType.TAB_CHARACTER, currentModeState.latexMode, null); case '_': case '^': /* Error: These are only allowed in MATH mode */ return createError(CoreErrorCode.TTEM03, position, position+1); case '#': /* Error: This is only allowed inside command/environment definitions */ return createError(CoreErrorCode.TTEG04, position, position+1); default: /* Plain text or some paragraph nonsense */ return readNextSimpleTextParaMode(); } }
243bf644-d179-49ee-8741-04356f895561
4
public int[] agileCarMove(int x, int y, Direction direction, Car movingCar) { //Precondition: direction != null; movingCar != null; x & y are coordinates on the map //Postcondition: returns int[] with 2 elements which has coordinates on the map int returnX, returnY; int[] tmpInt = direction.moveRight(); returnX = x + tmpInt[0]; returnY = y + tmpInt[1]; movingCar.setDirection(direction.turnRight()); if(-1 < returnX && returnX < width && -1 < returnY && returnY < height){ return new int[]{returnX, returnY}; } return new int[]{-1, -1}; }
328ea47d-5332-46e4-9121-1644867958e8
7
@Override protected void initCentroids(int k) { final int size = this.docs.size(); final Random rand = new Random(); final Double firstCendroid = rand.nextDouble() * size; this.centroids.add(firstCendroid.intValue()); Map<Integer, Double> distances; Double distanceSum; for (int i = 0; i < k - 1; i++) { distances = new HashMap<Integer, Double>(); distanceSum = 0.0; for (int j = 0; j < this.docs.size(); j++) { double termDistanceSqure = super.findClosestCentroidDistance(j); termDistanceSqure = termDistanceSqure * termDistanceSqure; distances.put(j, termDistanceSqure); distanceSum += termDistanceSqure; } final List<Map.Entry<Integer, Double>> distancesList = new LinkedList<Map.Entry<Integer, Double>>( distances.entrySet()); for (final Map.Entry<Integer, Double> docIdTodistance : distancesList) { docIdTodistance.setValue(docIdTodistance.getValue() / distanceSum); } Collections.sort(distancesList, new Comparator<Map.Entry<Integer, Double>>() { @Override public int compare(Map.Entry<Integer, Double> o1, Map.Entry<Integer, Double> o2) { return (o1.getValue()).compareTo(o2.getValue()); } }); final Map<Integer, Double> probDistMap = new LinkedHashMap<Integer, Double>(); Double sum = distancesList.get(0).getValue(); for (int j = 1; j < distancesList.size(); j++) { final Entry<Integer, Double> docIdTodistance = distancesList.get(j); probDistMap.put(docIdTodistance.getKey(), docIdTodistance.getValue() + sum); sum += docIdTodistance.getValue(); } final List<Entry<Integer, Double>> probDistList = new ArrayList<Entry<Integer, Double>>( probDistMap.entrySet()); Collections.sort(probDistList, new Comparator<Entry<Integer, Double>>() { @Override public int compare(Entry<Integer, Double> o1, Entry<Integer, Double> o2) { return o1.getValue().compareTo(o2.getValue()); } }); final double randNum = rand.nextDouble(); int clusterIndex = probDistList.get(0).getKey(); for (int j = 1; j < probDistList.size(); j++) { if (probDistList.get(j - 1).getValue() < randNum && probDistList.get(j).getValue() >= randNum) { clusterIndex = probDistList.get(j).getKey(); } } this.centroids.add(clusterIndex); } }
6e3a89e0-5cde-49d2-b8f2-1dc8cbaa2c67
6
@SuppressWarnings("deprecation") private void processDirectoryRequest(OMMSolicitedItemEvent event) { System.out.println(_instanceName + " Received Directory request"); OMMMsg msg = event.getMsg(); Token token = event.getRequestToken(); int msgType = msg.getMsgType(); switch (msgType) { case OMMMsg.MsgType.REQUEST: makeRequest(msg, token); return; case OMMMsg.MsgType.STREAMING_REQ: case OMMMsg.MsgType.NONSTREAMING_REQ: case OMMMsg.MsgType.PRIORITY_REQ: System.out.println("Received deprecated message type of " + OMMMsg.MsgType.toString(msg.getMsgType()) + ", not supported. "); return; case OMMMsg.MsgType.CLOSE_REQ: closeRequest(token); return; case OMMMsg.MsgType.GENERIC: System.out.println("Received generic message type, not supported. "); return; default: System.out.println("ERROR: Received unexpected message type. " + msgType); return; } }
f41a3e16-547d-4cfb-88b9-d07aef8af3cd
3
@SuppressWarnings("unchecked") public ArrayList<Integer> getCorrectChoiceIndexes() { ArrayList<Integer> indexList = new ArrayList<Integer>(); ArrayList<String> questionList = (ArrayList<String>) question; ArrayList<String> answerList = (ArrayList<String>) answer; for (int i = 1; i < questionList.size(); i++) for (int j = 0; j < answerList.size(); j++) { if (answerList.get(j).equals(questionList.get(i))) { indexList.add(new Integer(i)); break; } } return indexList; }
54f7f8e5-15a1-42a5-9c15-e62f10a69ad2
8
public String getContentType(File file) { String fileName = file.getName(); String contentType; if (fileName.endsWith(".htm") || fileName.endsWith(".html")) contentType = "text/html"; else if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) contentType = "image/jpeg"; else if (fileName.endsWith(".png")) contentType = "image/png"; else if (fileName.endsWith(".gif")) contentType = "image/gif"; else if (fileName.endsWith(".pdf")) contentType = "application/pdf"; else if (fileName.endsWith(".ico")) contentType = "image/x-icon"; else contentType = "text/plain"; return contentType; }
05eee7bf-10b4-433f-b850-960b32bc582f
4
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestDispatcher dispatcher = request.getRequestDispatcher(VIEW); //een boolean om te controleren of de testCookie aanwezig is boolean testCookieTest = false; //nagaan of er wel cookies zijn if (request.getCookies() != null) { //al de cookies overlopen en controlleren of de testCookie erbij zit for (Cookie cookie:request.getCookies()) { if (cookie.getName().equals("testCookie")) { request.setAttribute("cookieWaarde", "Ja, de cookie value is \"" + cookie.getValue() + "\""); testCookieTest = true; } } } //doorgeven als er geen testCookie bestaat if (! testCookieTest) { request.setAttribute("cookieWaarde", "Nee"); } dispatcher.forward(request, response); }
1773e855-1c2d-4e9c-af16-2b6b4424dac3
8
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Section other = (Section) obj; if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) { return false; } if ((this.title == null) ? (other.title != null) : !this.title.equals(other.title)) { return false; } return (this.uriTag == null) ? other.uriTag == null : this.uriTag.equals(other.uriTag); }
81c67901-3736-423e-a7de-074b46a6150b
5
private void utters(Actor a, String s) { boolean picked = false ; for (Dialogue d : sides()) { if (BaseUI.isPicked(d.actor())) picked = true ; } if (! picked) return ; final Actor opposite = a == actor ? other : actor ; final boolean onRight = onRight(a, opposite) ; final int side = onRight ? TalkFX.FROM_RIGHT : TalkFX.FROM_LEFT ; a.chat.addPhrase(s, side) ; }
cb3c965b-8155-4527-b379-c75dac747ca7
9
static Map<Package, List<Class<?>>> categorize(Collection<Class<?>> comp) { Map<Package, List<Class<?>>> packages = new HashMap<Package, List<Class<?>>>(); for (Class<?> c : comp) { Package p = c.getPackage(); List<Class<?>> tos = packages.get(p); if (tos == null) { tos = new ArrayList<Class<?>>(); packages.put(p, tos); } tos.add(c); } return packages; }
fc819db7-82b9-4ef5-a6c7-cef571c8c0a9
2
public void add(String word) { char[] wordChars = word.toCharArray(); for (int i = 0; i < wordChars.length; i++) { char before = wordChars[i]; wordChars[i] = (char) 0; String key = String.valueOf(wordChars); HashSet<String> valueSet = graph.get(key); if (valueSet == null) { valueSet = new HashSet<String>(); graph.put(key, valueSet); } valueSet.add(word); wordChars[i] = before; } }
597fa1f9-1fd1-4c85-bee4-0adbc671556f
5
@Override public int indexOf(Object o) { // TODO Auto-generated method stub if (o == null) { for (int i = 0; i < size(); i++) if (get(i)==null) return i; } else { for (int i = 0; i < size(); i++) if (((String)o).equalsIgnoreCase(get(i))) return i; } return -1; }
20de951d-57b7-48d7-846c-ecfbf50b89b7
6
public void listMouseClicked(MouseEvent e) { if(e.getClickCount() == 2) { ArrayList<GeometricObject> temp; if(mytabbedpane.getSelectedIndex()==0) { temp=geomListleft; } else { temp=geomListright; } switch (list.getSelectedValue()) { case "Kreis" : temp.add(new Kreis(1, 1, 51, 51)); break; case "Rechteck" : temp.add(new Rechteck(1, 1, 51, 51)); break; case "Linie" : temp.add(new Linie(1, 1, 51, 51)); break; case "Connector" : temp.add(new Connector(0,0)); break; } wasSaved = false; repaint(); } }
3a5502c3-cd2c-430d-aeb1-49b7dac145f5
0
public static void setFileBase(FileDataBase data){ fileBase = data; }
115ddaf0-90c2-47dd-bd58-62263c402a71
5
private int calculateNextOrderIndex() { int followingOrderIndex = 0; for (List<QualifiedValue<?>> vals : fields.values()) { for (QualifiedValue<?> val : vals) { if (val.getOrderIndex() >= followingOrderIndex) { followingOrderIndex = val.getOrderIndex() + 1; } } } return followingOrderIndex; }
789b6d4e-d593-4ab4-ada5-652b8c6b0e35
6
public void computeRoutingTables(int iterations,boolean splitHorizon){ String msg = "Calculating "+iterations+" iteration(s)."; if(splitHorizon){ msg += "\nSplit Horizon enabled."; } else { msg += "\nSplit Horizon disabled."; } System.out.println(msg); for(int i=0;i<iterations;i++){ boolean updated = false; this.currentIteration++; System.out.println("iteration: "+(i+1)); for(Node n : nodes){ updated = n.updateRoutingTable(); } if(!updated && i==0){ //after the first iteration, nothing has changed. So already stable System.out.println("Network already stable. "); return; } if(!updated){ //no changed to any routing table were made in the last iteration System.out.println("Network converged at "+i+"."); return; } } }
c9f6956d-c8d3-4e3c-b784-765d3575b4f2
1
public ArrayList<Handler> getHandlersList() throws ClassNotFoundException, IllegalAccessException, InstantiationException, IOException { ArrayList<Handler> outList = new ArrayList<Handler>(); Gson json = new Gson(); JsonReader jReader = new JsonReader(jFileReader); ArrayList<String> handlers = json.fromJson(jReader,new TypeToken<List<String>>(){}.getType()); for (int i = 0; i < handlers.size(); i++) { Class c = Class.forName(handlers.get(i)); Object o = c.newInstance(); outList.add((Handler) o); } return outList; }
a2167425-df8e-4297-a43c-ed7f628a3b04
3
public Email Abrir(int id){ try{ PreparedStatement comando = banco.getConexao() .prepareStatement("SELECT * FROM emails WHERE id = ? AND ativo = 1"); comando.setInt(1, id); ResultSet consulta = comando.executeQuery(); comando.getConnection().commit(); Email tmp = null; if(consulta.first()){ tmp = new Email(); tmp.setEndereco(consulta.getString("endereco")); tmp.setId(consulta.getInt("id")); } return tmp; }catch(SQLException ex){ ex.printStackTrace(); return null; }catch(ErroValidacaoException ex){ ex.printStackTrace(); return null; } }
7cdebc03-6b47-41ac-8a53-bc2237cfe27b
3
public static String[] getMaps() { File file = new File(CFG.DIR, "maps"); if (!file.exists() || !file.isDirectory()) { file.delete(); file.mkdir(); } String[] names = new String[file.list().length]; for (int i = 0; i < names.length; i++) { names[i] = file.list()[i].substring(0, file.list()[i].lastIndexOf(".")); } return names; }
fd99b3c5-e96d-49a9-b171-941144097f60
0
public void push(E element) { stack.insert(element); }
0dbd488c-e54d-4bc0-8e19-351718a7f4f7
9
@Override public void insert(String value) { // Keeps track if the value has a collision. boolean collisioned = false; // Gets rid of the values that are not words. if (value == null || !value.matches("^[a-zA-Z]+$")) return; int hashVal = hashFunc(value); // Iterate over the items until an opening is found (null) or if a same value already exists. while (hashArray[hashVal] != null && !hashArray[hashVal].getValue().equals(value)) { // If it is the first time, then check if the current item has the same hash value as the new one. if (!collisioned && hashFunc(hashArray[hashVal].getValue()) == hashVal) { collisioned = true; } hashVal++; hashVal %= arraySize; } // If the item is a new item, then put it in place and increase the number of elements. if (hashArray[hashVal] == null) { hashArray[hashVal] = new DataItem(value.toLowerCase(), 1); numOfElements++; if (collisioned) { collisionCounter++; } } // else the item already exists and increase the counter. else { hashArray[hashVal].increaseFrequency(); } // If after inserting the value, the load factor threshold is reached, then rehash the hash table. if (((double) size()) / arraySize > LOAD_FACTOR) rehash(); }
be2f005d-de94-46db-91a6-66c82518054b
5
public void combination(List<Integer> list,int[] candidates,int index, int target ){ if(target <= 0){ if(target == 0){ result.add(new ArrayList<Integer>(list)); } return; } for(int i =index; i < candidates.length;i++){ if(i > 1 && candidates[i] == candidates[i-1]) continue; list.add(candidates[i]); combination(list,candidates,i,target-candidates[i]); list.remove(list.size()-1); } }
791f8b61-1d54-46c3-a610-7ce75869d7dd
0
public String toString() { return "valve1 = " + valve1 + " " + "valve2 = " + valve2 + " " + "valve3 = " + valve3 + " " + "valve4 = " + valve4 + "\n" + "i = " + i + " " + "f = " + f + " " + "source = " + source; }
9247b10e-7aa0-411d-916c-2c9abf251a9f
3
public void disconnect() { boolean disconnected = false; synchronized(CONNECTION_LOCK) { if(isConnected) { logger.fine("Disconnecting from " + serverAddress + ":" + serverPort); disconnectQuietly(); disconnected = true; } else if(isAttemptingToConnect) { logger.fine("Cancelling connect request to " + serverAddress + ":" + serverPort); closeConnection(); } } if(disconnected) onDisconnected(ClientConnection.DISCONNECTED_BY_CLIENT); }
89cb8258-5e9c-4bda-9b6d-048dc90be0b8
4
public void setOption( String op, String val ) { if( op.equals( "lblAlign" ) ) { // ctr, l, r if( val.equals( "ctr" ) ) { at = 2; } else if( val.equals( "l" ) ) { at = 1; } else { at = 3; } } else if( op.equals( "lblOffset" ) ) { // 0-100 wOffset = (short) Integer.parseInt( val ); } updateRecord(); }
d05fc5b0-4bf0-4ba0-8f01-8a7d9322e012
8
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub JSONObject jb = new JSONObject(); String userId = request.getParameter("userId"); String groupId = request.getParameter("groupId"); Mongo mongo = new Mongo(); DB scheduleDB = mongo.getDB("schedule"); DBCollection groupCollection = scheduleDB.getCollection("group_"+userId); DBObject groupQuery = new BasicDBObject(); groupQuery.put("groupName", "All friends"); DBCursor defGroupCur = groupCollection.find(groupQuery); if(defGroupCur.hasNext()){ DBObject tarGroupDBObject = defGroupCur.next(); try { String defGroupMemberString = tarGroupDBObject.get("member").toString(); JSONArray defGroupMemberArray = new JSONArray(defGroupMemberString); JSONArray memberExcludeArray = new JSONArray(); for(int i = 0; i < defGroupMemberArray.length(); i++){ String memberId = defGroupMemberArray.get(i).toString(); DBObject tarGroupQuery = new BasicDBObject(); tarGroupQuery.put("_id", new ObjectId(groupId)); tarGroupQuery.put("member", memberId); DBCursor tarGroupCur = groupCollection.find(tarGroupQuery); if(!tarGroupCur.hasNext()){ DBCollection userCollection = scheduleDB.getCollection("user"); DBObject userQuery = new BasicDBObject(); userQuery.put("_id", new ObjectId(memberId)); DBCursor userCur = userCollection.find(userQuery); if(userCur.hasNext()){ DBObject newMemberObject = userCur.next(); String memberName = (String)newMemberObject.get("username"); String memberImage = (String)newMemberObject.get("image"); JSONObject stragerObject = new JSONObject(); stragerObject.put("memberId", memberId); stragerObject.put("memberName", memberName); stragerObject.put("memberImage", memberImage); memberExcludeArray.put(stragerObject); }else{ jb.put("result", Primitive.DBCONNECTIONERROR); break; } } } jb.put("result", Primitive.ACCEPT); jb.put("memberExcludeArray", memberExcludeArray); } catch(NullPointerException npe){ JSONArray memberExcludeArray = new JSONArray(); try { jb.put("result", Primitive.ACCEPT); jb.put("memberExcludeArray", memberExcludeArray); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } }catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else{ try { jb.put("result", Primitive.DBCONNECTIONERROR); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } response.setCharacterEncoding("UTF-8"); PrintWriter writer = response.getWriter(); String jbString = new String(jb.toString().getBytes(),"UTF-8"); writer.write(jbString); writer.flush(); writer.close(); }
3d6b9e20-ff58-4116-b1b1-3b2d5a09bcd6
4
private void initJoyStick(){ stick = new Joystick(screen, Vector2f.ZERO, (int)(screen.getWidth()/6)) { @Override public void onUpdate(float tpf, float deltaX, float deltaY) { float dzVal = .2f; // Dead zone threshold if (deltaX < -dzVal) { stateManager.getState(InteractionManager.class).up = false; stateManager.getState(InteractionManager.class).down = false; stateManager.getState(InteractionManager.class).left = true; stateManager.getState(InteractionManager.class).right = false; } else if (deltaX > dzVal) { stateManager.getState(InteractionManager.class).up = false; stateManager.getState(InteractionManager.class).down = false; stateManager.getState(InteractionManager.class).left = false; stateManager.getState(InteractionManager.class).right = true; } else if (deltaY < -dzVal) { stateManager.getState(InteractionManager.class).left = false; stateManager.getState(InteractionManager.class).right = false; stateManager.getState(InteractionManager.class).down = true; stateManager.getState(InteractionManager.class).up = false; } else if (deltaY > dzVal) { stateManager.getState(InteractionManager.class).left = false; stateManager.getState(InteractionManager.class).right = false; stateManager.getState(InteractionManager.class).down = false; stateManager.getState(InteractionManager.class).up = true; } else { stateManager.getState(InteractionManager.class).left = false; stateManager.getState(InteractionManager.class).right = false; stateManager.getState(InteractionManager.class).up = false; stateManager.getState(InteractionManager.class).down = false; } player.speedMult = FastMath.abs(deltaY); } }; // getGUIRegion returns region info “x=0|y=0|w=50|h=50″, etc TextureKey key = new TextureKey("Textures/barrel/D.png", false); Texture tex = assetManager.loadTexture(key); stick.setTextureAtlasImage(tex, "x=20|y=20|w=120|h=35"); stick.getThumb().setTextureAtlasImage(tex, "x=20|y=20|w=120|h=35"); screen.addElement(stick, true); stick.setPosition(screen.getWidth()/10 - stick.getWidth()/2, screen.getHeight() / 10f - interactButton.getHeight()/5); // Add some fancy effects Effect fxIn = new Effect(Effect.EffectType.FadeIn, Effect.EffectEvent.Show,.5f); stick.addEffect(fxIn); Effect fxOut = new Effect(Effect.EffectType.FadeOut, Effect.EffectEvent.Hide,.5f); stick.addEffect(fxOut); stick.show(); }
c53d18ca-2e69-44b5-92e1-c06649098aa2
1
@Override public void draw(Graphics page) { shipImage.drawImage(page, xLocation, yLocation);//Draws the plane on the component //Draws the collision Border if(this.getBorderVisibility()) { drawCollisionBorder(page,xLocation,yLocation,shipImage.getWidth(),shipImage.getHeight()); } }
eb4da94f-7b9b-4249-88d3-e67fea60150c
9
public static void main(String [] args) throws FileNotFoundException { //Read in all the possible data points into the arrayList that will hold them ArrayList<DataPoint> d = new ArrayList<DataPoint>(); Scanner s = new Scanner(new File("bitvals.txt")); //int i = 0; //p vals are bitvals all of which are collated into a single point double p1 = 0; double p2 = 0; double p3 = 0; double p4 = 0; double p5 = 0; //tvals are for timestamps int t1 =0; int t2 = 0; int t3 = 0; int t4 = 0; int t5 = 0; while(s.hasNextLine()/*&& i < 3500000*/) { //This pattern cuts out the commas from the file and combines the two values separated by decimal to a single double //If clauses prevent overrunning end of file and if we don't have all 5 necessary values then we throw them out and close the file s.findInLine("(\\d+)([0-9]*\\.[0-9]*)"); MatchResult m = s.match(); if(s.hasNextLine()) { t1 = Integer.parseInt(m.group(1)); p1 = Double.parseDouble(m.group(0)); s.nextLine(); //Create second value in a data point if(s.hasNextLine()) { s.findInLine("(\\d+)([0-9]*\\.[0-9]*)"); m = s.match(); t2 = Integer.parseInt(m.group(1)); p2 = Double.parseDouble(m.group(0)); s.nextLine(); //Create third value in a data point if(s.hasNextLine()) { s.findInLine("(\\d+)([0-9]*\\.[0-9]*)"); m = s.match(); t3 = Integer.parseInt(m.group(1)); p3 = Double.parseDouble(m.group(0)); s.nextLine(); //Create fourth value if(s.hasNextLine()) { s.findInLine("(\\d+)([0-9]*\\.[0-9]*)"); m = s.match(); t4 = Integer.parseInt(m.group(1)); p4 = Double.parseDouble(m.group(0)); s.nextLine(); //Create last value this is the one that we test against. I.E the first four values are read into the neural net as features and the output is the fifth //Thus in practice we will use four closest values for which we have data as features //Future implementations might compute the four values if data is unavailable before spitting out a final prediction if(s.hasNextLine()) { s.findInLine("(\\d+)([0-9]*\\.[0-9]*)"); m = s.match(); t5 = Integer.parseInt(m.group(1)); p5 = Double.parseDouble(m.group(0)); } else { t5 = 0; p5 = 0; break; } } else { t4 = 0; p4 = 0; break; } } else { t3 = 0; p3 = 0; break; } } else { t2 = 0; p2 = 0; } } else { t1=0; p1=0; } //Add our full data point to the array d.add(new DataPoint(p1,t1,p2,t2,p3,t3,p4,t4,p5,t5)); } s.close(); //tRM is the neural net used NeuralNet theRealMccoy = new NeuralNet(); //We define tRM's output function to be a linear combination of first degree poly's theRealMccoy.setOutputNeuron(new Neuron(new PolynomialTerm(1))); //We begin adding features. Here they are days of the week and month and then the first four values //The p values here add each successive feature to a list that the final function is based off of. Adding a feature to the neural net only creates a spot for it in the computed function p stores values that are assigned for each data point read in theRealMccoy.addInputNeuron(new Neuron(new PrimaryInput("Monday"))); PrimaryInput p = new PrimaryInput("Monday"); theRealMccoy.addInputNeuron(new Neuron(new PrimaryInput("Tuesday"))); p = new PrimaryInput("Tuesday"); theRealMccoy.addInputNeuron(new Neuron(new PrimaryInput("Wednesday"))); p = new PrimaryInput("Wednesday"); theRealMccoy.addInputNeuron(new Neuron(new PrimaryInput("Thursday"))); p = new PrimaryInput("Thursday"); theRealMccoy.addInputNeuron(new Neuron(new PrimaryInput("Friday"))); p = new PrimaryInput("Friday"); theRealMccoy.addInputNeuron(new Neuron(new PrimaryInput("Saturday"))); p = new PrimaryInput("Saturday"); theRealMccoy.addInputNeuron(new Neuron(new PrimaryInput("Sunday"))); p = new PrimaryInput("Sunday"); theRealMccoy.addInputNeuron(new Neuron(new PrimaryInput("January"))); p = new PrimaryInput("January"); theRealMccoy.addInputNeuron(new Neuron(new PrimaryInput("February"))); p = new PrimaryInput("February"); theRealMccoy.addInputNeuron(new Neuron(new PrimaryInput("March"))); p = new PrimaryInput("March"); theRealMccoy.addInputNeuron(new Neuron(new PrimaryInput("April"))); p = new PrimaryInput("April"); theRealMccoy.addInputNeuron(new Neuron(new PrimaryInput("May"))); p = new PrimaryInput("May"); theRealMccoy.addInputNeuron(new Neuron(new PrimaryInput("June"))); p = new PrimaryInput("June"); theRealMccoy.addInputNeuron(new Neuron(new PrimaryInput("July"))); p = new PrimaryInput("July"); theRealMccoy.addInputNeuron(new Neuron(new PrimaryInput("August"))); p = new PrimaryInput("August"); theRealMccoy.addInputNeuron(new Neuron(new PrimaryInput("September"))); p = new PrimaryInput("September"); theRealMccoy.addInputNeuron(new Neuron(new PrimaryInput("October"))); p = new PrimaryInput("October"); theRealMccoy.addInputNeuron(new Neuron(new PrimaryInput("November"))); p = new PrimaryInput("November"); theRealMccoy.addInputNeuron(new Neuron(new PrimaryInput("December"))); p = new PrimaryInput("December"); theRealMccoy.addInputNeuron(new Neuron(new PrimaryInput("p1"))); p = new PrimaryInput("p1"); theRealMccoy.addInputNeuron(new Neuron(new PrimaryInput("p2"))); p = new PrimaryInput("p2"); theRealMccoy.addInputNeuron(new Neuron(new PrimaryInput("p3"))); p = new PrimaryInput("p3"); theRealMccoy.addInputNeuron(new Neuron(new PrimaryInput("p4"))); p = new PrimaryInput("p4"); for(int j = 0; j<(int)((4.4*d.size())/5); j++ ) { //We assign values to the features for each data point DataPoint dp = d.get(j); p.setInput("Monday", dp.features[12]); p.setInput("Tuesday", dp.features[13]); p.setInput("Wednesday", dp.features[14]); p.setInput("Thursday", dp.features[15]); p.setInput("Friday", dp.features[16]); p.setInput("Saturday", dp.features[17]); p.setInput("Sunday", dp.features[18]); p.setInput("January", dp.features[0]); p.setInput("February", dp.features[1]); p.setInput("March", dp.features[2]); p.setInput("April", dp.features[3]); p.setInput("May", dp.features[4]); p.setInput("June", dp.features[5]); p.setInput("July", dp.features[6]); p.setInput("August", dp.features[7]); p.setInput("September", dp.features[8]); p.setInput("October", dp.features[9]); p.setInput("November", dp.features[10]); p.setInput("December", dp.features[11]); p.setInput("p1", dp.fVals[0]); p.setInput("p2", dp.fVals[1]); p.setInput("p3", dp.fVals[2]); p.setInput("p4", dp.fVals[3]); //Learn updates the weights for each feature based on how close the current model is to the prediction for each successive data point in the training set. The alpha value makes sure that each incremental change is not too large but the amount changed is based off the gradient of the error between expected and returned theRealMccoy.learn(dp); } System.out.println("Final Equation with variables plugged in: " + theRealMccoy.getOutputNeuron()); for(int k =(int) (4.4*d.size()/5); k<d.size();k++) { //Repeat same proccess for testing DataPoint dp = d.get(k); p.setInput("Monday", dp.features[12]); p.setInput("Tuesday", dp.features[13]); p.setInput("Wednesday", dp.features[14]); p.setInput("Thursday", dp.features[15]); p.setInput("Friday", dp.features[16]); p.setInput("Saturday", dp.features[17]); p.setInput("Sunday", dp.features[18]); p.setInput("January", dp.features[0]); p.setInput("February", dp.features[1]); p.setInput("March", dp.features[2]); p.setInput("April", dp.features[3]); p.setInput("May", dp.features[4]); p.setInput("June", dp.features[5]); p.setInput("July", dp.features[6]); p.setInput("August", dp.features[7]); p.setInput("September", dp.features[8]); p.setInput("October", dp.features[9]); p.setInput("November", dp.features[10]); p.setInput("December", dp.features[11]); p.setInput("p1", dp.fVals[0]); p.setInput("p2", dp.fVals[1]); p.setInput("p3", dp.fVals[2]); p.setInput("p4", dp.fVals[3]); //The only real difference is here we do not learn. Rather we are interested in how close our prediction for each data point is to the actual value recorded as the fifth value in each data point in the testing set. //Squared error gets +- error of expected versus actual squares it and adds it in accordance with the error model for neural nets theRealMccoy.getSquaredError(dp); } //Math things into place by dividing for number of points and taking square root System.out.println("Average error of our net:" +Math.sqrt(theRealMccoy.getAverageLoss(d))); //This is largely unneccessary its just a comparison to what the prediction would be for each point if our algorithm was just to take the average of the four closest values and use that as our guess. Note that a shitty neural net beats the tar out of it by more than plus or minus 100 in many cases. double sMEV = 0; for(DataPoint dp : d) { sMEV += Math.pow(dp.getExpected()-(dp.fVals[0]+dp.fVals[1]+dp.fVals[2]+dp.fVals[3]+dp.fVals[4])/5, 2); } sMEV /= d.size(); sMEV = Math.pow(sMEV, 0.5); System.out.println("Error of the naive expectation: "+ sMEV); }
8d9da374-b11d-4eb6-9aa7-8b7cde8a047e
0
public static void main(String[] args) { long[]arr = new long[]{2,3,4}; arr[0] = 1; System.out.println(arr[0]); System.out.println(arr[1]); System.out.println(arr[2]); System.out.println(arr[3]); }
1dfde07e-1746-4c21-bd0e-fb6af50ac513
4
public static String readFile(String path){ //System.out.println("path : " + path + " reading..."); String sCurrentLine; String sJSON = ""; BufferedReader bReader = null; try{ FileReader fReader = new FileReader(path); bReader = new BufferedReader(fReader,16000); while ((sCurrentLine = bReader.readLine()) != null) { sJSON += sCurrentLine; } } catch (IOException e) { e.printStackTrace(); } finally { try { if (bReader != null)bReader.close(); } catch (IOException ex) { ex.printStackTrace(); } } //System.out.println("reading done"); //System.exit(0); return sJSON; }
a250436d-dcad-47b4-8000-669259e4250b
5
private boolean boardIsFull() { for (int x=0; x < boardWidth; x++) { for (int y=0; y < boardWidth; y++) { if (sudokuTextFields[y][x].getText() == null || sudokuTextFields[y][x].getText().isEmpty() || boardVals[y][x] == NULL_VAL) return false; } } return true; }
288faa98-f8ea-4f72-8d5e-29a2b2df08aa
0
public void close(){ this.vue.setVisible(false); }
830eea0b-195a-4049-99ae-4c569ad56c84
9
private void enableUpdater() { if(config.getBoolean("Updater.check-for-updates")) { Updater updater = new Updater(this, 55348, this.getFile(), Updater.UpdateType.NO_DOWNLOAD, false); if(config.getBoolean("Updater.notify-console")) { if(updater.getResult() == UpdateResult.NO_UPDATE) console.sendMessage(pre + "§aUpdater: You are running the latest version! :)"); else if(updater.getResult() == UpdateResult.UPDATE_AVAILABLE) console.sendMessage(pre + "§4Updater: Update available! (Colored)Armor " + updater.getLatestName() + " (" + updater.getLatestType().name() + ") for " + updater.getLatestGameVersion()); else if(updater.getResult() == UpdateResult.FAIL_BADID) console.sendMessage(pre + "§cUpdater: Fail Bad ID!"); else if(updater.getResult() == UpdateResult.FAIL_DBO) console.sendMessage(pre + "§cUpdater: Fail unable to contact download file!"); else if(updater.getResult() == UpdateResult.FAIL_NOVERSION) console.sendMessage(pre + "§cUpdater: Fail no version!"); else if(updater.getResult() == UpdateResult.FAIL_APIKEY) console.sendMessage(pre + "§cUpdater: Invalid API Key!"); else if(updater.getResult() == UpdateResult.DISABLED) console.sendMessage(pre + "§cUpdater: The Updater is disabled!"); } } }
6a23f195-12a4-4330-868b-e25f0052dbb6
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()) { String str = info.getName(); if ("Nimbus".equals(info.getName())) { //Nimbus GTK+ javax.swing.UIManager.setLookAndFeel(info.getClassName()); //break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Gphelper.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Gphelper.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Gphelper.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Gphelper.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new Gphelper().setVisible(true); } }); }
27d41215-bffe-4dca-8fae-561d2c3cfc70
3
private void addCall(final Instruction inst, final int kind) { final MemberRef method = (MemberRef) inst.operand(); final Type type = method.nameAndType().type(); final Type[] paramTypes = type.paramTypes(); final Expr[] params = new Expr[paramTypes.length]; for (int i = paramTypes.length - 1; i >= 0; i--) { params[i] = stack.pop(paramTypes[i]); } Expr top; if (inst.opcodeClass() != Opcode.opcx_invokestatic) { final Expr obj = stack.pop(Type.OBJECT); top = new CallMethodExpr(kind, obj, params, method, type .returnType()); } else { top = new CallStaticExpr(params, method, type.returnType()); } if (type.returnType().equals(Type.VOID)) { addStmt(new ExprStmt(top)); } else { stack.push(top); } }
c2afb4cc-f50e-43e6-9713-69211f1b3bec
0
public int[] sort() { int length; length = array.length; this.tempMergArr = new int[length]; doMergeSort(0, length - 1); return array; }
5f461ad1-490d-4092-b9d6-f03b4178eb02
0
private static ImageProcessor yGradient(ImageProcessor ip){ ImageProcessor result = ip.duplicate(); int[] Gy = {-1, -2, -1, 0, 0, 0, 1, 2, 1}; result.convolve3x3(Gy); return result; }
d5f4f04c-6356-469a-99d8-fe02fa8bcdfa
5
public Map<String,String> toParameterMap() { Map<String,String> parameters = new LinkedHashMap<String,String>(); parameters.put("merchant_id",getMerchantId()); if (GoCoin.hasValue(getStatus())) { parameters.put("status",getStatus()); } if (GoCoin.hasValue(getStartTs())) { parameters.put("start_time",getStartTsString()); } if (GoCoin.hasValue(getEndTs())) { parameters.put("end_time",getEndTsString()); } if (GoCoin.hasValue(getPageNumber())) { parameters.put("page_number",getPageNumber()); } if (GoCoin.hasValue(getPerPage())) { parameters.put("per_page",getPerPage()); } return parameters; }
0e6e546e-76de-4d4a-9021-11de1782804d
4
@Override public Value evaluate(Value... arguments) throws Exception { // Check the number of argument if (arguments.length == 1) { // get Value Value value = arguments[0]; // If numerical if (value.getType().isNumeric()) { return new Value(new Double(Math.sin(value.getDouble()))); } if (value.getType() == ValueType.ARRAY) { Value[] vector = value.getValues(); Value result[] = new Value[vector.length]; for (int i = 0; i < vector.length; i++) { result[i] = evaluate(vector[i]); } return new Value(result); } // the type is incorrect throw new EvalException(this.name() + " function does not handle " + value.getType().toString() + " type"); } // number of argument is incorrect throw new EvalException(this.name() + " function only allows one numerical parameter"); }
882003e2-005d-4f26-93bf-0706bc32b9a9
4
private static Line below(LinkedList<Line> tLines, Line l) { int index = -1; for (Line l0 : tLines) { if (l0 == l) { index = tLines.indexOf(l); break; } } if (index < tLines.size() - 1) { return tLines.get(index + 1); } else if (index == tLines.size() - 1) { return null; } return null; }
2a2ccf77-d26c-4d29-98cc-fd56435b8e0d
8
public void parseMethod(Parser parser, CompilationUnitDeclaration unit) { //connect method bodies if (unit.ignoreMethodBodies) return; //members if (this.memberTypes != null) { int length = this.memberTypes.length; for (int i = 0; i < length; i++) this.memberTypes[i].parseMethod(parser, unit); } //methods if (this.methods != null) { int length = this.methods.length; for (int i = 0; i < length; i++) { this.methods[i].parseStatements(parser, unit); } } //initializers if (this.fields != null) { int length = this.fields.length; for (int i = 0; i < length; i++) { final FieldDeclaration fieldDeclaration = this.fields[i]; switch(fieldDeclaration.getKind()) { case AbstractVariableDeclaration.INITIALIZER: ((Initializer) fieldDeclaration).parseStatements(parser, this, unit); break; } } } }
c2ff4e57-fbb7-4a37-9a03-6da96f8adc6b
1
@Override public void recieveEvent(Event event) { if(event.getEventType() == EventType.OUTPUT) { String text = (String) event.getData(); voice.speak(text); } // System.out.println(this.getClass().toString() + " recieved event:"); // System.out.println(event); }
20046a3b-5a4b-423b-8b23-8adb399345e6
4
public static void main(String[] args) throws Exception { MakeHandsOns prog = new MakeHandsOns(); if (args.length == 0) { System.err.printf("Usage: %s directory [...]%n", MakeHandsOns.class.getSimpleName()); } else if (args[0].equals("-h")) { doHelp(); } else for (String arg : args) { if (".".equals(arg)) { System.err.println( "Sorry, you can't use '.', use '*solution' or individual solution directory."); System.exit(42); } File fileArg = new File(arg); prog.makeIgnoreList(fileArg); prog.descendFileSystem(fileArg); } }
877b01d5-80c0-4415-beea-efaf43ae2586
7
public String [] getOptions() { String [] options = new String [12]; int current = 0; if (m_unpruned) { options[current++] = "-U"; } if (m_reducedErrorPruning) { options[current++] = "-R"; } if (m_binarySplits) { options[current++] = "-B"; } options[current++] = "-M"; options[current++] = "" + m_minNumObj; if (!m_reducedErrorPruning) { options[current++] = "-C"; options[current++] = "" + m_CF; } if (m_reducedErrorPruning) { options[current++] = "-N"; options[current++] = "" + m_numFolds; } options[current++] = "-Q"; options[current++] = "" + m_Seed; if (!m_useMDLcorrection) { options[current++] = "-J"; } while (current < options.length) { options[current++] = ""; } return options; }
0c9c253d-d443-4b83-8bee-912172afa889
6
private void punizione(CalcioPiazzato a){ a.tipo="punizione"; match.scout.addTiro(a.team); Giocatore p=null;//portiere //selezione tiratore e portiere if(a.team.equals("casa")){ a.tiratore=match.getCasa().getRigorista(); p=match.getOspiti().getGiocatore(Ruolo.GK).get(0); }else{ a.tiratore=match.getOspiti().getRigorista(); p=match.getCasa().getGiocatore(Ruolo.GK).get(0); } //decisione gol/nogol e costruzione report a.partecipanti.add(a.tiratore); a.reportAzione.add("si appresta a calciare direttamente in porta..."); boolean gol=true; for(int i=0;i<2;i++){ if(Math.random()<0.5-((double)a.tiratore.getTiro()/100)){ gol=false; } } if(gol){ if(Math.random()<0.5+((double)a.tiratore.getTiro()-p.getPortiere())/10){//gol a.setGoal(true); a.partecipanti.add(a.tiratore); addGol(a.team); a.reportAzione.add("segna un gran goal, "+match.getRisultato()); }else{//parata a.partecipanti.add(p); a.reportAzione.add("compie una strepitosa parata, ancora "+match.getRisultato()); } } else{ //fuori a.partecipanti.add(a.tiratore); if(Math.random()<0.5) a.reportAzione.add("sarà certamente contrariato per l'occasione sprecata!"); else a.reportAzione.add("spreca una buona occasione per segnare"); } }
7dda485c-e000-49a6-85b1-aaa2ad94ff0d
3
@Override public void execute(double t) { Matrix data = new ColumnMatrix(output.getDim()); if (input.isConnected() && input.getSource() != null) { data = input.getInput(); } try { output.setOutput(data); } catch (OrderException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
5ed2189f-98d1-4ae0-ae1f-080c39c029df
3
public static void main(String[] args) { try { BrickGame.path = args[0]; Master.setConfig(); FieldGame.init_sub(10, 8); Status.ifWin = -1; BrickGame.error = new String[2]; BrickGame.error[0] = "fatal"; BrickGame.error[1] = "writeproblem"; String[] names = new String[4]; names[0]="Test1"; names[1]="Test2"; names[2]="Test3"; names[3]="Test4"; int[][] coords = new int[4][3]; coords[0][0]=1; coords[0][1]=1; coords[0][2]=1; FieldGame.setField(1, 1, 1, -1); coords[1][0]=2; coords[1][1]=4; coords[1][2]=2; FieldGame.setField(1, 2, 4, -1); coords[2][0]=5; coords[2][1]=3; coords[2][2]=3; FieldGame.setField(1, 5, 3, -1); coords[3][0]=1; coords[3][1]=5; coords[3][2]=4; FieldGame.setField(1, 1, 5, -1); FieldGame.setField(2, 2, 2, -1); FieldGame.setField(1, 1, 2, -1); BrickGame.init(names, coords,true); Gui.init(); while(true){ Thread.sleep(500); if(Status.stop){Status.stop();} } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
68a32263-29a2-406b-bab0-a26598316c65
0
public void setWarmerPlateStatus(int status) { this.warmerPlateStatus = status; }
ac2c0b04-3c8f-4ddf-bef4-869dac76f08e
6
public void drawCircuit(String output, String output_file) { GraphViz gv = new GraphViz(); gv.addln(gv.start_graph()); gv.addln("rankdir=LR;"); String[] lines = output.split("\n"); int max_lines = lines.length; Matcher matcher = Pattern.compile("STATES_NO:([0-9]+)").matcher( lines[0]); matcher.find(); String num_states = matcher.group(1); gv.addln("size=\"" + num_states + "\";"); gv.addln("node [shape = circle];"); matcher = Pattern.compile("(.+):").matcher(lines[3]); matcher.find(); for (int i = 3; i < max_lines;) { String beginning = matcher.group(1); i++; while (i < max_lines) { matcher = Pattern.compile("(.+):").matcher(lines[i]); if (matcher.find()) break; String[] splitted_line = lines[i].split("->"); // splitted_line[0] has inputs, splitted_line[1] has outputs and // next state. String label = ""; Pattern p = Pattern.compile("([^=]+)=(0|1)"); matcher = p.matcher(splitted_line[0]); while (matcher.find()) { label += matcher.group(2); } matcher = p.matcher(splitted_line[1]); if (matcher.find()) { label += "/"; label += matcher.group(2); while (matcher.find()) { label += matcher.group(2); } } String state_movement = beginning + " -> "; matcher = Pattern.compile("(S[0-9]+)") .matcher(splitted_line[1]); matcher.find(); state_movement += matcher.group(1); gv.addln(state_movement + " [ label = \"" + label + "\" ]"); i++; } } gv.addln(gv.end_graph()); File out = new File(output_file); String dotSource = gv.getDotSource(); byte[] image = gv.getGraph(dotSource, "pdf"); gv.writeGraphToFile(image, out); }
1a51f0db-4a43-4ed2-a893-231f21abc594
5
private void movePlayer(){ if(!inside){ checkCollisionsOut(); }else{ checkCollisionIn(); } playerRect.x += xDirection; playerRect.y += yDirection; playerLeft.x += xDirection; playerLeft.y += yDirection; playerRight.x += xDirection; playerRight.y += yDirection; playerTop.x += xDirection; playerTop.y += yDirection; playerFeet.x += xDirection; playerFeet.y += yDirection; if(xDirection != 0 || yDirection != 0){ moving = true; }else if(xDirection == 0 && yDirection == 0){ moving = false; } justChanged = false; }
7856ef4d-fc24-4980-991e-d1cfe004fa34
7
public static void main(String[] args) { Primes primes = new Primes(); ConsecPrimeSum s = new ConsecPrimeSum(); ArrayList<Integer> list = new ArrayList<>(); //System.out.println(s.primeSumBelow(1000000)); //List<Integer> list = primes.getPrimes(1000000); long num = 0; long largestConsec = 2; boolean breakIt = false; for (int i = 3; i < 1000000; i++) { if (isPrime(i)) { largestConsec += i; if (largestConsec > 1000000) { break; } if (isPrime((int) largestConsec)) { list.add((int) largestConsec); } } } System.out.println(); System.out.println(); System.out.println(); System.out.println(); int largest = 0; for (int i = 0; i < list.size(); i++) { if (isPrime(list.get(i))) { if (list.get(i) > largest) ; largest = list.get(i); } } System.out.println(largest); System.out.println(); System.out.println(); System.out.println(); System.out.println(); System.out.println(); System.out.println(); System.out.println(); System.out.println(isPrime(958577)); }
7b246a61-bb6c-45e2-b137-eaf59dd9488a
5
protected int backfillGridlets() { int nStarted = 0; if(jobOrder != null) { Collections.sort(waitingJobs, jobOrder); } Iterator<SSGridlet> it = waitingJobs.iterator(); while(it.hasNext()) { SSGridlet gl = it.next(); if(gl.getStartTime() > 0) { continue; } if(startGridlet(gl)) { nStarted++; it.remove(); } else { double avSlowdown = this.getXFactorThreshold(gl); if(getXFactor(gl) > avSlowdown) { scheduleGridlet(gl); } } } return nStarted; }
3fcd81fc-a7c7-4805-8533-e0edfea0b495
3
@Override public Class getColumnClass(int column) { Class returnValue; if ((column >= 0) && (column < getColumnCount())) { if(getValueAt(0, column)==null) return Object.class; returnValue = getValueAt(0, column).getClass(); } else { returnValue = Object.class; } return returnValue; }
498161f0-8b14-4050-b396-c577f2ccf390
3
public static void print(Object obj) { Class<?> c = obj.getClass(); if (!c.isArray()) { return; } System.out.println("\nArray length: " + Array.getLength(obj)); for (int i = 0; i < Array.getLength(obj); i++) { System.out.print(Array.get(obj, i) + " "); } }
cad19692-173a-49ed-88c1-fcd351497338
9
public String createSQL() throws SQLException { String returnValue = "select "; String where = ""; boolean first = true; for (Field field : getXmlline().getFields()) { if (!field.isUse()) continue; if (first) { first = false; returnValue += field.getName(); } else { returnValue += (", " + field.getName()); } } returnValue += (" from " + getSQLSchemaName() + getXmlline().getTableName()); if (first) { LOGGER.severe("Error no field"); return null; } first = true; for (Field field : getXmlline().getFields()) { if (!field.isUse()) continue; if (getPrimaries().contains(field.getName())) { if (first) { first = false; where += (field.getName() + "=?"); } else { where += (" and " + field.getName() + "=?"); } } } if (!where.equals("")) { returnValue += (" where " + where); } return returnValue; }
74f0e4c0-7d5f-405c-8064-75cf37424558
2
public boolean hasStatistics() { for (StatMethod m : methods) { if (m.invocations != 0) { return true; } } return false; }
be6668b5-8f9b-427a-87f3-9f65d3f7a040
5
private void jButtonCompresserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCompresserActionPerformed if (!this.jTextFieldNameFile.getText().isEmpty() && !this.jTextAreaChaineACompresser.getText().isEmpty()) { JOptionPane d = new JOptionPane(); d.showMessageDialog( this.jPanel1, "Seul un des deux champs doit être remplit !", "Attention", WARNING_MESSAGE); } else if (this.jTextFieldNameFile.getText().isEmpty() && this.jTextAreaChaineACompresser.getText().isEmpty()) { JOptionPane d = new JOptionPane(); d.showMessageDialog( this.jPanel1, "Aucun champ est remplit", "Attention", WARNING_MESSAGE); } else { as.initAscii(); this.b = new BurrowsWheelerTransform(as); if (!this.jTextAreaChaineACompresser.getText().isEmpty()) { this.codeBWT = this.b.encodage(this.jTextAreaChaineACompresser.getText()); this.tailleChaineDepart = this.jTextAreaChaineACompresser.getText().length(); } else { ReadFile rd = new ReadFile(); String chaine = rd.readFile(this.jTextFieldNameFile.getText()); this.codeBWT = this.b.encodage(chaine); this.tailleChaineDepart = chaine.length(); } this.mvt = new MoveToFront(b.getPosition(),as); this.codeMTF = this.mvt.compressionMTF(codeBWT); this.hf = new Huffman(this.codeMTF); this.codeHuffman = hf.coder(); this.tailleChaineFin = ceil((double)this.codeHuffman.length()/8); this.affichageCompression(); } }//GEN-LAST:event_jButtonCompresserActionPerformed
8b9d710f-1416-41f5-8fe1-c701a49fe1e5
5
@Override public void actionPerformed(ActionEvent e) { Object s = e.getSource(); if (s==Save) { Game.map.parse.encode(Game.edit.mapname); } else if (s==Load) { new LoadMap(); } else if (s==Change) { ValidateMapSize(Integer.parseInt(Height.getText()),Integer.parseInt(Width.getText())); ValidateMapName(Name.getText()); } else if (s==Return) { MenuHandler.CloseMenu(); } else if (s==Quit) { Game.gui.LoginScreen(); } }
763d217d-eff6-4bf5-9d8b-6880d1ca486d
3
void removePredecessor(Instruction pred) { /* Hopefully it doesn't matter if this is slow */ int predLength = preds.length; if (predLength == 1) { if (preds[0] != pred) throw new alterrs.jode.AssertError( "removing not existing predecessor"); preds = null; } else { Instruction[] newPreds = new Instruction[predLength - 1]; int j; for (j = 0; preds[j] != pred; j++) newPreds[j] = preds[j]; System.arraycopy(preds, j + 1, newPreds, j, predLength - j - 1); preds = newPreds; } }
e32e8c22-dbf9-4a97-82b4-53d4adbbc6f8
7
public Image getCompoundTerrainImage(TileType type, double scale) { // Currently used for hills and mountains Image terrainImage = getTerrainImage(type, 0, 0, scale); Image overlayImage = getOverlayImage(type, 0, 0, scale); Image forestImage = type.isForested() ? getForestImage(type, scale) : null; if (overlayImage == null && forestImage == null) { return terrainImage; } else { GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment() .getDefaultScreenDevice().getDefaultConfiguration(); int width = terrainImage.getWidth(null); int height = terrainImage.getHeight(null); if (overlayImage != null) { height = Math.max(height, overlayImage.getHeight(null)); } if (forestImage != null) { height = Math.max(height, forestImage.getHeight(null)); } BufferedImage compositeImage = gc.createCompatibleImage(width, height, Transparency.TRANSLUCENT); Graphics2D g = compositeImage.createGraphics(); g.drawImage(terrainImage, 0, height - terrainImage.getHeight(null), null); if (overlayImage != null) { g.drawImage(overlayImage, 0, height - overlayImage.getHeight(null), null); } if (forestImage != null) { g.drawImage(forestImage, 0, height - forestImage.getHeight(null), null); } g.dispose(); return compositeImage; } }
92ab1cf8-4d00-4dcf-ad5a-c1d9ea1ccb5b
9
private void addItemOkPressed(String itemName, String itemPrice, String itemQuantity) { StringBuffer errorMessage = new StringBuffer(); double price = 0.0; int quantity = 0; boolean nameValid = false; boolean priceValid = false; boolean quantityValid = false; nameValid = itemName.length() > 0; if (!nameValid) { errorMessage.append("A non-empty name must be entered for the product!\n"); } else if (!model.getWarehouseTableModel().validateNameUniqueness(itemName)) { errorMessage.append("Entered name already exists!\n"); nameValid = false; } try { price = Double.parseDouble(itemPrice); priceValid = (price >= 0.0); } catch (NumberFormatException ex) {} if (!priceValid) { errorMessage.append("Entered price is not valid!\n"); } try { quantity = Integer.parseInt(itemQuantity); quantityValid = (quantity >= 0); } catch (NumberFormatException ex) {} if (!quantityValid) { errorMessage.append("Entered quantity is not valid!"); } if (nameValid && priceValid && quantityValid) { StockItem newItem = new StockItem(itemName, "", price, quantity); controller.createStockItem(newItem); // Show the error messages } else { JOptionPane.showMessageDialog( null, errorMessage.toString(), "Error", JOptionPane.ERROR_MESSAGE ); } }
e484a8be-8d7a-4b9a-998a-72747d2361a3
7
public void analyze(Reader input, Writer output) throws IOException { Analyzer analyzer = Morfeusz.getInstance().getAnalyzer(); int words = 0; long start = System.currentTimeMillis(); StreamTokenizer tokenizer = new StreamTokenizer(input); int token; while (StreamTokenizer.TT_EOF != (token = tokenizer.nextToken())) { if (token == StreamTokenizer.TT_WORD) { output.write(tokenizer.sval); output.write(" "); words++; InterpMorf[] analysis = analyzer.analyze(tokenizer.sval); if (analysis == null) { output.write("?"); } else { for (int j=0; j<analyzer.getTokensNumber(); j++) { String part = analysis[j].getTokenImage(); String lemma = analysis[j].getLemmaImage(); String tag = analysis[j].getTagImage(); if (j>0) output.write("; "); output.write(part); output.write(","); output.write(lemma); output.write(","); output.write(tag); if (parseTags) { try { Tag.create(tag); } catch (RuntimeException e) { System.err.println("Could not parse tag for: " + tokenizer.sval + " ('" + tag + "'); Error: " + e.toString()); } } } } output.write("\n"); } else { // ignore other tokens } } input.close(); output.close(); long time = (System.currentTimeMillis() - start); System.err.println("Analyzed: " + words + " words in " + time + " milliseconds." ); System.err.println( (int)(words / (time / 1000.0f)) + " words per second."); }
ca2ade4f-946f-4f02-9585-627ce4fa6c3e
3
public boolean getPlayerName(String josh) { try { FileInputStream fStream = new FileInputStream("playernames.txt"); DataInputStream in = new DataInputStream(fStream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String line; while ((line = br.readLine()) != null) { if (line.contains(josh)) { return true; } } } catch (Exception e) { e.printStackTrace(); } return false; }
3cadccf3-3e51-48fa-9067-676b024c82dd
9
public boolean setParameterString(String paramString) { try { int i = Integer.parseInt(paramString); if (i < 1) { return false; } setTimes(i); this.random = false; return true; } catch (NumberFormatException localNumberFormatException1) { try { StringTokenizer localStringTokenizer = new StringTokenizer(paramString, "-", false); int j = 0; int[] arrayOfInt = new int[2]; while (localStringTokenizer.hasMoreTokens()) { arrayOfInt[j] = Integer.parseInt(localStringTokenizer.nextToken()); if (arrayOfInt[j] < 1) { return false; } j++; } if (j != 2) { return false; } if (arrayOfInt[0] == arrayOfInt[1]) { setTimes(arrayOfInt[0]); this.random = false; return true; } if (arrayOfInt[0] > arrayOfInt[1]) { int k = arrayOfInt[0]; arrayOfInt[0] = arrayOfInt[1]; arrayOfInt[1] = k; } this.randomvals = arrayOfInt; this.random = true; genRandom(); return true; } catch (NumberFormatException localNumberFormatException2) { return false; } catch (ArrayIndexOutOfBoundsException localArrayIndexOutOfBoundsException) { } } return false; }
5756528a-ea71-4aff-a5e9-8f37aa7598ea
8
public void doEmote(Tickable ticking, String emote) { MOB emoter=null; emote=CMStrings.replaceAll(emote,"$p",ticking.name()); emote=CMStrings.replaceAll(emote,"$P",ticking.name()); if(ticking instanceof Area) { emoter=CMClass.getMOB("StdMOB"); emoter.setName(ticking.name()); emoter.charStats().setStat(CharStats.STAT_GENDER,'N'); for(final Enumeration r=((Area)ticking).getMetroMap();r.hasMoreElements();) { final Room R=(Room)r.nextElement(); emoteHere(R,emoter,emote); } emoter.destroy(); } else if(ticking instanceof Room) { emoter=CMClass.getMOB("StdMOB"); emoter.setName(ticking.name()); emoter.charStats().setStat(CharStats.STAT_GENDER,'N'); emoteHere((Room)ticking,emoter,emote); emoter.destroy(); } else if(ticking instanceof MOB) { emoter=(MOB)ticking; if(!canFreelyBehaveNormal(ticking)) return; emoteHere(((MOB)ticking).location(),emoter,emote); } else { if((ticking instanceof Item)&&(!CMLib.flags().isInTheGame((Item)ticking,false))) return; final Room R=getBehaversRoom(ticking); if(R!=null) { emoter=CMClass.getMOB("StdMOB"); emoter.setName(ticking.name()); emoter.charStats().setStat(CharStats.STAT_GENDER,'N'); emoteHere(R,emoter,emote); emoter.destroy(); } } }
8b0f2eb9-f23f-425a-bb72-999f8f4f5719
6
private void LogInButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LogInButtonActionPerformed try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection("jdbc:odbc:VideoStore", "", ""); Statement stat = con.createStatement(); String query = new String(MoviePasswordField.getPassword()); ResultSet results = stat.executeQuery("SELECT * FROM Users " + "WHERE user_name = '" + UserNameTextField.getText() + "' AND password = '" + query + "'"); if (!results.next()) { throw new InvalidPasswordException(); } else { JOptionPane.showMessageDialog(null, "You are successfully logon", "Logon Status", 1); MovieTitleATextField.setEnabled(true); MovieGenreTextField.setEnabled(true); MovieDescTextField.setEnabled(true); MovieAddButton.setEnabled(true); GenreNameTextField.setEnabled(true); GenreAddButton.setEnabled(true); MovieTitleRTextField.setEnabled(true); MovieTitleRemoveButton.setEnabled(true); LogInButton.setEnabled(false); try { userSocket = new Socket("127.0.0.1", 6666); out = new PrintWriter(userSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(userSocket.getInputStream())); } catch (UnknownHostException e) { JOptionPane.showMessageDialog(null, e, "Error Message", 0); } catch (IOException e) { JOptionPane.showMessageDialog(null, e, "Error Message", 0); } } stat.close(); } catch (SQLException e) { JOptionPane.showMessageDialog(null, e, "Error Message", 0); } catch (ClassNotFoundException e) { JOptionPane.showMessageDialog(null, e, "Error Message", 0); } catch (InvalidPasswordException e) { JOptionPane.showMessageDialog(null, e, "Error Message", 0); } }//GEN-LAST:event_LogInButtonActionPerformed
05f720b4-a642-47be-8d96-b3a8973123a9
5
private void setGameOverMessage() { long formattedScore = (long) (mPlayer.getScore() - mPlayer.getScore() % 5); String text = "GAME OVER! Level: " + mLevel + ", Score: " + formattedScore + ". "; if (mLevel < 6) { text += "Keep practicing!"; } else if (mLevel < 12) { text += "Not bad!"; } else if (mLevel < 18) { text += "Nice one!"; } else if (mLevel < 24) { text += "Impressive!"; } else if (mLevel < 30) { text += "Holy crap!"; } else { text += "You are a god."; } mScoreBar.setText(text + " Press 'r' to try again."); }
b9ec6fd3-f163-4c90-b941-2d7fa9c5f901
8
public void ponerPrimerFicha() { int tlt = Domino.listaTablero.size(); while (true) { for (int i = 0; i < Domino.listaFichaPc.size(); i++) { if (Domino.listaFichaPc.get(i).getCabeza() == Domino.listaTablero.get(0).getCola()) { Domino.listaFichaPc = mst.addFichaTablero(i, false, Domino.listaFichaPc);//Añade Ficha al listaTablero break; } else if (Domino.listaFichaPc.get(i).getCola() == Domino.listaTablero.get(0).getCola()) { int z = Domino.listaFichaPc.get(i).getCabeza(); Domino.listaFichaPc.get(i).setCabeza(Domino.listaFichaPc.get(i).getCola()); Domino.listaFichaPc.get(i).setCola(z); Domino.listaFichaPc = mst.addFichaTablero(i, false, Domino.listaFichaPc);//Añade Ficha al listaTablero break; } else if (Domino.listaFichaPc.get(i).getCabeza() == Domino.listaTablero.get(Domino.listaTablero.size() - 1).getCabeza()) { int z = Domino.listaFichaPc.get(i).getCabeza(); Domino.listaFichaPc.get(i).setCabeza(Domino.listaFichaPc.get(i).getCola()); Domino.listaFichaPc.get(i).setCola(z); Domino.listaFichaPc = mst.addFichaTablero(i, true, Domino.listaFichaPc);//Añade Ficha al listaTablero break; } else if (Domino.listaFichaPc.get(i).getCola() == Domino.listaTablero.get(Domino.listaTablero.size() - 1).getCabeza()) { Domino.listaFichaPc = mst.addFichaTablero(i, true, Domino.listaFichaPc);//Añade Ficha al listaTablero break; } } if (tlt == Domino.listaTablero.size()) { Domino.robarFicha(false); } else { break; } } if (Domino.listaFichaPc.size() == 0) { JOptionPane.showMessageDialog(null, "Gano PC"); } }
66f98c25-54a0-4438-9f58-c7803ebea7bc
9
public Histogram getGaussianSmoothed(double standardDeviation) { if(standardDeviation < 0.0) { throw new IllegalArgumentException(JaiI18N.getString("Histogram8")); } else if(standardDeviation == 0.0) { return this; } // Create a new, identical but empty Histogram. Histogram smoothedHistogram = new Histogram(getNumBins(), getLowValue(), getHighValue()); // Get a reference to the bins of the new Histogram. int[][] smoothedBins = smoothedHistogram.getBins(); // Get the total counts for all bands. getTotals(); // Determine the number of weights (must be odd). int numWeights = (int)(2*2.58*standardDeviation + 0.5); if(numWeights % 2 == 0) { numWeights++; } // Initialize the smoothing weights. double[] weights = new double[numWeights]; int m = numWeights/2; double var = standardDeviation*standardDeviation; double gain = 1.0/Math.sqrt(2.0*Math.PI*var); double exp = -1.0/(2.0*var); for(int i = m; i < numWeights; i++) { double del = i - m; weights[i] = weights[numWeights-1-i] = gain*Math.exp(exp*del*del); } for(int band = 0; band < numBands; band++) { // Cache bin-dependent values and references. int[] counts = getBins(band); int[] smoothedCounts = smoothedBins[band]; int nBins = smoothedHistogram.getNumBins(band); // Clear the band total count for the smoothed histogram. int sum = 0; for(int b = 0; b < nBins; b++) { // Determine clipped range. int min = Math.max(b - m, 0); int max = Math.min(b + m, nBins); // Calculate the offset into the weight array. int offset = m > b ? m - b : 0; // Accumulate the total for the range. double acc = 0; double weightTotal = 0; for(int i = min; i < max; i++) { double w = weights[offset++]; acc += counts[i]*w; weightTotal += w; } // Round the accumulated value. smoothedCounts[b] = (int)(acc/weightTotal + 0.5); // Accumulate total for band. sum += smoothedCounts[b]; } // Rescale the counts such that the band total is approximately // the same as for the same band of the original histogram. double factor = (double)totals[band]/(double)sum; for(int b = 0; b < nBins; b++) { smoothedCounts[b] = (int)(smoothedCounts[b]*factor + 0.5); } } return smoothedHistogram; }
faba1821-7bc3-457a-811f-7d93c3e4872e
1
public Simulation(String[] config, boolean verbose) { //set the output Person file outPerson = new OutputFile("personCreated.txt"); //set the output BusStop file outBusStop = new OutputFile("busstopCreated.txt"); //set the output Person file outBus = new OutputFile("busCreated.txt"); //set the output BusStop file outBusStopActivity = new OutputFile("busstopActivity.txt"); //set the output BusStop file screen = new OutputFile("output.txt"); //set the summary file summary = new OutputFile("summary.txt"); //set the Bus-Stop summary file summaryBusStop = new OutputFile("summaryBusStop.txt"); //set the Bus summary file summaryBus = new OutputFile("summaryBus.txt"); //person file header outPerson.WriteToFile("Time, Person, Bus-Stop, Arrival Interval, Arrival time "); //Busstop file header outBusStop.WriteToFile("BusStop"); //Bus file header outBus.WriteToFile("Time, Bus"); //person file header outBusStopActivity.WriteToFile("Person,Arrival-BusStop,Start-BusStop,Stop-BusStop,TimeonBus,TimeoffBus,WaitTime,NumberOfTimesLeftbyBus"); //Bus-Stop file header summaryBusStop.WriteToFile("Bus-Stop, Avg-Person, Avg-WaitTime, Min-Per(s), Max-Per(s)"); //Bus file header summaryBus.WriteToFile("Bus, Trips, Empty-Trip(s), Left-At-BusStop, Transported, Min-Per(s), Max-Per(s)"); //set verbose this.verbose = verbose; //set time time = 0; //set selected bus stop to none selectedBusStop = -1; //set the bus number busNumber = 0; //set the configuration list this.config = config; try { //configure the simulation ConfigSetup(); //create all BusStops, CreateEntities(); //start Simulation RunSimulation(); } catch(Exception e) { System.out.println("Error: "+e.getMessage()); } }
dd499550-01f3-4f60-b0f1-93136f5dec0c
5
public void writeToAdjacencyMatrix(String file){ int[][] A = new int[network.size()][network.size()]; for(Node N:network) { for(int i=0;i<N.getDegree();i++) { A[N.id][N.getNeighbour(i).id] = 1; } } try { BufferedWriter out = new BufferedWriter(new FileWriter(file)); String row = ""; for(int i=0;i<A.length;i++) { row = ""; for(int j =0;j<A.length;j++) { row += A[i][j] + " "; } row += "\n"; out.write(row); } out.flush(); out.close(); } catch (IOException ex) { Logger.getLogger(experiment.class.getName()).log(Level.SEVERE, null, ex); } }
aa765f0d-e58c-4715-bf51-e0236213e416
3
@Override public long computeCostOfAllocation(BaseInterval<Integer> allocation) { long cost = 0; // next walk thgrought edges and compute for all new added occurrences for (ValuedInterval<Integer, IntervalMultimap.MultimapEdge<Occurrence>> valuedInterval : this.solution.allocationsMultimap().valuesChangesInInterval(allocation)) { // add length of element times number of occurrences allocated there. cost += valuedInterval.getValues().size() * (valuedInterval.getEnd() - valuedInterval.getStart()); } // remove amount countet for occurrence own if (allocatingOccurrence != null && allocatingOccurrence.getAllocation() != null) { cost -= Math.max( 0, Math.min( allocatingOccurrence.getAllocation().getEnd(), allocation.getEnd() ) - Math.max( allocatingOccurrence.getAllocation().getStart(), allocation.getStart()) ); } return cost; }
8a5b3473-e711-4e19-9f41-8bec6357c4f2
4
public void sellTower(int x, int y) { if (map.getTile(x, y).getTower() != null) { Tower t = map.getTile(x, y).getTower(); towerList.remove(t); for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { map.getTile(t.getTileX() + i, t.getTileY() + j).setPassable(true); map.getTile(t.getTileX() + i, t.getTileY() + j).setTower(null); } } credits += t.getPrice() / 2; try { enemyHandler.recalculatePaths(); } catch (Exception ex) { } } }
31061f72-5a81-47c5-a47b-900ad7c7c15a
3
public DefaultComboBoxModel<String> buildVariableModel() { DefaultComboBoxModel<String> model = new DefaultComboBoxModel<String>(); BufferedReader reader; try { reader = new BufferedReader(new FileReader(System.getProperty("resources") + "/database/variables")); String line; while((line = reader.readLine()) != null) { model.addElement(line); } reader.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return model; }
20b7e0cd-43b5-4862-b139-132b2a3a44b1
8
public void check_random(RandomNumberGenerator generator, int seed) { // set the seed of the random number generator generator.set_seed(seed); clear_histogram(); // test odd/even of numbers // test average number for (int i = 0; i < this.max_size; i++) { int value = generator.next_int(this.max_size); this.histogram_[value]++; this.average_of_all_ += value; this.counter_++; if (this.previous_ >= 0) { if (is_odd(this.previous_)) { if (is_odd(value)) { this.odd_odd_count_++; } else { this.odd_even_count_++; } } else { if (is_odd(value)) { this.even_odd_count_++; } else { this.even_even_count_++; } } } this.previous_ = value; } Arrays.sort(this.histogram_); // max_size iterations tested. now see how many zeros while (this.histogram_[this.number_of_zeros_after_ten_thousand] == 0) { this.number_of_zeros_after_ten_thousand++; } fill_array(generator); // determine how many calls to next_int are required // to hit every number // time how long it takes to generate 10,000,000 numbers long start_time = System.nanoTime(); for (int i = 0; i < 10000000; i++) { generator.next_int(10000); } long end_time = System.nanoTime(); // finally print some stats: System.out.println("\n -- Random Number Tester Stats --\n"); System.out.printf( "Time to generate 10000000 random numbers is: %.1f seconds\n\n", (float) ((end_time - start_time) / 1000000000.0)); System.out.println("Number of Zeros after " + this.max_size + " tries: " + this.number_of_zeros_after_ten_thousand); System.out.println("Number of odd_even pairs: " + this.odd_even_count_); System.out.println("Number of odd_odd pairs: " + this.odd_odd_count_); System.out.println("Number of even_odd pairs: " + this.even_odd_count_); System.out.println("Number of even_even pairs: " + this.even_even_count_ + "\n"); System.out.println("Average number is: " + (float) this.average_of_all_ / (float) this.counter_); System.out.println("Median number of times a number was generated: " + this.histogram_[this.histogram_.length / 2]); System.out.println("Min number of times a number was generated: " + this.histogram_[0]); System.out.println("Max number of times a number was generated: " + this.histogram_[this.histogram_.length - 1] + "\n"); System.out.println("Repeatability on Same Seed: " + test_seed(generator) + "\n"); if (this.numbers_filled < this.max_size) { System.out.println("Could not fill histogram after " + 1000000 + " tries."); System.out.println("There were still " + (this.max_size - this.numbers_filled) + " indices empty\n"); } else { System.out.println("It took " + this.numbers_generated + " generated numbers to hit every possibility from 0 to " + this.max_size); } } // end check_random
83c48201-43a6-4561-befe-ff2813785431
8
public SettingsHandler(final GenericTestMonitorApplication application, final PreselectionPanel preselectionPanel) { _application = application; final String kvPid = _application.getConnection().getLocalConfigurationAuthority().getPid(); _preferences = Preferences.userRoot().node("/gtm").node(kvPid); // durch Angabe des "/" wird vom Wurzelverzeichnis ausgegangen _lastUsedPreferences = _preferences.node("lastusedsettings"); _savedPreferences = _preferences.node("savedsettings"); _preselectionLists = preselectionPanel.getPreselectionLists(); _preselectionTree = preselectionPanel.getPreselectionTree(); _dataModel = _application.getConnection().getDataModel(); _savedSettingsTable = new JTable() { public Component prepareRenderer(TableCellRenderer renderer, int row, int col) { Component comp = super.prepareRenderer(renderer, row, col); SettingsData settingsData = (SettingsData)_savedSettingsList.get(row); if(!settingsData.isValid() && !isCellSelected(row, col)) { comp.setForeground(Color.LIGHT_GRAY); } else if(settingsData.isValid() && !isCellSelected(row, col)) { comp.setForeground(getForeground()); } return comp; } }; _lastUsedSettingsTable = new JTable() { public Component prepareRenderer(TableCellRenderer renderer, int row, int col) { Component comp = super.prepareRenderer(renderer, row, col); SettingsData settingsData = (SettingsData)_lastUsedSettingsList.get(row); if(!settingsData.isValid() && !isCellSelected(row, col)) { comp.setForeground(Color.LIGHT_GRAY); } else if(settingsData.isValid() && !isCellSelected(row, col)) { comp.setForeground(getForeground()); } return comp; } }; // die Tabellen sollen nicht editierbar sein _savedSettingsTableModel = new DefaultTableModel() { public boolean isCellEditable(int row, int column) { return false; } }; _lastUsedSettingsTableModel = new DefaultTableModel() { public boolean isCellEditable(int row, int column) { return false; } }; // anordnen der Panel _settingsPanel = new JPanel(new BorderLayout()); JPanel tablePanel = new JPanel(new GridLayout(2, 1)); tablePanel.add(createSavedSettingsPanel()); tablePanel.add(createLastUsedSettingsPanel()); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS)); buttonPanel.add(createModuleButtonPanel()); buttonPanel.add(Box.createVerticalStrut(10)); buttonPanel.add(createExportImportPanel()); setButtonWidth(); _settingsPanel.add(tablePanel, BorderLayout.CENTER); _settingsPanel.add(buttonPanel, BorderLayout.EAST); actualizeTable(); // Dimension dim = new Dimension(100, 205); Dimension dim = _settingsPanel.getPreferredSize(); dim.setSize(dim.getWidth(), buttonPanel.getPreferredSize().getHeight()); _settingsPanel.setPreferredSize(dim); _settingsPanel.setMinimumSize(dim); }
a715eabb-a9c8-4858-9ab6-fe5c8b8947af
0
protected Iterator configKeys() { return props.keySet().iterator(); }
5e2953ea-1b56-4b1e-b30a-26de22b233a0
9
@Override public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { Player player = (Player)sender; if (command.getLabel().toLowerCase().equals("favor")) { if (player.hasPermission("favordisfavor.favor") || player.isOp()) { this.fdInterface.favor(args[0]); player.sendMessage("Player has been favored."); return true; } } else if (command.getLabel().toLowerCase().equals("disfavor")) { if (player.hasPermission("favordisfavor.disfavor") || player.isOp()) { this.fdInterface.disfavor(args[0]); player.sendMessage("Player has been disfavored."); return true; } } else if (command.getLabel().toLowerCase().equals("getvalue")) { if (player.hasPermission("favordisfavor.getvalue") || player.isOp()) { byte value = this.fdInterface.getPlayerValue(args[0]); player.sendMessage("Player " + args[0] + " has a score of " + value + '.'); return true; } } return false; }
8fc3e143-05a6-43e3-9eb9-1bf42c473cec
9
private static void render(String s) { if (s.equals("{")) { buf_.append("\n"); indent(); buf_.append(s); _n_ = _n_ + 2; buf_.append("\n"); indent(); } else if (s.equals("(") || s.equals("[")) buf_.append(s); else if (s.equals(")") || s.equals("]")) { backup(); buf_.append(s); buf_.append(" "); } else if (s.equals("}")) { _n_ = _n_ - 2; backup(); backup(); buf_.append(s); buf_.append("\n"); indent(); } else if (s.equals(",")) { backup(); buf_.append(s); buf_.append(" "); } else if (s.equals(";")) { backup(); buf_.append(s); buf_.append("\n"); indent(); } else if (s.equals("")) return; else { buf_.append(s); buf_.append(" "); } }