text
stringlengths
14
410k
label
int32
0
9
public SpringAttachable findAttachableElement(double x) { for (PhysicsElement e: elements) if (e instanceof SpringAttachable) if (e.contains(x,0)) return (SpringAttachable)e; return null; }
3
public void animation() { animationt--; if (animationt >= 45) { setImage(swordfish1); } else if (animationt < 45 && animationt >= 30) { setImage(swordfish2); } else if (animationt < 30 && animationt >= 15) { setImage(swordfish1); } else if (animationt < 15 && animationt >= 0) { setImage(swordfish3); } else if (animationt <= 0) { animationt = 60; } else { setImage(swordfish1); } }
8
public static void main(String[] args) { first : { System.out.print("Hello, "); here : System.out.println("World!"); } }
0
public static void main(String[] args) { boolean[] isPrime = EulerMath.getSieve(N); boolean found = false; for(int c = 9; c < isPrime.length; c += 2) if( !isPrime[c] ) { found = false; for(int p = 2; !found && p < c; p++) { if( !isPrime[p] ) continue; for(int s = 1; !found && p+2*s*s <= c; s++) if( c == p+2*s*s ) found = true; } if( !found ) { System.out.println(c); break; } } }
9
static double incompleteBetaFraction1(double a, double b, double x) throws ArithmeticException { double xk, pk, pkm1, pkm2, qk, qkm1, qkm2; double k1, k2, k3, k4, k5, k6, k7, k8; double r, t, ans, thresh; int n; k1 = a; k2 = a + b; k3 = a; k4 = a + 1.0; k5 = 1.0; k6 = b - 1.0; k7 = k4; k8 = a + 2.0; pkm2 = 0.0; qkm2 = 1.0; pkm1 = 1.0; qkm1 = 1.0; ans = 1.0; r = 1.0; n = 0; thresh = 3.0 * MACHEP; do { xk = -(x * k1 * k2) / (k3 * k4); pk = pkm1 + pkm2 * xk; qk = qkm1 + qkm2 * xk; pkm2 = pkm1; pkm1 = pk; qkm2 = qkm1; qkm1 = qk; xk = (x * k5 * k6) / (k7 * k8); pk = pkm1 + pkm2 * xk; qk = qkm1 + qkm2 * xk; pkm2 = pkm1; pkm1 = pk; qkm2 = qkm1; qkm1 = qk; if (qk != 0) { r = pk / qk; } if (r != 0) { t = Math.abs((ans - r) / r); ans = r; } else { t = 1.0; } if (t < thresh) { return ans; } k1 += 1.0; k2 += 1.0; k3 += 2.0; k4 += 2.0; k5 += 1.0; k6 -= 1.0; k7 += 2.0; k8 += 2.0; if ((Math.abs(qk) + Math.abs(pk)) > big) { pkm2 *= biginv; pkm1 *= biginv; qkm2 *= biginv; qkm1 *= biginv; } if ((Math.abs(qk) < biginv) || (Math.abs(pk) < biginv)) { pkm2 *= big; pkm1 *= big; qkm2 *= big; qkm1 *= big; } } while (++n < 300); return ans; }
7
public boolean matches(Identifier ident) { String test = ident.getFullName(); if (firstStar == -1) { if (wildcard.equals(test)) { return true; } return false; } if (!test.startsWith(wildcard.substring(0, firstStar))) return false; test = test.substring(firstStar); int lastWild = firstStar; int nextWild; while ((nextWild = wildcard.indexOf('*', lastWild + 1)) != -1) { String pattern = wildcard.substring(lastWild + 1, nextWild); while (!test.startsWith(pattern)) { if (test.length() == 0) return false; test = test.substring(1); } test = test.substring(nextWild - lastWild - 1); lastWild = nextWild; } return test.endsWith(wildcard.substring(lastWild + 1)); }
6
public void setGrid(Grid grid) { boolean test = false; if (test || m_test) { System.out.println("GameBoardGraphics :: setGrid() BEGIN"); } m_grid = grid; repaint(); if (test || m_test) { System.out.println("GameBoardGraphics :: setGrid() END"); } }
4
private void resetLater(final ExprInfo exprInfo, final Phi phi) { phi.setLater(false); final Iterator blocks = cfg.nodes().iterator(); while (blocks.hasNext()) { final Block block = (Block) blocks.next(); final Phi other = exprInfo.exprPhiAtBlock(block); if (other == null) { continue; } final Iterator e = other.operands().iterator(); while (e.hasNext()) { final Def def = (Def) e.next(); if ((def == phi) && other.later()) { resetLater(exprInfo, other); break; } } } }
5
public boolean mousewheel(Coord c, int amount) { int mod = ui.modflags(); if ((mod & 6) == 6) { // mod = 7; } if (amount < 0) wdgmsg("xfer", -1, mod); if (amount > 0) wdgmsg("xfer", 1, mod); return (true); }
3
@Override public void onPacketReceived(NetworkPacket pPacket) { switch (pPacket.getHeader()) { case REGISTER_RESULT_REP: if (pPacket.getReqResult() == true) { ScreenManager.getInstance().showLoginLayer(); } else { final BaseDialog.IOnButtonClickedEvent event = new BaseDialog.IOnButtonClickedEvent() { @Override public void onButtonClicked() { ScreenManager.getInstance().showRegistryLayer(); } }; switch (Integer.parseInt(pPacket.getMessage())) { case 1: ScreenManager.getInstance().showDialog(Constants.DIALOG_REGISTER_ACCOUNT_EXISTED_TEXT, event); break; case 2: ScreenManager.getInstance().showDialog(Constants.DIALOG_REGISTER_FAILED_TEXT, event); break; default: break; } } break; case LOGIN_RESULT_REP: ScreenManager.getInstance().hideLoadingLayer(); if (pPacket.getReqResult() == true) { ScreenManager.getInstance().showOnlineScene(); GameManager.getInstance().setCurrentGameMode(GameMode.ONLINE); // TODO: Hide Login Layer and show Online Scene ScreenManager.getInstance().showOnlineScene(); } else { final BaseDialog.IOnButtonClickedEvent event = new BaseDialog.IOnButtonClickedEvent() { @Override public void onButtonClicked() { ScreenManager.getInstance().showLoginLayer(); } }; switch (Integer.parseInt(pPacket.getMessage())) { case 1: ScreenManager.getInstance().showDialog(Constants.DIALOG_LOGIN_FAILED_TEXT, event); break; case 2: ScreenManager.getInstance().showDialog(Constants.DIALOG_LOGIN_ACCOUNT_LOGGED_TEXT, event); break; default: break; } } break; default: break; } }
8
public List<Organism> GAstep_crossover() throws Exception { // TODO /* crossover entre les species !!! */ /* crossover */ List<Organism> childList = new ArrayList<Organism>(); for (int i = 0; i < this.getSpeciesNumber(); i++) { if (species.get(i).getNumberOrganisms() > 1) { childList.addAll(species.get(i).crossover(getGenerationNumber())); } } //this.countFitnessAllPop(); /** * speciate */ if (!childList.isEmpty()) { speciate(childList); } return childList; }
3
@PUT() @Path("trade/{playerId}/newteam/{teamId}") @Produces("application/json") @SportService(ServiceType.MLB) public Player tradePlayer(@PathParam("playerId") int iPlayerId, @PathParam("teamId") int iTeamId) { Player p = new Player(); UserTransaction utx = null; try { p = emNfl.find(Player.class, iPlayerId); System.out.println("BEFORE: Player id : "+p.getId()+" Player name = "+p.getFirstName()+" "+p.getLastName()+" Position = "+p.getPosition()+" team ID = "+p.getTeamId()); p.setTeamId(iTeamId); utx = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction"); utx.begin(); emNfl.merge(p); emNfl.flush(); utx.commit(); System.out.println("AFTER: Player id : "+p.getId()+" Player name = "+p.getFirstName()+" "+p.getLastName()+" Position = "+p.getPosition()+" team ID = "+p.getTeamId()); } catch (Exception e) { if (utx == null) {} else { try { utx.rollback(); } catch (Exception ex) { System.out.println("Exception = "+ex.getMessage()); } } System.out.println("Exception = "+e.getMessage()); } return p; }
3
@Override public void removeInheritence(String inher) { do { inheritence.remove(inher); } while (inheritence.contains(inher)); }
1
protected void resize( int width, int height ) { if( width==fWidth && height==fHeight ) return; fWidth = width; fHeight= height; MutableAttributeSet attr = new SimpleAttributeSet(); attr.addAttribute(HTML.Attribute.WIDTH ,Integer.toString(width)); attr.addAttribute(HTML.Attribute.HEIGHT,Integer.toString(height)); ((StyledDocument)getDocument()).setCharacterAttributes( fElement.getStartOffset(), fElement.getEndOffset(), attr, false); }
2
private void setStateOfComboBox(JComboBox cb, int index) { Action a = cb.getAction(); ActionListener[] al = cb.getActionListeners(); ItemListener[] il = cb.getItemListeners(); cb.setAction(null); if (al != null) { for (ActionListener i : al) cb.removeActionListener(i); } if (il != null) { for (ItemListener i : il) cb.removeItemListener(i); } cb.setSelectedIndex(index); cb.setAction(a); if (al != null) { for (ActionListener i : al) cb.addActionListener(i); } if (il != null) { for (ItemListener i : il) cb.addItemListener(i); } }
8
public double findMedianSortedArrays(int A[], int B[]) { // Start typing your Java solution below // DO NOT write main() function int m = A.length; int n = B.length; if (m == 0 && n == 0) { return 0; } int i = 0; int j = 0; int s = (m + n) / 2; System.out.println(s); int m1 = -1; int m2 = -1; while (s >= 0) { int a = (i < m) ? A[i] : Integer.MAX_VALUE; int b = (j < n) ? B[j] : Integer.MAX_VALUE; m1 = m2; if (a < b) { m2 = a; i++; } else { m2 = b; j++; } s--; } if ((m + n) % 2 == 0) { return (m1 + m2) / 2.0; } return m2; }
7
public static boolean isOrdered(List<Partition> partitions) { List<Long> lengths = new ArrayList<Long>(); for (Partition partition : partitions) { lengths.add(partition.getLength()); } // Ignore trailing 0 length blocks. while (lengths.size() > 0 && lengths.get(lengths.size() -1) == 0) { lengths.remove(lengths.size() -1); } for (int index = 0; index < lengths.size() - 1; index++) { if (lengths.get(index) > lengths.get(index + 1)) { return false; } } return true; }
5
public static int getMinimumLoadableVersionOfTag(Class<?> objClass) { XmlTagMinimumVersion tagVersion = objClass.getAnnotation(XmlTagMinimumVersion.class); return tagVersion != null ? tagVersion.value() : 0; }
2
public String getDescription() { if(fullDescription == null) { if(description == null || isExtensionListInDescription()) { fullDescription = description==null ? "(" : description + " ("; // build the description from the extension list Enumeration extensions = filters.keys(); if(extensions != null) { fullDescription += "." + (String) extensions.nextElement(); while (extensions.hasMoreElements()) { fullDescription += ", ." + (String) extensions.nextElement(); } } fullDescription += ")"; } else { fullDescription = description; } } return fullDescription; }
6
private static final Object get_impl( final NonBlockingHashMap topmap, final Object[] kvs, final Object key, final int fullhash ) { final int len = len (kvs); // Count of key/value pairs, reads kvs.length final CHM chm = chm (kvs); // The CHM, for a volatile read below; reads slot 0 of kvs final int[] hashes=hashes(kvs); // The memoized hashes; reads slot 1 of kvs int idx = fullhash & (len-1); // First key hash // Main spin/reprobe loop, looking for a Key hit int reprobe_cnt=0; while( true ) { // Probe table. Each read of 'val' probably misses in cache in a big // table; hopefully the read of 'key' then hits in cache. final Object K = key(kvs,idx); // Get key before volatile read, could be null final Object V = val(kvs,idx); // Get value before volatile read, could be null or Tombstone or Prime if( K == null ) return null; // A clear miss // We need a volatile-read here to preserve happens-before semantics on // newly inserted Keys. If the Key body was written just before inserting // into the table a Key-compare here might read the uninitalized Key body. // Annoyingly this means we have to volatile-read before EACH key compare. // . // We also need a volatile-read between reading a newly inserted Value // and returning the Value (so the user might end up reading the stale // Value contents). Same problem as with keys - and the one volatile // read covers both. final Object[] newkvs = chm._newkvs; // VOLATILE READ before key compare // Key-compare if( keyeq(K,key,hashes,idx,fullhash) ) { // Key hit! Check for no table-copy-in-progress if( !(V instanceof Prime) ) // No copy? return (V == TOMBSTONE) ? null : V; // Return the value // Key hit - but slot is (possibly partially) copied to the new table. // Finish the copy & retry in the new table. return get_impl(topmap,chm.copy_slot_and_check(topmap,kvs,idx,key),key,fullhash); // Retry in the new table } // get and put must have the same key lookup logic! But only 'put' // needs to force a table-resize for a too-long key-reprobe sequence. // Check for too-many-reprobes on get - and flip to the new table. if( ++reprobe_cnt >= reprobe_limit(len) || // too many probes K == TOMBSTONE ) // found a TOMBSTONE key, means no more keys in this table return newkvs == null ? null : get_impl(topmap,topmap.help_copy(newkvs),key,fullhash); // Retry in the new table idx = (idx+1)&(len-1); // Reprobe by 1! (could now prefetch) } }
8
public static <E extends Enum<?>> E caseInsensitiveValueOf(E[] enumValues, String constant) { for (E candidate : enumValues) { if (candidate.toString().equalsIgnoreCase(constant)) { return candidate; } } throw new IllegalArgumentException(String.format( "constant [%s] does not exist in enum type %s", constant, enumValues.getClass().getComponentType().getName())); }
3
public void init(SmaliMethod method, int linesCount, boolean doMapParams) { if(isInitialized) return; isInitialized = true; this.linesCount = linesCount; this.sliceLength = method.getRegisters(); this.timeline = new ArrayList<ArrayList<RegisterInfo>>(linesCount); for(int i = 0; i < linesCount; i++) { ArrayList<RegisterInfo> slice = new ArrayList<RegisterInfo>(sliceLength); this.timeline.add(slice); for(int j = 0; j < sliceLength; j++) slice.add(new RegisterInfo()); } if(doMapParams) { List<Param> params = method.getParams(); boolean isMethodStatic = method.isFlagSet(SmaliEntity.STATIC); int localsCount = method.getLocals(); ArrayList<RegisterInfo> slice = this.timeline.get(0); int delta = 0; if(!isMethodStatic) { slice.get(localsCount).isThis = true; slice.get(localsCount).type = method.getSmaliClass().getClassName(); delta = 1; } for(int i = 0; i < params.size() ; i++) { Param param = params.get(i); if(param.info.is64bit) { RegisterInfo info = slice.get(localsCount + delta + i); info.is64bit = true; info.is64bitMaster = true; info.type = param.info.type; delta++; info = slice.get(localsCount + delta + i); info.is64bit = true; info.is64bitMaster = false; info.type = param.info.type; } else { RegisterInfo info = slice.get(localsCount + delta + i); info.type = param.info.type; } } } //end if(doMapParams) }
7
public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException { PC = (PistolCaveGame) game; //socket connecting to client Socket s = null; //connect to client if(renderWait != 0 && connections.size() < 2){ try { s = ss.accept(); System.out.println("Connecting to client."); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //add new connection to connection array and start a new thread for the client. Connection con = new Connection(s, PC); Thread thread = new Thread(con); thread.start(); System.out.println("Started new thread."); connections.add(con); } renderWait = 1; }
3
public String encodeUrl(String value) throws Exception { try { if (value != null) { return URLEncoder.encode(value.trim(), "UTF-8").replaceAll("\\+", "%20"); } else { return null; } } catch (Exception e) { throw e; } }
2
public boolean start() { synchronized (optOutLock) { // Did we opt out? if (isOptOut()) { return false; } // Is metrics already running? if (task != null) { return true; } // Begin hitting the server with glorious data task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() { private boolean firstPost = true; public void run() { try { // This has to be synchronized or it can collide with the disable method. synchronized (optOutLock) { // Disable Task, if it is running and the server owner decided to opt-out if (isOptOut() && task != null) { task.cancel(); task = null; // Tell all plotters to stop gathering information. for (Graph graph : graphs) { graph.onOptOut(); } } } // We use the inverse of firstPost because if it is the first time we are posting, // it is not a interval ping, so it evaluates to FALSE // Each time thereafter it will evaluate to TRUE, i.e PING! postPlugin(!firstPost); // After the first post we set firstPost to false // Each post thereafter will be a ping firstPost = false; } catch (IOException e) { if (debug) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage()); } } } }, 0, PING_INTERVAL * 1200); return true; } }
7
@SuppressWarnings("unchecked") public void tabulateTest(Test t) throws IOException{ //Takes a Test given by the user and shows all response results for the Test. Test tes = t; ArrayList<ArrayList<Response>> resp = new ArrayList<ArrayList<Response>>(); final File dir = new File("responses"); if (!dir.exists()){ // files folder does not exist Out.getDisp().renderLine("Folder \"responses\" not found. Please take the Test first to create this folder and populate it with responses."); return; }else{ // files folder does exist for(final File fileEntry : dir.listFiles()){ String ext = fileEntry.getName().substring(fileEntry.getName().lastIndexOf(".") + 1, fileEntry.getName().length()); //Take the extension of each file if (ext.equals("resp")){ //If the extension is .resp, check for the right survey String surveyName = fileEntry.getName().substring(0,fileEntry.getName().indexOf("_")); //Take the Survey/Test name in the response file if (surveyName.equals(tes.getName())){ //If it is the right survey, add to the list of files //Deserialization try { FileInputStream fileIn = new FileInputStream("responses/" + fileEntry.getName()); ObjectInputStream read = new ObjectInputStream(fileIn); resp.add((ArrayList<Response>) read.readObject()); read.close(); fileIn.close(); }catch(IOException i) { i.printStackTrace(); return; }catch(ClassNotFoundException c) { Out.getDisp().renderLine("Response not found."); c.printStackTrace(); return; }//try catch }//if (surveyName.equals(surv.getName())) }//if (ext.equals("resp")) }//for(final File fileEntry : dir.listFiles()) }//else if (resp.size() == 0){ Out.getDisp().renderLine("No responses found for this Test."); }else{ tes.tabulate(resp); //Tabulate the ArrayList of ArrayList of Responses } }
7
public void visitInsn(final int opcode) { buf.setLength(0); buf.append(tab2).append(OPCODES[opcode]).append('\n'); text.add(buf.toString()); if (mv != null) { mv.visitInsn(opcode); } }
1
public static void main(String[] args) { Set set = new Set(); Speler[] spelers = new Speler[5]; for(int i = 0; i < spelers.length; i++){ spelers[i] = new Speler(); } for(int i = 0; i <Vars.aantalTests; i++){ set.schud(); Kaart[] opTafel = new Kaart[5]; for(int j = 0; j < opTafel.length; j++) opTafel[j] = set.nextKaart(); for(Speler speler : spelers){ speler.speel(new Kaart[]{set.nextKaart(), set.nextKaart()}, opTafel); } } for(int i = 0; i < spelers.length; i++){ System.out.println(spelers[i].toString()); } }
5
public int distSingle(int[] inds, int pos, int ch) { int size = inds.length; int[] inds2; int d = 0, i; if(ch >= 0) { inds2 = rp2c[pos][ch]; for(i = 0; i < size; i++) if(i != pos && (ch=inds[i]) != inds2[i]) d += ch >= 0 ? 2 : 1; } else { for(i = 0; i < size; i++) if(i != pos && (ch=inds[i]) >= 0 && rp2c[i][ch][pos] != -1) d++; } return d; }
9
public SimpleVector getDirection() { return cam.getDirection(); }
0
public boolean equals(Object other) { if (other == this) return true; if (other == null) return false; if (other.getClass() != this.getClass()) return false; Point2D that = (Point2D) other; return this.x == that.x && this.y == that.y; }
4
public final void comment(final char[] ch, final int off, final int len) throws SAXException { try { closeElement(); writeIdent(); w.write("<!-- "); w.write(ch, off, len); w.write(" -->\n"); } catch (IOException ex) { throw new SAXException(ex); } }
1
@Override public T poll() { T result = null; if (firstItem != null) { result = (T) firstItem.value; if (firstItem.getNextItem() != null) { firstItem = firstItem.getNextItem(); } } length--; return result; }
2
public static ScriptableObject initStandardObjects(Context cx, ScriptableObject scope, boolean sealed) { if (scope == null) { scope = new NativeObject(); } scope.associateValue(LIBRARY_SCOPE_KEY, scope); (new ClassCache()).associate(scope); BaseFunction.init(scope, sealed); NativeObject.init(scope, sealed); Scriptable objectProto = ScriptableObject.getObjectPrototype(scope); // Function.prototype.__proto__ should be Object.prototype Scriptable functionProto = ScriptableObject.getFunctionPrototype(scope); functionProto.setPrototype(objectProto); // Set the prototype of the object passed in if need be if (scope.getPrototype() == null) scope.setPrototype(objectProto); // must precede NativeGlobal since it's needed therein NativeError.init(scope, sealed); NativeGlobal.init(cx, scope, sealed); NativeArray.init(scope, sealed); NativeString.init(scope, sealed); NativeBoolean.init(scope, sealed); NativeNumber.init(scope, sealed); NativeDate.init(scope, sealed); NativeMath.init(scope, sealed); NativeWith.init(scope, sealed); NativeCall.init(scope, sealed); NativeScript.init(scope, sealed); boolean withXml = cx.hasFeature(Context.FEATURE_E4X) && cx.getE4xImplementationFactory() != null; for (int i = 0; i != lazilyNames.length; i += 2) { String topProperty = lazilyNames[i]; String className = lazilyNames[i + 1]; if (!withXml && className.equals("(xml)")) { continue; } else if (withXml && className.equals("(xml)")) { className = cx.getE4xImplementationFactory().getImplementationClassName(); } new LazilyLoadedCtor(scope, topProperty, className, sealed); } Continuation.init(scope, sealed); return scope; }
8
public boolean kickClient(int cientID, boolean onlyChannelKick, String kickReason) { resetLastError(); if (!isConnected()) { saveLastError("kickClient(): Not connected to TS3 server!"); return false; } HashMap<String, String> hmIn; try { String command = "clientkick clid=" + Integer.toString(cientID) + " reasonid=" + (onlyChannelKick ? "4" : "5"); if (kickReason != null && kickReason.length() > 0) { command += " reasonmsg=" + encodeTS3String(kickReason); } hmIn = doInternalCommand(command); if (!hmIn.get("id").equals("0")) { saveLastError("kickClient()", hmIn.get("id"), hmIn.get("msg"), hmIn.get("extra_msg"), hmIn.get("failed_permid")); return false; } } catch (Exception e) { if (DEBUG) e.printStackTrace(); saveLastError("Exception kickClient(): " + e.toString()); return false; } return true; }
7
@Override public void actionPerformed(ActionEvent event) { if (event.getSource() == setBPMButton) { try { bpmTextField.commitEdit(); bpmSetEvent(); } catch (ParseException e) { bpmTextField.setText((String) bpmTextField.getValue()); } } else if (event.getSource() == increaseBPMButton) { System.out.println("increase clicked"); bpmIncreasedEvent(); } else if (event.getSource() == decreaseBPMButton) { System.out.println("decreased clicked"); bpmDecreasedEvent(); } else { System.out.println("else"); } }
4
public static double asin(double x) { if (x != x) { return Double.NaN; } if (x > 1.0 || x < -1.0) { return Double.NaN; } if (x == 1.0) { return Math.PI/2.0; } if (x == -1.0) { return -Math.PI/2.0; } if (x == 0.0) { // Matches +/- 0.0; return correct sign return x; } /* Compute asin(x) = atan(x/sqrt(1-x*x)) */ /* Split x */ double temp = x * HEX_40000000; final double xa = x + temp - temp; final double xb = x - xa; /* Square it */ double ya = xa*xa; double yb = xa*xb*2.0 + xb*xb; /* Subtract from 1 */ ya = -ya; yb = -yb; double za = 1.0 + ya; double zb = -(za - 1.0 - ya); temp = za + yb; zb += -(temp - za - yb); za = temp; /* Square root */ double y; y = sqrt(za); temp = y * HEX_40000000; ya = y + temp - temp; yb = y - ya; /* Extend precision of sqrt */ yb += (za - ya*ya - 2*ya*yb - yb*yb) / (2.0*y); /* Contribution of zb to sqrt */ double dx = zb / (2.0*y); // Compute ratio r = x/y double r = x/y; temp = r * HEX_40000000; double ra = r + temp - temp; double rb = r - ra; rb += (x - ra*ya - ra*yb - rb*ya - rb*yb) / y; // Correct for rounding in division rb += -x * dx / y / y; // Add in effect additional bits of sqrt. temp = ra + rb; rb = -(temp - ra - rb); ra = temp; return atan(ra, rb, false); }
6
private static HashMap<String, Integer> getCollectionFrequency(String dirName, Normalizer normalizer) throws IOException { // Création de la table des mots HashMap<String, Integer> hits = new HashMap<String, Integer>(); File dir = new File(dirName); String wordLC; if (dir.isDirectory()) { // Liste des fichiers du répertoire // ajouter un filtre (FileNameFilter) sur les noms // des fichiers si nécessaire String[] fileNames = dir.list(); // Parcours des fichiers et remplissage de la table // TODO ! Integer number; for (String fileName : fileNames) { System.err.println("Analyse du fichier " + fileName); // Appel de la méthode de normalisation ArrayList<String> words = normalizer.normalize(new File(dirName + File.separator + fileName)); // Pour chaque mot de la liste, on remplit un dictionnaire // du nombre d'occurrences pour ce mot for (String word : words) { wordLC = word; wordLC = wordLC.toLowerCase(); number = hits.get(wordLC); // Si ce mot n'était pas encore présent dans le dictionnaire, // on l'ajoute (nombre d'occurrences = 1) if (number == null) { hits.put(wordLC, 1); } // Sinon, on incrémente le nombre d'occurrence else { hits.put(wordLC, ++number); } } } } return hits; }
4
public void startConsole() { System.out.println("Welcome aboard! Type 'help' for more information"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (true) { System.out.print("> "); String line = null; try { line = br.readLine(); } catch (IOException e) { LOG.fatal("read command error", e); System.exit(-1); } processCommand(line); } }
2
@Override @RequestMapping(value = "/beers", method = RequestMethod.PUT) @ResponseBody @Transactional public BeerResponse create(@RequestBody BeerRequest beerRequest) { Beer beer = new Beer(); beer = persistenceService.create(beer); return update(beer.getId(), beerRequest); }
0
@Test public void testSendStatus() throws Exception{ AccessControlServer server = new AccessControlServer(1926); server.start(); SpotStub security = new SpotStub("Security",1926); security.start(); String ans = ""; int x = 0; while(x == 0){ ans = security.getAnswer(); //sleep(100); if(ans != ""){ x = 1; } } assertEquals(ans,"successful connection!"); security.resetAnswer(); security.setReListen(); server.sendStatus(); ans = ""; x = 0; while(x == 0){ ans = security.getAnswer(); //sleep(100); if(ans != ""){ x = 1; } } assertEquals(ans,"4 Parking #312 Type:Student Floor:3 Direction:North Status:Free Connection:Off"); }
4
@Override public void run() { while(true) { //random time sleeping int timeToSleep = randInt(3, 10); try { TimeUnit.SECONDS.sleep(timeToSleep); } catch (InterruptedException e) { e.printStackTrace(); } //now speak a random word String[] words = {"humpty dumpty", "lol", "okay", "i'm here", "words", "cheese cake"}; int chosenIndex = randInt(0, words.length - 1); String chosenWord = words[chosenIndex]; emit(new Event(EventType.OUTPUT, this, chosenWord)); } }
2
public JMenuBar createMenuBar() { // Create the menu bar final JMenuBar menuBar = new JMenuBar(); // Menu for all beans to demo JMenu componentsMenu = new JMenu("Components"); componentsMenu.setMnemonic('C'); menuBar.add(componentsMenu); for (int i = 0; i < beans.length; i++) { Icon icon; JMenuItem menuItem; try { URL iconURL = beans[i].getClass().getResource( "images/" + beans[i].getName() + "Color16.gif"); icon = new ImageIcon(iconURL); menuItem = new JMenuItem(beans[i].getName(), icon); } catch (Exception e) { System.out.println("JCalendarDemo.createMenuBar(): " + e + " for URL: " + "images/" + beans[i].getName() + "Color16.gif"); menuItem = new JMenuItem(beans[i].getName()); } componentsMenu.add(menuItem); final JComponent bean = beans[i]; ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent e) { installBean(bean); } }; menuItem.addActionListener(actionListener); } // Menu for the look and feels (lnfs). UIManager.LookAndFeelInfo[] lnfs = UIManager.getInstalledLookAndFeels(); ButtonGroup lnfGroup = new ButtonGroup(); JMenu lnfMenu = new JMenu("Look&Feel"); lnfMenu.setMnemonic('L'); menuBar.add(lnfMenu); for (int i = 0; i < lnfs.length; i++) { if (!lnfs[i].getName().equals("CDE/Motif")) { JRadioButtonMenuItem rbmi = new JRadioButtonMenuItem( lnfs[i].getName()); lnfMenu.add(rbmi); // preselect the current Look & feel rbmi.setSelected(UIManager.getLookAndFeel().getName() .equals(lnfs[i].getName())); // store lool & feel info as client property rbmi.putClientProperty("lnf name", lnfs[i]); // create and add the item listener rbmi.addItemListener( // inlining new ItemListener() { public void itemStateChanged(ItemEvent ie) { JRadioButtonMenuItem rbmi2 = (JRadioButtonMenuItem) ie .getSource(); if (rbmi2.isSelected()) { // get the stored look & feel info UIManager.LookAndFeelInfo info = (UIManager.LookAndFeelInfo) rbmi2 .getClientProperty("lnf name"); try { menuBar.putClientProperty( "jgoodies.headerStyle", "Both"); UIManager.setLookAndFeel(info.getClassName()); // update the complete application's // look & feel SwingUtilities .updateComponentTreeUI(JCalendarDemo.this); for (int i = 0; i < beans.length; i++) { SwingUtilities .updateComponentTreeUI(beans[i]); } // set the split pane devider border to // null BasicSplitPaneDivider divider = ((BasicSplitPaneUI) splitPane .getUI()).getDivider(); if (divider != null) { divider.setBorder(null); } } catch (Exception e) { e.printStackTrace(); System.err.println("Unable to set UI " + e.getMessage()); } } } }); lnfGroup.add(rbmi); } } // the help menu JMenu helpMenu = new JMenu("Help"); helpMenu.setMnemonic('H'); JMenuItem aboutItem = helpMenu.add(new AboutAction(this)); aboutItem.setMnemonic('A'); aboutItem.setAccelerator(KeyStroke.getKeyStroke('A', java.awt.Event.CTRL_MASK)); menuBar.add(helpMenu); return menuBar; }
8
private void reply (String x) { try { Soutput.writeObject (x); Soutput.flush (); } catch (Exception e) { } }
1
public synchronized Object getNext() { Object obj = null; if (getSize() > 0) { obj = queue.firstElement(); queue.removeElementAt(0); } return obj; }
1
@Override public boolean equals(Object obj) { if (!(obj instanceof Block)) return false; Block block = (Block) obj; if ((block.xPos == this.xPos) && (block.yPos == this.yPos) && (block.width == this.width) && (block.height == this.height)) { return true; } return false; }
5
public String toString() { StringBuffer result; int i; int n; boolean found; result = new StringBuffer(); // title result.append(this.getClass().getName().replaceAll(".*\\.", "") + "\n"); result.append(this.getClass().getName().replaceAll(".*\\.", "").replaceAll(".", "=") + "\n"); // model if (m_ActualClusterer != null) { // output clusterer result.append(m_ActualClusterer + "\n"); // clusters to classes result.append("Clusters to classes mapping:\n"); for (i = 0; i < m_ClustersToClasses.length - 1; i++) { result.append(" " + (i+1) + ". Cluster: "); if (m_ClustersToClasses[i] < 0) result.append("no class"); else result.append( m_OriginalHeader.classAttribute().value((int) m_ClustersToClasses[i]) + " (" + ((int) m_ClustersToClasses[i] + 1) + ")"); result.append("\n"); } result.append("\n"); // classes to clusters result.append("Classes to clusters mapping:\n"); for (i = 0; i < m_OriginalHeader.numClasses(); i++) { result.append( " " + (i+1) + ". Class (" + m_OriginalHeader.classAttribute().value(i) + "): "); found = false; for (n = 0; n < m_ClustersToClasses.length - 1; n++) { if (((int) m_ClustersToClasses[n]) == i) { found = true; result.append((n+1) + ". Cluster"); break; } } if (!found) result.append("no cluster"); result.append("\n"); } result.append("\n"); } else { result.append("no model built yet\n"); } return result.toString(); }
7
byte[] buildBrush(byte[] brush, CPBrushInfo brushInfo) { int intSize = (int) (brushInfo.curSize + .99f); float center = intSize / 2.f; float sqrRadius = (brushInfo.curSize / 2) * (brushInfo.curSize / 2); float xFactor = 1f + brushInfo.curSqueeze * MAX_SQUEEZE; float cosA = (float) Math.cos(brushInfo.curAngle); float sinA = (float) Math.sin(brushInfo.curAngle); int offset = 0; for (int j = 0; j < intSize; j++) { for (int i = 0; i < intSize; i++) { float x = (i + .5f - center); float y = (j + .5f - center); float dx = (x * cosA - y * sinA) * xFactor; float dy = (y * cosA + x * sinA); float sqrDist = dx * dx + dy * dy; if (sqrDist <= sqrRadius) { brush[offset++] = (byte) 0xff; } else { brush[offset++] = 0; } } } return brush; }
3
public void toXML( TreeNode treeRoot, Element node ) { if ( treeRoot.ChildNodes == null ) { return ; } for ( String SituName:treeRoot.ChildNodes.keySet() ) { Element nextNode = node.addElement(treeRoot.AttributeName); TreeNode childNode = treeRoot.ChildNodes.get(SituName); nextNode.addAttribute("value", childNode.SituationName); if ( childNode.isLeafNode ) { nextNode.setText(childNode.AttributeName); } toXML( childNode, nextNode ); } }
3
public Dimension resize(final Dimension newSize, final boolean isLoading) { if (ancestor == null) return newSize; float[] objectBounds = getModel().getBoundsOfObjects(); if (objectBounds != null) { float xmin = objectBounds[0]; float ymin = objectBounds[1]; float xmax = objectBounds[2]; float ymax = objectBounds[3]; RectangularBoundary boundary = getModel().getBoundary(); if (isLoading) { // leave 1 margin in checking if every object is contained within the boundary, // because particles may slightly penetrate into the walls if (!boundary.contains(new Rectangle((int) (xmin + 1), (int) (ymin + 1), (int) (xmax - xmin - 2), (int) (ymax - ymin - 2)))) { EventQueue.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(JOptionPane.getFrameForComponent(MDView.this), "Some objects overlap with the boundary lines. This may have been caused by changing periodic boundary\nto reflecting boundary. Please move those particles off the border and re-save.", "Size Error", JOptionPane.ERROR_MESSAGE); } }); return newSize; } } else { if (boundary.getType() == RectangularBoundary.DBC_ID) { if (xmax > newSize.width + 1 || ymax > newSize.height + 1) { Dimension d = getSize(); resizeTo(d, false, false); EventQueue.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(JOptionPane.getFrameForComponent(MDView.this), "The Model Container cannot be resized to the specified dimension.\nSome objects would be out of boundary.", "Resizing Error", JOptionPane.ERROR_MESSAGE); } }); return d; } } } } EventQueue.invokeLater(new Runnable() { public void run() { resizeTo(newSize, isLoading, !doNotFireUndoEvent); } }); return newSize; }
7
@Scheduled(fixedRate = 60000) public void scheduledPoll() { Optional<Status> status = Optional.absent(); if (url != null) { status = statusPoller.poll(url); } if (!status.isPresent()) { System.out.println(String.format("not status found at url %s", url)); return; } if(status.get().getLastUnstableBuild() == null) { System.out.println(String.format("no unstable build at url %s", url)); return; } if( unstableBuild.isPresent() && status.get().getLastUnstableBuild().getNumber() == unstableBuild.get().getNumber()) { System.out.println(String.format("build number %d unstability already reported", unstableBuild.get().getNumber())); return; } unstableBuild = Optional.of(status.get().getLastUnstableBuild()); System.err.println(String.format("build %s unstable", unstableBuild.get().getNumber())); }
5
public static Object setValue(String key,Object obj, Object newValue) { String error = ""; if ( obj instanceof Map ) { ((Map)obj).put(key,newValue); return newValue; } try { BeanInfo binfo = Introspector.getBeanInfo(obj.getClass(), Object.class); PropertyDescriptor[] props = binfo.getPropertyDescriptors(); for (int i = 0; i < props.length; i++) { String pname = props[i].getName(); if ( key.equals(pname) ) { Method m = props[i].getWriteMethod(); m.invoke(obj, newValue); m = props[i].getReadMethod(); return m.invoke(obj, null); } }//for } catch (IntrospectionException ex) { error = ex.getMessage(); } catch (IllegalAccessException ex) { error = ex.getMessage(); } catch (java.lang.reflect.InvocationTargetException ex) { error = ex.getMessage(); } throw new NullPointerException("An object of type " + obj.getClass() + " doesn't contain a field with a name " + key + "(" + error + ")"); }
6
public static int binarySearchUnknownLength(List<Integer> A, int k) { // Find the possible range where k exists. int p = 0; while (true) { try { int val = A.get((1 << p) - 1); if (val == k) { return (1 << p) - 1; } else if (val > k) { break; } } catch (Exception e) { break; } ++p; } // Binary search between indices 2^(p - 1) and 2^p - 2. // Need max below in case k is smaller than all entries // in A, since p becomes 0. int left = max(0, 1 << (p - 1)), right = (1 << p) - 2; while (left <= right) { int m = left + ((right - left) / 2); try { int val = A.get(m); if (val == k) { return m; } else if (val > k) { right = m - 1; } else { // A[m] < k left = m + 1; } } catch (Exception e) { right = m - 1; // Search the left part if out of boundary. } } return -1; // Nothing matched k. }
8
public void refresh() { myCases = myLemma.getDoneDescriptions(); /* * Let the table know that data has changed. */ ((AbstractTableModel)myTable.getModel()).fireTableDataChanged(); if(myCases.size() == 0) { myDone.setEnabled(false); myClearAll.setEnabled(false); } else { myDone.setEnabled(true); myClearAll.setEnabled(true); } repaint(); }
1
public static int cmpDstMaj(final int[] buffer, final int first, final int second) { // if (buffer[first + IDX_DST] < buffer[second + IDX_DST]) return SMALLER; if (buffer[first + IDX_DST] > buffer[second + IDX_DST]) return BIGGER; if (buffer[first + IDX_SRC] < buffer[second + IDX_SRC]) return SMALLER; if (buffer[first + IDX_SRC] > buffer[second + IDX_SRC]) return BIGGER; // return EQUAL; }
4
@Override public void mouseReleased(MouseEvent e) { super.mouseReleased(e); Vertex chosenPoint = chooseVertex(e); if (e.getButton() == MouseEvent.BUTTON1) addPoint(draggedToX, draggedToY); else if (e.getButton() == MouseEvent.BUTTON2) toggleWallMode(chosenPoint); else if (e.getButton() == MouseEvent.BUTTON3) closeLoop(); vertices.buildGraph(); gui.repaint(); }
3
public void windowDeiconified(WindowEvent e) { isIdle=false; }
0
public int getMaxJaar() { int jaar = 0; // Itereer de datasets for (DataSet set: this.datasets) { for (Category cat: set.categories) { for (SubCategory scat: cat.subcategories) { SubCategory subcat = new SubCategory(scat.id, scat.naam, scat.datatype, scat.weight, scat.red, scat.green, scat.blue, false); for (Period per: scat.periods) { if (per.year > jaar) { jaar = per.year; } } } } } return jaar; }
5
public void setData(InputStream data) { this.data = data; }
0
@Override public void update(Observable o, Object arg) { Route route = (Route) arg; if (route.to == null) { VoieEnum ve = (VoieEnum) ((VoieExterne)route.from).getEnum(); voituresEnAttentes.get(ve).incrementAndGet(); voituresEntrees.get(ve).incrementAndGet(); } else if (route.from instanceof VoieExterne && route.to instanceof VoieInterne) { VoieEnum ve = (VoieEnum) ((VoieExterne)route.from).getEnum(); voituresEnAttentes.get(ve).decrementAndGet(); voituresEngagees.incrementAndGet(); attenteParVoie.get(ve).addAndGet(route.toAt - route.fromAt); voituresEngageesParVoies.get(ve).incrementAndGet(); } else if (route.from instanceof VoieInterne && route.to instanceof VoieExterne) { VoieEnum ve = (VoieEnum) ((VoieExterne)route.to).getEnum(); voituresSorties.get(ve).incrementAndGet(); voituresEngagees.decrementAndGet(); } }
5
private char getChar(int i) { if(i >= 0 && i < 10) { return (char) ('0' + i); } switch (i) { case 10: return 'A'; case 11: return 'B'; case 12: return 'C'; case 13: return 'D'; case 14: return 'E'; case 15: return 'F'; } throw new IllegalArgumentException(); }
8
private ObjectDefinition method457() { int i = -1; if (varbitFileId != -1) { VarBit varBit = VarBit.cache[varbitFileId]; int configId = varBit.configId; int shift = varBit.anInt649; int amountBits = varBit.anInt650; int j1 = Client.anIntArray1232[amountBits - shift]; i = client.configStates[configId] >> shift & j1; } else if (anInt1602 != -1) { i = client.configStates[anInt1602]; } if (i < 0 || i >= childIds.length || childIds[i] == -1) { return null; } else { return ObjectDefinition.forId(childIds[i]); } }
5
@Override public String buscarDocumentoPorEmpresa(String empresa) { ArrayList<Compra> geResult= new ArrayList<Compra>(); ArrayList<Compra> dbCompras = tablaCompras(); String result=""; try{ for (int i = 0; i < dbCompras.size() ; i++){ if(dbCompras.get(i).getEmpresa().equalsIgnoreCase(empresa)){ geResult.add(dbCompras.get(i)); } } }catch (NullPointerException e) { result="No existe la compra con la empresa: "+empresa; } if (geResult.size()>0){ result=imprimir(geResult); } else { result="No se ha encontrado ningun registro"; } return result; }
4
private void updateTabla(){ //** pido los datos a la tabla Object[][] vcta = this.getDatos(); //** se colocan los datos en la tabla DefaultTableModel datos = new DefaultTableModel(); tabla.setModel(datos); datos = new DefaultTableModel(vcta,colum_names_tabla); tabla.setModel(datos); //ajustamos tamaño de la celda Fecha Alta /*TableColumn columna = tabla.getColumn("Fecha Alta"); columna.setPreferredWidth(100); columna.setMinWidth(100); columna.setMaxWidth(100);*/ if (!field_id_loc.getText().equals("")){ posicionarAyuda(field_id_loc.getText()); } else{ if ((fila_ultimo_registro-1 >= 0)&&(fila_ultimo_registro-1 < tabla.getRowCount())){ tabla.setRowSelectionInterval(fila_ultimo_registro-1,fila_ultimo_registro-1); scrollCellToView(this.tabla,fila_ultimo_registro-1,fila_ultimo_registro-1); cargar_ValoresPorFila(fila_ultimo_registro-1); } else{ if ((fila_ultimo_registro+1 >= 0)&&(fila_ultimo_registro+1 <= tabla.getRowCount())){ tabla.setRowSelectionInterval(fila_ultimo_registro,fila_ultimo_registro); scrollCellToView(this.tabla,fila_ultimo_registro,fila_ultimo_registro); cargar_ValoresPorFila(fila_ultimo_registro); } } } }
5
@Override protected void finalize() { if(m_resource.RemoveReference() && !m_fileName.isEmpty()) { s_loadedShaders.remove(m_fileName); } }
2
private void loadData() throws IOException, InvalidConfigurationException { File folder = getDataFolder(); if (!folder.exists()) { folder.mkdir(); } else { // Delete the old config file if it is there File oldConfigFile = new File(folder.getPath() + File.separator + "config.yml"); if (oldConfigFile.exists()) { oldConfigFile.delete(); } } String dataPath = folder.getPath() + File.separator; File configFolder = new File(dataPath + "configuration"); if (!configFolder.exists()) { configFolder.mkdir(); } Config.loadOptionConfig(this); Config.loadConfigValues(this); Config.loadWeaponConfig(this, WeaponType.ARMOR); Config.loadWeaponConfig(this, WeaponType.ITEM); Config.loadWeaponConfig(this, WeaponType.TOOL); Config.loadWeaponConfig(this, WeaponType.WEAPON); loadBlockStore(dataPath); }
3
public <T> BeansContainer register(Class<? extends T> impl, Class<T> iface) { registry.put(iface, impl); return this; }
1
public Element toElement() { cleanTableFrom(); DocumentFactory factory = DocumentFactory.getInstance(); Element root = factory.createElement(DbSchema.DBSELECT_FIELD); root.addAttribute(DbSchema.OFFSET_ATTRIBUTE, Integer.toString(offset)); root.addAttribute(DbSchema.LIMIT_ATTRIBUTE, Integer.toString(limit)); if (selected.isEmpty()) { return root; } Element select = factory.createElement(DbSchema.SELECTED_FIELD); for (DbField field : selected) { Element efield = factory.createElement(DbSchema.FIELD_FIELD); efield.setText(field.toString()); select.add(efield); } root.add(select); Element from = factory.createElement(DbSchema.FROM_FIELD); for (DbTable table : fromTables.values()) { Element efield = factory.createElement(DbSchema.TABLE_FIELD); efield.setText(table.toString()); from.add(efield); } root.add(from); if (! conditions.isEmpty()) { Element econd = factory.createElement(DbSchema.CONDITIONS_FIELD); for (DbCondition condition : conditions) { Element efield = condition.toElement(); econd.add(efield); } root.add(econd); } if (! orderByAsc.isEmpty()) { Element eorder = factory.createElement(DbSchema.ORDERASC_FIELD); for (DbField field : orderByAsc.values()) { Element efield = factory.createElement(DbSchema.FIELD_FIELD); efield.setText(field.toString()); eorder.add(efield); } root.add(eorder); } if (! orderByDesc.isEmpty()) { Element eorder = factory.createElement(DbSchema.ORDERDESC_FIELD); for (DbField field : orderByDesc.values()) { Element efield = factory.createElement(DbSchema.FIELD_FIELD); efield.setText(field.toString()); eorder.add(efield); } root.add(eorder); } return root; }
9
public final Texture getCoinTexture(final BlockType type) { switch (type) { case BLUE_FACE: return coinBlue; case RED_FACE: return coinRed; case GREEN_FACE: return coinGreen; case GREY_FACE: return coinGrey; case BROWN_FACE_BROKEN: return coinPotion; default: return null; } }
5
private void step3Recursiv(String usedEdge, int delta, String target) { if (usedEdge != null && usedEdge.length() > 0 && delta > 0) { int flowAtEdge = this.graph.getValE(usedEdge, this.attrEdgeFlow); //Bin ich Source oder Target String source = this.graph.getSource(usedEdge); if (!source.equals(target)) { //target bin das Ziel also normale Kante this.graph.setValE(usedEdge, this.attrEdgeFlow, (flowAtEdge + delta)); String newUsedEdge = this.graph.getStrV(source, this.attrNodeUsedEdge); this.step3Recursiv(newUsedEdge, delta, source); } else { //target bin der Source also entgegengesetzt... backtracking... source = this.graph.getTarget(usedEdge); System.out.println("Rückwärtskante von " + target + " nach " + source + "."); backtracks++; this.graph.setValE(usedEdge, this.attrEdgeFlow, (flowAtEdge - delta)); String newUsedEdge = this.graph.getStrV(source, this.attrNodeUsedEdge); this.step3Recursiv(newUsedEdge, delta, source); } } }
4
public static synchronized DataAccessLayer getInstance(){ if (null == instance) { instance = new DataAccessLayer(); } return instance; }
1
@Override protected void execute() { Map<Integer, Set<String>> m = new TreeMap<Integer, Set<String>>(); seq(new WalkToSegment(19, 17)); seq(Segment.skip(1)); seqMove(new WriteMemory(0xd3b1, 0x00)); // set index to 0 qsave(); for (int map=MIN_MAP;map<=MAX_MAP;map++) { if(excludedMaps.contains(map)) continue; qload(); seqMove(new WriteMemory(0xd3b2, map)); // set map seq(new WalkToSegment(3,8, false)); System.out.println("Map "+map); seq(Segment.skip(10)); int[] memory = curGb.getCurrentMemory(); for (int i=20;i<0x80;i++) { int add = 0xd31e+2*i; if (/*memory[add] == 0x48 || memory[add] == 0x49 || memory[add] == 0x4e || memory[add] == 0x29 ||memory[add] == 0xc5 || */memory[add] == 0x1f) { String desc = ""+Util.toHex(map,2)+"("+map+"):"+i+"("+Util.toHex(add,4)+")"; add(memory[add], desc, m); } } } for (Entry<Integer, Set<String>> e : m.entrySet()) { System.out.print(e.getKey()+":"); for (String pos : e.getValue()) System.out.print(" | "+pos); System.out.println(); } }
6
@Test public void testShowAllTrackedJobs() throws LuaScriptException { String jid = addNewTestJob(); String jid2 = addJob(UUID.randomUUID().toString(), TEST_QUEUE); // Track both jobs performTrackingAction("track", jid); performTrackingAction("track", jid2); // Get tracked status List<String> emptyKeys = new ArrayList<String>(); String json = (String) _luaScript.callScript(this.scriptName(), emptyKeys, emptyKeys); // Fix potential parsing issues upfront json = JsonHelper.fixArrayField(json, "jobs"); json = JsonHelper.fixArrayField(json, "expired"); Map<String, Object> tracked = JsonHelper.parseMap(json); @SuppressWarnings("unchecked") List<Map<String, Object>> trackedJobs = (List<Map<String, Object>>) tracked .get("jobs"); for (Map<String, Object> job : trackedJobs) { assertEquals("true", job.get("tracked").toString()); if (job.get("jid").toString().equals(jid)) { assertEquals(jid, job.get("jid").toString()); } else if (job.get("jid").toString().equals(jid2)) { assertEquals(jid2, job.get("jid").toString()); } } untrackAndRemove(jid); untrackAndRemove(jid2); }
3
public int[] getPitchShifts(String tuningscheme, double bendrange, int rootnote, int tuningnote, double tuningfreq) throws Exception, IndexOutOfBoundsException { Double[] pitchratios = getRatios(tuningscheme); int[] pitchshift = {0,0,0,0,0,0,0,0,0,0,0,0}; // midi specs use a numerical value from (0 to 16383) with 8192 meaning no bend Boolean messagesent = false; for(int nnote=0; nnote < 12; nnote++){ // convert frequency ratio from file into a midi pitch shift parameter pitchshift[nnote] = 8192+(int)(8191.0*((12.0*Math.log(pitchratios[nnote])/Math.log(2.0))-nnote)/bendrange); if((pitchshift[nnote] < 0)||(pitchshift[nnote] > 16383)){ pitchshift[nnote] = 0; if(!messagesent){ Exception ex = new Exception("A pitch bend is out of range! Your tuning is too extreme for this method. Try using a tuning root closer to A440 or a tuning scheme closer to equal temperament. Outputing garbage until you fix this."); messagesent = true; throw ex; } } } // add offset to tune tuningnote to tuningfreq // This is what the frequency of the tuning note is in A440 TET double standardfreq = 440.0*Math.pow(2.0,((double)(tuningnote-9))/12.0); // This is how many semitones the desired frequency is from the freq above double semisoff = 12*Math.log(tuningfreq/standardfreq)/Math.log(2.0); // This is what the pitchshift should be for the tuningnote to achieve this int tunerootoffset = 8192 + (int)((8191.0*semisoff)/bendrange); // This is how many half-steps the tunintnote is above the rootnote int tuneaboveroot = tuningnote - rootnote; if(tuneaboveroot < 0) tuneaboveroot += 12; // This is what we need to add to the tuningnote pitch shift to get it // to the right frequency. So we'll move everything by this much int offset = tunerootoffset - pitchshift[tuneaboveroot]; for(int nnote = 0; nnote < 12; nnote++){ pitchshift[nnote] += offset; if((pitchshift[nnote] < 0)||(pitchshift[nnote] > 16383)){ pitchshift[nnote] = 0; //System.out.println("Note: "+Integer.toString(nnote)+" Pitchshift: "+Integer.toString(pitchshift[nnote])+" Offset: "+Integer.toString(offset)); if(!messagesent){ Exception ex = new Exception("A pitch bend is out of range! Your tuning is too extreme for this method. Try using a tuning root closer to A440 or a tuning scheme closer to equal temperament. Outputing garbage until you fix this."); messagesent = true; //throw ex; } } } return(pitchshift); }
9
public void shellSort() { int inc, i, j, s, s1, p1, p2, p3; Integer[] seq = new Integer[myArray.length]; p1 = p2 = p3 = 1; s1 = -1; do { if ( (++s1 % 2) != 0 ) { seq[s1] = 8 * p1 - 6 * p2 + 1; } else { seq[s1] = 9 * p1 - 9 * p3 + 1; p2 *= 2; p3 *= 2; } p1 *= 2; } while (3 * seq[s1] < myArray.length); if (s1 > 0) { --s1; } else { s1 = 0; } s = s1; while (s >= 0) { inc = seq[s--]; for (i = inc; i < myArray.length; i++) { T temp = myArray[i]; for (j = i - inc; (j >= 0) && (myArray[j].compareTo(temp) > 0); j -= inc) { myArray[j + inc] = myArray[j]; } myArray[j + inc] = temp; } } }
7
public TestEmbeddedServer( String host, int port ) { this.host = host; this.port = port; this.community_url = host + ":" + port + "/community"; getKeys(); TrustManager[] osTrustManager = new TrustManager[] { new LiberalTrustManager() }; try { sslcontext = SSLContext.getInstance("SSL"); sslcontext.init(null, osTrustManager, null); } catch (NoSuchAlgorithmException e) { System.err.println(e); e.printStackTrace(); } catch (KeyManagementException e) { System.err.println(e); e.printStackTrace(); } threadPool = Executors.newFixedThreadPool(300, new ThreadFactory(){ public Thread newThread(Runnable r) { Thread t = new Thread(r, "Request thread pool thread"); // t.setDaemon(true); return t; }}); }
2
public void addDocument(File f) throws IOException { String document = ""; BufferedReader io = new BufferedReader(new FileReader(f)); String line; boolean markUpFile = false, captureText = false; while((line = io.readLine()) != null) { if(line.startsWith("<DOC>")) markUpFile = true; else if(!markUpFile) captureText = true; if(markUpFile && line.startsWith("<TEXT>")) { captureText = true; continue; } if(markUpFile && line.startsWith("</TEXT>")) captureText = false; if(!captureText) continue; document += line + " "; if(line.equals("\n")) { stemDocument(document); document = ""; } } stemDocument(document); }
9
public final IServiceProvider getSite() { return privateSite; }
0
public ArrayList<Pallet> getPalletsWithBlockStatus(boolean status) { ArrayList<Pallet> pallets = new ArrayList<Pallet>(); String sql = "Select * from Pallets where isBLocked = ? "; PreparedStatement ps = null; try { ps = conn.prepareStatement(sql); ps.setBoolean(1, status); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { ResultSet rs = ps.executeQuery(); while (rs.next()) { pallets.add(extractPallet(rs)); } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } finally { if(ps != null) try { ps.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return pallets; }
5
* @param colony The <code>Colony</code> to unload to, * or null if unloading in Europe. * @return True if the unload succeeded. */ private boolean unloadGoods(Goods goods, Unit carrier, Colony colony) { if (colony == null && carrier.isInEurope() && carrier.getOwner().canTrade(goods)) return sellGoods(goods); GoodsType type = goods.getType(); int oldAmount = carrier.getGoodsContainer().getGoodsCount(type); ColonyWas colonyWas = (colony == null) ? null : new ColonyWas(colony); UnitWas unitWas = new UnitWas(carrier); if (askServer().unloadCargo(goods) && carrier.getGoodsContainer().getGoodsCount(type) != oldAmount) { if (colonyWas != null) colonyWas.fireChanges(); unitWas.fireChanges(); return true; } return false; }
7
protected void _allocate(int cap) { initialCapacity=cap; buf=new byte[cap]; index=0; }
0
public String toString(){ if(identifer != null)return this.identifer.getNewName(false); else if(literal != null)return this.literal.getValue(); else return expression.toString(); }
2
@SuppressWarnings("unchecked") @Override public void refreshView(Map<String, Map<String, Object>> state) { // Extract the maps from the state // Map<String, Object> mapState = state.get("mapState"), dayState = state .get("dayState"); LinkedList<Map<String, Object>> elementList = (LinkedList<Map<String, Object>>) mapState .get("elements"); Map<String, Integer> count = new HashMap<String, Integer>(); Iterator<Map<String, Object>> elementIterator = elementList.iterator(); Map<String, Object> element; Integer x = (Integer) mapState.get("x"), y = (Integer) mapState .get("y"); for (int i = 0; i < y; i++) { for (int j = 0; j < x; j++) { element = elementIterator.next(); if (element != null) { if(count.get(element.get("type")) == null){ count.put((String)element.get("type"), 0); } if(element.get("state") != "Dead"){ count.put((String)element.get("type"), count.get(element.get("type"))+1); } } } } graph.update((int)(dayState == null ? 0 : dayState.get("day")), count); c.processViewCommand(Command.NEXTDAY); }
6
@Override public void update(Observable o, Object arg1) { if (o == model){ view.displayData(model.getData()); view.displayScore(model.getScore()); view.displayHint(model.getHint()); if(model.isSucceed()){ view.gameOver(true); } if(model.isStuck()){ view.gameOver(false); } } if (o == view){ if(arg1 == "save"){ model.setFileName(view.getFileNamePath()); } if(arg1 == "load"){ model.setFileName(view.getFileNamePath()); } if(arg1 == "solve"){ model.setDepth(view.getDepth()); model.setHintsNum(view.getHintNum()); } model.doUserCommand(view.getUserCommand()); } }
7
public void printSudoku() { for (int i = 1; i <= countRow; i++) { for (int j = 1; j <= countRow; j++) { if (selectCellCoord(i, j).openValues.size() == 1) System.out.print(selectCellCoord(i, j).openValues + " "); else System.out.print("[ ] "); } System.out.println(); } System.out.println("---------------------------------"); }
3
@Override public int read() throws IOException { synchronized (this) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } return -1; }
1
protected void processEntity(IXMLReader reader, IXMLEntityResolver entityResolver) throws Exception { if (! XMLUtil.checkLiteral(reader, "NTITY")) { XMLUtil.skipTag(reader); return; } XMLUtil.skipWhitespace(reader, null); char ch = XMLUtil.readChar(reader, '\0'); if (ch == '%') { XMLUtil.skipWhitespace(reader, null); entityResolver = this.parameterEntityResolver; } else { reader.unread(ch); } String key = XMLUtil.scanIdentifier(reader); XMLUtil.skipWhitespace(reader, null); ch = XMLUtil.readChar(reader, '%'); String systemID = null; String publicID = null; switch (ch) { case 'P': if (! XMLUtil.checkLiteral(reader, "UBLIC")) { XMLUtil.skipTag(reader); return; } XMLUtil.skipWhitespace(reader, null); publicID = XMLUtil.scanString(reader, '%', this.parameterEntityResolver); XMLUtil.skipWhitespace(reader, null); systemID = XMLUtil.scanString(reader, '%', this.parameterEntityResolver); XMLUtil.skipWhitespace(reader, null); XMLUtil.readChar(reader, '%'); break; case 'S': if (! XMLUtil.checkLiteral(reader, "YSTEM")) { XMLUtil.skipTag(reader); return; } XMLUtil.skipWhitespace(reader, null); systemID = XMLUtil.scanString(reader, '%', this.parameterEntityResolver); XMLUtil.skipWhitespace(reader, null); XMLUtil.readChar(reader, '%'); break; case '"': case '\'': reader.unread(ch); String value = XMLUtil.scanString(reader, '%', this.parameterEntityResolver); entityResolver.addInternalEntity(key, value); XMLUtil.skipWhitespace(reader, null); XMLUtil.readChar(reader, '%'); break; default: XMLUtil.skipTag(reader); } if (systemID != null) { entityResolver.addExternalEntity(key, publicID, systemID); } }
9
public static void analytics() { String uuid=""; try { BufferedReader in=new BufferedReader(new InputStreamReader(new FileInputStream(Main.path+"uuid.txt"), "UTF-8")); String ln; String out=""; while ((ln=in.readLine())!=null) out+=ln; uuid=out; } catch (Exception e) {} if (uuid.equals("")) { install(); } try { BufferedReader in=new BufferedReader(new InputStreamReader(new FileInputStream(Main.path+"uuid.txt"), "UTF-8")); String ln; String out=""; while ((ln=in.readLine())!=null) out+=ln; uuid=out; } catch (Exception e) {} String os=System.getProperty("os.name"); os=os.replaceAll(" ", ""); String version=System.getProperty("os.version"); version=version.replaceAll(" ", " "); String url="http://"+Main.ip+"/d0941e68da8f38151ff86a61fc59f7c5cf9fcaa2/analityc_for_desktop/analitika.php?mac_hash="+uuid+"&os="+os+"&osVersion="+version+"&appVersion="+Main.currentVersion; try { URL url1=new URL(url); BufferedReader inn=new BufferedReader(new InputStreamReader(url1.openStream())); inn.close(); } catch (Exception e) {} }
6
@Override public boolean tick(Tickable ticking, int tickID) { if(!super.tick(ticking,tickID)) return false; if(tickID!=Tickable.TICKID_MOB) return false; if((affecting()!=null)&&(affecting() instanceof MOB)) { final MOB M=(MOB)affecting(); final Room room=M.location(); final MOB invoker=(invoker()!=null) ? invoker() : M; if((room!=null) &&(room.getArea().getClimateObj().weatherType(room)==Climate.WEATHER_THUNDERSTORM) &&(CMLib.dice().rollPercentage()>M.charStats().getSave(CharStats.STAT_SAVE_ELECTRIC))) { final int damage=CMLib.dice().roll(1,3,0); CMLib.combat().postDamage(invoker,M,null,damage,CMMsg.MASK_MALICIOUS|CMMsg.MASK_ALWAYS|CMMsg.TYP_ELECTRIC,Weapon.TYPE_STRIKING,L("The electricity in the air <DAMAGE> <T-NAME>!")); CMLib.combat().postRevengeAttack(M, invoker); } } return true; }
8
@Override public void run() { byte[] receiveData = new byte[1024]; while(active) { try { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); String sentence = new String(receivePacket.getData(), 0, receivePacket.getLength()); InetAddress ipAddress = receivePacket.getAddress(); if(sentence.equals(QueryResponse.REQUEST_PHRASE)) { if(serverAddr != null && server != null) { byte[] response = createResponse().getResponseData().getBytes(); int port = receivePacket.getPort(); DatagramPacket sendPacket = new DatagramPacket(response, response.length, ipAddress, port); serverSocket.send(sendPacket); } } else { log.err("Bad request from " + ipAddress.getHostAddress() + "!"); } }catch(IOException e) { log.err("Error while waiting for request! Never mind..."); log.excp(e); } } }
5
public String getName() { return name; }
0
private LinkedList<Node> getAllNodes(Node in) { LinkedList<Node> list = new LinkedList<Node>(); list.add(in); int i = 0; while ( i < list.size() ) { for ( Node n : list.get(i).getNeighbors() ) { if ( n != null && !list.contains(n) ) list.addLast(n); } i++; } return list; }
4
@Basic @Column(name = "password") public String getPassword() { return password; }
0
public String getPlace() { return place; }
0
public String row(int i) throws Exception { int h = this.contents.height(); // The top and bottom of the box if ((i == 0) || (i == h + 1)) { return "+" + TBUtils.dashes(this.contents.width()) + "+"; } // Stuff within the box else if ((i > 0) && (i <= h)) { return "|" + this.contents.row(i - 1) + "|"; } // Everything else else { throw new Exception("Invalid row " + i); } } // row(int)
4
@Override public void render(GameContainer gc, Graphics g) { _animation[facing].draw(position.getX(), position.getY()); if(GameInfo.SHOW_DEBUG_INFO) { if(considered != null && isCurrentlyMoving) { g.setColor(new Color(0, 255, 255, 64)); for(Node node : considered) { Vector2 pos = node.getPosition(); g.fillRect(pos.getX() * 16, pos.getY() * 16, Constants.TILE_WIDTH, Constants.TILE_HEIGHT); } g.setColor(new Color(255, 255, 255, 64)); for(Node node : usedPath) { Vector2 pos = node.getPosition(); g.fillRect(pos.getX() * 16, pos.getY() * 16, Constants.TILE_WIDTH, Constants.TILE_HEIGHT); } } } if(follower != null) follower.render(gc, g); }
6
public Map<Position, List<ElementInfo>> getElements() { final Map<Position, List<ElementInfo>> elements = new HashMap<Position, List<ElementInfo>>(); for (Entry<Position, List<Element>> entry : getGrid().getElementsOnGridMap().entrySet()) elements.put(entry.getKey(), new ArrayList<ElementInfo>(entry.getValue())); return elements; }
1
public double leiaDouble() { double numero = 0 ; String linha ; BufferedReader entra = new BufferedReader(new InputStreamReader(System.in)) ; try { linha = entra.readLine() ; numero = Double.valueOf(linha).doubleValue(); } catch (Exception erro) { System.out.println("erro de entrada de dados"); } return numero ; }
1
public void startWorking(BufferedReader in, PrintWriter out) throws IOException { new Thread(() -> { try { String input; while ((input = in.readLine()) != null) { lastInput = input; event.run(); } } catch (IOException e) { System.err.println("[Connection] Error pt1 : " + e); } try { in.close(); } catch (IOException e) { System.err.println("[Connection] Error pt 2: " + e); } out.close(); isWorking.set(false); if (close != null) close.run(); }).start(); new Thread(() -> { Timer t=new Timer(); t.schedule( new TimerTask() { public void run() { sendMessages(out); if (!isWorking.get()) this.cancel(); } }, 0, 5); }).start(); }
5
@Override public void executeTask() { /* Redundant code here in the event Server and Client start diverting. */ try { /* NULL indicates no node was registered. */ if (node != null) { Node mNode = new Client(); switch(node.NODE) { case CLIENT: mNode = RoutingTable.getInstance().getPrimaryServer(); if(RoutingTable.getInstance().registerClient((Client) node)) { mNode.addStringMessage("REGISTER_OKAY"); } else { mNode.addStringMessage("REGISTRATION_ERROR"); } break; case NODE: mNode.addStringMessage("Node " + node.getCurrentIP() + " did not have a NODE_TYPE"); break; case SERVER: if(RoutingTable.getInstance().registerServer((Server) node)){ mNode.addStringMessage("REGISTER_OKAY"); } else { mNode.addStringMessage("REGISTRATION_ERROR"); } break; default: break; } mNode.setDestinationIP(node.getCurrentIP()); mNode.setDestinationPort(node.getDestinationPort()); buffer = mNode.toBytes(); dataGram = new DatagramPacket(buffer, buffer.length); dataGram.setPort(mNode.getDestinationPort()); dataGram.setAddress(InetAddress .getByName(mNode.getDestinationIP())); SocketManager.getInstance().sendDatagram(dataGram); } } catch (IOException e) { e.printStackTrace(); } stopTask(); }
7