text
stringlengths
14
410k
label
int32
0
9
private int runDvi(String fileName, int resolution) throws IOException, InterruptedException, ServletException { int depth = 0; String[] command = String.format(DVI_COMMAND, Integer.toString(RESOLUTIONS[resolution]), fileName + IMAGE_SUFFIX, fileName + ".dvi").split(" "); SystemCommandHandler dvi = new SystemCommandHandler(command); dvi.setDirectory(dir); dvi.enableStdOutStore(); dvi.executeAndWait(); if (dvi.getStdOutIOException() != null) throw new ServletException("An IO error occuring when running 'dvi'.", dvi.getStdOutIOException()); if (dvi.getStdErrIOException() != null) throw new ServletException("An IO error occuring when running 'dvi'.", dvi.getStdErrIOException()); if (dvi.getExitCode() != 0) throw new DviException("Command 'dvi' failed during execution."); for (String output : dvi.getStdOutStore()) { Matcher matcher = DEPTH_PATTERN.matcher(output); if (matcher.matches()) { String depthStr = matcher.group(1); depth = Integer.parseInt(depthStr); break; } } return depth; }
5
public void atualizar() { jComboBoxEdicao.removeAllItems(); jComboBoxAnoPublicacao.removeAllItems(); jComboBoxAutor.removeAllItems(); jComboBoxEditora.removeAllItems(); jComboBoxCategoria.removeAllItems(); jComboBoxPublico.removeAllItems(); jComboBoxFormato.removeAllItems(); jComboBoxStatu.removeAllItems(); jComboBoxEdicao.addItem("Todos"); for (Edicao edicao : listaView.getEstoqueComboBox().getMaterialComboBox().getEdicoes()) { jComboBoxEdicao.addItem(edicao); } jComboBoxAnoPublicacao.addItem("Todos"); for (AnoPublicacao anoPublicacao : listaView.getEstoqueComboBox().getMaterialComboBox().getAnosPublicacoes()) { jComboBoxAnoPublicacao.addItem(anoPublicacao); } jComboBoxAutor.addItem("Todos"); for (Autor autor : listaView.getEstoqueComboBox().getMaterialComboBox().getAutores()) { jComboBoxAutor.addItem(autor); } jComboBoxEditora.addItem("Todos"); for (Editora editora : listaView.getEstoqueComboBox().getMaterialComboBox().getEditoras()) { jComboBoxEditora.addItem(editora); } jComboBoxCategoria.addItem("Todos"); for (Categoria categoria : listaView.getEstoqueComboBox().getMaterialComboBox().getCategorias()) { jComboBoxCategoria.addItem(categoria); } jComboBoxPublico.addItem("Todos"); for (Publico publico : listaView.getEstoqueComboBox().getMaterialComboBox().getPublicos()) { jComboBoxPublico.addItem(publico); } jComboBoxFormato.addItem("Todos"); for (Formato formato : listaView.getEstoqueComboBox().getMaterialComboBox().getFormatos()) { jComboBoxFormato.addItem(formato); } jComboBoxStatu.addItem("Todos"); for (Statu statu : listaView.getEstoqueComboBox().getStatus()) { jComboBoxStatu.addItem(statu); } }
8
private void setupDisplay() throws LWJGLException { try { DisplayMode displayMode = null; DisplayMode[] modes = Display.getAvailableDisplayModes(); for (int i = 0; i < modes.length; i++) { if (modes[i].getWidth() == WorldSettings.SCREEN_WIDTH && modes[i].getHeight() == WorldSettings.SCREEN_HEIGHT && modes[i].isFullscreenCapable()) { displayMode = modes[i]; break; } } Display.setDisplayMode(displayMode); Display.setFullscreen(WorldSettings.FULLSCREEN); Display.create(); } catch (LWJGLException e) { e.printStackTrace(); } }
5
public void run() { while(true) { try { repaint(); Thread.sleep(5); } catch(InterruptedException ie) { stop(); } } }
2
public void modificarCliente(Cliente c){ try { int especial = 0; if(c.isEspecial()){ especial = 1; } Statement comando=connection.createStatement(); comando.executeUpdate("UPDATE Cliente SET " + "Nombre='"+c.getNombre()+"'," + "Apellidos='"+c.getApellidos()+"'," + "Apodo='"+c.getApodo()+"'," + "Especial='"+Integer.toString(especial)+"'" + " WHERE idCliente='"+c.getIdCliente()+"'"); } catch (SQLException ex) { Logger.getLogger(GestionarCliente.class.getName()).log(Level.SEVERE, null, ex); } }
2
private void initialiseSequencer() { try { // Attempt to locate the MIDE sequencer as one of the MIDI devices MidiDevice.Info[] midiDeviceInfo = MidiSystem.getMidiDeviceInfo(); int sequencerPos = -1; for (int idx = 0; idx < midiDeviceInfo.length; idx++) { if (midiDeviceInfo[idx].getName().indexOf("Sequencer") != -1) { sequencerPos = idx; } } if (sequencerPos != -1) { sequencer = (Sequencer) MidiSystem.getMidiDevice( midiDeviceInfo[sequencerPos] ); } if (sequencer == null) { throw new MidiUnavailableException(); } // Now that a sequencer has been found, open it sequencer.open(); // Attempt to locate and open a suitable synthesizer for the sequencer if (!(sequencer instanceof Synthesizer)) { synthesizer = MidiSystem.getSynthesizer(); synthesizer.open(); Receiver synthReceiver = synthesizer.getReceiver(); Transmitter seqTransmitter = sequencer.getTransmitter(); seqTransmitter.setReceiver(synthReceiver); } else { synthesizer = (Synthesizer) sequencer; } } catch (MidiUnavailableException e) { throw new IllegalStateException("MidiAsset.initialiseSequencer: " + "Cannot initialise sequencer"); } }
6
static Direction counterclockwise(Direction direction) { if (direction == NORTH) return WEST; if (direction == WEST) return SOUTH; if (direction == SOUTH) return EAST; return NORTH; }
3
public boolean isOptOut() { synchronized (optOutLock) { try { // Reload the metrics file configuration.load(getConfigFile()); } catch (IOException ex) { if (debug) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); } return true; } catch (InvalidConfigurationException ex) { if (debug) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); } return true; } return configuration.getBoolean("opt-out", false); } }
4
public MClientCmdListener(String analyticsServerRef, String billingServerRef, ExecutorService mClientExecutionService) { this.analyticsServerRef = analyticsServerRef; this.billingServerRef = billingServerRef; this.mClientExecutionService = mClientExecutionService; // create EventListener Remote Object try { eventListener = new EventListener_Impl(); } catch (RemoteException e1) { logger.error("EventListener Remote Exception"); } readProperties(); try { registry = LocateRegistry.getRegistry(registryHost, registryPort); } catch (RemoteException e1) { System.out.println("Couldn't find Registry!"); } try { mClientHandler = (MClientHandler_RO) registry.lookup(analyticsServerRef); } catch (AccessException e1) { logger.error("Access to the registry denied"); } catch (RemoteException e1) { System.out.println("Remote Objects from the Analytics Server cannot be found. For further usage please " + "contact the support team and restart the client!"); } catch (NotBoundException e1) { logger.error("Analytic Server not bound"); } try { billingServer = (BillingServer_RO) registry.lookup(billingServerRef); } catch (AccessException e1) { logger.error("Access to the registry denied"); } catch (RemoteException e1) { System.out.println("Remote Objects from the Billing Server cannot be found. For further usage please " + "contact the support team and restart the client!"); } catch (NotBoundException e1) { logger.error("Billing Server not bound"); } }
8
public StatistikZusammenfassung<Team> getStatistikZusammenfassung(String teamId) { Team team = eloPersistence.findById(Team.class, teamId); int anzahlSiege = 0; int toreGeschossen = 0; int toreGefangen = 0; int eloMinimum = Integer.MAX_VALUE; int eloMaximum = Integer.MIN_VALUE; for (EloPunktzahl punktzahl : team.getPunktzahlHistorie()) { if (punktzahl.getPunktzahl() < eloMinimum) { eloMinimum = punktzahl.getPunktzahl(); } if (punktzahl.getPunktzahl() > eloMaximum) { eloMaximum = punktzahl.getPunktzahl(); } } List<Spiel> spiele = eloPersistence.findAll(Spiel.class, Integer.MAX_VALUE, "order by m.zeitpunkt desc"); for (Iterator<Spiel> i = spiele.iterator(); i.hasNext();) { Spiel spiel = i.next(); if (!spiel.getGewinner().getId().equals(teamId) && !spiel.getVerlierer().getId().equals(teamId)) { i.remove(); } } for (Spiel spiel : spiele) { boolean gewonnen = true; if (!spiel.getGewinner().getId().equals(teamId)) { gewonnen = false; } if (gewonnen) { anzahlSiege++; toreGeschossen += spiel.getToreGewinner(); toreGefangen += spiel.getToreVerlierer(); } else { toreGefangen += spiel.getToreGewinner(); toreGeschossen += spiel.getToreVerlierer(); } } StatistikZusammenfassung<Team> result = new StatistikZusammenfassung<Team>(team, spiele.size(), anzahlSiege, toreGeschossen, toreGefangen, eloMinimum, eloMaximum); return result; }
9
public int putRef(int tag, Reference ref) { String className = ref.getClazz(); String typeSig = ref.getType(); if (tag == FIELDREF) TypeSignature.checkTypeSig(typeSig); else TypeSignature.checkMethodTypeSig(typeSig); int classIndex = putClassType(className); int nameIndex = putUTF8(ref.getName()); int typeIndex = putUTF8(typeSig); int nameTypeIndex = putIndexed(NAMEANDTYPE, ref.getName(), nameIndex, typeIndex); return putIndexed(tag, className, classIndex, nameTypeIndex); }
1
@Override public void setToNative(long i, Object o) { if (o == null) { stringLengths.setShort(i, (short) -1); } else { if (!(o instanceof String)) { throw new IllegalArgumentException(o + " is not a string."); } String s = (String) o; if (s.length() > maxStringLength) { throw new IllegalArgumentException("String " + s + " is too long."); } byte[] tmp; try { tmp = s.getBytes(CHARSET); } catch (UnsupportedEncodingException ex) { return; } int strLen = tmp.length; if (strLen > Short.MAX_VALUE) { throw new IllegalArgumentException("String " + s + " is too long."); } stringLengths.setShort(i, (short) strLen); long offset = sizeof * i * maxStringLength * CHARSET_SIZE; for (int j = 0; j < strLen; j++) { Utilities.UNSAFE.putByte(ptr + offset + sizeof * j, tmp[j]); } } }
6
public void txtToJson(String txtPath) { Json json = new Json(); json.prettyPrint(json); FileReader fileReader = null; BufferedReader br = null; try { fileReader = new FileReader(txtPath); br = new BufferedReader(fileReader); String strLine; // Read File Line By Line while ((strLine = br.readLine()) != null) { // Print the content on the console System.out.println(strLine); } // Close the input stream } catch (Exception e) {// Catch exception if any System.err.println("Error: " + e.getMessage()); } finally { try { fileReader.close(); br.close(); } catch (IOException e) { e.printStackTrace(); } } }
3
static final public void unary() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case MINUS: jj_consume_token(MINUS); element(); break; case CONSTANT: case 12: element(); break; default: jj_la1[5] = jj_gen; jj_consume_token(-1); throw new ParseException(); } }
4
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Field other = (Field) obj; if (x != other.x) return false; if (y != other.y) return false; return true; }
5
@Test public void adenAskStudentPriceTest(){ LocalDate date = LocalDate.now(); int dayOfWeek = date.getDayOfWeek(); boolean weekend = false; Canteen c3 = new Canteen(new CanteenData(CanteenNames.ADENAUERRING, 0)); int dayShift = (dayOfWeek + 2) % 7; if(dayOfWeek == 0 || (dayOfWeek == 6)) { // weekends c3 = new Canteen(new CanteenData(CanteenNames.ADENAUERRING, dayShift)); weekend = true; } userInput.add("hi"); userInput.add("xizhe"); if( !weekend ){ userInput.add("what's in canteen today"); }else { if(dayShift == 1) { userInput.add("what's in canteen next monday"); }else userInput.add("what's in canteen next tuesday"); } String meal = c3.getCanteenData().getLines().get(0).getTodayMeals().get(0).getMealName(); // line one userInput.add("how much is " + meal); // line two is closed now meal = c3.getCanteenData().getLines().get(2).getTodayMeals().get(0).getMealName();// line three userInput.add("how much costs " + meal); meal = c3.getCanteenData().getLines().get(3).getTodayMeals().get(0).getMealName();// line four userInput.add("what's the price of " + meal); meal = c3.getCanteenData().getLines().get(8).getTodayMeals().get(0).getMealName();// line six userInput.add("what is the price of " + meal); ArrayList<MealData> cafeMeals = c3.getCanteenData().getLines().get(9).getTodayMeals(); // cafeteria for( MealData m : cafeMeals ){ meal = m.getMealName(); userInput.add("how much is " + meal); } /* side dish test */ userInput.add("how much is blattSalat"); userInput.add("how much costs currywurst"); userInput.add("how much is belgische pommes"); userInput.add("how much is country potatoes"); runMainActivityWithTestInput(userInput); String strAmount = String.valueOf(2.50); assertTrue(nlgResults.get(3).contains(strAmount));// line one price float price = c3.getCanteenData().getLines().get(2).getTodayMeals().get(0).getS_price(); strAmount = String.valueOf(price); assertTrue( nlgResults.get(4).contains(strAmount) ); price = c3.getCanteenData().getLines().get(3).getTodayMeals().get(0).getS_price(); strAmount = String.valueOf(price); assertTrue(nlgResults.get(5).contains(strAmount)); price = c3.getCanteenData().getLines().get(8).getTodayMeals().get(0).getS_price(); strAmount = String.valueOf(price); assertTrue(nlgResults.get(6).contains(strAmount)); boolean correct = false; for(int i = 1; i <= cafeMeals.size(); i++) { price = cafeMeals.get(i - 1).getS_price(); strAmount = String.valueOf(price); if(nlgResults.get(i + 6).contains(strAmount)){ correct = true; }else correct = false; } assertTrue(correct); strAmount = String.valueOf(0.75); //System.out.println(nlgResults.get(7 + cafeMeals.size())); assertTrue(nlgResults.get(7 + cafeMeals.size()).contains(strAmount)); // blatsalat is always 0.75 strAmount = String.valueOf(1.7); assertTrue(nlgResults.get(8 + cafeMeals.size()).contains(strAmount)); strAmount = String.valueOf(1.15); assertTrue(nlgResults.get(9 + cafeMeals.size()).contains(strAmount)); strAmount = String.valueOf(0.9); assertTrue(nlgResults.get(10 + cafeMeals.size()).contains(strAmount)); }
7
public Packing createPacking(String type){ Packing pack = null; if(type.equalsIgnoreCase("cloth")){ pack = new Cloth(); } else{ if(type.equalsIgnoreCase("cellophane")){ pack = new Cellophane(); } else{ if(type.equalsIgnoreCase("mesh")){ pack = new Mesh(); } else{ if(type.equalsIgnoreCase("paper")){ pack = new Paper(); } else{ if(type.equalsIgnoreCase("tape")){ pack = new Tape(); } } } } } return pack; }
5
@Test public void testUS36_consultationFicheVideo() { //intLgTitreVideo = Integer.parseInt(lgTitreVideo); String titreVideoC = null; String lgTitreVideo; int intLgTitreVideo; int intCptVideo; String cptVideo; String varVideoTitle; String varVideoTitleComplete; String pointSuspension; String recupereTitreV; String lgNomDansListe; selenium.open("/ovp-web/catalogue.html"); // Le clic sur une vid�o emm�ne sur sa fiche d�taill� String titreVideoCarroussel = selenium.getText("css=h1"); System.out.println(titreVideoCarroussel); // R�cup�rer le nombre de vid�o dans le carroussel String k = "2"; //Commencer par la vid�o 2 pour tester le carroussel int intk = Integer.parseInt(k); Number nombreVideoCarroussel = selenium.getXpathCount("//li[@class='roundabout-moveable-item']"); Number nombreVideoCarroussel1 = selenium.getXpathCount("//li[@class='roundabout-moveable-item roundabout-in-focus']"); nombreVideoCarroussel = nombreVideoCarroussel.intValue()+nombreVideoCarroussel1.intValue(); System.out.println(nombreVideoCarroussel); // Parcours du carroussel pour l'affichage d'une fiche vidéo dont la longueur du titre est inférieur à 11 caractères while(intk < nombreVideoCarroussel.intValue()){ titreVideoC = selenium.getText("xpath=(//li[@id='videoBlocDefault']/div/div/h1)[" + k + "]"); System.out.println(titreVideoC); lgTitreVideo = selenium.getEval(selenium.getEval("'" + titreVideoC + "'.length")); intLgTitreVideo = Integer.parseInt(lgTitreVideo); if(intLgTitreVideo>=11){ selenium.click("xpath=(//li[@id='videoBlocDefault']/a)[" + k + "]"); k = selenium.getEval(k + "+1"); intk = Integer.parseInt(k); }else{ selenium.click("xpath=(//li[@id='videoBlocDefault']/a)[" + k + "]"); selenium.waitForPageToLoad("30000"); break; } } // Affichage de la fiche vid�o selenium.click("xpath=(//li[@id='videoBlocDefault']/a)[" + k + "]"); // V�rifier que le titre de la vid�o du carroussel correspond au titre de la fiche d�taill�e System.out.println("Fiche carroussel = "+titreVideoC); //a voir selenium.waitForPageToLoad("30000"); selenium.click("xpath=(//li[@id='videoBlocDefault']/a)[" + k + "]"); selenium.waitForPageToLoad("60000"); selenium.click("xpath=(//li[@id='videoBlocDefault']/a)[" + k + "]"); selenium.waitForPageToLoad("30000"); selenium.waitForPageToLoad("30000"); String titreVideoFiche = selenium.getText("id=videoTitle"); System.out.println("Fiche vid�o = "+titreVideoFiche); assertEquals(titreVideoC, titreVideoFiche); assertTrue(selenium.isElementPresent("//aside[@id='listVideo']")); System.out.println("R�int�grer ce test \"verifyElementPresent //aside[@style='display: block; background-color: rgb(33, 33, 33);']\""); // R�cup�ration du nombre de vid�o parmi la liste Number nombreVideo = selenium.getXpathCount("//li[@style='display: list-item;']"); System.out.println(nombreVideo); // Le compteur de vid�o 'cptVideo' est initialis� � 1 pour r�cup�r� la premi�re vid�o de la liste afin de l'analyser cptVideo = "1"; System.out.println(cptVideo); intCptVideo=Integer.parseInt(cptVideo); while(intCptVideo <= nombreVideo.intValue()){ String nomVideo = selenium.getText("//li[" + cptVideo + "]/div[@class='infos']"); String longueurNom = selenium.getEval(selenium.getEval("'" + nomVideo + "'.length")); int intLongueurNom = Integer.parseInt(longueurNom); if(intLongueurNom >= 11){ // R�cup�ration des dix premiers caract�res � partir du titre de la vid�o selenium.click("xpath=(//li[@id='miniVideoBlocDefault']/a)[" + cptVideo + "]"); selenium.waitForPageToLoad("30000"); String videoTitle = selenium.getText("id=videoTitle"); System.out.println(videoTitle); // Retour � la fiche vid�o pr�c�dente //String back = selenium.getEval(cptVideo + "-1"); String back = selenium.getEval(cptVideo); selenium.open("/ovp-web/videoDetails.html?campaignId=1&videoId=" + back); System.out.println(back); String i = "0"; int inti=Integer.parseInt(i); varVideoTitleComplete = ""; while(inti<10){ varVideoTitle = selenium.getEval("'" + videoTitle + "'['" + i + "']"); lgNomDansListe = selenium.getEval(selenium.getEval("'" + videoTitle + "'.length")); int intLgNomDansListe = Integer.parseInt(lgNomDansListe); if(intLgNomDansListe>=11){ //varVideoTitleComplete = selenium.getEval("storedVars['varVideoTitleComplete']+storedVars['varVideoTitle']"); varVideoTitleComplete=varVideoTitleComplete.concat(varVideoTitle); i = selenium.getEval(i + "+1;"); inti=Integer.parseInt(i); } } // Construction du titre avec les points de suspensions System.out.println(varVideoTitleComplete); pointSuspension = "..."; //recupereTitreV = selenium.getEval("storedVars['varVideoTitleComplete']+storedVars['pointSuspension']"); recupereTitreV = varVideoTitleComplete.concat(pointSuspension); System.out.println(recupereTitreV); // Comparaison du nom construit avec les points de suspensions avec le nom affiché dans la liste des vidéos assertEquals(recupereTitreV, nomVideo); System.out.println("La nom de la vid�o "+nomVideo+" est bien test�"); cptVideo = selenium.getEval(cptVideo + "+1"); intCptVideo=Integer.parseInt(cptVideo); }else{ cptVideo = selenium.getEval(cptVideo + "+1"); intCptVideo=Integer.parseInt(cptVideo); } } selenium.selectWindow("null"); }
6
public static boolean closedPropositionP(Proposition self) { { MemoizationTable memoTable000 = null; Cons memoizedEntry000 = null; Stella_Object memoizedValue000 = null; if (Stella.$MEMOIZATION_ENABLEDp$) { memoTable000 = ((MemoizationTable)(Logic.SGT_LOGIC_F_CLOSED_PROPOSITIONp_MEMO_TABLE_000.surrogateValue)); if (memoTable000 == null) { Surrogate.initializeMemoizationTable(Logic.SGT_LOGIC_F_CLOSED_PROPOSITIONp_MEMO_TABLE_000, "(:MAX-VALUES 500 :TIMESTAMPS (:META-KB-UPDATE))"); memoTable000 = ((MemoizationTable)(Logic.SGT_LOGIC_F_CLOSED_PROPOSITIONp_MEMO_TABLE_000.surrogateValue)); } memoizedEntry000 = MruMemoizationTable.lookupMruMemoizedValue(((MruMemoizationTable)(memoTable000)), self, ((Context)(Stella.$CONTEXT$.get())), Stella.MEMOIZED_NULL_VALUE, null, -1); memoizedValue000 = memoizedEntry000.value; } if (memoizedValue000 != null) { if (memoizedValue000 == Stella.MEMOIZED_NULL_VALUE) { memoizedValue000 = null; } } else { memoizedValue000 = (Proposition.helpClosedPropositionP(self, Stella.NIL) ? Stella.TRUE_WRAPPER : Stella.FALSE_WRAPPER); if (Stella.$MEMOIZATION_ENABLEDp$) { memoizedEntry000.value = ((memoizedValue000 == null) ? Stella.MEMOIZED_NULL_VALUE : memoizedValue000); } } { BooleanWrapper value000 = ((BooleanWrapper)(memoizedValue000)); return (BooleanWrapper.coerceWrappedBooleanToBoolean(value000)); } } }
7
public boolean useCard(int id) throws JSONException { // Würfel eine 2 (id = 6) // POST /bundesklatsche/get_data/0/3/2 HTTP/1.1\r\n // Freiwurf (id = 4) // POST /bundesklatsche/get_data/0/1 // refresh info(0); int field = getCard(id); if (field == 0) { return false; } Utils.getString("bundesklatsche/get_data/0/" + field); Output.printTabLn("Benutze " + id2Card(id), Output.INFO); // refresh info(0); return true; }
1
@Override public void mouseReleased(MouseEvent e) { if (!potentialDrag) return; source.removeMouseMotionListener( this ); potentialDrag = false; if (changeCursor) source.setCursor( originalCursor ); if (destination instanceof JComponent) { ((JComponent)destination).setAutoscrolls( autoscrolls ); } // Layout the components on the parent container if (autoLayout) { if (destination instanceof JComponent) { ((JComponent)destination).revalidate(); } else { destination.validate(); } } }
5
public NondeterminismAction(Automaton automaton, Environment environment) { super("Highlight Nondeterminism", null); this.automaton = automaton; this.environment = environment; }
0
@SuppressWarnings("nls") @Override public String toString() { StringBuilder buffer = new StringBuilder(); if (getParent() == null) { buffer.append("FLOATING "); } buffer.append("Dock Container [x:"); buffer.append(getX()); buffer.append(" y:"); buffer.append(getY()); buffer.append(" w:"); buffer.append(getWidth()); buffer.append(" h:"); buffer.append(getHeight()); int count = mDockables.size(); for (int i = 0; i < count; i++) { buffer.append(' '); if (i == mCurrent) { buffer.append('*'); } buffer.append('d'); buffer.append(i); buffer.append(':'); buffer.append(mDockables.get(i).getTitle()); } buffer.append("]"); return buffer.toString(); }
3
public long writeToOutputStream(OutputStream out) throws IOException { long documentLength = documentSeekableInput.getLength(); SeekableInputConstrainedWrapper wrapper = new SeekableInputConstrainedWrapper( documentSeekableInput, 0L, documentLength, false); try { wrapper.prepareForCurrentUse(); byte[] buffer = new byte[4096]; int length; while ((length = wrapper.read(buffer, 0, buffer.length)) > 0) { out.write(buffer, 0, length); } } catch (Throwable e) { logger.log(Level.FINE, "Error writting PDF output stream.", e); throw new IOException(e.getMessage()); } finally { try { wrapper.close(); } catch (IOException e) { } } return documentLength; }
3
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Schedule schedule = (Schedule) o; if (id != schedule.id) return false; if (seqNumber != schedule.seqNumber) return false; return true; }
5
@Override public void keyPressed(int key, char character, GUIComponent component) { String entryString = entryText.getText(); if (GraphicalFont.isStandardChar(character)) { setEntryText(entryString + character); } switch (key) { case (Keyboard.KEY_RETURN) : { this.deactivate(); actionPerformed(); break; } case (Keyboard.KEY_ESCAPE) : { this.deactivate(); break; } case (Keyboard.KEY_DELETE) : { if (entryString.length() > 0) { setEntryText(entryString.substring(0, entryString.length() - 1)); } break; } case (Keyboard.KEY_BACK) : { if (entryString.length() > 0) { setEntryText(entryString.substring(0, entryString.length() - 1)); } break; } } }
7
private byte[] encrypt(byte[] plain, byte[][] _iv){ if(passphrase==null) return plain; if(cipher==null) cipher=genCipher(); byte[] iv=_iv[0]=new byte[cipher.getIVSize()]; if(random==null) random=genRandom(); random.fill(iv, 0, iv.length); byte[] key=genKey(passphrase, iv); byte[] encoded=plain; // PKCS#5Padding { //int bsize=cipher.getBlockSize(); int bsize=cipher.getIVSize(); byte[] foo=new byte[(encoded.length/bsize+1)*bsize]; System.arraycopy(encoded, 0, foo, 0, encoded.length); int padding=bsize-encoded.length%bsize; for(int i=foo.length-1; (foo.length-padding)<=i; i--){ foo[i]=(byte)padding; } encoded=foo; } try{ cipher.init(Cipher.ENCRYPT_MODE, key, iv); cipher.update(encoded, 0, encoded.length, encoded, 0); } catch(Exception e){ //System.err.println(e); } Util.bzero(key); return encoded; }
5
private void startConnectLoop() { connectLoop = new Thread() { @Override public void run() { final int numSlots = 20; int numAttempts = firstConnection ? 0 : 1; try { while(connectLoop != null) { Random random = new Random(); int upperBound = Math.min((int)Math.pow(2, numAttempts), numSlots) - 1; long waitTime = random.nextInt(upperBound + 1) * 60 * 1000 / numSlots; if(numAttempts > 0 || !firstConnection) { print("Waiting " + waitTime / 1000 + "s"); } Thread.sleep(waitTime); try { print("---------------------------------------------------"); XmppConnection connection = new XmppConnection(jid); connection.connect(); print("-------------------- Connected --------------------"); postMessage(MessageType.CONNECTED, connection); break; } catch (IOException e) { print("---------------- Failed to connect ----------------"); } catch (XmppException e) { postMessage(MessageType.ERROR, e); break; } ++numAttempts; } } catch(InterruptedException _) { } } }; connectLoop.start(); }
7
private boolean indexWithinCapacity(int index) { return index < array.length && index >= 0; }
1
public void prune() { ConstPool cp = compact0(); LinkedList newAttributes = new LinkedList(); AttributeInfo invisibleAnnotations = getAttribute(AnnotationsAttribute.invisibleTag); if (invisibleAnnotations != null) { invisibleAnnotations = invisibleAnnotations.copy(cp, null); newAttributes.add(invisibleAnnotations); } AttributeInfo visibleAnnotations = getAttribute(AnnotationsAttribute.visibleTag); if (visibleAnnotations != null) { visibleAnnotations = visibleAnnotations.copy(cp, null); newAttributes.add(visibleAnnotations); } AttributeInfo signature = getAttribute(SignatureAttribute.tag); if (signature != null) { signature = signature.copy(cp, null); newAttributes.add(signature); } ArrayList list = methods; int n = list.size(); for (int i = 0; i < n; ++i) { MethodInfo minfo = (MethodInfo)list.get(i); minfo.prune(cp); } list = fields; n = list.size(); for (int i = 0; i < n; ++i) { FieldInfo finfo = (FieldInfo)list.get(i); finfo.prune(cp); } attributes = newAttributes; constPool = cp; }
5
@Override public Categoria ListById(int id_categoria) { Connection conn = null; PreparedStatement pstm = null; ResultSet rs = null; Categoria c = new Categoria(); try{ conn = ConnectionFactory.getConnection(); pstm = conn.prepareStatement(LISTBYID); pstm.setInt(1, id_categoria); rs = pstm.executeQuery(); while(rs.next()){ c.setDescricao(rs.getString("descricao_ct")); } }catch(Exception e){ JOptionPane.showMessageDialog(null,"Erro ao listar por id" + e); }finally{ try{ ConnectionFactory.closeConnection(conn, pstm, rs); }catch(Exception e){ JOptionPane.showMessageDialog(null,"Erro ao desconectar com o banco" + e); } } return c; }
3
public static void menuprincipal() { Scanner input = new Scanner(System.in); System.out.println("--------------------------------------------------------------------"); System.out.println("------------------------ MENU PRINCIPAL ----------------------------"); System.out.println("--------------------------------------------------------------------"); System.out.println("SELECIONE UMA DAS OPÇÕES DO MENU:"); System.out.println("(1) - VENDAS"); System.out.println("(2) - CADASTRAR FUNCIONÁRIOS"); System.out.println("(3) - CADASTRAR EVENTOS"); System.out.println("(4) - CADASTRAR CLIENTES"); System.out.println("(5) - GERAR RELATÓRIOS"); System.out.println("(6) - LOGOUT"); System.out.println("(7) - FECHAR"); System.out.println("--------------------------------------------------------------------"); String o = input.next(); int opcao = Integer.parseInt(o); switch (opcao) { case 1: { menuVendas(); break; } case 2: { cadastrarFuncionario(); break; } case 3: { menuEventos(); break; } case 4: { cadastrarCliente(); break; } case 5: { gerarRelatorios(); break; } case 6: { logout(); break; } case 7: { sair(); break; } default: System.out.println("Opção inválida!"); menuprincipal(); break; } }
7
public void findRoomType(String roomType) { Query q = em.createQuery("SELECT t from TypeEntity t"); for (Object o : q.getResultList()) { TypeEntity p = (TypeEntity) o; if (p.getName().equals(roomType)) { typeEntity = p; } } }
2
public void run() { while(Project1.applicationRunning){ /** * Highest Priority is to send Clock Replies. * So sending them first. */ while(!sendClockReplyQueue.isEmpty()){ Message toSend=sendClockReplyQueue.poll(); //System.out.println(toSend.getRecieverAddress()+String.valueOf(toSend.getRecieverPort())); int destNodeID=Project1.mapNodesByAddress.get(toSend.getRecieverAddress()+toSend.getRecieverPort()).getNodeID(); // toSend.setMessageId(this.getUnicastMessageID(Project1.nodeID,destNodeID)); sendMessage(Project1.mapNodesByAddress.get(toSend.getRecieverAddress()+String.valueOf(toSend.getRecieverPort())).getNodeID(),toSend); } /** * Second Highest Priority is to send MAx Clock Replies. * So sending them second. */ while(!sendMaxClock.isEmpty()){ MultiCastMessage objMulti=sendMaxClock.poll(); for(Message msg:objMulti.getMessages()){ //msg.setMessageId(this.getMulticastMessageIDMaxClock(Project1.nodeID)); sendMessage(Project1.mapNodesByAddress.get(msg.getRecieverAddress()+String.valueOf(msg.getRecieverPort())).getNodeID(),msg); } } while(!sendQueue.isEmpty() && Project1.getClockReplies()==0){ MultiCastMessage objMulti= sendQueue.poll(); String id=this.getMulticastMessageID(Project1.nodeID); LC.incrementValue(); for(Message msg:objMulti.getMessages()){ msg.setMessageId(id); msg.setLogicalClockValue(LC.getValue()); sendMessage(Project1.mapNodesByAddress.get(msg.getRecieverAddress()+String.valueOf(msg.getRecieverPort())).getNodeID(),msg); Project1.incrementClockReplies(); } } } System.out.println("Quitting"); }
7
public static List<COIN> getCoinsForAmount(float amount) { List<COIN> coins = new ArrayList<COIN>(); /* Well, the canadian govt has decided to abandon 1 cent penny. So, we can't dispense exact change, but will do closest to 5 cent change. I am just implementing it using Greedy algorithm, but it's the classic 'knapsack' algorithm design problem which can be solved in multiple ways. Just to be clear, that problem is about selecting the minimum number of coins to equal the denomination of the input amount, which, AFAIK, is an NP-Hard problem. */ System.out.println("Amount input = " + amount); int numberOfToonies = (new Float(amount / TOONIE.getValue())).intValue(); float amountToBeReturned = numberOfToonies * TOONIE.getValue(); float leftOverAmount = amount - amountToBeReturned; System.out.println("Amount in Toonies = " + amountToBeReturned); for(int i = 0; i < numberOfToonies; i++) coins.add(TOONIE); int numberOfLoonies = (new Float(leftOverAmount / LOONIE.getValue())).intValue(); amountToBeReturned = numberOfLoonies * LOONIE.getValue(); leftOverAmount -= amountToBeReturned; System.out.println("Amount in Loonies = " + amountToBeReturned); for(int i = 0; i < numberOfLoonies; i++) coins.add(LOONIE); int numberOfFiftyCent = (new Float(leftOverAmount / FIFTY_CENT.getValue())).intValue(); amountToBeReturned = numberOfFiftyCent * FIFTY_CENT.getValue(); leftOverAmount -= amountToBeReturned; System.out.println("Amount in Fifty Cents = " + amountToBeReturned); for(int i = 0; i < numberOfFiftyCent; i++) coins.add(FIFTY_CENT); int numberOfQuarters = (new Float(leftOverAmount / QUARTER.getValue())).intValue(); amountToBeReturned = numberOfQuarters * QUARTER.getValue(); leftOverAmount -= amountToBeReturned; System.out.println("Amount in Quarters = " + amountToBeReturned); for(int i = 0; i < numberOfQuarters; i++) coins.add(QUARTER); int numberOfDimes = (new Float(leftOverAmount / DIME.getValue())).intValue(); amountToBeReturned = numberOfDimes * DIME.getValue(); leftOverAmount -= amountToBeReturned; System.out.println("Amount in Dimes = " + amountToBeReturned); for(int i = 0; i < numberOfDimes; i++) coins.add(DIME); int numberOfNickels = (new Float(leftOverAmount / NICKEL.getValue())).intValue(); amountToBeReturned = numberOfNickels * NICKEL.getValue(); leftOverAmount -= amountToBeReturned; System.out.println("Amount in Nickels = " + amountToBeReturned); for(int i = 0; i < numberOfNickels; i++) coins.add(NICKEL); DecimalFormat currencyFormat = new DecimalFormat("#.##"); System.out.println("Not returning coins for amount = " + currencyFormat.format(leftOverAmount)); return coins; }
6
@SuppressWarnings({ "deprecation", "unchecked" }) public List<ComponentOut> search(Map<String, String> criterias) { List<ComponentOut> results; Set<String> keys = criterias.keySet(); Session session = HibernateUtil.sessionFactory.getCurrentSession(); session.beginTransaction(); Criteria criteria = session.createCriteria(ComponentOut.class); for (String key : keys) { switch (key) { case "componentId": criteria.add(Restrictions.like("component.id", criterias.get(key) + "%")); break; case "date": criteria.add(Restrictions.eq("date", new Date(criterias.get(key)))); break; case "countBegin": criteria.add(Restrictions.ge("count", Integer.parseInt(criterias.get(key)))); break; case "countEnd": criteria.add(Restrictions.le("count", Integer.parseInt(criterias.get(key)))); break; case "eId": criteria.add(Restrictions.like("eid", criterias.get(key) + "%")); break; case "person": criteria.createCriteria("person").add(Restrictions.eq("name", criterias.get(key))); break; } } results = criteria.list(); session.getTransaction().commit(); return results; }
7
public static void helium(String sourceFile, String targetFile) { Sound sourceObj = new Sound(sourceFile); //Construct a new Sound object called sourceObj. A sourceObject now represents the sourceFile object. Sound target = new Sound(sourceObj); //Construct a new Sound object called target. The target object now represents the targetFile object. int sampleValue = 0; //The sampleValue variable is declare as an int and is initialized to 0. int targetIndex = 0; //The targetIndex variable is declared as an int and is initialized to 0. for(int index = 0; index < sourceObj.getLength(); index+=2) //A for loop is created to traverse the length of the sourceObj. Notice that the loop increments by two each time, not 1. { sampleValue = sourceObj.getSampleValueAt(index); //The getSampleValueAt() method gets the sample value at index position of sampleObj. target.setSampleValueAt(targetIndex,sampleValue); //The setSampleValueAt() method sets the sample value at the targetIndex position in the target file. targetIndex++; //The targetIndex variable is incremented by 1 each time through the loop. } int targetLength = target.getLength(); while(targetIndex < targetLength) { target.setSampleValueAt(targetIndex, 0); targetIndex++; } // target.play(); //The play() method is invoked on the target object to play the audio with the high pitched audio. if(targetFile != null) target.write(targetFile + File.separatorChar + "helium.wav"); //The write() method is invoked on the target object and the audio with the new higher pitch is saved as a .wav file. }
3
private static int[] getBestUsers(List<Map<Integer, Integer>> userMaps, int userID, int size) { int[] retVals = new int[size]; Map<Integer, Integer> nSimMap = new LinkedHashMap<Integer, Integer>(); if (userID < userMaps.size()) { Map<Integer, Integer> tags = userMaps.get(userID); for (int i = 0; i < userMaps.size(); i++) { if (i != userID) { Map<Integer, Integer> nTags = userMaps.get(i); int count = (int)getOccurences(tags, nTags); nSimMap.put(i, count); } } Map<Integer, Integer> sortedResults = new TreeMap<Integer, Integer>(new IntMapComparator(nSimMap)); sortedResults.putAll(nSimMap); int j = 0; for (int id : sortedResults.keySet()) { if (j < size) { retVals[j++] = id; } } return retVals; } return null; }
5
private void findNextPotentialReference(int startPosition) { nextPotentialReferencePosition = Math.max(startPosition, nextSemicolonPosition - MAX_REFERENCE_SIZE); do { nextPotentialReferencePosition = originalMessage.indexOf('&', nextPotentialReferencePosition); if (nextSemicolonPosition != -1 && nextSemicolonPosition < nextPotentialReferencePosition) nextSemicolonPosition = originalMessage.indexOf(';', nextPotentialReferencePosition + 1); boolean isPotentialReference = nextPotentialReferencePosition != -1 && nextSemicolonPosition != -1 && nextPotentialReferencePosition - nextSemicolonPosition < MAX_REFERENCE_SIZE; if (isPotentialReference) { break; } if (nextPotentialReferencePosition == -1) { break; } if (nextSemicolonPosition == -1) { nextPotentialReferencePosition = -1; break; } nextPotentialReferencePosition = nextPotentialReferencePosition + 1; } while (nextPotentialReferencePosition != -1); }
8
protected static int getInt(String key, JSONObject json) throws JSONException { String str = json.getString(key); if(null == str || "".equals(str)||"null".equals(str)){ return -1; } return Integer.parseInt(str); }
3
@Override public String toString() { return String.format( "annotatedWith(%s)", this.annotation ); }
0
public TimerTest() { super(); }
0
private String scanFlowScalarBreaks () { StringBuilder chunks = new StringBuilder(); String pre = null; for (;;) { pre = prefix(3); if ((pre.equals("---") || pre.equals("...")) && NULL_BL_T_LINEBR.indexOf(peek(3)) != -1) throw new TokenizerException("While scanning a quoted scalar, found unexpected document separator."); while (BLANK_T.indexOf(peek()) != -1) forward(); if (FULL_LINEBR.indexOf(peek()) != -1) chunks.append(scanLineBreak()); else return chunks.toString(); } }
6
public boolean isOptOut() { synchronized (optOutLock) { try { // Reload the metrics file configuration.load(getConfigFile()); } catch (IOException ex) { if (debug) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); } return true; } catch (InvalidConfigurationException ex) { if (debug) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); } return true; } return configuration.getBoolean("opt-out", false); } }
4
@Override public Component getTreeCellRendererComponent(final JTree tree, final Object value, final boolean selected, final boolean expanded, final boolean leaf, final int row, final boolean hasFocus) { final NBTRecord rec = (NBTRecord) value; final String chg = rec.hasChanged() ? "*" : " "; final String name = rec.getName(); if(name == null) return new JLabel(chg + (rec.isTextEditable() ? rec.getParseablePayload() : "")); final String type = " (" + rec.getTypeInfo() + ")"; return new JLabel(chg + name + type + (rec.isTextEditable() ? ": " + rec.getParseablePayload() : "")); }
4
public MemberBean getMemberInfo(String id) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; MemberBean member = null; try { conn = getConnection(); pstmt = conn.prepareStatement("select * from member where id=?"); pstmt.setString(1, id); rs = pstmt.executeQuery(); if (rs.next()) { member = new MemberBean(); member.setId(id); member.setPasswd(rs.getString("password")); member.setName(rs.getString("name")); member.setBirth_date(rs.getDate("birth_date")); member.setEmail(rs.getString("email")); member.setLast_login_time(rs.getTimestamp("last_login_time")); member.setPhone(rs.getString("phone")); member.setLocate(rs.getString("locate")); member.setNickname(rs.getString("nickname")); member.setReg_date(rs.getTimestamp("reg_date")); member.setLast_login_ip(rs.getString("last_login_ip")); member.setPoint(rs.getInt("point")); } } catch (Exception e) { e.printStackTrace(); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (pstmt != null) { try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } return member; }
8
public void addToWealth(int val){ iMoneyInBank += val; if(iMoneyInBank < 0) iMoneyInBank = 0; }
1
public static boolean getImagesHaveBeenLoaded() { return imagesHaveBeenLoaded; }
0
public Date floor(Date date, int field) { Calendar cal = Calendar.getInstance(); cal.setTime(date); for (int currentField : fields) { if (currentField > field) { if (currentField == Calendar.DAY_OF_MONTH && (field == Calendar.WEEK_OF_MONTH || field == Calendar.WEEK_OF_YEAR)) { continue; } cal.set(currentField, cal.getActualMinimum(currentField)); } } if (field == Calendar.WEEK_OF_MONTH || field == Calendar.WEEK_OF_YEAR) { cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek()); } return cal.getTime(); }
7
private static void debug(String str) { if(debug) System.out.println(str); }
1
public void actionPerformed(ActionEvent arg0) { Object[] inputDetails = new Object[16]; int counter = 0; for(int i = 0; i < comps.length; i++){ if(comps[i].getClass() == JTextField.class){ JTextField compTemp = (JTextField) comps[i]; inputDetails[counter] = compTemp.getText(); counter++; } if(comps[i].getClass() == JCheckBox.class){ JCheckBox compTemp = (JCheckBox) comps[i]; inputDetails[counter] = compTemp.isSelected(); counter++; } if(comps[i].getClass() == JList.class){ JList<String> compTemp = (JList<String>) comps[i]; inputDetails[counter] = compTemp.getSelectedValue(); break; } } switch(target){ case "artist": String nameA = (String) inputDetails[0]; String genreA = (String) inputDetails[1]; String miscA = (String) inputDetails[2]; IO.getInstance().getFestival().addArtist(new Artist(nameA,genreA,miscA)); break; case "stage": String nameS = (String) inputDetails[0]; int maxVisitorsS = Integer.parseInt((String) inputDetails[1]); boolean isMainStageS = (boolean) inputDetails[2]; IO.getInstance().getFestival().addStage(new Stage(nameS, maxVisitorsS, isMainStageS)); break; case "performance": String nameP = (String) inputDetails[0]; float startTimeP = Float.parseFloat((String) inputDetails[1]); float endTimeP = Float.parseFloat((String) inputDetails[2]); int popularityP = Integer.parseInt((String) inputDetails[3]); Stage stageP = IO.getInstance().getFestival().findStage((String) inputDetails[4]); IO.getInstance().getFestival().addPerformance(new Performance(nameP, startTimeP,endTimeP,popularityP,stageP)); JList<String> artistsList = (JList<String>) comps[12]; DefaultListModel<String> artistsModel = (DefaultListModel<String>) artistsList.getModel(); Object[] artistsArray = artistsModel.toArray(); for(Object s : artistsArray){ IO.getInstance().getFestival().findPerformance(nameP).addArtists(IO.getInstance().getFestival().findArtist((String) s)); } break; } frame.dispose(); }
8
@Override public IRemoteCallObject call(String command, Object params) throws Exception { checkInitiate(); final IRemoteCallObject rco = new RemoteCallObject(); synchronized (rco) { long callId = getNextCallId(); rco.setCallObjectId(callId); rco.setMetaDataObject(new RemoteCallObjectMetaData(command, RemoteCallObjectType.Query)); rco.setDataObject(new RemoteCallObjectData(params)); putCallObj(callId, rco); //..put object to map try { send(SerializeUtils.serializeToBytes(rco)); //..to do call and wait response try { rco.wait(); //..wait response from server side socket } catch(InterruptedException e) { throw e; } //..comming response from server side socket, accept it (with error or not) return acceptResponse(rco); } finally { remCallObj(callId); //..remove object from map } } }
1
public int compareTo(Object obj) { if (obj instanceof Mark) { int pos = ((Mark)obj).position; return position - pos; } return -1; }
1
public Ligne jouer(LigneMarqueur marqVerif){ if(derniereCombiJouee != null){ // Si derniereCombinaison n'a pas été initilaisé, càd si l'IA joue pour la première fois listePossibles.supprimeCombiImp(derniereCombiJouee, marqVerif); } derniereCombiJouee = listePossibles.choixCombi(); return derniereCombiJouee; }
1
public String preProcess(String s){ int n = s.length(); if(n == 0) return ""; StringBuilder sb = new StringBuilder(); for(int i = 0; i < n; i++){ sb.append('#'); sb.append(s.charAt(i)); } sb.append('#'); return sb.toString(); }
2
private boolean jj_3R_72() { if (jj_scan_token(IDENTIFIER)) return true; return false; }
1
public void testRead() { try { ConfigurationManager.init("src/test/resources/test.json"); try { Object[] test_array = ConfigurationManager.read.getArrayItem("test", "array"); assertEquals(123L, test_array[0]); Long test_long = ConfigurationManager.read.getLongItem("test", "long"); assertEquals(new Long(321), test_long); // Direct test without the casting methods test_long = (Long) ConfigurationManager.read.getItem("test", "long"); assertEquals(new Long(321), test_long); int test_integer = ConfigurationManager.read.getIntegerItem("test", "integer"); assertEquals(321, test_integer); Double test_double = ConfigurationManager.read.getDoubleItem("test", "double"); assertEquals(new Double(1.23), test_double); Float test_float = ConfigurationManager.read.getFloatItem("test", "float"); assertEquals(new Float(3.21), test_float); String test_string = ConfigurationManager.read.getStringItem("test", "string"); assertEquals("test", test_string); JSONObject test_object = ConfigurationManager.read.getJSONObjectItem("test", "object"); assertEquals("test", test_object.get("test")); Boolean test_boolean = ConfigurationManager.read.getBooleanItem("test_bool"); assertEquals(true, test_boolean); // Top level test String test_string_top = ConfigurationManager.read.getStringItem("test_2"); assertEquals("test", test_string_top); } catch (ReaderException e) { e.printStackTrace(); } } catch (ReaderException e) { e.printStackTrace(); } }
2
private void checkSpikes(){ int fromTileX = TileMap.pixelsToTiles(player.getPos().getX()); int fromTileY = TileMap.pixelsToTiles(player.getPos().getY()); int toTileX = TileMap.pixelsToTiles(player.getPos().getX() + player.getWidth()); int toTileY = TileMap.pixelsToTiles(player.getPos().getY() + player.getHeight()); for (int i = 0; i < map.getSpikeTilesSize(); i++){ Point spikeTile = map.getSpikeTile(i); for (int x = fromTileX; x <= toTileX; x++) { for (int y = fromTileY; y <= toTileY; y++) { if (spikeTile.x == x && spikeTile.y == y) { midisL.stop(); gameOver = true; } } } } }
5
static private Object interpretToken(String s) throws Exception{ if(s.equals("nil")) { return null; } else if(s.equals("true")) { return RT.T; } else if(s.equals("false")) { return RT.F; } else if(s.equals("/")) { return SLASH; } else if(s.equals("clojure.core//")) { return CLOJURE_SLASH; } Object ret = null; ret = matchSymbol(s); if(ret != null) return ret; throw new Exception("Invalid token: " + s); }
6
private void ekskey(byte data[], byte key[]) { int i; int koffp[] = { 0 }, doffp[] = { 0 }; int lr[] = { 0, 0 }; int plen = P.length, slen = S.length; for (i = 0; i < plen; i++) P[i] = P[i] ^ streamtoword(key, koffp); for (i = 0; i < plen; i += 2) { lr[0] ^= streamtoword(data, doffp); lr[1] ^= streamtoword(data, doffp); encipher(lr, 0); P[i] = lr[0]; P[i + 1] = lr[1]; } for (i = 0; i < slen; i += 2) { lr[0] ^= streamtoword(data, doffp); lr[1] ^= streamtoword(data, doffp); encipher(lr, 0); S[i] = lr[0]; S[i + 1] = lr[1]; } }
3
public boolean deleteTask(int id) throws SQLException { if (daoList.idExists(id)) { daoList.deleteById(id); return true; } return false; }
1
protected void addIndividualPath(String path, U target, boolean named, int defaultHttpMethods) { PathPattern<U> pattern = new PathPattern<U>(target, path, named, defaultHttpMethods); String key = pattern.getKey(); List<PathPattern<U>> list = map.get(key); if (list == null) { list = new ArrayList<PathPattern<U>>(); map.put(key, list); } list.add(pattern); }
1
@Override public void onUpdate(World apples) { if (!apples.inBounds((int)X, (int)Y)||apples.checkCollision((int)X, (int)Y)) { alive = false; //apples.explode(X, Y, 32, 8, 16); } for (Player p:apples.playerList) { if (apples.pointDis(X, Y, p.x, p.y)<radius&&maker!=p.ID) { alive = false; } } if (gravity++>3) { yspeed+=1; gravity = 0; } /*if (yspeed<12) { yspeed++; }*/ }
6
*/ public void testLargeReadWrite() throws Exception { ByteBuffer b = ByteBuffer.allocate(4000); log.info("getting all proper connections"); int size = 40; String[] methodNames = new String[size]; for(int i = 0; i < size; i++) { methodNames[i] = "connected"; } TCPChannel[] clients = new TCPChannel[size]; for(int i = 0; i < size; i++) { clients[i] = chanMgr.createTCPChannel("Client["+i+"]", getClientFactoryHolder()); clients[i].oldConnect(svrAddr, (ConnectionCallback)mockConnect); } mockConnect.expect(methodNames); log.info("done getting all connections"); for(TCPChannel client : clients) { client.registerForReads((DataListener)mockHandler); } int numWrites = 100; String payload = "hello"; for(int i = 0; i < 3000; i++) { payload+="i"; } helper.putString(b, payload); helper.doneFillingBuffer(b); int numBytes = b.remaining(); log.info("size="+b.remaining()); methodNames = new String[size*numWrites]; for(int i = 0; i < size*numWrites; i++) { methodNames[i] = "incomingData"; } PerfTimer timer = new PerfTimer(); PerfTimer timer2 = new PerfTimer(); timer.start(); timer2.start(); for(TCPChannel client : clients) { for(int i = 0; i < numWrites; i++) { FutureOperation future = client.write(b); future.waitForOperation(5000); b.rewind(); } } long result2 = timer2.stop(); CalledMethod[] methods = mockHandler.expect(methodNames); long result = timer.stop(); ByteBuffer actualBuf = (ByteBuffer)methods[6].getAllParams()[1]; String actual = helper.readString(actualBuf, actualBuf.remaining()); assertEquals(payload, actual); log.info("payload="+actual); long readWriteTime = result/size; long byteTime = 100*result / (numWrites*numBytes); log.info("total write time ="+result2); log.info("total write/read time ="+result); log.info("--time per 100 bytes ="+byteTime); log.info("test result info:"); log.info("--time per write/read ="+readWriteTime); log.info("--time to beat ="+getLargerReadWriteTimeLimit()); assertTrue(readWriteTime < getLargerReadWriteTimeLimit()); }
7
public static Tile[][] read(File file){ BufferedImage paintImage = null; try{ paintImage = loadImage(file); }catch(Exception e){ Logger.logErr("Was not able to read image located at " + file.getAbsolutePath() + "\n Cause: " + e.getCause(),MapReader.class); } Tile[][] tileMap = new Tile[paintImage.getHeight()][paintImage.getWidth()]; for(int x = 0; x < paintImage.getWidth();x++){ for(int y = 0 ; y < paintImage.getHeight();y++){ Tile workingTile = new Tile(x,y); int rgbValue = paintImage.getRGB(x, y); int red = getRed(rgbValue); int blue = getBlue(rgbValue); int green = getGreen(rgbValue); if(green == 255 && blue + red == 0){ workingTile.setLandType(LANDTYPE.GRASS); } // V -----V-----V---DENOTES WHITE COLOR else if(green + red + blue == 255 + 255 + 255){ workingTile.setLandType(LANDTYPE.CLEAR); } // V---V---V---DENOTES BLACK COLOR else if(green + red + blue == 0 + 0 + 0){ workingTile.setLandType(LANDTYPE.WALL); } tileMap[x][y] = workingTile; } } return tileMap; }
7
public void setValue(int x, int y, Pixel value) { if (x >= getWidth() || y >= getHeight() || x < 0 || y < 0) { return; } rawData[x][y] = value; }
4
public int executeWriteQuery(String sqlStatement) { int rc = 0; try { Class.forName(this.sqlDriver); con = DriverManager.getConnection(sqlURL, this.sqlUser, this.sqlPassword); Statement stmt = con.createStatement(); System.out.println("insertSQL: " + sqlStatement); rc = stmt.executeUpdate(sqlStatement); } catch (ClassNotFoundException classEx) { System.out.println("Unable to find the class for the SQL Driver: " + this.sqlDriver); classEx.printStackTrace(); } catch (SQLException sqlEx) { System.out.println("The SQL statement is not valid"); sqlEx.printStackTrace(); } catch (Exception ex) { System.out.println("An unknown error has occured"); ex.printStackTrace(); } finally { try { con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return rc; }
4
protected String[][] create_matrix(String plain) { ArrayList<String> s=new ArrayList<String>(); boolean dig; if(di_begin) { dig=true; } else { dig=false; } int string_index=0; int plain_size=plain.length(); while(string_index<plain_size) { if(dig) { if(string_index==plain_size-1) { s.add(plain.substring(string_index,string_index+1)); string_index++; } else { s.add(plain.substring(string_index,string_index+2)); string_index+=2; } dig=false; } else { s.add(plain.substring(string_index,string_index+1)); string_index++; dig=true; } } int col=period; int row=s.size()/col; if(s.size()%col!=0) { row++; } String[][] matrix=new String[row][col]; int s_index=0; int cur_row=0; int cur_col=0; while(s_index<s.size()) { matrix[cur_row][cur_col]=s.get(s_index); s_index++; if(cur_col<period-1) { cur_col++; } else { cur_row++; cur_col=0; } } return matrix; }
7
public Event getNextEvent(){ Event a=this.ListCust.peek(); return (a!=null) ? this.ListCust.remove() : null; }
1
public void checkLogin(String msg){ try{ if(containsMoreThanNeeded(msg)){ CC.getDataTransfer().sendMessage("Sorry but that was an invalid username/password"); CC.Terminate(); return; } msg = msg.replaceFirst("Login ", ""); String[] usernpass = msg.split(":"); if(!ClientHandler.getClientMap().isLoggedIn(usernpass[0]) && ClientHandler.getDataQueuer().isRealUser(usernpass[0], usernpass[1])){ CC.getClient().setUsername(usernpass[0]); //System.out.println("Setting the username to " + usernpass[0]); CC.getClient().setPassword(usernpass[1]); //System.out.println("Setting the password to " + usernpass[1]); CC.getDataTransfer().sendMessage("Your Account Has Been Verified!"); System.out.println(usernpass[0]+" Has Been Logged In!"); }else{ CC.getDataTransfer().sendMessage("Sorry but that was an invalid username/password"); CC.Terminate(); } }catch(Exception e){ try{CC.getDataTransfer().sendMessage("Sorry but that was an invalid username/password");CC.Terminate(); }catch(Exception ex){} } }
5
@Override public Object execute(HttpServletRequest request, HttpServletResponse response) throws Exception { Contexto oContexto = (Contexto) request.getAttribute("contexto"); oContexto.setVista("jsp/alumno/form.jsp"); AlumnoBean oAlumnoBean; AlumnoDao oAlumnoDao; oAlumnoBean = new AlumnoBean(); AlumnoParam oAlumnoParam = new AlumnoParam(request); oAlumnoBean = oAlumnoParam.loadId(oAlumnoBean); oAlumnoDao = new AlumnoDao(oContexto.getEnumTipoConexion()); try { oAlumnoBean = oAlumnoDao.get(oAlumnoBean); } catch (Exception e) { throw new ServletException("AlumnoController: Update Error: Phase 1: " + e.getMessage()); } try { oAlumnoBean = oAlumnoParam.load(oAlumnoBean); } catch (NumberFormatException e) { oContexto.setVista("jsp/mensaje.jsp"); return "Tipo de dato incorrecto en uno de los campos del formulario"; } return oAlumnoBean; }
2
public static TFTPPacket fromOPCode(short opcode){ switch(opcode){ case 1 : return new RRQPacket(); case 2 : return new WRQPacket(); case 3 : return new DataPacket(); case 4 : return new AckPacket(); case 5 : return new ErrorPacket(); } return null; }
5
public String simplifyPath(String path) { if (path == null || path.length() == 0) return path; String[] paths = path.split("/+"); LinkedList<String> list = new LinkedList<>(); for (String tmp : paths) { if ("..".equals(tmp)) { if (!list.isEmpty()) { list.removeLast(); } } else if (!"".equals(tmp) && !".".equals(tmp)) { list.add(tmp); } } if (list.isEmpty()) { return "/"; } StringBuilder sb = new StringBuilder(); for (String tmp : list) { sb.append("/").append(tmp); } return sb.toString(); }
9
public static void tpAll( String sender, String target ) { BSPlayer p = PlayerManager.getPlayer( sender ); BSPlayer t = PlayerManager.getPlayer( target ); if ( t == null ) { p.sendMessage( Messages.PLAYER_NOT_ONLINE ); return; } for ( BSPlayer player : PlayerManager.getPlayers() ) { if ( !player.equals( p ) ) { teleportPlayerToPlayer( player, t ); } player.sendMessage( Messages.ALL_PLAYERS_TELEPORTED.replace( "{player}", t.getDisplayingName() ) ); } }
3
static private boolean glob0(byte[] pattern, int pattern_index, byte[] name, int name_index){ if(name.length>0 && name[0]=='.'){ if(pattern.length>0 && pattern[0]=='.'){ if(pattern.length==2 && pattern[1]=='*') return true; return glob(pattern, pattern_index+1, name, name_index+1); } return false; } return glob(pattern, pattern_index, name, name_index); }
6
private boolean parseFlags(String parameter) { boolean success = false; if (parameter.matches("-[^-]*v[^-]*")) { verboseMode = true; success = true; } if (parameter.matches("-[^-]*d[^-]*")) { devMode = true; success = true; } if (parameter.matches("-[^-]*n[^-]*")) { System.out.println("Disable GUI."); disableGui = true; success = true; } /* Log format: */ if (parameter.matches("-[^-]*x[^-]*")) { System.out.println("Use XML for logging."); logFormat = LOG_FORMAT.XML; success = true; } if (parameter.matches("-[^-]*h[^-]*")) { System.out.println("Use HTML for logging."); logFormat = LOG_FORMAT.HTML; success = true; } return success; }
5
public boolean restartLevel() { GameState state = StateUtil.getGameState(proxy); if(state == GameState.WON || state == GameState.LOST) { proxy.send( new ProxyClickMessage(420,380));//Click the left most button at the end page System.out.println(" restart the level "); try { Thread.sleep(2000); } catch (InterruptedException e1) { e1.printStackTrace(); } } else if(state == GameState.PLAYING) { proxy.send(new ProxyClickMessage(100,39)); try { Thread.sleep(1000); } catch (InterruptedException e1) { e1.printStackTrace(); } } //Wait 4000 seconds for loading the level try { Thread.sleep(4000); } catch (InterruptedException e1) { e1.printStackTrace(); } //Zooming out System.out.println("Zooming out"); for (int k = 0; k < 15; k++) { proxy.send(new ProxyMouseWheelMessage(-1)); } try { Thread.sleep(2000); } catch (InterruptedException e1) { e1.printStackTrace(); } return true; }
8
public static boolean is_integer(String str) { if (str == null) return false; if (str.equals("")) return false; Character c = str.charAt(0); if (!c.equals('-') && !c.equals("+") && !Character.isDigit(c)) return false; try { @SuppressWarnings("unused") Integer test = parseInt(str); } catch (NumberFormatException e) { return false; } return true; }
6
@Override public void happens() { // TODO: add movement to the patio for this case ArrayList<Character> characters = Game.getInstance().getCharacters(); for(Character character: characters){ if (character.getCurrentRoom().getNameEnum() == RoomName.GARDENS || character.getCurrentRoom().getNameEnum() == RoomName.GRAVEYARD || character.getCurrentRoom().getNameEnum() == RoomName.TOWER || character.getCurrentRoom().getNameEnum() == RoomName.BALCONY || character.getCurrentRoom().getExternalWindows() != 0){ int rollResult = character.getTraitRoll(Trait.SANITY); if(rollResult >=0 && rollResult <= 2){ Trait chosenTrait = Game.getInstance().chooseAPhysicalTrait(); int damage = Game.getInstance().rollDice(1); character.decrementTrait(chosenTrait, damage); } } } }
8
@Test public void testCarbohydratePercentage() { MealRepartition mr = new MealRepartition(); try { mr.setCarbohydratePercentage(0.49); fail("A BadCarbohydratePercentageException should have been thrown."); } catch (BadCarbohydratePercentageException e) {} try { mr.setCarbohydratePercentage(0.56); fail("A BadCarbohydratePercentageException should have been thrown."); } catch(BadCarbohydratePercentageException e) {}; try { mr.setCarbohydratePercentage(0.53); } catch(BadCarbohydratePercentageException e) { fail("A BadCarbohydratePercentageException has been thrown."); } }
3
public boolean isPalindrome(int x) { //if nagetive if (x < 0) { return false; } //0~9 is palindrome if (x < 10) { return true; } //10, 100, etc. are not palindrome if (x % 10 == 0) { return false; } int r = 0; //calculate the number from the end. //if in palindrome, x will equal to r or x == r/10 while (x > 0 && x > r) { r = r * 10; r = r + x % 10; x = x / 10; } if (x != 0 && (x == r || x == r / 10)) { return true; } else { return false; } }
8
public void run() { try { //init IO-Stream from/to client and send Ready-Message inFromClient = new BufferedReader(new InputStreamReader( connectionSocket.getInputStream())); outToClient = new DataOutputStream( connectionSocket.getOutputStream()); send(outToClient, "+OK proxyServer ready"); //take authorization of client while (!belive) { if (isRegisteredUser(inFromClient.readLine(), outToClient)) { while (!belive) { belive = isRightPass(inFromClient.readLine(), outToClient); } } } //authorization successful, start transaction if (belive) { //client collects his email if (client.getTyp().startsWith("POP3Client")) { pop3transaction(); //client sendet neu email } else if (client.getTyp().startsWith("SMTPClient")) { smtpTransaction(); //something else } else { send(outToClient, "QUIT"); } } //close client-connection connectionSocket.close(); System.out.println("connection is broken"); } catch (Exception e) { // System.out.println(e.getMessage()); } }
7
@Override protected void buildModel() throws Exception { for (int iter = 1; iter <= numIters; iter++) { errs = 0; loss = 0; // for each rated user-item (u,i) pair for (int u : trainMatrix.rows()) { SparseVector Ru = trainMatrix.row(u); for (VectorEntry ve : Ru) { // each rated item i int i = ve.index(); double rui = ve.get(); int j = -1; while (true) { // draw an item j with probability proportional to popularity double sum = 0, rand = Randoms.random(); for (KeyValPair<Integer> en : itemProbs) { int k = en.getKey(); double prob = en.getValue(); sum += prob; if (sum >= rand) { j = k; break; } } // ensure that it is unrated by user u if (!Ru.contains(j)) break; } double ruj = 0; // compute predictions double pui = predict(u, i), puj = predict(u, j); double dij = Math.sqrt(1 - itemCorrs.get(i, j)); double sj = s.get(j); double e = sj * (pui - puj - dij * (rui - ruj)); errs += e * e; loss += e * e; // update vectors double ye = lRate * e; for (int f = 0; f < numFactors; f++) { double puf = P.get(u, f); double qif = Q.get(i, f); double qjf = Q.get(j, f); P.add(u, f, -ye * (qif - qjf)); Q.add(i, f, -ye * puf); Q.add(j, f, ye * puf); } } } errs *= 0.5; loss *= 0.5; if (isConverged(iter)) break; } }
9
@Override public void onMouseButtonPress(int buttonID) { for(GuiButton button : buttons) { if(button.isMouseOver()) { Sound.button_hit.play(); button.onClick(); } } }
2
public String getSerialNo() { return serialNo; }
0
public void sanitise() { if (this.modName == null || this.modName.length() < 1) this.modName = "all"; if (this.modVersion == null || this.modVersion < 0.0F) this.modVersion = 0.0F; if (this.remoteCacheTimeSeconds < 0) this.remoteCacheTimeSeconds = 600L; }
5
public void partActivated(IWorkbenchPart partArg) { if ((partArg == this.part) && (this.timestamp > -1L) && ((this.resource == null) || (this.resource.exists()) || (this.part .isDirty()))) { if (!readable()) { String[] buttons = { "Save", "Close" }; MessageDialog dialog = new MessageDialog( this.part.getSite().getShell(), "File not accessible", null, "The file has been deleted or is not accessible. Do you want to save your changes or close the editor without saving?", 3, buttons, 0); if (dialog.open() == 0) { this.part.doSave(new NullProgressMonitor()); } this.part .getSite() .getShell() .getDisplay() .asyncExec( (Runnable) new EditorInputWatcher( (IQtEditor) this)); } else { long newtimestamp = getCurrentTimeStamp(); if ((newtimestamp != this.timestamp) && (MessageDialog .openQuestion( this.part.getSite().getShell(), "File changed", "The file has been changed on the file system. Do you want to replace the editor contents with these changes?"))) { this.part.reload(); } } updateTimeStamp(); } }
9
public boolean contains(Vector2 point) { Vector2 min = this.getMinimumPoint(); Vector2 max = this.getMaximumPoint(); return (point.x >= min.x && point.x <= max.x && point.y >= min.y && point.y <= max.y); }
3
public List<Sailplane> getRecentSailplane() { try{ List<Sailplane> sailplanes = DatabaseDataObjectUtilities.getSailplanes(); List<Sailplane> recentSailplaneList = new ArrayList<Sailplane>(); if(instance == null) { return null; } else { for (int index = 0; (index < instance.recentSailplane.size()) && (recentSailplaneList.size() < 5); index++){ for (int index2 = 0; (index2 < sailplanes.size()); index2++){ if (sailplanes.get(index2).getId().equals(instance.recentSailplane.get(index))){ recentSailplaneList.add(sailplanes.get(index2)); } } } return recentSailplaneList; } }catch(SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException ex) { Logger.getLogger(RecentLaunchSelections.class.getName()).log(Level.SEVERE, null, ex); } return null; }
7
NodeListGraph(int vecticeCount) { if(vecticeCount <= 0) { throw new IllegalArgumentException(); } @SuppressWarnings("unchecked") LinkedList<EdgePair>[] nodeListArray = (LinkedList<EdgePair>[]) new LinkedList<?>[vecticeCount]; edges = new TreeSet<Integer>(); for(int i = 0; i < vecticeCount; i++) { nodeListArray[i] = new LinkedList<>(); } this.nodeListArray = nodeListArray; }
3
@Override public Optimus1Ddata FindMaxMin(ArrayID aid, PID pid, OptimusShape pshape, OptimusShape start, OptimusShape off) throws Exception { // TODO Auto-generated method stub OptimusData data = this.readDouble(aid, pid, pshape, start, off); if (data == null) return null; double[] fdata = data.getData(); double[] rminmax = new double[2]; rminmax[0] = fdata[0]; rminmax[1] = fdata[0]; for (int i = 1; i < fdata.length; i++) { if (fdata[i] > rminmax[0]) { rminmax[0] = fdata[i]; } else if (fdata[i] < rminmax[1]) { rminmax[1] = fdata[i]; } } return new Optimus1Ddata(rminmax); }
4
private void ValidateTag(Iterator<ITag> iter, Class<? extends ITag>... classes) { if (isValid) { while ((iter.hasNext()) && this.isValid) { boolean pass = false; ITag child = iter.next(); Class<? extends ITag> childClass = child.getClass(); for (Class<? extends ITag> type : classes) { if (type.isAssignableFrom(childClass)) { pass = true; } } this.isValid = pass; } } }
8
@Override public void mouseEntered(MouseEvent e) { }
0
public static String findCollisions(ArrayList<Planet> planets) { String collisions = ""; for (int i = 0; i < planets.size(); i++) { for (int j = 0; j < planets.size(); j++) { if (i != j) { if (Planet.areColliding(planets.get(i), planets.get(j))) { collisions += "Die Planeten " + planets.get(i).getLabel() + " und " + planets.get(j).getLabel() + " kollidieren.\n"; planets.remove(i); i = (i > 0) ? i -= 1 : i; j = (j > 0) ? j -= 1 : j; } } } } return collisions; }
6
public RackRequestHandler(FilterConfig config) { log.info("Creating new RubyRequestHandler instance"); // Configure ignore paths String pathCfg = config.getInitParameter("ignorePaths"); if (pathCfg != null) { this.ignorePaths = pathCfg.split("\\s+"); } else { ignorePaths = new String[]{"/images", "/stylesheets", "/javascript", "/favicon.ico"}; } if (log.isInfoEnabled()) for (int x=0; x<ignorePaths.length; x++) log.info(ignorePaths[x] + " is configured as an ignore path."); // If jruby home is not sepcified for us, try to find it in the environment if (config.getInitParameter("JRUBY_HOME") != null) JRUBY_HOME = config.getInitParameter("JRUBY_HOME"); else JRUBY_HOME = System.getenv("JRUBY_HOME"); if (JRUBY_HOME == null) { final String message = "JRUBY_HOME is not set. This must be " + "provided by the envoironment or set as as " + "init-parameter in web.inf"; log.fatal(message); throw new RuntimeException(message); } log.info("Using JRUBY_HOME = "+JRUBY_HOME); // Try to find the root directory of the ruby web app. If not specified, assume that it // is the parent directory of the public root if (config.getInitParameter("APP_HOME") != null) APP_HOME = config.getInitParameter("APP_HOME"); else { File publicRoot = new File(config.getServletContext().getRealPath(PS)); APP_HOME = publicRoot.getParent(); } log.info("Using APP_HOME = "+APP_HOME); // JRuby Paths List<String> loadPath = new ArrayList<String>(); loadPath.add(JRUBY_HOME+PS+"lib"+PS+"ruby"+PS+"site_ruby"+PS+RUBY_VERSION); loadPath.add(JRUBY_HOME+PS+"lib"+PS+"ruby"+PS+"site_ruby"); loadPath.add(JRUBY_HOME+PS+"lib"+PS+"ruby"+PS+RUBY_VERSION); loadPath.add(JRUBY_HOME+PS+"lib"+PS+"ruby"+PS+RUBY_VERSION+PS+"java"); // Set up Ruby Runtime this.runtime = JavaEmbedUtils.initialize(loadPath); this.runtime.setKCode(UTF8); this.runtime.setJRubyHome(JRUBY_HOME); this.runtime.setCurrentDirectory(APP_HOME); // Instantiate rack adapter try { final String framework = config.getInitParameter("framework"); rackAdapter = RackAdapterBuilder.getAdaptorForFramework(runtime, framework); log.debug("Loaded "+framework+" rack adapter: " + rackAdapter.inspect()); } catch (Exception e) { String message = "Can't load rack adapter."; log.error(message, e); throw new RuntimeException(message, e); } }
7
@Override public int eval(int player, int alpha, int beta, int depth, int nt, int stackIndex, State4 s) { StackFrame frame = stack[stackIndex]; if(nt != SearchContext.NODE_TYPE_PV && depth <= 3 * Search34.ONE_PLY && !frame.pawnPrePromotion && !frame.alliedKingAttacked && frame.hasNonPawnMaterial && //c.futilityPrune && frame.nonMateScore){ final int futilityMargin; if(depth <= 1 * Search34.ONE_PLY){ futilityMargin = 250; } else if(depth <= 2 * Search34.ONE_PLY){ futilityMargin = 300; } else { //depth <= 3*ONE_PLY futilityMargin = 425; } final int futilityScore = frame.eval - futilityMargin; if(futilityScore >= beta){ return futilityScore; } } return next.eval(player, alpha, beta, depth, nt, stackIndex, s); }
9
public String name() { if (this.tooltip != null) return (this.tooltip); Resource res = this.res.get(); if ((res != null) && (res.layer(Resource.tooltip) != null)) { return res.layer(Resource.tooltip).t; } return null; }
3
private static void buildBasicSet(Release set, List<SeperatorDefinition> seps) throws MalformedURLException { for(MagicColor c: MagicColor.values()) { if (!c.includeInDefaultSets()) continue; SeperatorDefinition def = new SeperatorDefinition(); def.addLeftSymbol(new ImageIconDrawer(SymbolFactory.getIcon(c))); for(Rarity r: Rarity.values()) def.addRightSymbol(new ImageIconDrawer(SymbolFactory.getIcon(set, r))); seps.add(def); } SeperatorDefinition def = new SeperatorDefinition(); def.addLeftSymbol(new TextSymbolDrawer("Lands")); for(Rarity r: Rarity.values()) def.addRightSymbol(new ImageIconDrawer(SymbolFactory.getIcon(set, r))); seps.add(def); }
4
public Chord pickRandomWeighted(Chord chord){ String next =""; double total = 0; String chordString = chord.toString(); if(histogram.get(chordString).isEmpty()){ return null; } for(Integer i: histogram.get(chordString).values()){ total+=i; } int random = (int) (Math.random()*(total+1)); for (Entry<String, Integer> entry : histogram.get(chordString).entrySet()){ random -= entry.getValue(); if (random <= 0.0d){ next = entry.getKey(); break; } } if(next.equals("")){ return null; } return chordList.get(next); }
5
public List<List<Integer>> subsetsWithDup(int[] num){ Arrays.sort(num); int size = num.length ; int total = (int)Math.pow(2,size); List<List<Integer>> result= new ArrayList<List<Integer>>(); for(int i=0;i < total;i++) result.add(new ArrayList<Integer>()); for(int i =0;i < size;i++) for(int j=0;j < total;j++) if(((j >> i) & 1)==1) result.get(j).add(num[i]); List<List<Integer>> result2 = new ArrayList<List<Integer>>(); for(int i = 0 ; i< size;i++){ if(!result2.contains(result.get(i))){ result2.add(result.get(i)); } } return result2; }
6