text
stringlengths
14
410k
label
int32
0
9
public ArrayList getSolutionsRunningOnSpecificDevice(int tmpClassID, String tmpDeviceName) { if(printDebugInfo) { System.out.println("\ngetSolutionsRunningOnSpecificDevice --- START"); System.out.println("\t" + getClassNameByID(tmpClassID) + "(s) running on " + tmpDeviceName + ":"); } ArrayList result = new ArrayList<Solution>(); int tmpCounter = 0; ArrayList<Solution> allSolutionInstances = getInstances(tmpClassID); if(allSolutionInstances != null) { for(int i=0; i<allSolutionInstances.size(); i++) { Solution tmpSolution = allSolutionInstances.get(i); if(tmpSolution.runsOnDevice != null && tmpSolution.runsOnDevice.toLowerCase().indexOf(tmpDeviceName.toLowerCase()) != -1) { result.add(tmpSolution); tmpCounter++; if(printDebugInfo) System.out.println("\t\t" + Integer.toString(tmpCounter) + ") " + tmpSolution.hasSolutionName); } } } if(printDebugInfo) System.out.println("getSolutionsRunningOnSpecificDevice --- END"); return result; }
7
private boolean makeServiceNameUnique(ServiceInfoImpl info) { final String originalQualifiedName = info.getQualifiedName(); final long now = System.currentTimeMillis(); boolean collision; do { collision = false; // Check for collision in cache for (DNSCache.CacheNode j = cache.find(info.getQualifiedName().toLowerCase()); j != null; j = j .next()) { final DNSRecord a = (DNSRecord) j.getValue(); if ((a.type == DNSConstants.TYPE_SRV) && !a.isExpired(now)) { final DNSRecord.Service s = (DNSRecord.Service) a; if (s.port != info.port || !s.server.equals(localHost.getName())) { logger .finer("makeServiceNameUnique() JmDNS.makeServiceNameUnique srv collision:" + a + " s.server=" + s.server + " " + localHost.getName() + " equals:" + (s.server.equals(localHost.getName()))); info.setName(incrementName(info.getName())); collision = true; break; } } } // Check for collision with other service infos published by JmDNS final Object selfService = services.get(info.getQualifiedName().toLowerCase()); if (selfService != null && selfService != info) { info.setName(incrementName(info.getName())); collision = true; } } while (collision); return !(originalQualifiedName.equals(info.getQualifiedName())); }
8
@Override public void copySources( HashMap<String, Source> srcMap ) { if( srcMap == null ) return; Set<String> keys = srcMap.keySet(); Iterator<String> iter = keys.iterator(); String sourcename; Source source; // Make sure the buffer map exists: if( bufferMap == null ) { bufferMap = new HashMap<String, SoundBuffer>(); importantMessage( "Buffer Map was null in method 'copySources'" ); } // remove any existing sources before starting: sourceMap.clear(); SoundBuffer buffer; // loop through and copy all the sources: while( iter.hasNext() ) { sourcename = iter.next(); source = srcMap.get( sourcename ); if( source != null ) { buffer = null; if( !source.toStream ) { loadSound( source.filenameURL ); buffer = bufferMap.get( source.filenameURL.getFilename() ); } if( !source.toStream && buffer != null ) { buffer.trimData( maxClipSize ); } if( source.toStream || buffer != null ) { sourceMap.put( sourcename, new SourceJavaSound( listener, source, buffer ) ); } } } }
9
public boolean IniciarServidor() { MensajeServidor("Servidor Iniciado"); try { // Se abre el host en el puerto esperando que un cliente llegue ServerSocket s = new ServerSocket(puerto); MensajeServidor("Esperando Conexion......"); String url = "http://localhost:"+puerto; if(Desktop.isDesktopSupported()){ Desktop desktop = Desktop.getDesktop(); try { desktop.browse(new URI(url)); } catch (IOException | URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else{ Runtime runtime = Runtime.getRuntime(); try { runtime.exec("xdg-open " + url); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /* Se crea un cliente, con su respectivo metodo run*/ tcpcliente = new AppCliente(); Thread t = new Thread(tcpcliente); t.start(); while(true) { Socket cliente = s.accept(); //Se instancia un cliente, y se inicia en su respectivo thread con la clase start. Peticion pCliente = new Peticion(cliente,tcpcliente); pCliente.start(); } } catch (IOException e) { MensajeServidor("Error en servidor\n" + e.toString()); //Si ocurre algun problema al instanciar el servidor se lanza este mensaje de error } return true; }
5
public Product grabAProduct(){ Document doc = null; try { doc = Jsoup.connect("http://www.mathem.se/sok?q=socker&qtype=p").get(); } catch (IOException ex) { Logger.getLogger(ProductRetriever.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("!=!=!=!=!=!=!=!=!==!=!=!=!=!=!=!=!=!==!==!=!=!=!=!=!=!=!"+doc.data()); Element prodDiv = doc.body().getElementById("productResultContainer"); System.out.println(prodDiv.toString()); List<Element> prods = prodDiv.getAllElements(); for (Element product : prods) { for (Element prodChild : product.children()) { Product prod = new Product(); prod.setName(prodChild.getElementsByClass("priceKg").text()); return prod; } } return null; }
3
private boolean displayModesMatch(DisplayMode m1, DisplayMode m2) { if(m1.getWidth() != m2.getWidth() || m1.getHeight() != m2.getHeight()) {return false;} if(m1.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && m2.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && m1.getBitDepth() != m2.getBitDepth()) {return false;} if(m1.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && m2.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && m1.getRefreshRate() != m2.getRefreshRate()) {return false;} return true; }
8
public void clear_buffer() { for (int i = 0; i < channels; ++i) bufferp[i] = (short)i; }
1
private int returnStep (int vertex) { int maxVertex = 0; int i, j; for (Vertex incidentVertex : numberToVertex.get(vertex).getIncidentVertices()) { j = vertexToNumber.get(incidentVertex); if (j < vertex) { maxVertex = j; } } j = maxVertex; boolean []goodColor = new boolean[vertices.size() + 1]; for (i = 0; i < vertices.size(); ++i) { goodColor[i] = true; } goodColor[color[j]] = false; for (Vertex incidentVertex : numberToVertex.get(j).getIncidentVertices()) { i = vertexToNumber.get(incidentVertex); if (0 != color[i]) { goodColor[color[i]] = false; } } int newColor = 0; for (i = color[j] + 1; i < maxColor; ++i) { if (goodColor[i]) { newColor = i; break; } } if (0 == newColor) { if (0 != j) { return returnStep(j); } else { return 0; } } else { color[j] = newColor; return j; } }
9
public static StandardObject walkFirstArgumentToFunction(MethodSlot fnslot, Cons tree) { { List ptypespecs = fnslot.methodParameterTypeSpecifiers(); StandardObject targetts = ((StandardObject)(ptypespecs.first())); if (!fnslot.methodEvaluateArgumentsP()) { tree.rest = MethodSlot.quoteArguments(fnslot, tree.rest); } if (((BooleanWrapper)(KeyValueList.dynamicSlotValue(fnslot.dynamicSlots, Stella.SYM_STELLA_METHOD_VARIABLE_ARGUMENTSp, Stella.FALSE_WRAPPER))).wrapperValue && (ptypespecs.length() == 1)) { tree.rest = Cons.walkVariableArguments(tree.rest, fnslot, null); return (Stella.SGT_STELLA_UNKNOWN); } if ((tree.rest == Stella.NIL) || fnslot.methodParameterTypeSpecifiers().emptyP()) { return (Stella.SGT_STELLA_UNKNOWN); } { Stella_Object otree = null; StandardObject otype = null; { Object [] caller_MV_returnarray = new Object[1]; otree = Stella_Object.walkExpressionTree(tree.rest.value, targetts, fnslot.slotName, true, caller_MV_returnarray); otype = ((StandardObject)(caller_MV_returnarray[0])); } tree.secondSetter(otree); if (Surrogate.subtypeOfIntegerP(Stella_Object.safePrimaryType(otree))) { { IntegerWrapper otree000 = ((IntegerWrapper)(otree)); { Symbol testValue000 = fnslot.slotName; if (testValue000 == Stella.SYM_STELLA_GET_SYM) { GeneralizedSymbol.registerSymbol(Symbol.getSymFromOffset(otree000.wrapperValue)); } else if (testValue000 == Stella.SYM_STELLA_GET_SGT) { GeneralizedSymbol.registerSymbol(Surrogate.getSgtFromOffset(otree000.wrapperValue)); } else if (testValue000 == Stella.SYM_STELLA_GET_KWD) { GeneralizedSymbol.registerSymbol(Keyword.getKwdFromOffset(otree000.wrapperValue)); } else { } } } } else { } return (otype); } } }
9
public void body() { // Gets the PE's rating for each Machine in the list. // Assumed one Machine has same PE rating. MachineList list = super.resource_.getMachineList(); int size = list.size(); machineRating_ = new int[size]; for (int i = 0; i < size; i++) { machineRating_[i] = super.resource_.getMIPSRatingOfOnePE(i, 0); } // a loop that is looking for internal events only Sim_event ev = new Sim_event(); while ( Sim_system.running() ) { super.sim_get_next(ev); // if the simulation finishes then exit the loop if (ev.get_tag() == GridSimTags.END_OF_SIMULATION || super.isEndSimulation()) { break; } // Internal Event if the event source is this entity if (ev.get_src() == super.myId_ && gridletInExecList_.size() > 0) { updateGridletProcessing(); // update Gridlets checkGridletCompletion(); // check for finished Gridlets } } // CHECK for ANY INTERNAL EVENTS WAITING TO BE PROCESSED while (super.sim_waiting() > 0) { // wait for event and ignore since it is likely to be related to // internal event scheduled to update Gridlets processing super.sim_get_next(ev); System.out.println(super.resName_ + ".SpaceSharedWithFailure.body(): ignore internal events"); } }
7
private void ScheduleSessionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ScheduleSessionActionPerformed // TODO add your handling code here: if(memID != null){ int day, month, year; Boolean facial, haircut, massage,pedicure; try{ day = Integer.parseInt(DayInput.getText()); month = Integer.parseInt(MonthInput.getText()); year = Integer.parseInt(YearInput.getText()); Date date = new Date(year, month, day); String query = "insert into SPASERVICES (MEMBERID,DATEOFSERVICE,SERVICES)" + "values ("+memID+", '"+date.getMonth()+"-"+date.getDay()+"-"+date.getYear()+"', '"; if(Facial.isSelected()){ query += "Facial "; } if(Haircut.isSelected()){ query += "Haircut "; } if(Massage.isSelected()){ query += "Massage "; } if(Pedicure.isSelected()){ query += "Pedicure "; } query += "')"; conn.execUpdate(query); } catch(java.lang.NumberFormatException nfe){ } catch (SQLException ex) { Logger.getLogger(MenuPage.class.getName()).log(Level.SEVERE, null, ex); } } }//GEN-LAST:event_ScheduleSessionActionPerformed
7
private ArrayList<Coordinate> getAvailableMoves() { boolean test = false; if (test || m_test) { System.out.println("OthelloAI :: getAvailableMoves() BEGIN"); } ArrayList<Coordinate> list = new ArrayList<Coordinate>(); if (getYourTurn()) { for (int y = 0; y < GAME_HEIGHT; y++) { for (int x = 0; x < GAME_WIDTH; x++) { Coordinate c1 = new Coordinate(x, y, getGame() .getPlayerTurn()); if (getGame().isValidMove(c1)) { list.add(c1); } } } } if (test || m_test) { System.out.println("OthelloAI :: getAvailableMoves() END"); } return list; }
8
public boolean agregar(String tabla, String campos, String[] valores) { String query = "INSERT INTO " + tabla; String[] camp = campos.split(","); int max = camp.length; query += campos(max, camp); query += valores(max); //System.out.println(query); if (prepararEstados(query, valores)) { //Devuelve verdadero cuando ha surgido algun error //System.out.println("agregar falso"); return false; } else { //Devuelve falso cuando todo ha salido bien //System.out.println("agregar verdadero"); return true; } }
1
public static StompFrame factory(String wholeMessage){ HashMap<String, String> headers=parseHeaders(wholeMessage); if (headers == null) return ErrorFrame.factory(wholeMessage, "cannot read headers"); if (headers.get("destination") == null) return ErrorFrame.factory(wholeMessage, "invalid subscribe: no destination entered"); if (headers.get("id") == null) return ErrorFrame.factory(wholeMessage, "invalid subscribe: no id entered"); return new SubscribeFrame(wholeMessage); }
3
@Override public Iterable<K> keySet() { ArrayList<K> keys = new ArrayList<>();// return container for (int i = 0; i < capacity; i++) { if ((bucket[i] != null) && (bucket[i] != available)) keys.add(bucket[i].getKey()); } return keys; }
3
public boolean equivalentWasEndedBys (WasEndedBy description1, WasEndedBy description2) { return bothNull (description1, description2) || (neitherNull (description1, description2) && equivalentIdentifiers (description1, description2) && equivalentAttributes (description1, description2) && equivalentEventArguments (description1, description2) && equivalentEntities (description1.getTrigger (), description2.getTrigger ()) && equivalentActivities (description1.getEnded (), description2.getEnded ()) && equivalentActivities (description1.getEnder (), description2.getEnder ())); }
7
public void remove(Item item) { if (item == null) throw new IllegalArgumentException("Item can't be null!"); if (!items.contains(item)) throw new IllegalArgumentException("The item is not in the inventory!"); items.remove(item); }
2
public static String cleanPath(String path) { if (path == null) { return null; } String pathToUse = replace(path, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR); // Strip prefix from path to analyze, to not treat it as part of the // first path element. This is necessary to correctly parse paths like // "file:core/../core/io/Resource.class", where the ".." should just // strip the first "core" directory while keeping the "file:" prefix. int prefixIndex = pathToUse.indexOf(":"); String prefix = ""; if (prefixIndex != -1) { prefix = pathToUse.substring(0, prefixIndex + 1); pathToUse = pathToUse.substring(prefixIndex + 1); } if (pathToUse.startsWith(FOLDER_SEPARATOR)) { prefix = prefix + FOLDER_SEPARATOR; pathToUse = pathToUse.substring(1); } String[] pathArray = delimitedListToStringArray(pathToUse, FOLDER_SEPARATOR); List<String> pathElements = new LinkedList<String>(); int tops = 0; for (int i = pathArray.length - 1; i >= 0; i--) { String element = pathArray[i]; if (CURRENT_PATH.equals(element)) { // Points to current directory - drop it. } else if (TOP_PATH.equals(element)) { // Registering top path found. tops++; } else { if (tops > 0) { // Merging path element with element corresponding to top path. tops--; } else { // Normal path element found. pathElements.add(0, element); } } } // Remaining top paths need to be retained. for (int i = 0; i < tops; i++) { pathElements.add(0, TOP_PATH); } return prefix + collectionToDelimitedString(pathElements, FOLDER_SEPARATOR); }
8
public void insert(Key v) { if (N == pq.length - 1) resize(pq.length * 2); pq[++N] = v; swim(N); }
1
public static String stripNonDoubleChars(final String value) { final StringBuilder newString = new StringBuilder(); for (int i = 0; i < value.length(); i++) { final char c = value.charAt(i); if (c >= '0' && c <= '9' || c == '-' || c == '.') { newString.append(c); } } final int sLen = newString.length(); final String s = newString.toString(); if (sLen == 0 || sLen == 1 && (".".equals(s) || "-".equals(s))) { return "0"; } return newString.toString(); }
9
public static Tuple[] fromResultSet(ResultSet in) throws SQLException { List<Tuple> res = new ArrayList<Tuple>(); int colCount = in.getMetaData().getColumnCount(); boolean empty = !in.next(); while (!in.isAfterLast() && !empty) { Object[] objects = new Object[colCount]; for (int i = 0; i < colCount; i++) objects[i] = in.getObject(i + 1); res.add(new Tuple(objects)); in.next(); } DatabaseManager.clean(in); return res.toArray(new Tuple[] {}); }
3
private boolean isDataEnd() { String flag = buffer.substring( buffer.lastIndexOf( "\n" ) + 1, buffer.length() ); int indexLeft = flag.lastIndexOf( "[" ); int indexRight = flag.lastIndexOf( "@" ); if ( indexLeft == -1 || indexRight == -1 || indexLeft > indexRight ) { return false; } if ( flag.substring( indexLeft, indexRight ) .equals( "[" + username ) ) { return true; } return false; }
4
private void loadUserSettings(){ if(!this.fUserData.exists()){ File fDir = new File(sDir); if(!fDir.exists()){ fDir.mkdir(); } try { this.fUserData.createNewFile(); saveUserSettings(); } catch (Exception e) { e.printStackTrace(); } } // Initialise or load the User Settings this.userSettings = (HashMap<String, String>)(this.xstream.fromXML(fUserData)); this.username = userSettings.get(sUsername); this.savedUsername = Boolean.parseBoolean(userSettings.get(sSavedUsername)); this.showTimestamp = Boolean.parseBoolean(userSettings.get(sShowTimestamp)); this.layoutType = Integer.parseInt(userSettings.get(sLayoutType)); }
3
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MenuCreationEntreprise.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MenuCreationEntreprise.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MenuCreationEntreprise.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MenuCreationEntreprise.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MenuCreationEntreprise().setVisible(true); } }); }
6
public static Enumeration getClassesAndPackages(final String packageName) { final Enumeration enum_ = classpath.listFiles(packageName.replace('.', '/')); return new Enumeration() { public boolean hasMoreElements() { return enum_.hasMoreElements(); } public Object nextElement() { String name = (String) enum_.nextElement(); if (!name.endsWith(".class")) // This is a package return name; return name.substring(0, name.length() - 6); } }; }
1
@Test /* No output should be printed about unhandled tokens */ public void testLoadString() { File dir = new File(graphics.core.Model.MODEL_PATH); // Loop through all models in models directory for(String file: dir.list()) { if (file.toLowerCase().endsWith(graphics.core.Model.MODEL_EXTENSION)) WavefrontObjLoader.load("foo", graphics.core.Model.MODEL_PATH + file); if (WavefrontObjLoader.getErrors().size() > 0) { for (WavefrontLoaderError err: WavefrontObjLoader.getErrors()) System.err.println(err); fail(); } if (WavefrontMtlLoader.getErrors().size() > 0) { for (WavefrontLoaderError err: WavefrontMtlLoader.getErrors()) System.err.println(err); fail(); } } }
6
public static void main(String[] args){ DataStoreImpl dataStoreImpl = new DataStoreImpl(); if(dataStoreImpl.loginUser("randomUser", "password")){ System.out.println("success"); } else { System.out.println("fail"); } }
1
public T get(final int index) { final int i0 = index >>> 24; final T[][] map1; if (i0 != 0) { if (map == null) return null; // NOT_FOUND; map1 = map[i0]; if (map1 == null) return null; // NOT_FOUND; } else { map1 = map10; } final T[] map2 = map1[(index >>> 12) & 0xfff]; if (map2 == null) return null; // NOT_FOUND; return map2[index & 0xfff]; }
4
public int atrLookback( int optInTimePeriod ) { if( (int)optInTimePeriod == ( Integer.MIN_VALUE ) ) optInTimePeriod = 14; else if( ((int)optInTimePeriod < 1) || ((int)optInTimePeriod > 100000) ) return -1; return optInTimePeriod + (this.unstablePeriod[FuncUnstId.Atr.ordinal()]) ; }
3
public EventBranch findEventBranchById(final Long id) { return new EventBranch(); }
0
public static ArrayList<DebtAccount> readDebtAccounts(String filename) { File file = new File(filename); if (file.exists()) { ObjectInputStream ois = null; try { // // Read the previously stored SecretKey. // SecretKey key = (SecretKey) readFromFile(KEY_FILE.toString()); ArrayList<DebtAccount> accountList = new ArrayList<DebtAccount>(); ois = new ObjectInputStream(new FileInputStream(filename)); DebtAccount tempAccount = null; SealedObject tempSealed = null; boolean eof = false; while (!eof) { tempSealed = (SealedObject) ois.readObject(); // // Preparing Cipher object from decryption. // String algorithmName = tempSealed.getAlgorithm(); Cipher objCipher = Cipher.getInstance(algorithmName); objCipher.init(Cipher.DECRYPT_MODE, key); tempAccount = (DebtAccount) tempSealed.getObject(objCipher); if (tempAccount == null) { eof = true; break; } accountList.add(tempAccount); } return accountList; } catch (EOFException e) { } catch (Exception e) { e.printStackTrace(); } finally { try { if (ois != null) { ois.close(); } } catch (IOException e) { e.printStackTrace(); } } } return null; }
7
public MainFrame() { lf = null; sponsorlopen = new ArrayList<Sponsorloop>(); setSize(200, 200); lab1 = new JLabel("Sponsorlopen", JLabel.CENTER); lab2 = new JLabel(); listModel = new DefaultListModel(); list = new JList(listModel); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); deselect(); list.setVisibleRowCount(5); b1 = new JButton("Nieuwe Sponsorloop"); b2 = new JButton("Verwijder Sponsorloop"); JScrollPane listScrollPane = new JScrollPane(list); JPanel lowerPane = new JPanel(); // lowerPane.setLayout(new BoxLayout(lowerPane, BoxLayout.Y_AXIS)); lowerPane.setLayout(new BorderLayout()); //Wat er gebeurt bij veranderen van selectie in het menu list.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent arg0) { if (!arg0.getValueIsAdjusting()) { if (lf != null) { lf.dispose(); if (lf.getSf() != null) { lf.getSf().dispose(); } } if (list.getSelectedValue() != null) { lf = new LoperFrame(vindLoop((String) list .getSelectedValue())); updateAantal(); b2.setEnabled(true);; geefDoor(); } if (list.getSelectedValue() == null) { b2.setEnabled(false); } } } }); add(lab1, BorderLayout.NORTH); lowerPane.add(lab2, BorderLayout.NORTH); lowerPane.add(b1, BorderLayout.CENTER); lowerPane.add(b2, BorderLayout.SOUTH); b2.setEnabled(false); add(listScrollPane, BorderLayout.CENTER); add(lowerPane, BorderLayout.SOUTH); b1.addActionListener(this); b2.addActionListener(this); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); this.setLocation(250, dim.height / 2 - this.getSize().height / 2); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); }
5
@Override public List<Usuario> Buscar(Usuario obj) { String sql = "select a from Usuario a"; String filtros = ""; if(obj != null){ if(obj.getId() != null){ filtros += "a.id = " + obj.getId(); } if(obj.getNome() != null){ if(filtros.length() > 0) filtros += " and "; filtros += "a.nome like '%" + obj.getNome() + "%'"; } //if(obj.getCpf() != null){ // if(filtros.length() > 0) // filtros += " and "; // filtros += "a.cpf like '%" + obj.getCpf() + "%'"; // } } if(filtros.length() > 0){ sql += " where " + filtros; } Query consulta = manager.createQuery(sql); return consulta.getResultList(); }
5
public String addMoreInfo() throws Exception { Connection conn = null; Statement stmt = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(url, user, psw); if (!conn.isClosed()) System.out.println("Success connecting to the Database!"); else System.out.println("Fail connecting to the Database!"); stmt = conn.createStatement(); int changeCount = 0; System.out.println("realName is:"+realName); System.out.println("gender is:"+gender); System.out.println("location is:"+location); System.out.println("occupation is:"+occupation); System.out.println("age is:"+age); System.out.println("hobby is:"+hobby); System.out.println("userName is:"+userName); System.out.println("passWord is:"+passWord); changeCount = stmt.executeUpdate("update member set age = '" + age + "',location='" + location + "' ,occupation='" + occupation + "' ,hobby='" + hobby + "', gender='" + gender + "', real_name='" + realName + "' where user_name = '" + userName + "' and pass_word='" + passWord + "'"); System.out.println("changeCount is :"+changeCount); if (changeCount != 0) { return SUCCESS; } else { return ERROR; } } catch (Exception e) { System.out.print("connection error!"); e.printStackTrace(); return ERROR; } }
3
public Teaches add(Teacher t, ClassGroup c) { Teaches newTeach = new Teaches(c, t); if (!this.teachingList.contains(newTeach)) { this.teachingList.add(newTeach); // If a object matching the new instance has been recently deleeted, remove that record. if (this.deletedTeaching.contains(newTeach)) this.deletedTeaching.remove(newTeach); return newTeach; } return null; }
2
public void actionPerformed(ActionEvent e) { if ("btnOpen".equals(e.getActionCommand())) { if (chart != null) chart.closeChart(); frame.setVisible(false); getList(); // chart = new ValueChart(vc_files); if (btnVC.isSelected()) { con = new ConstructionView(ConstructionView.FROM_VC); con.filename = "SuperUser.vc"; filename = "SuperUser.vc"; } else { con = new ConstructionView(ConstructionView.FROM_XML); con.filename = "SuperUser.xml"; filename = "SuperUser.xml"; } con.list = vc_files; con.setInit(false); //noOfEntries = countEntries(filename); // if (noOfEntries > 10) // con.setDisplayType(ConstructionView.SIDE_DISPLAY); con.showChart(true); con.filename = filename; //temp holder for a new filename } else if ("btnCancel".equals(e.getActionCommand())) { if (chart == null) System.exit(0); else frame.dispose(); } else if (e.getActionCommand().equals("Select All")) { lstFiles.setSelectionInterval(0, listModel.size()); } else if (e.getActionCommand().equals("btnVC")) { setListVC(); } else if (e.getActionCommand().equals("btnXML")) { setListXML(); } }
8
public void setSource(int x, int y, double value) { if (_maxValue < value) { _maxValue = value; } _source[y][x] = value; }
1
private long waitForBackupSizeToBecomeStable(Date timeoutDate, String backupName) throws ReadTimeoutException { com.unispezi.cpanelremotebackup.tools.Console.print("Polling for backup file size to become stable"); long lastFileSize = 0; long currentFileSize = 0; Date now = new Date(); while (((currentFileSize < minFileBytes) || (currentFileSize != lastFileSize)) && (now.before(timeoutDate))) { com.unispezi.cpanelremotebackup.tools.Console.print("."); FTPFile backupWeStarted = ftp.getFileDetails(backupName); lastFileSize = currentFileSize; currentFileSize = backupWeStarted.getSize(); try { Thread.sleep(pollIntervalSeconds * 1000); } catch (InterruptedException e) { //Do nothing } now = new Date(); } com.unispezi.cpanelremotebackup.tools.Console.println(" " + currentFileSize + " bytes"); if (now.after(timeoutDate)){ throw new ReadTimeoutException("Download of file exceeded timeout"); } return currentFileSize; }
5
@Override public void actionPerformed(ActionEvent arg0) { if(item.getLabel().equals("Square")) { b.mousetype = "square"; b.last_mouse_type.add("square"); } else if(item.getLabel().equals("Circle")) { b.mousetype = "circle"; b.last_mouse_type.add("circle"); } else if(item.getLabel().equals("Rectangle")) { b.mousetype = "rectangle"; b.last_mouse_type.add("rectangle"); } else if(item.getLabel().equals("Color")) { b.mousetype = "color"; b.color_chosen = JColorChooser.showDialog(b, "Choose a Color", Color.WHITE); } else if(item.getLabel().equals("Filled Circle")) { b.mousetype = "filledcircle"; b.last_mouse_type.add("filledcircle"); } else if(item.getLabel().equals("Filled Square")) { b.mousetype = "filledsquare"; b.last_mouse_type.add("filledsquare"); } else if(item.getLabel().equals("Line")) { b.mousetype = "line"; b.last_mouse_type.add("line"); } else if(item.getLabel().equals("Filled Rectangle")) { b.mousetype = "filledrect"; b.last_mouse_type.add("filledrect"); } else if(item.getLabel().equals("Delete")) { b.mousetype = "delete"; b.last_mouse_type.add("delete"); } }
9
public static IntArrayBag union(IntArrayBag b1, IntArrayBag b2) { IntArrayBag answer = new IntArrayBag(b1.getCapacity() + b2.getCapacity()); System.arraycopy(b1.data, 0, answer.data, 0, b1.manyItems); System.arraycopy(b2.data, 0, answer.data, b1.manyItems, b2.manyItems); answer.manyItems = b1.manyItems + b2.manyItems; return answer; }
0
public FileStream(RandomAccessFile source) throws OggFormatException, IOException { this.source=source; ArrayList po=new ArrayList(); int pageNumber=0; try { while(true) { po.add(new Long(this.source.getFilePointer())); // skip data if pageNumber>0 OggPage op=getNextPage(pageNumber>0); if(op==null) { break; } LogicalOggStreamImpl los=(LogicalOggStreamImpl)getLogicalStream(op.getStreamSerialNumber()); if(los==null) { los=new LogicalOggStreamImpl(this, op.getStreamSerialNumber()); logicalStreams.put(new Integer(op.getStreamSerialNumber()), los); } if(pageNumber==0) { los.checkFormat(op); } los.addPageNumberMapping(pageNumber); los.addGranulePosition(op.getAbsoluteGranulePosition()); if(pageNumber>0) { this.source.seek(this.source.getFilePointer()+op.getTotalLength()); } pageNumber++; } } catch(EndOfOggStreamException e) { // ok } catch(IOException e) { throw e; } //System.out.println("pageNumber: "+pageNumber); this.source.seek(0L); pageOffsets=new long[po.size()]; int i=0; Iterator iter=po.iterator(); while(iter.hasNext()) { pageOffsets[i++]=((Long)iter.next()).longValue(); } }
8
@Override public boolean activate() { return (Bank.isOpen() && !Widgets.get(13, 0).isOnScreen() && !Settings.usingFlask && !Settings.usingHerb ); }
3
public void setPictureMimeType(String pictureMimeType) { if (pictureMimeType != null && !pictureMimeType.equals("") && !pictureMimeType.equals("image/") && !pictureMimeType.equals("image/jpg") && !pictureMimeType.equals("image/png")) throw new IllegalArgumentException("The picture mime type field in the " + frameType.getId() + " frame contains an invalid value, " + pictureMimeType + ".\n" + "It must be either \"\", \"image/\", \"image/jpg\", or \"image/png\"."); this.dirty = true; this.pictureMimeType = pictureMimeType == null || pictureMimeType.length() == 0 ? "image/" : pictureMimeType; }
7
private ModDatabase() { try { Properties p = new Properties(); InputStream in = getClass().getResourceAsStream(".password"); p.load(in); in.close(); host = p.getProperty("host"); database = p.getProperty("database"); user = p.getProperty("user"); password = p.getProperty("password"); if (user == null || password == null) { throw new DatabaseException("Password file needs a user and a password entry."); } } catch (IOException e) { throw new DatabaseException("Missing password file.", e); } }
3
public LinkedList<CarteTroupe> initialisationPaquetTroupe(){ LinkedList<CarteTroupe> llct = new LinkedList<CarteTroupe>(); int i=1; for(Troupes t : hashTroupes){ CarteTroupe ct = new CarteTroupe(t); // On met 6 fois la même carte dans la liste for(int k=0; k<6; k++){ llct.add(ct); } // il faut également mettre un carte avec deux troupes (en tout 6 cartes) int j = 1; for(Troupes t2 : hashTroupes){ // On ne reprend pas les cartes précédentes (elles ont déjà ét traitées) if(i== j || i<j){ CarteTroupe ct2 = new CarteTroupe(t,t2); llct.add(ct2); } j++; } i++; } // On mélange le paquet Collections.shuffle(llct); return llct; }
5
private void postPlugin(final boolean isPing) throws IOException { // The plugin's description file containg all of the plugin data such as name, version, author, etc final PluginDescriptionFile description = plugin.getDescription(); // Construct the post data final StringBuilder data = new StringBuilder(); data.append(Metrics.encode("guid")).append('=') .append(Metrics.encode(guid)); Metrics.encodeDataPair(data, "version", description.getVersion()); Metrics.encodeDataPair(data, "server", Bukkit.getVersion()); Metrics.encodeDataPair(data, "players", Integer.toString(Bukkit.getServer().getOnlinePlayers().length)); Metrics.encodeDataPair(data, "revision", String.valueOf(Metrics.REVISION)); // If we're pinging, append it if (isPing) { Metrics.encodeDataPair(data, "ping", "true"); } // Acquire a lock on the graphs, which lets us make the assumption we also lock everything // inside of the graph (e.g plotters) synchronized (graphs) { final Iterator<Graph> iter = graphs.iterator(); while (iter.hasNext()) { final Graph graph = iter.next(); for (final Plotter plotter : graph.getPlotters()) { // The key name to send to the metrics server // The format is C-GRAPHNAME-PLOTTERNAME where separator - is defined at the top // Legacy (R4) submitters use the format Custom%s, or CustomPLOTTERNAME final String key = String.format("C%s%s%s%s", Metrics.CUSTOM_DATA_SEPARATOR, graph.getName(), Metrics.CUSTOM_DATA_SEPARATOR, plotter.getColumnName()); // The value to send, which for the foreseeable future is just the string // value of plotter.getValue() final String value = Integer.toString(plotter.getValue()); // Add it to the http post data :) Metrics.encodeDataPair(data, key, value); } } } // Create the url final URL url = new URL(Metrics.BASE_URL + String.format(Metrics.REPORT_URL, Metrics.encode(plugin.getDescription().getName()))); // Connect to the website URLConnection connection; // Mineshafter creates a socks proxy, so we can safely bypass it // It does not reroute POST requests so we need to go around it if (this.isMineshafterPresent()) { connection = url.openConnection(Proxy.NO_PROXY); } else { connection = url.openConnection(); } connection.setDoOutput(true); // Write the data final OutputStreamWriter writer = new OutputStreamWriter( connection.getOutputStream()); writer.write(data.toString()); writer.flush(); // Now read the response final BufferedReader reader = new BufferedReader(new InputStreamReader( connection.getInputStream())); final String response = reader.readLine(); // close resources writer.close(); reader.close(); if (response == null || response.startsWith("ERR")) { throw new IOException(response); // Throw the exception } else { // Is this the first update this hour? if (response.contains("OK This is your first update this hour")) { synchronized (graphs) { final Iterator<Graph> iter = graphs.iterator(); while (iter.hasNext()) { final Graph graph = iter.next(); for (final Plotter plotter : graph.getPlotters()) { plotter.reset(); } } } } } }
9
private static String[] readTokens() throws IOException { Set<String> result = new TreeSet<String>(); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String t; while (true) { System.out.print("Enter token or blank line to end input: "); t = reader.readLine(); if (t == null || (t = t.trim()).isEmpty()) { break; } result.add(t); } return result.toArray(new String[result.size()]); }
3
public static void addEnder(List<LabeledToken> parsedContents) { int offset=0, length=0; if (parsedContents==null) { parsedContents=new ArrayList<LabeledToken>(); } if (parsedContents.size()>0) { LabeledToken lastToken=parsedContents.get(parsedContents.size()-1); offset=lastToken.getOffset(); length=lastToken.getMain().length(); } LabeledToken enderToken= new LabeledToken(ENDER,(offset+length),ENDER,'O'); parsedContents.add(enderToken); }
2
public boolean equals (Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Path other = (Path)obj; if (dir == null) { if (other.dir != null) return false; } else if (!dir.equals(other.dir)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; }
9
private static void displayApparentPlace(double t, ApparentPlace ap, int referenceSystem, PrintStream ps) { switch (referenceSystem) { case EQUATORIAL: displayApparentPlaceEquatorial(t, ap, ps); break; case ECLIPTIC: displayApparentPlaceEcliptic(t, ap, ps); break; } }
2
@SuppressWarnings("unchecked") public Map<String, BEValue> getMap() throws InvalidBEncodingException { if (this.value instanceof HashMap) { return (Map<String, BEValue>)this.value; } else { throw new InvalidBEncodingException("Expected Map<String, BEValue> !"); } }
1
public int compareTo(Object object) { if (this instanceof CycConstant) { if (object instanceof CycConstant) return this.toString().compareTo(object.toString()); else if (object instanceof CycNart) return this.toString().compareTo(object.toString().substring(1)); else throw new ClassCastException("Must be a CycFort object"); } else { if (object instanceof CycNart) return this.toString().compareTo(object.toString()); else if (object instanceof CycConstant) return this.toString().substring(1).compareTo(object.toString()); else throw new ClassCastException("Must be a CycFort object"); } }
5
@Override public void deserialize(Buffer buf) { spellId = buf.readShort(); if (spellId < 0) throw new RuntimeException("Forbidden value on spellId = " + spellId + ", it doesn't respect the following condition : spellId < 0"); cellId = buf.readShort(); if (cellId < -1 || cellId > 559) throw new RuntimeException("Forbidden value on cellId = " + cellId + ", it doesn't respect the following condition : cellId < -1 || cellId > 559"); }
3
public List<Double> getDoubleList(String path) { List<?> list = getList(path); if (list == null) { return new ArrayList<Double>(0); } List<Double> result = new ArrayList<Double>(); for (Object object : list) { if (object instanceof Double) { result.add((Double) object); } else if (object instanceof String) { try { result.add(Double.valueOf((String) object)); } catch (Exception ex) { } } else if (object instanceof Character) { result.add((double) ((Character) object).charValue()); } else if (object instanceof Number) { result.add(((Number) object).doubleValue()); } } return result; }
8
@Override public void actionPerformed(ActionEvent e) { if(e.getSource() == btnChars[0]){ //System.out.println("Green Char"); _Model.setBallChoice(GameModel.ballGreen); } if(e.getSource() == btnChars[1]){ //System.out.println("Blue Char"); _Model.setBallChoice(GameModel.ballBlue); } if(e.getSource() == btnChars[2]){ //System.out.println("Pink Char"); _Model.setBallChoice(GameModel.ballPink); } for(JButton btnChar : btnChars){ if(e.getSource() == btnChar){ // GamePanel pas aanmaken wanneer nodig // Overschrijft vorige game panel. _Model.setCurrentPane(4); _Model.setResetGame(true); _Controller.getCL().show(_Controller, "Game"); } } }
5
public void editNextShip() { if(editingPos < shipSizes.length-1) { editingPos++; if(myTurnEditing) { editingShip = new Ship(shipSizes[editingPos], mySea.sea.length, mySea.sea[0].length, mySea.fleet); mySea.renderEditingShip = true; } else { editingShip = new Ship(shipSizes[editingPos], theirSea.sea.length, theirSea.sea[0].length, theirSea.fleet); theirSea.renderEditingShip = true; } } else { editingShip = new Ship(); editingShip.xSize = 0; editingShip.ySize = 0; endEditingTurn(); } }
2
public static MapleShop createFromDB(int id, boolean isShopId) { MapleShop ret = null; int shopId; try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement(isShopId ? "SELECT * FROM shops WHERE shopid = ?" : "SELECT * FROM shops WHERE npcid = ?"); ps.setInt(1, id); ResultSet rs = ps.executeQuery(); if (rs.next()) { shopId = rs.getInt("shopid"); ret = new MapleShop(shopId, rs.getInt("npcid")); rs.close(); ps.close(); } else { rs.close(); ps.close(); return null; } ps = con.prepareStatement("SELECT * FROM shopitems WHERE shopid = ? ORDER BY position ASC"); ps.setInt(1, shopId); rs = ps.executeQuery(); List<Integer> recharges = new ArrayList<Integer>(rechargeableItems); while (rs.next()) { if (InventoryConstants.isThrowingStar(rs.getInt("itemid")) || InventoryConstants.isBullet(rs.getInt("itemid"))) { MapleShopItem starItem = new MapleShopItem((short) 1, rs.getInt("itemid"), rs.getInt("price")); ret.addItem(starItem); if (rechargeableItems.contains(starItem.getItemId())) { recharges.remove(Integer.valueOf(starItem.getItemId())); } } else { ret.addItem(new MapleShopItem((short) 1000, rs.getInt("itemid"), rs.getInt("price"))); } } for (Integer recharge : recharges) { ret.addItem(new MapleShopItem((short) 1000, recharge.intValue(), 0)); } rs.close(); ps.close(); } catch (SQLException e) { System.err.println("Could not load shop" + e); } return ret; }
8
public Reader createReader() { return new Reader() { public Iterable<? extends Player> readPlayers(String key) throws KeyNotFoundException { try { // ToDo return DatabaseFactory.createDatabase(key); } catch (FileNotFoundException e) { throw new KeyNotFoundException(key, e); } } }; }
2
public void drawImageString(JGEngineInterface eng, String string, double x, double y, int align, String imgmap, int char_offset, int spacing,boolean pf_relative) { ImageMap map = (ImageMap) imagemaps.get(imgmap); if (map==null) throw new JGameError( "Font image map '"+imgmap+"' not found.",true ); if (align==0) { x -= (map.tilex+spacing) * string.length()/2; } else if (align==1) { x -= (map.tilex+spacing) * string.length(); } //Image img = map.getScaledImage(); StringBuffer lettername_buf = new StringBuffer(imgmap+"# "); int lastchar = lettername_buf.length()-1; String lettername=null; for (int i=0; i<string.length(); i++) { int imgnr = -char_offset+string.charAt(i); //String lettername = imgmap+"#"+string.charAt(i); lettername_buf.setCharAt(lastchar,string.charAt(i)); lettername=lettername_buf.toString(); if (!existsImage(lettername)) { defineImage(lettername, "FONT", 0, getSubImage(imgmap,imgnr), "-", 0,0,0,0); } JGImage letter = getImage(lettername); eng.drawImage(x,y,lettername,pf_relative); //eng.drawImage(buf_gfx, x,y,lettername,pf_relative); x += map.tilex + spacing; } }
5
* * @throws UnknownHostException if cyc server host not found on the network * @throws IOException if a data communication error occurs * @throws CycApiException if the api request results in a cyc server error */ public CycList converseList(Object command) throws UnknownHostException, IOException, CycApiException { Object[] response = {null, null}; response = converse(command); if (response[0].equals(Boolean.TRUE)) { if (response[1].equals(CycObjectFactory.nil)) { return new CycList(); } else { if (response[1] instanceof CycList) { return (CycList) response[1]; } } } throw new ConverseException(command, response); }
3
@Basic @Column(name = "SOL_ID_ELEMENTO") public Integer getSolIdElemento() { return solIdElemento; }
0
@Override public void executeMsg(Environmental myHost, CMMsg affect) { super.executeMsg(myHost, affect); if((affect.target()!=null)&&(affect.target().equals(affected)) &&(affect.tool()!=null)&&(affect.tool().ID().equals("Scrapping"))) { final Item item=(Item)affect.target(); final MOB mob = affect.source(); if (mob != null) { final Room room = mob.location(); final int damage = 3 * item.phyStats().weight(); CMLib.combat().postDamage(mob, mob, item, damage*2, CMMsg.MASK_ALWAYS|CMMsg.TYP_FIRE, Weapon.TYPE_PIERCING, L("Scrapping @x1 causes an explosion which <DAMAGE> <T-NAME>!!!",item.Name())); final Set<MOB> theBadGuys=mob.getGroupMembers(new HashSet<MOB>()); for (final Object element : theBadGuys) { final MOB inhab=(MOB)element; if (mob != inhab) CMLib.combat().postDamage(inhab, inhab, item, damage, CMMsg.MASK_ALWAYS|CMMsg.TYP_FIRE, Weapon.TYPE_PIERCING, L("Fragments from @x1 <DAMAGE> <T-NAME>!",item.Name())); } room.recoverRoomStats(); } item.destroy(); } }
7
public Color stringToColor(String color) { if(color.equals("white")) return Color.white; else if(color.equals("red")) return Color.red; else if(color.equals("blue")) return Color.blue; else if(color.equals("green")) return Color.green; else if(color.equals("gray")) return Color.gray; else if(color.equals("yellow")) return Color.yellow; else if(color.equals("magenta")) return Color.magenta; else if(color.equals("cyan")) return Color.cyan; else return Color.black; }
8
@Override public int compare(Rate a, Rate b) { if (a.get() > b.get()) { return 1; } else { return -1; } }
1
public void updateMissileTime(int time, String missileId, String type, String destination, int damage, int flyTime) { Iterator<String> keySetIterator = map.keySet().iterator(); Iterator<String> destuctorsSetIterator = destructors.keySet() .iterator(); if (type == "missile") { while (keySetIterator.hasNext()) { // for missiles String key = keySetIterator.next(); if (key.equalsIgnoreCase(missileId)) { progressBar = map.get(key); progressBar.setForeground(Color.LIGHT_GRAY); progressBar.setValue(time); JLabel temp = (JLabel) progressBar.getComponent(0); temp.setText("Missile id#" + missileId + " Will Hit " + destination + " for " + damage + " damage in " + (flyTime - time) + "s"); } } } else if (type == "launcherDestroyer") { while (destuctorsSetIterator.hasNext()) { // for desturctors String key = destuctorsSetIterator.next(); if (key.equalsIgnoreCase(missileId)) { progressBar = destructors.get(key); progressBar.setForeground(Color.CYAN); progressBar.setValue(time); JLabel temp = (JLabel) progressBar.getComponent(0); temp.setText(destination + " Will Hit Launcher #" + missileId + " in " + (flyTime - time) + "s"); } } } else if (type == "IronDome") { while (destuctorsSetIterator.hasNext()) { // for desturctors String key = destuctorsSetIterator.next(); if (key.equalsIgnoreCase(missileId)) { progressBar = destructors.get(key); progressBar.setForeground(Color.CYAN); progressBar.setValue(time); JLabel temp = (JLabel) progressBar.getComponent(0); temp.setText(destination + " Will Hit Missile #" + missileId + " in " + (flyTime - time) + "s"); } } } }
9
public CategoryServlet() { super(); // TODO Auto-generated constructor stub }
0
@Override public void actionPerformed(ActionEvent e) { if (e.getSource()==questionDeleteButton) { this.setVisible(false); this.getParent().remove(this); this.invalidate(); } }
1
public double getDouble(String key) throws JSONException { Object object = this.get(key); try { return object instanceof Number ? ((Number) object).doubleValue() : Double.parseDouble((String) object); } catch (Exception e) { throw new JSONException("JSONObject[" + quote(key) + "] is not a number."); } }
2
public static double[] readAudioFile( File audioFile, float sampleRate ) throws IOException, UnsupportedAudioFileException { AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile); AudioFormat audioFormat = new AudioFormat(sampleRate, 16, 1, true, true); DataInputStream dataStream = new DataInputStream( new BufferedInputStream( AudioSystem.getAudioInputStream(audioFormat, audioStream))); int m = (int) audioStream.getFrameLength(); double[] audioData = new double[m]; for ( int i = 0; i < m; ++i ) audioData[i] = dataStream.readShort() / ((double) - Short.MIN_VALUE); return(audioData); }
1
public XmlParser(String src) { try { xmlFile = new File(src); } catch (Exception e) { System.out.println("Erro ao abrir o arquivo XML\nErro: " + e.getMessage()); } }
1
@Override public void doLogic() { if (inputList[0] == true && inputList[1] == true){ this.power = true; this.solved = true; } else { this.power = false; } if (solved == false){ inputList[0] = false; inputList[1] = false; } }
3
public Metrics(final Plugin plugin) throws IOException { if (plugin == null) { throw new IllegalArgumentException("Plugin cannot be null"); } this.plugin = plugin; // load the config configurationFile = getConfigFile(); configuration = YamlConfiguration.loadConfiguration(configurationFile); // add some defaults configuration.addDefault("opt-out", false); configuration.addDefault("guid", UUID.randomUUID().toString()); configuration.addDefault("debug", false); // Do we need to create the file? if (configuration.get("guid", null) == null) { configuration.options().header("http://mcstats.org").copyDefaults(true); configuration.save(configurationFile); } // Load the guid then guid = configuration.getString("guid"); debug = configuration.getBoolean("debug", false); }
2
@Override public void mouseClicked(MouseEvent e) { }
0
public MiniAirplaneTurnImage(String imageURL, PlaneColor color) { super(imageURL); totalFrame=8;//3 frames per plane delayCounter=0;//delay counter starts at 0 //Set the image to military color if(color==PlaneColor.MILITARY) { yLocationSpriteSheet=136; } //Set the image to white color else if(color==PlaneColor.WHITE) { yLocationSpriteSheet=103; } //Set the image to green color else if(color==PlaneColor.GREEN) { yLocationSpriteSheet=70; } //Set the image to blue color else if(color==PlaneColor.BLUE) { yLocationSpriteSheet=37; } //Set the image for the plane this.setImage(frameNumber*32+frameNumber+5, yLocationSpriteSheet, width,height ,newWidth, newHeight); }
4
private BitSet[] findElementaryCycles( BitSet reachables ) { ArrayList<BitSet> elementaryCycles = new ArrayList<BitSet>(); ArrayList<Integer> queue = new ArrayList<Integer>(); queue.add(0); BitSet bitSet; int last, parent, son; for ( int source = dRun.length - 1; source >= 0; source-- ) if ( reachables.get(source) ) { // we find all the elementary cycles with "source" as minimum bitSet = new BitSet(); queue.add(source); while ( ! queue.isEmpty() ) { last = queue.get( queue.size() - 1 ); if ( ! bitSet.get(last) && source <= last ) { // elementary cycle not founded bitSet.set(last); queue.add( succ0(last) ); } else { if ( last == source ) // elementary cycle founded with s as minimum! elementaryCycles.add( (BitSet) bitSet.clone() ); // (queue.length > 1) holds here // now we perform the backtracking queue.remove( queue.size() - 1 ); son = last; parent = queue.get( queue.size() - 1 ); while ( son == succ1( parent ) && queue.size() > 1 ) { queue.remove( queue.size() - 1 ); bitSet.clear( parent ); son = parent; parent = queue.get( queue.size() - 1 ); } if ( son != succ1( parent )) // the search isn't ended // we insert in the queue the 1-successor of "parent" queue.add( succ1( parent ) ); else // queue.size() == 1 // we founded all cycles with "source" as minimum queue.remove(0); } } } return elementaryCycles.toArray(new BitSet[elementaryCycles.size()]); }
9
public void setPackageName(String name) { this.packageName = name; }
0
protected void shiftCell(Object cell, double dx, double dy, double x0, double y0, double right, double bottom, double fx, double fy, boolean extendParent) { mxGraph graph = getGraph(); mxCellState state = graph.getView().getState(cell); if (state != null) { mxIGraphModel model = graph.getModel(); mxGeometry geo = model.getGeometry(cell); if (geo != null) { model.beginUpdate(); try { if (isShiftRightwards()) { if (state.getX() >= right) { geo = (mxGeometry) geo.clone(); geo.translate(-dx, 0); } else { double tmpDx = Math.max(0, state.getX() - x0); geo = (mxGeometry) geo.clone(); geo.translate(-fx * tmpDx, 0); } } if (isShiftDownwards()) { if (state.getY() >= bottom) { geo = (mxGeometry) geo.clone(); geo.translate(0, -dy); } else { double tmpDy = Math.max(0, state.getY() - y0); geo = (mxGeometry) geo.clone(); geo.translate(0, -fy * tmpDy); } if (geo != model.getGeometry(cell)) { model.setGeometry(cell, geo); // Parent size might need to be updated if this // is seen as part of the resize if (extendParent) { graph.extendParent(cell); } } } } finally { model.endUpdate(); } } } }
8
public void run(int interfaceId, int componentId) { if (stage == -1) { sendEntityDialogue((short) 241, new String[] { player.getDisplayName(), "Sure, let's see what I can set it to!" }, (byte) 0, player.getIndex(), 9827); stage = 1; } else if (stage == 1) { sendDialogue((short) 238, new String[] { "Select an option", "<col=ef7216>Hard</col>: 2x RuneScape", "<col=676ad9>Easy</col>: 35x RuneScape", "<col=0006ff>No Challenge</col>: 50x RuneScape", "<col=de4ac0>Normal</col>: 15x RuneScape", "Nevermind" }); stage = 2; } else if (stage == 2) { if (componentId == 1) { player.combatExperience = 2; sendEntityDialogue(SEND_2_TEXT_CHAT, new String[] { NPCDefinitions.getNPCDefinitions(npcId).name, "Excellent! Your combat rate is now 2x RuneScape.", "Have fun!" }, (byte) 1, npcId, 9850); } else if (componentId == 2) { player.combatExperience = 35; sendEntityDialogue(SEND_2_TEXT_CHAT, new String[] { NPCDefinitions.getNPCDefinitions(npcId).name, "Excellent! Your combat rate is now 35x RuneScape.", "Have fun!" }, (byte) 1, npcId, 9850); } else if (componentId == 3) { player.combatExperience = 50; sendEntityDialogue(SEND_2_TEXT_CHAT, new String[] { NPCDefinitions.getNPCDefinitions(npcId).name, "Excellent! Your combat rate is now 50x RuneScape.", "Have fun!" }, (byte) 1, npcId, 9850); } else if (componentId == 4) { player.combatExperience = 15; sendEntityDialogue(SEND_2_TEXT_CHAT, new String[] { NPCDefinitions.getNPCDefinitions(npcId).name, "Excellent! Your combat rate is now 15x RuneScape.", "Have fun!" }, (byte) 1, npcId, 9850); } else { end(); } } }
7
private Image warpImage(String imagePath){ BufferedImage image = null; //load image try { image = ImageIO.read(this.getClass().getResource(imagePath)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //wrap image in the transformer object javaxt.io.Image warped = new javaxt.io.Image(image); int width = warped.getWidth(); int height = warped.getHeight(); //apply the transform if (surface.roomView.sidePassage){ //here we use skew to slide the far away edge towards the center (side passages only) int closeWidth = (int) (width * 0.8); int farWidth = (int) (width * 0.4); if (surface.roomView.sidePassageLeft){ //we are in a side passage, so have to skew to one side //left side if (ceiling){ warped.setCorners(0, 0, //UL closeWidth, 0, //UR width, height, //LR width - farWidth, height);//LL } else { //floor warped.setCorners(width - farWidth, 0, //UL width, 0, //UR closeWidth, height, //LR 0, height);//LL } } else { //right side if (ceiling){ warped.setCorners(width - closeWidth, 0, //UL closeWidth, 0, //UR farWidth, height, //LR 0, height);//LL } else { //floor warped.setCorners(0, 0, //UL farWidth, 0, //UR width, height, //LR width - closeWidth, height);//LL } } } else { //normal transform, just have to shrink the far edge if (ceiling){ warped.setCorners(0, 0, //UL width, 0, //UR (3 * (width / 4)), height, //LR (width / 4), height);//LL } else { //floor warped.setCorners((3 * (width / 4)), 0, //UL (width / 4), 0, //UR 0, height, //LR width, height);//LL } } return warped.getImage(); }
6
private void parse(CommandLine line) throws FileNotFoundException, UnsupportedEncodingException { if(line.getArgList().isEmpty() || line.hasOption("help")) { printUsage(); return; } if(line.hasOption("in")) { String inFile = line.getOptionValue("in"); File file = new File(inFile); if(!file.exists()) { System.err.println("File not found at " + file); return; } inputStream = new FileInputStream(file); } else { System.out.println("Waiting for data in standard input"); inputStream = System.in; } if(line.hasOption("out")) { String outFile = line.getOptionValue("out"); File file = new File(outFile); if(file.exists()) { System.out.println("File " + file + " will be overwritten"); } File parentFile = file.getParentFile(); if(!parentFile.mkdirs() && !parentFile.exists()) { System.err.println("Failed to create parent directory at " + parentFile); return; } out = new PrintStream(new FileOutputStream(file, false), true, "utf-8"); } else { out = System.out; } fontName = line.getOptionValue("font", "jd"); dotExec = line.getOptionValue("dot", "/usr/local/bin/dot"); direction = line.getOptionValue("direction", "TD"); }
8
private boolean checkTouchBullet() { boolean tocat = false; this.setVisible(true); ArrayList<Line2D.Double> linies = this.getBoundLines(); if (!Board.getBullets().isEmpty()) { for (int i = 0; i < linies.size(); i++) { for (int t = 0; t < Board.getBullets().size(); t++) { if (Board.getBullets().get(t).getOwner() != this) { if (linies.get(i).getBounds().contains(Board.getBullets().get(t).getX(), Board.getBullets().get(t).getY())) { if(Board.getBullets().get(t).isVisible() != false){ this.setLives(this.getLives()-1); if(this.lives <= 0){ URL explosionAnimImgUrl = this.getClass().getResource("/resources/images/exploteDeath.png"); try { explosionAnimImg = ImageIO.read(explosionAnimImgUrl); } catch (IOException ex) { Logger.getLogger(Robot.class.getName()).log(Level.SEVERE, null, ex); } Explote expAnim = new Explote(explosionAnimImg, 130, 130, 64, 20, false, (int)this.x-50, (int)this.y - explosionAnimImg.getHeight()/3, 0); Board.getExpAnim().add(expAnim); this.die(); } } Board.getBullets().get(t).setVisible(false); } } } } } return tocat; }
8
public void move(int m) { int pX = x; int pY = y; switch (m) { case 0: { pY--; break; } case 2: { pY++; break; } case 1: { pX++; break; } case 3: { pX--; break; } } Map.movePlayer(this, pX, pY); }
4
@EventHandler public void onDisconnectEvent(ClientDisconnectEvent event){ try{ Client c = ClientManager.get(event.sc); if(c.isLoggedIn()){System.out.println(c.getUsername() + " Disconnected!");} else{System.out.println(event.sc.getLocalAddress()+" Disconnected!");} ClientManager.remove(event.getSocketChannel()); IPMap.remove(event.getSocketChannel().getLocalAddress()); }catch(Exception e){e.printStackTrace();} }
2
public void fixAllBarrows() { int totalCost = 0; int cashAmount = c.getItems().getItemAmount(995); for (int j = 0; j < c.playerItems.length; j++) { boolean breakOut = false; for (int i = 0; i < c.getItems().brokenBarrows.length; i++) { if (c.playerItems[j]-1 == c.getItems().brokenBarrows[i][1]) { if (totalCost + 80000 > cashAmount) { breakOut = true; c.sendMessage("You have run out of money."); break; } else { totalCost += 80000; } c.playerItems[j] = c.getItems().brokenBarrows[i][0]+1; } } if (breakOut) break; } if (totalCost > 0) c.getItems().deleteItem(995, c.getItems().getItemSlot(995), totalCost); }
6
public String searchANDdescribe() { StringBuilder result = new StringBuilder(); for(K k : this) { if(k.getClass().equals(PapaBuilding.class)){ result.append(((PapaBuilding) k).getAttributes()); }else if(k.getClass().equals(PapaBicho.class)){ result.append(((PapaBicho) k).getAttributes()); }else if(k.getClass().equals(Monk.class)){ result.append(((PapaBicho) k).getAttributes()); }else if(k.getClass().equals(Harvester.class)){ result.append(((PapaBicho) k).getAttributes()); }else if (k.getClass().equals(Healer.class)){ result.append(((PapaBicho) k).getAttributes()); }else if(k.getClass().equals(Kamikaze.class)){ result.append(((PapaBicho) k).getAttributes()); }else if(k.getClass().equals(Base.class)){ result.append(((PapaBuilding) k).getAttributes()); }else if (k.getClass().equals(House.class)){ result.append(((PapaBuilding) k).getAttributes()); } } return result.toString(); }
9
static void quick_sort (int lowerIndex, int higherIndex,int array[]) { int i = lowerIndex; int j = higherIndex; // calculate pivot number, I am taking pivot as middle index number int pivot = array[lowerIndex+(higherIndex-lowerIndex)/2]; // Divide into two arrays while (i <= j) { /** * In each iteration, we will identify a number from left side which * is greater then the pivot value, and also we will identify a number * from right side which is less then the pivot value. Once the search * is done, then we exchange both numbers. */ while (array[i] < pivot) { i++; } while (array[j] > pivot) { j--; } if (i <= j) { int temp = array[i]; array[i] = array[j]; array[j] = temp; //move index to next position on both sides i++; j--; } } // call quickSort() method recursively if (lowerIndex < j) quick_sort(lowerIndex, j,array); if (i < higherIndex) quick_sort(i, higherIndex,array); for (int j1:array) { System.out.print(j1+","); } System.out.println(); }
7
private int splitOutputFile(final File tempOutputFile, final File outputFolder) throws IOException { //output should be words_1.dict....words_n.dict InputStream inputStream = new FileInputStream(tempOutputFile); int file_postfix = 0; int current_output_file_size = 0; byte[] buffer = new byte[4 * 1024]; OutputStream outputStream = null; int read = 0; XmlWriter xml = new XmlWriter(dict_id_array); xml.writeEntity("resources"); xml.writeEntity("array").writeAttribute("name", "words_dict_array"); while ((read = inputStream.read(buffer)) > 0) { if (outputStream != null && current_output_file_size >= DICT_FILE_CHUNK_SIZE) { outputStream.flush(); outputStream.close(); outputStream = null; } if (outputStream == null) { file_postfix++; xml.writeEntity("item").writeText("@raw/words_"+file_postfix).endEntity(); current_output_file_size = 0; File chunkFile = new File(outputFolder, "words_" + file_postfix + ".dict"); outputStream = new FileOutputStream(chunkFile); System.out.println("Writing to dict file " + chunkFile.getAbsolutePath()); } outputStream.write(buffer, 0, read); current_output_file_size += read; } xml.endEntity(); xml.endEntity(); xml.close(); inputStream.close(); if (outputStream != null) { outputStream.flush(); outputStream.close(); } System.out.println("Done. Wrote " + file_postfix + " files."); return file_postfix; }
5
public static int removeElement(int[] A, int elem) { if (A == null || A.length == 0) return 0; int foundNum = 0; int i = 0; while (i < A.length && i <= A.length - 1 - foundNum) { if (A[i] == elem) { int j = A.length - 1 - foundNum; while (j > i) { if (A[j] == elem) foundNum++; else break; j--; } foundNum++; A[i] = A[j]; } i++; } return A.length - foundNum; }
7
private void moveGhosts(){ if (this.ghostMoveCounter == 0){ for (int i=0; i < 4; i++){ if (this.ghosts[i].getIsAlive() && (i != 2)) this.ghosts[i].move(); } if (this.ghosts[2].getIsAlive()) if (!didGhostsCollide()) this.ghosts[2].move(); } }
6
private int handleL(String value, DoubleMetaphoneResult result, int index) { result.append('L'); if (charAt(value, index + 1) == 'L') { if (conditionL0(value, index)) { result.appendAlternate(' '); } index += 2; } else { index++; } return index; }
2
private String[] getTroisMeilleurs(String nomJeu, String xmlJeu, String xmlUsers) { String[] result = new String[3]; HashMap<String, List<String>> partiesParJoueur = getParties(nomJeu, xmlUsers); if (partiesParJoueur == null) return result; HashMap<Integer, Integer> pointParSituation = getPoints(xmlJeu); List<classement> classement = new ArrayList<>(); for (Entry<String, List<String>> partie : partiesParJoueur.entrySet()) { String joueur = partie.getKey(); List<String> deroules = partie.getValue(); for (String deroule : deroules) { classement position = new classement(); int points = 0; String[] codes = deroule.split(";"); for (int i = 0; i < codes.length; i++) { int codeInteger = 0; try { codeInteger = Integer.parseInt(codes[i]); } catch (Exception e) { continue; } points += pointParSituation.get(codeInteger) != null ? pointParSituation.get(codeInteger) : 0; } position.joueur = joueur; position.points = points; classement.add(position); } } Collections.sort(classement, new Comparator<classement>() { @Override public int compare(classement o1, classement o2) { return Integer.compare(o2.points,o1.points); } }); int max = classement.size(); for (int i = 0; i < (max < 3 ? max : 3); i++) { classement score = classement.get(i); result[i] = score.joueur + " " + score.points + "pts"; } return result; }
8
public static void initbardas() { try { for (Class<?> c : barda) Class.forName(c.getName(), true, c.getClassLoader()); } catch (ClassNotFoundException e) { e.printStackTrace(); throw (new Error(e)); } }
3
public static Cons yieldContextSensitiveSlotValueSetterTree(StorageSlot slot, Stella_Object objectref, Stella_Object valueref, StandardObject returntype, Cons csoptions, Object [] MV_returnarray) { { boolean contextsensitiveP = !((csoptions != null) && (Cons.searchPlist(csoptions, Stella.KWD_CONTEXT_SENSITIVEp) == Stella.SYM_STELLA_FALSE)); Symbol copytochildren = (((csoptions != null) && (Cons.searchPlist(csoptions, Stella.KWD_COPY_TO_CHILDRENp) == Stella.SYM_STELLA_TRUE)) ? Stella.SYM_STELLA_TRUE : Stella.SYM_STELLA_FALSE); Surrogate realbasetype = slot.slotBaseType; CompoundTypeSpecifier realtypespec = ((CompoundTypeSpecifier)(KeyValueList.dynamicSlotValue(slot.dynamicSlots, Stella.SYM_STELLA_SLOT_TYPE_SPECIFIER, null))); Symbol objectvar = null; Symbol valuevar = null; Symbol oldvaluevar = null; Symbol newvaluevar = null; Cons oldvaluetree = null; Cons setnewvaluetree = null; slot.slotBaseType = Stella.SGT_STELLA_OBJECT; if (realtypespec != null) { KeyValueList.setDynamicSlotValue(slot.dynamicSlots, Stella.SYM_STELLA_SLOT_TYPE_SPECIFIER, null, null); } slot.slotContextSensitiveP = false; if (contextsensitiveP) { objectvar = Stella.localGensym("OBJECT"); valuevar = Stella.localGensym("VALUE"); oldvaluevar = Stella.localGensym("OLD-VALUE"); newvaluevar = Stella.localGensym("NEW-VALUE"); Symbol.pushVariableBinding(objectvar, slot.slotOwner); Symbol.pushVariableBinding(newvaluevar, Stella.SGT_STELLA_OBJECT); oldvaluetree = Stella_Object.sysTree(Stella_Object.walkWithoutTypeTree(Cons.list$(Cons.cons(Stella.SYM_STELLA_SLOT_VALUE, Cons.cons(objectvar, Cons.cons(Cons.cons(slot.slotName, Stella.NIL), Stella.NIL))))), Stella.SGT_STELLA_OBJECT, new Object[1]); setnewvaluetree = Stella_Object.sysTree(Stella_Object.walkWithoutTypeTree(Cons.list$(Cons.cons(Stella.SYM_STELLA_SETF, Cons.cons(Cons.list$(Cons.cons(Stella.SYM_STELLA_SLOT_VALUE, Cons.cons(objectvar, Cons.cons(Cons.cons(slot.slotName, Stella.NIL), Stella.NIL)))), Cons.cons(newvaluevar, Cons.cons(Stella.NIL, Stella.NIL)))))), Stella.SGT_STELLA_OBJECT, new Object[1]); } else { setnewvaluetree = Stella_Object.sysTree(Stella_Object.walkWithoutTypeTree(Cons.list$(Cons.cons(Stella.SYM_STELLA_SETF, Cons.cons(Cons.list$(Cons.cons(Stella.SYM_STELLA_SLOT_VALUE, Cons.cons(objectref, Cons.cons(Cons.cons(slot.slotName, Stella.NIL), Stella.NIL)))), Cons.cons(valueref, Cons.cons(Stella.NIL, Stella.NIL)))))), Stella.SGT_STELLA_OBJECT, new Object[1]); } slot.slotBaseType = realbasetype; if (realtypespec != null) { KeyValueList.setDynamicSlotValue(slot.dynamicSlots, Stella.SYM_STELLA_SLOT_TYPE_SPECIFIER, realtypespec, null); } slot.slotContextSensitiveP = true; if (!contextsensitiveP) { { Cons _return_temp = setnewvaluetree; MV_returnarray[0] = Stella.SGT_STELLA_OBJECT; return (_return_temp); } } Stella.popVariableBinding(); Stella.popVariableBinding(); { Cons _return_temp = Cons.list$(Cons.cons(Stella.SYM_STELLA_VRLET, Cons.cons(Cons.list$(Cons.cons(Cons.cons(objectvar, Cons.cons(objectref, Stella.NIL)), Cons.cons(Cons.cons(valuevar, Cons.cons(realbasetype, Cons.cons(valueref, Stella.NIL))), Cons.cons(Cons.cons(oldvaluevar, Cons.cons(oldvaluetree, Stella.NIL)), Cons.cons(Cons.cons(newvaluevar, Cons.cons(Cons.list$(Cons.cons(Stella.SYM_STELLA_UPDATE_IN_CONTEXT, Cons.cons(oldvaluevar, Cons.cons(Cons.cons(valuevar, Cons.list$(Cons.cons(Cons.list$(Cons.cons(Stella.SYM_STELLA_HOME_CONTEXT, Cons.cons(objectvar, Cons.cons(Stella.NIL, Stella.NIL)))), Cons.cons(copytochildren, Cons.cons(Stella.NIL, Stella.NIL))))), Stella.NIL)))), Stella.NIL)), Cons.cons(Stella.NIL, Stella.NIL)))))), Cons.cons(Cons.list$(Cons.cons(Stella.SYM_STELLA_WHEN, Cons.cons(Cons.list$(Cons.cons(Stella.SYM_STELLA_NOT, Cons.cons(Cons.list$(Cons.cons(Stella.SYM_STELLA_CS_VALUEp, Cons.cons(oldvaluevar, Cons.cons(Stella.NIL, Stella.NIL)))), Cons.cons(Stella.NIL, Stella.NIL)))), Cons.cons(setnewvaluetree, Cons.cons(Stella.NIL, Stella.NIL))))), Cons.cons(valuevar, Cons.cons(Stella.NIL, Stella.NIL)))))); MV_returnarray[0] = returntype; return (_return_temp); } } }
7
public Queue<String> escoltaXMLUnit (){ try { path = new File(".").getCanonicalPath(); FileInputStream file = new FileInputStream(new File(path + "/xml/papabicho.xml")); DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderFactory.newDocumentBuilder(); Document xmlDocument = builder.parse(file); XPath xPath = XPathFactory.newInstance().newXPath(); System.out.println("************************************"); String expression01 = "/Units/Unit[@class='Escolta']"; NodeList nodeList; Node node01 = (Node) xPath.compile(expression01) .evaluate(xmlDocument, XPathConstants.NODE); if(null != node01) { nodeList = node01.getChildNodes(); for (int i = 0;null!=nodeList && i < nodeList.getLength(); i++){ Node nod = nodeList.item(i); if(nod.getNodeType() == Node.ELEMENT_NODE){ System.out.println(nodeList.item(i).getNodeName() + " : " + nod.getFirstChild().getNodeValue()); list.append(nod.getFirstChild().getNodeValue()); } } } System.out.println("************************************"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (XPathExpressionException e) { e.printStackTrace(); } return list; }
9
public boolean after(Temps t) { boolean aft=true; if (this.heures<t.heures) { aft=false; } else { if (this.heures==t.heures) { if (this.minutes<t.minutes) { aft=false; } else { if (this.minutes==t.minutes) { if (this.secondes<= t.secondes) { aft=false; } } } } } return aft; }
5
public static double ddot_f77 (int n, double dx[], int incx, double dy[], int incy) { double ddot; int i,ix,iy,m; ddot = 0.0; if (n <= 0) return ddot; if ((incx == 1) && (incy == 1)) { // both increments equal to 1 m = n%5; for (i = 1; i <= m; i++) { ddot += dx[i]*dy[i]; } for (i = m+1; i <= n; i += 5) { ddot += dx[i]*dy[i] + dx[i+1]*dy[i+1] + dx[i+2]*dy[i+2] + dx[i+3]*dy[i+3] + dx[i+4]*dy[i+4]; } return ddot; } else { // at least one increment not equal to 1 ix = 1; iy = 1; if (incx < 0) ix = (-n+1)*incx + 1; if (incy < 0) iy = (-n+1)*incy + 1; for (i = 1; i <= n; i++) { ddot += dx[ix]*dy[iy]; ix += incx; iy += incy; } return ddot; } }
8
public boolean supprimerPointLivraison(Noeud noeudASup) throws HorsPlageException{ boolean trouve = false; int i; Chemin cheminAvant = null; Chemin cheminApres = null; for (i=0 ; i<cheminsResultats.size() ; i++) { int idNoeudASup = noeudASup.getId(); if ((cheminsResultats.get(i).getDestination().getIdNoeud() == idNoeudASup) && (cheminsResultats.get(i+1).getOrigine().getIdNoeud() == idNoeudASup)){ cheminAvant = cheminsResultats.get(i); cheminApres = cheminsResultats.get(i+1); trouve = true; break; } } this.zone.modifierLivraisonEnNoeud(noeudASup.getId(), new Noeud(noeudASup.getId(), noeudASup.getXMetre(), noeudASup.getYMetre(),noeudASup.getSortants())); if (trouve) { //Création des variables nécessaires LivraisonGraphVertex lgvOrigine = cheminAvant.getOrigine(); LivraisonGraphVertex lgvDestination = cheminApres.getDestination(); LivraisonGraphVertex lgvMilieu = cheminAvant.getDestination(); Chemin chemin = Dijkstra.plusCourtChemin(zone, lgvOrigine, lgvDestination); cheminsResultats.remove(i); cheminsResultats.remove(i); cheminsResultats.add(i, chemin); graph.noeuds.remove(lgvMilieu); this.calculerHeuresLivraison(); return true; } return false; }
4
public static void main( String[] args ) throws Exception { CUI c = new CUI(); String cui = "C0032344"; System.out.println(cui); System.out.println("----------"); System.out.println("Definition: "); System.out.println(c.retreiveDefinition(cui)); System.out.println("----------"); System.out.println("Synonyms:"); ArrayList<String> syn = (ArrayList<String>) c.retreiveSynonyms(cui); for(String x:syn) { System.out.println(x); } System.out.println("----------"); System.out.println("Semantic Types:"); ArrayList<String> sty = (ArrayList<String>) c.retreiveSemanticType(cui); for(String x:sty) { System.out.println(x); } }
2
protected BufferedImage initOffsets() { BufferedImage img = image; if( img == null ) return img; scale = 1; while( img.getWidth() * (scale+1) <= getWidth() && img.getHeight() * (scale+1) <= getHeight() ) { ++scale; } while( scale > 1 && (img.getWidth() * scale > getWidth() || img.getHeight() * scale > getHeight()) ) { --scale; } offX = (int)(getWidth() - img.getWidth() * scale) / 2; offY = (int)(getHeight() - img.getHeight() * scale) / 2; return img; }
6
public RuleMatch matchRule(Rule rule) { List<UnificationPair> mgu = unifier.unify(new UnificationPair(rule.getHead(), target)); // If there exists a most general unifier, then we have found a suitable rule if (mgu != null) { return new RuleMatch(rule, mgu); } else { return null; } }
1