text
stringlengths
14
410k
label
int32
0
9
private boolean mpChecker(LinkedList<String>left,LinkedList<String>middle, LinkedList<String>consequent) { /* * assume (a=>b) * assume ((a=>b)=>(b=>c)) * mp 1 2 (b=>c) * * */ LinkedList<String> fullExpression; LinkedList<String> predicate; if (left.size() > middle.size()) { fullExpression = left; predicate = middle; } else { fullExpression = middle; predicate = left; } //System.out.println(fullExpression.toArray().toString()); //System.out.println(predicate.toArray().toString()); if (fullExpression.pop().equals("=>")) { String fullBuff = ""; //check predicate matches left side of full expression for(int i=0; i < predicate.size();i++) { try { fullBuff = fullExpression.pop(); assert predicate.pop().equals(fullBuff); } catch (Exception e) { return false; } } //check consequent matches right side of full expression for(int i=0; i < consequent.size();i++) { try { fullBuff = fullExpression.pop(); assert consequent.pop().equals(fullBuff); } catch (Exception e) { return false; } } try { assert fullExpression.size()==0; return true; } catch (Exception e) { return false; } } return false; }
7
public boolean isLeftDiverse(Node node) { if (node.leaves.size() == 0 || node.leaves.get(0) == 1) { return true; } char temp = input.charAt(node.leaves.get(0) - 2); for (int i = 1; i < node.leaves.size(); i++) { if (temp != input.charAt(node.leaves.get(i) - 2)) { // System.out.println(input.charAt(node.leaves.get(i) - 2)); return true; } } return false; }
4
public static Item getItemTester(String name){ // get item Item item = ItemStorageInventory.create().getItemfromStorage(name); if(item != null) System.out.println("you just get "+ item + " from item list \n"); else System.out.println("getting "+ item + " failed\n"); return item; }
1
private JSONWriter append(String string) throws JSONException { if (string == null) { throw new JSONException("Null pointer"); } if (this.mode == 'o' || this.mode == 'a') { try { if (this.comma && this.mode == 'a') { this.writer.write(','); } this.writer.write(string); } catch (IOException e) { throw new JSONException(e); } if (this.mode == 'o') { this.mode = 'k'; } this.comma = true; return this; } throw new JSONException("Value out of sequence."); }
7
private static void doDir(File f, ClassLoader cl) { final String name = f.getPath(); System.out.println("SourceUtils.doDir(): " + name); if (!f.exists()) { throw new IllegalStateException(name + " does not exist"); } if (f.isFile()) { final String className = f.getPath().substring(1+startPath.length()); try { result.add(doFile(f, cl, className)); } catch (Exception e) { System.err.println("Warning: non-classifiable: " + f); } } else if (f.isDirectory()) { File objects[] = f.listFiles(); for (int i=0; i<objects.length; i++) doDir(objects[i], cl); } else System.err.println("Unknown: " + name); }
5
public int getWidth() { Window window = device.getFullScreenWindow(); if (window != null) { return window.getWidth(); } else { return 0; } }
1
public void mouseReleased(MouseEvent e) { }
0
@Override public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("setImagePath")) { JFileChooser chooser = new JFileChooser(); FileNameExtensionFilter filter1 = new FileNameExtensionFilter("Image files", "png", "jpeg", "jpg", "bmp"); chooser.addChoosableFileFilter(filter1); chooser.setFileFilter(filter1); int outcome = chooser.showOpenDialog(frame); if (outcome == JFileChooser.APPROVE_OPTION) { try { //ImageIcon ii = new ImageIcon(chooser.getSelectedFile().getAbsolutePath()); //hmf.imageLabel.setIcon(ii); property.path = chooser.getSelectedFile().getAbsolutePath(); property.zoom = 1.0d; property.imageOffsetX = 0; property.imageOffsetY = 0; frame.reRenderCard(); frame.hm.card.changed = true; } catch (Exception ex) { ex.printStackTrace(); } } } if (e.getActionCommand().equals("setImageZoom")) { String s = JOptionPane.showInputDialog(frame, "Enter the Image Zoom", property.zoom); if (s == null) { s = "" + property.zoom; } if (s != null && s.isEmpty()) { s = "" + property.zoom; } try { property.zoom = Double.parseDouble(s); } catch (Exception ex) { JOptionPane.showMessageDialog(null, ex.getMessage()); } frame.setCursor (Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); frame.reRenderCard(); frame.hm.card.changed = true; frame.setCursor (Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } }
8
public void actionPerformed(ActionEvent evt) { JButton bouton = (JButton) evt.getSource() ; String texte = bouton.getText() ; if (texte.equals(BTN_RETOUR)) modelePanneau.setChoix(MENU_PRINCIPAL); if (texte.equals(BTN_FACILE)) { difficulteChoisi = DIFF_FACILE; Facade.getInstance(new Jeu(new ConfigurationJeu(new Difficulte(DIFF_FACILE)))); modelePanneau.setChoix(RECREER_PLATEAU_JEU); modelePanneau.setChoix(PLATEAU_JEU); } else if (texte.equals(BTN_MOYEN)) { difficulteChoisi = DIFF_MOYENNE; Facade.getInstance(new Jeu(new ConfigurationJeu(new Difficulte(DIFF_MOYENNE)))); modelePanneau.setChoix(RECREER_PLATEAU_JEU); modelePanneau.setChoix(PLATEAU_JEU); } else if (texte.equals(BTN_DIFFICILE)) { difficulteChoisi = DIFF_DIFFICILE; Facade.getInstance(new Jeu(new ConfigurationJeu(new Difficulte(DIFF_DIFFICILE)))); modelePanneau.setChoix(RECREER_PLATEAU_JEU); modelePanneau.setChoix(PLATEAU_JEU); } modeleDifficulte.setNbRondes((int) champTexteNombreRonde.getValue()); // Test si la partie est en réseau if (Client.getInstance() != null) { try { Client.getInstance().avertirUtiliserPanneauJeuMastermind(difficulteChoisi, ModeleMenuDeDifficulte.getInstance().getNbRondes()); } catch (IOException e) { System.err.println("Erreurs d'entrée/sortie lors de l'avertissement de changement de panneau " + e); } } }
6
public boolean validateInput() { int i = 0, j = 0; for(i = 0; i < 9; i++) { for(j = 0; j < 9; j++) { try { if(Integer.parseInt(entries[i][j].getText()) < 1) { return false; } } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, "Invalid input. Enter an integer at row " + (i+1) + " column " + (j+1), "Error", JOptionPane.ERROR_MESSAGE); return false; } } } return true; }
4
public void Refresh(CellVariable[][] cells) throws ContradictionException { System.out.println("begin refresh"); solver.clear(); solver.read(model); System.out.println("model read"); for(int x = 0; x < sudokuSize; x++) { for(int y = 0; y < sudokuSize; y++) { if(cells[x][y].current != -1 && !cells[x][y].contradicting) { if(solver.getVar(cellVars[x][y]) == null) { System.out.println("Could not get var at : " + x + " - " + y); } solver.getVar(cellVars[x][y]).setVal(cells[x][y].current); } } } solver.propagate(); }
5
public int getPages(int intRegsPerPag, ArrayList<FilterBean> alFilter, HashMap<String, String> hmOrder) throws Exception { int pages; try { oMysql.conexion(enumTipoConexion); pages = oMysql.getPages("backlog", intRegsPerPag, alFilter, hmOrder); oMysql.desconexion(); return pages; } catch (Exception e) { throw new Exception("BacklogDao.getPages: Error: " + e.getMessage()); } finally { oMysql.desconexion(); } }
1
private void compileArgumentsList() throws ParseException, IOException { //empty arguments list if ((tokenizer.tokenType() == Tokenizer.SYMBOL) && (tokenizer.symbol() == ')')) { return; } do { // <data-type> Type type = compileDataType(); // <argument-name> if (tokenizer.tokenType() != Tokenizer.IDENTIFIER) { throw new ParseException("argument name is excepted after type", tokenizer.lineNumber()); } Function.currentFunction.addParameter(tokenizer.getIdentifier(), type); advance("program not ended"); // , if ((tokenizer.tokenType() != Tokenizer.SYMBOL) || (tokenizer.symbol() != ',')) { break; } advance("program not ended"); } while (true); }
6
public N getHigherNode(T payLoad) { N p = m_root; while (p != null) { int cmp = compare(payLoad, p.getPayload()); if (cmp < 0) { if (p.getLeft() != null) p = p.getLeft(); else return p; } else { if (p.getRight() != null) { p = p.getRight(); } else { N parent = p.getParent(); N ch = p; while (parent != null && ch == parent.getRight()) { ch = parent; parent = parent.getParent(); } return parent; } } } return null; }
6
public static JSONObject toJSONObject(String string) throws JSONException { JSONObject jo = new JSONObject(); XMLTokener x = new XMLTokener(string); while (x.more() && x.skipPast("<")) { parse(x, jo, null); } return jo; }
2
@Override public void doRound(Game game){ Iterator<Player> it = game.getPlayerList().iterator(); Player player1 = it.next(); Player player2 = it.next(); int roll1 = player1.doRoll(); int roll2 = player2.doRoll(); if(roll1>roll2){ roll1=roll2-2; roll2=roll2+2; }else if(roll2>roll1){ roll2=roll1-2; roll1=roll1+2; } this.getRollResult().add(roll1); this.getRollResult().add(roll2); storeResult(); }
2
private boolean lataaPelaaja() { String[] pelaajat = PelaajatIO.haeLadattavatPelaajat(); if (pelaajat == null || pelaajat.length == 0) { System.out.println("Ei ladattavia pelaajia."); return false; } System.out.println("\nLadattavat pelaajat:"); for (String p : pelaajat) { String nimi = p.substring(0, p.length() - 2); System.out.println(nimi); } while (true) { String nimi = kysyString("Anna ladattavan pelaajan nimi:"); try { if (!pelilauta.lataaPelaaja(nimi)) { System.out.println("Nimellä " + nimi + " ei löytynyt pelaajaa."); continue; } return true; } catch (IOException e) { System.out.println("Pelaajan lataus epäonnistui!"); System.exit(0); } catch (ClassCastException e) { System.out.println("Ladattavan pelaajan tiedosto oli väärässä muodossa."); return false; } catch (ClassNotFoundException e) { return false; } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); return false; } } }
9
@Override public void initialize(URL url, ResourceBundle rb) { udpflood = new UDPFlood(); }
0
public void setLocation(Location newLocation) { // If either the add or remove involves a colony, call the // colony-specific routine... Colony oldColony = (location instanceof WorkLocation) ? this.getColony() : null; Colony newColony = (newLocation instanceof WorkLocation) ? newLocation.getColony() : null; // However if the unit is moving within the same colony, // do not call the colony-specific routines. if (oldColony == newColony) oldColony = newColony = null; boolean result = true; if (location != null) { result = (oldColony != null) ? oldColony.removeUnit(this) : location.remove(this); } /*if (!result) return false;*/ location = newLocation; // Explore the new location now to prevent dealing with tiles // with null (unexplored) type. getOwner().setExplored(this); // It is possible to add a unit to a non-specific location // within a colony by specifying the colony as the new // location. if (newLocation instanceof Colony) { newColony = (Colony) newLocation; location = newLocation = newColony.getWorkLocationFor(this); } if (newLocation != null) { result = (newColony != null) ? newColony.addUnit(this, (WorkLocation) newLocation) : newLocation.add(this); } return /*result*/; }
8
public static int unsignedShort (byte[] byteArray, int selector, int byteOrdering) { // byteOrdering tells how bytes are stored // selector should always point to lowest byte position of range // local vars int a = 0 ; // case out on the storage scheme switch (byteOrdering) { case HI_TO_LO: // aka BIG_ENDIAN a = ((int) (byteArray[selector++] & 0xFF)) << 8; a += ((int) (byteArray[selector] & 0xFF)) ; break ; case LO_TO_HI: // aka LITTLE_ENDIAN a = ((int) (byteArray[selector++] & 0xFF)) ; a += ((int) (byteArray[selector++] & 0xFF)) << 8; break ; default: break ; } // end switch // bye bye return a ; } // end method unsignedShort
2
private void calculateNextRandomDirection() { int newDirection = randomGenerator.nextInt(4); while (!isAValidDirection(newDirection)) { newDirection = (newDirection + 1) % 4; } setDirection(newDirection); }
1
private void eliminarTarea(String titulo) { int indice; switch (jCBEstado.getSelectedIndex()) { case 1: indice = buscarTarea(this.proyectos.get(index).getProximo(), titulo); if (indice != -1) { this.proyectos.get(index).getProximo().remove(indice); } break; case 2: indice = buscarTarea(this.proyectos.get(index).getHaciendo(), titulo); if (indice != -1) { this.proyectos.get(index).getHaciendo().remove(indice); } break; case 3: indice = buscarTarea(this.proyectos.get(index).getHecho(), titulo); if (indice != -1) { this.proyectos.get(index).getHecho().remove(indice); } break; default: indice = buscarTarea(this.proyectos.get(index).getEspera(), titulo); if (indice != -1) { this.proyectos.get(index).getEspera().remove(indice); } break; } jTabla.updateUI(); }
7
public void nextMove() { if (exitDelay > 0) { exitDelay--; return; } progress(PIXELS); nextPhotogram(); }
1
private Set<SootClass> collectAllInterfaces(SootClass sootClass) { Set<SootClass> interfaces = new HashSet<SootClass>(sootClass.getInterfaces()); for (SootClass i : sootClass.getInterfaces()) interfaces.addAll(collectAllInterfaces(i)); return interfaces; }
1
private static byte[] parseBase64Binary(String str) { // strict parser, must have length divisble by 4 if (str.length() % 4 != 0) { throw new IllegalArgumentException("Invalid Base64 string"); } // base64Str has 65 characters, with '=' at the end which is masked away int parsedLen = (str.length() * 3) / 4; byte[] decoded = new byte[parsedLen]; char[] inChars = str.toCharArray(); int pos = 0; for (int i = 0; i < inChars.length; ) { int bits = (base64Str.indexOf(inChars[i++]) & MASK_6BIT) << 18 | (base64Str.indexOf(inChars[i++]) & MASK_6BIT) << 12 | (base64Str.indexOf(inChars[i++]) & MASK_6BIT) << 6 | (base64Str.indexOf(inChars[i++]) & MASK_6BIT); decoded[pos++] = (byte) ((bits >>> 16) & MASK_8BIT); decoded[pos++] = (byte) ((bits >>> 8) & MASK_8BIT); decoded[pos++] = (byte) (bits & MASK_8BIT); } // fixup avoiding Arrays.copyRange if (str.endsWith("==")) { byte[] result = new byte[parsedLen - 2]; System.arraycopy(decoded, 0, result, 0, parsedLen - 2); return result; } else if (str.endsWith("=")) { byte[] result = new byte[parsedLen - 1]; System.arraycopy(decoded, 0, result, 0, parsedLen - 1); return result; } return decoded; }
4
public void createIndexArff(String in, ArrayList<Integer> years) { String result = ""; int instances = 0; result += "@RELATION " + in + "\r\n"; result += "@ATTRIBUTE day NUMERIC " + "\r\n"; result += "@ATTRIBUTE djia NUMERIC " + "\r\n"; result += "@ATTRIBUTE nasdaq NUMERIC " + "\r\n"; result += "@ATTRIBUTE eurostoxx NUMERIC " + "\r\n"; result += "@ATTRIBUTE dollar NUMERIC " + "\r\n"; result += "@ATTRIBUTE euro NUMERIC " + "\r\n"; result += "@ATTRIBUTE gain NUMERIC " + "\r\n"; result += "@ATTRIBUTE price NUMERIC " + "\r\n"; result += "@DATA " + "\r\n"; String indexName = in.toUpperCase(); for (Integer i : years) { try { File f = new File("src/datas/indices/" + indexName + "/" + indexName + "_" + i.toString() + ".csv"); Scanner sc = new Scanner(f); String line = ""; String ld = ""; while (sc.hasNext()) { line = sc.nextLine(); String date = line.split(";")[0]; if (!date.equals(ld)) { instances++; String price = line.split(";")[1].equals("N/A") ? "?" : line.split(";")[1]; String gain = line.split(";")[2].equals("N/A") ? "?" : line.split(";")[2]; String replacePrice = price.replace(",", "."); String replaceGain = gain.replace(",", "."); String toSave = instances + "," + djiaData[instances - 1] + "," + nasdaqData[instances - 1] + "," + eurostoxxData[instances - 1] + "," + dollarData[instances - 1] + "," + euroData[instances - 1] + "," + replaceGain + "," + replacePrice + "\r\n"; result += toSave; for (Node n : indices) { if (n.getKey().equals(in)) { n.value[instances - 1] = replacePrice; break; } } } ld = date; } } catch (FileNotFoundException ex) { Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null, ex); } } result = "%" + instances + "\r\n" + result; try { File f = new File("src/datas/indices/" + indexName + "/" + indexName + ".arff"); f.delete(); f.createNewFile(); PrintWriter out = null; out = new PrintWriter(new BufferedWriter(new FileWriter("src/datas/indices/" + indexName + "/" + indexName + ".arff", true))); out.print(result); out.close(); } catch (IOException ex) { Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null, ex); } }
9
@Override public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { String data; try { ArrayList<FilterBean> alFilter = new ArrayList<>(); if (request.getParameter("filter") != null) { if (request.getParameter("filteroperator") != null) { if (request.getParameter("filtervalue") != null) { FilterBean oFilterBean = new FilterBean(); oFilterBean.setFilter(request.getParameter("filter")); oFilterBean.setFilterOperator(request.getParameter("filteroperator")); oFilterBean.setFilterValue(request.getParameter("filtervalue")); oFilterBean.setFilterOrigin("user"); alFilter.add(oFilterBean); } } } if (request.getParameter("systemfilter") != null) { if (request.getParameter("systemfilteroperator") != null) { if (request.getParameter("systemfiltervalue") != null) { FilterBean oFilterBean = new FilterBean(); oFilterBean.setFilter(request.getParameter("systemfilter")); oFilterBean.setFilterOperator(request.getParameter("systemfilteroperator")); oFilterBean.setFilterValue(request.getParameter("systemfiltervalue")); oFilterBean.setFilterOrigin("system"); alFilter.add(oFilterBean); } } } ComisionDao oComisionDAO = new ComisionDao(Conexion.getConection()); int pages = oComisionDAO.getCount(alFilter); data = "{\"data\":\"" + Integer.toString(pages) + "\"}"; return data; } catch (Exception e) { throw new ServletException("ComisionGetregistersJson: View Error: " + e.getMessage()); } }
7
private void getStayHotelCollection(AbstractDao dao, List<Direction> directions) throws DaoException { for (Direction dir : directions) { Criteria crit = new Criteria(); crit.addParam(DAO_ID_DIRECTION, dir.getIdDirection()); List<DirectionStayHotel> stays = dao.findDirectionStayHotel(crit); dir.setStayCollection(getHotelInfo(dao, stays)); } }
1
public ReturnObject get(int i) { ReturnObjectImpl returnValue = new ReturnObjectImpl(); if (i < 0 || i >= size()) { returnValue.value = ErrorMessage.INDEX_OUT_OF_BOUNDS; return returnValue; } if (nextElement.index == i) { returnValue.value = nextElement.value; return returnValue; } else { return nextElement.get(i); } }
3
protected String runProgramGetResp (List<String> args) throws IOException, InterruptedException { logger.entering(getClass().getName(), "runProgramGetResp", args); String response = ""; ProcessBuilder procBuilder = new ProcessBuilder(args); Process proc = procBuilder.start(); proc.waitFor(); // Evaluate exit value. int ev = proc.exitValue(); if (ev != 0) { StringBuffer errSB = new StringBuffer(); errSB.append(args.get(0) + ": returned " + ev + "."); InputStreamReader err = new InputStreamReader(proc.getErrorStream()); char[] cbuf = new char[8192]; int length = err.read(cbuf); if (length > 0) { errSB.append("\n" + new String(cbuf, 0, length)); } err.close(); throw new IOException(errSB.toString()); } InputStream is = proc.getInputStream(); // to capture output from command response = convertStreamToStr(is); logger.finer("runProgramGetResp response: " + response); logger.exiting(getClass().getName(), "runProgramGetResp"); return response; }
2
@Override public void performAction() { if(!started) { performActionStartup(); } else { unit.addX(pathSegment.getDir().x); unit.addY(pathSegment.getDir().y); } }
1
public void generateUpdatedEntries() { _modifiedEntries.clear(); HashSet<String> newEntries = new HashSet<String>(); for (int i = 0; i < 5; i++) { OrderEntry orderEntry = null; int action = _random.nextInt(100); if (_orderEntries.size() == 0 || action >= _deleteFactor + _updateFactor) { // Action Add if (_orderEntries.size() >= _maxEntries) { continue; } orderEntry = getNewOrder(); _orderEntries.add(orderEntry); } else if (action < _deleteFactor) { // Action Delete int index = _random.nextInt(_orderEntries.size()); orderEntry = (OrderEntry)_orderEntries.get(index); if (newEntries.contains(orderEntry.provSymb)) { continue; } orderEntry.action = OMMMapEntry.Action.DELETE; _orderEntries.remove(orderEntry); } else { // Action Update int index = _random.nextInt(_orderEntries.size()); OrderEntry updateEntry = (OrderEntry)_orderEntries.get(index); if (newEntries.contains(updateEntry.provSymb)) { continue; } updateOrder(updateEntry); orderEntry = (OrderEntry)updateEntry.clone(); orderEntry.action = OMMMapEntry.Action.UPDATE; } newEntries.add(orderEntry.provSymb); _modifiedEntries.add(orderEntry); } }
7
public boolean isLambdaTransition(Transition transition) { PDATransition trans = (PDATransition) transition; String input = trans.getInputToRead(); String toPop = trans.getStringToPop(); String toPush = trans.getStringToPush(); if (input.equals(LAMBDA) && toPop.equals(LAMBDA) && toPush.equals(LAMBDA)) return true; return false; }
3
public long overlap(Interval interval) { long millis = 0; for (Interval i : this) { Interval match = interval.overlap(i); if (match != null && match.toDurationMillis() > 0) { millis += match.toDurationMillis(); } } return millis; }
3
protected boolean generateNext(){ int[] actors = getActors(); // if not yet initialized do it if (actors == null){ actors = new int[ actorLength ]; actors[actorLength - 1] = 1; setActors(actors); return true; } // move onto the next scenario, which is greater than the previous by 1 else{ int actor; int overflow = 1; for (int i=actorLength-1; i>=0; i--){ actor = actors[i]; switch(actor + overflow){ case 1: actors[i] = 1; overflow = 0; break; case 2: actors[i] = 0; overflow = 1; break; case 3: actors[i] = 1; overflow = 1; break; } if (overflow == 0){ break; } } int numberOfOnes = 0; for (int i=0; i<actorLength;i++){ if (actors[i] == 1){ numberOfOnes++; } } if (numberOfOnes < actorLength){ return true; } else{ return false; } } }
9
private String replaceHexWithNames(String line) { int indexOfhash = line.indexOf("#"); if (line.length() >= 7 && indexOfhash != -1 && indexOfhash + 7 <= line.length()) { String colorHex = line.substring(indexOfhash + 1, indexOfhash + 7); int endOfHex = -1; if (colorHex.matches("[a-fA-F0-9][a-fA-F0-9][a-fA-F0-9][a-fA-F0-9][a-fA-F0-9][a-fA-F0-9]")) { endOfHex = indexOfhash + 7; } else { colorHex = line.substring(indexOfhash + 1, indexOfhash + 4); if (colorHex.matches("[a-fA-F0-9][a-fA-F0-9][a-fA-F0-9]")) { endOfHex = indexOfhash + 4; } } //System.out.println(colorHex + " " + indexOfhash + ")(" + endOfHex); if (hexToColors.containsKey(colorHex)) { colorHex = hexToColors.get(colorHex); } } return line; }
6
public int size() { return size; }
0
public byte[] decompress(HuffmanTree tree, int uncompressedLength, Byte[] byteArray) { System.out.println("Decompressing Byte[]."); System.out.println("Compressed Message ByteCount: " + byteArray.length); // For each byte, // Get each byte's value from the huffman tree. // Compose the new values. List<Byte> newByteList = new ArrayList<Byte>(); Bits bits = new Bits(); //Add each byte to bits. for (Byte b : byteArray) { boolean[] bitsInByte = bits(b); b = Byte.valueOf(Integer.toString(b.intValue())); for (int i = 0; i < 8; i++) { bits.add(bitsInByte[i]); } } System.out.println("ByteCount = " + bits.size() / 8); //This is 52389 with JC's thing. //Get the codes using bits. while(bits.size() > 0){ newByteList.add(tree.toByte(bits)); } System.out.println("ByteCount = " + newByteList.size()); //This is 55035 // Bits now represents byteArray after huffman decoding. System.out.println("NewByteListBuilt."); System.out.println("Transferring from Bytes to bytes."); byte[] resultbytes = new byte[newByteList.size()]; int i = 0; for (Byte b : newByteList) { resultbytes[i++] = b; } System.out.println("Returning decompressed Byte Array."); System.out.println("Decompressed ByteCount: " + resultbytes.length); return resultbytes; }
4
static final Class348_Sub41 method2661(int i, int i_0_, int i_1_, boolean bool, int i_2_) { if (i_2_ != 2) method2661(31, -43, 32, true, -110); anInt4189++; Class348_Sub41 class348_sub41 = new Class348_Sub41(); ((Class348_Sub41) class348_sub41).anInt7050 = i; ((Class348_Sub41) class348_sub41).anInt7053 = i_1_; Class125.aClass356_4915.putNode((long) i_0_, class348_sub41); Class348_Sub7.method2772(i, (byte) 110); Widget class46 = AbstractFontRasterizer.getWidget(i_0_); if (class46 != null) Class251.method1916(-9343, class46); if (BufferedRasterizer.aClass46_4730 != null) { Class251.method1916(-9343, BufferedRasterizer.aClass46_4730); BufferedRasterizer.aClass46_4730 = null; } Class348_Sub42_Sub17.method3270((byte) 120); if (class46 != null) Class251.method1913(!bool, i_2_ + -104, class46); if (!bool) ScriptExecutor.method703(i); if (!bool && (r.anInt9721 ^ 0xffffffff) != 0) Class239_Sub12.method1775((byte) -8, r.anInt9721, 1); return class348_sub41; }
7
public static File createTestTempFileOrDir(File parent, String name, boolean dir) throws IOException { File f = new File(parent, name); f.deleteOnExit(); if (dir && !f.mkdirs()) { throw new IOException("디렉토리를 생성할 수 없습니다: " + f); } return f; }
2
@RequestMapping(value = "/room-event-picture-list/{roomEventId}", method = RequestMethod.GET) @ResponseBody public CreativeMaterialListResponse roomEventPictureList( @PathVariable(value = "roomEventId") final String roomEventIdStr ) { return typedCreativeMaterialList(roomEventIdStr, CreativeMaterialType.PICTURE_TYPE_NAME); }
0
public Vector<Move> commuteNextMove ( ) { final Vector<Move> moves = new Vector<Move> ( ) ; /* * Go through each square on the board and if it is blank get the words from * it by going though each word in the dictionary and getting the up and * down words from it. */ for ( int i = 0 ; i < Player.board.boardHeight ; i++ ) { for ( int j = 0 ; j < Player.board.boardWidth ; j++ ) { if ( Player.board.charGrid[ i ][ j ] != Player.board.blank ) { for ( final Word word : this.dictionary.dictionary ( ) ) { this.getMovesFromWord ( word, i, j, moves, true ) ; ; this.getMovesFromWord ( word, i, j, moves, false ) ; } } } } Collections.sort ( moves, new MoveComparator ( ) ) ; return moves ; }
4
@Override public void updateLong() { super.updateLong(); if (inventory.getUsedSlots() == 0) { isDirty = true; } }
1
public static Dimension extractDimension(String buffer) { int[] values = extractIntegers(buffer); if (values.length == 2) { return new Dimension(values[0], values[1]); } return null; }
1
public StringBuffer showWhoShort(MOB who, int[] colWidths) { final StringBuffer msg=new StringBuffer(""); msg.append("["); if(!CMSecurity.isDisabled(CMSecurity.DisFlag.RACES)) { if(who.charStats().getCurrentClass().raceless()) msg.append(CMStrings.padRight(" ",colWidths[0])+" "); else msg.append(CMStrings.padRight(who.charStats().raceName(),colWidths[0])+" "); } String levelStr=who.charStats().displayClassLevel(who,true).trim(); final int x=levelStr.lastIndexOf(' '); if(x>=0) levelStr=levelStr.substring(x).trim(); if(!CMSecurity.isDisabled(CMSecurity.DisFlag.CLASSES)) { if(who.charStats().getMyRace().classless()) msg.append(CMStrings.padRight(" ",colWidths[1])+" "); else msg.append(CMStrings.padRight(who.charStats().displayClassName(),colWidths[1])+" "); } if(!CMSecurity.isDisabled(CMSecurity.DisFlag.LEVELS)) { if(who.charStats().getMyRace().leveless() ||who.charStats().getCurrentClass().leveless()) msg.append(CMStrings.padRight(" ",colWidths[2])); else msg.append(CMStrings.padRight(levelStr,colWidths[2])); } String name=getWhoName(who); msg.append("] "+CMStrings.padRight(name,colWidths[3])); msg.append("\n\r"); return msg; }
8
public int getPageNumber(PDFObject page) throws IOException { if (page.getType() == PDFObject.ARRAY) { page = page.getAt(0); } // now we've got a page. Make sure. PDFObject typeObj = page.getDictRef("Type"); if (typeObj == null || !typeObj.getStringValue().equals("Page")) { return 0; } int count = 0; while (true) { PDFObject parent = page.getDictRef("Parent"); if (parent == null) { break; } PDFObject kids[] = parent.getDictRef("Kids").getArray(); for (int i = 0; i < kids.length; i++) { if (kids[i].equals(page)) { break; } else { PDFObject kcount = kids[i].getDictRef("Count"); if (kcount != null) { count += kcount.getIntValue(); } else { count += 1; } } } page = parent; } return count; }
8
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; LinhaVenda other = (LinhaVenda) obj; if (id != other.id) return false; return true; }
4
public final T getInTestLinkListener() { return inTestLinkListener; }
0
protected void _upload( BlobInfo bi, String tag ) throws ServerError, IOException { if( bi instanceof FileInfo ) { transferTracker.sendingFile( ((FileInfo)bi).getPath() ); } InputStream is = bi.openInputStream(); try { URL url = urlFor(bi.getUrn()); if( inducePutErrors ) { throw new ServerError("Not a real server error; yuk yuk.", 599, null, "PUT", url.toString()); } HttpURLConnection urlCon = (HttpURLConnection)url.openConnection(); urlCon.setRequestMethod("PUT"); urlCon.setDoOutput(true); OutputStream os = urlCon.getOutputStream(); int totalSize = 0; try { byte[] buf = new byte[1024*1024]; int r; while( (r = is.read(buf)) > 0 ) { totalSize += r; os.write(buf, 0, r); } } finally { os.close(); } int status = urlCon.getResponseCode(); if( debug ) System.err.println("PUT "+url+" ("+totalSize+" bytes) -> "+status); if( status < 200 || status >= 300 ) { byte[] errorText = null; try { errorText = StreamUtil.slurp(urlCon.getErrorStream()); } catch( Exception e ) { } throw new ServerError( "PUT received unexpected response code "+status+"; "+urlCon.getResponseMessage(), status, errorText, "PUT", url.toString() ); } } finally { is.close(); } transferTracker.transferred(bi.getSize(), 1, tag); }
7
public static void main(String[] args) { if (args.length != 2) { System.out.println("Usage: CopyFile source target"); return; } String sourceName = args[0]; String targetName = args[1]; FileReader sourceFile = null; FileWriter targetFile = null; Scanner source = null; try { sourceFile = new FileReader(sourceName); } catch (FileNotFoundException e) { System.out.println("Source file `" + sourceName + "` not found!"); return; } try { targetFile = new FileWriter(targetName); source = new Scanner(sourceFile); StringBuilder writeBuffer = new StringBuilder(); while (source.hasNext()) { writeBuffer.append(source.nextLine()).append("\r\n"); } targetFile.write(writeBuffer.toString().trim()); } catch (IOException e) { System.out.println("You do not have the necessary privileges to write to `" + targetName +"`."); return; } finally { if (sourceFile != null) { try { sourceFile.close(); } catch (IOException e) { System.out.println("There was an error closing `" + sourceName + "`."); return; } } if (targetFile != null) { try { targetFile.close(); } catch (IOException e) { System.out.println("There was an error closing `" + targetName + "`."); return; } } if (source != null) { source.close(); } } System.out.println("Contents of `" + sourceName + "` successfully copied to `" + targetName + "`."); }
9
public void send(final byte[] frame, final boolean waitForCon) throws KNXPortClosedException, KNXAckTimeoutException, InterruptedException { final boolean group = (frame[3] & 0x80) == 0x80; KNXAddress dst = null; if (group) { dst = new GroupAddress(new byte[] { frame[6], frame[7] }); addresses.add(dst); } try { final byte[] data = toUartServices(cEmiToTP1(frame)); if (logger.isLoggable(LogLevel.TRACE)) logger.trace("UART services " + DataUnitBuilder.toHex(data, " ")); req = (byte[]) frame.clone(); final long start = System.nanoTime(); synchronized (enterIdleLock) { if (!idle) enterIdleLock.wait(); } if (logger.isLoggable(LogLevel.TRACE)) { logger.trace("UART ready for sending after " + (System.nanoTime() - start) / 1000 + " us"); logger.trace("write UART services, " + (waitForCon ? "waiting for .con" : "non-blocking")); } os.write(data); state = ConPending; if (!waitForCon) return; if (waitForCon()) return; throw new KNXAckTimeoutException("no ACK for L-Data.con"); } catch (final InterruptedIOException e) { throw new InterruptedException(e.getMessage()); } catch (final IOException e) { close(); throw new KNXPortClosedException("I/O error", portId, e); } finally { req = null; addresses.remove(dst); } }
9
public static String removeStart(String str, String remove) { if (isEmpty(str) || isEmpty(remove)) { return str; } if (str.startsWith(remove)) { return str.substring(remove.length()); } return str; }
3
public <A extends Appendable> A appendTo(A appendable, Iterator<?> parts) { try { if (parts.hasNext()) { appendable.append(toString(parts.next())); while (parts.hasNext()) { appendable.append(separator); appendable.append(toString(parts.next())); } } return appendable; } catch (IOException e) { throw new RuntimeException(e); } }
4
@Override public void render(Art art, Level level) { if (!collected) { frame++; frame %= (4 * 6); art.drawTile(art.spriteSheet, getX(), getY(), 13 + frame / 6, 8); } }
1
private void thresholdEdges() { for (int i = 0; i < picsize; i++) { data[i] = data[i] > 0 ? -1 : 0xff000000; } }
2
private void generateInitialRooms() { for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { // create north walls rooms[i][j] = new Room(i, j); if (i == 0) { rooms[i][j].north = new Wall(rooms[i][j]); } else { rooms[i][j].north = new Wall(rooms[i - 1][j], rooms[i][j]); walls.add(rooms[i][j].north); } if (i == height - 1) { rooms[i][j].south = new Wall(rooms[i][j]); } if (j == 0) { rooms[i][j].west = new Wall(rooms[i][j]); } else { rooms[i][j].west = new Wall(rooms[i][j - 1], rooms[i][j]); walls.add(rooms[i][j].west); } if (j == width - 1) { rooms[i][j].east = new Wall(rooms[i][j]); } rooms[i][j].roomName = roomNumber++;// we will name the rooms } } // initalize entrance and exit rooms[0][0].west.isGone = true;// you can replace .west.isGone with .north.isGone // this is just saying the roomName for top left is 0 rooms[0][0].roomName = 0; // we will remove the south wall of the last room rooms[height - 1][width - 1].south.isGone = true; // this is just saying the roomName for bottom right is the last element in the mxn room matrix rooms[height - 1][width - 1].roomName = (height * width); }
6
public void handleImmediateReservation(ARObject obj, int senderID, int sendTag) { // check whether the requested PE is sufficient to handle or not if (obj.getNumPE() > super.totalPE_) { super.replyCreateReservation(senderID, sendTag, NOT_FOUND, GridSimTags.AR_CREATE_FAIL_RESOURCE_NOT_ENOUGH_PE); return; } // at the moment, this scheduler doesn't support immediate reservations // with duration or end time = 0. if (obj.getDurationTime() <= 0) { System.out.println(super.get_name() + ".handleImmediateReservation(): Error - can't handle " + "duration or end time = 0."); super.replyCreateReservation(senderID, sendTag, NOT_FOUND, GridSimTags.AR_CREATE_ERROR_INVALID_END_TIME); return; } // for immediate reservations, start time is the current time long startTime = super.getCurrentTime(); obj.setStartTime(startTime); // determine when it will be expired. For immediate reservation, // expiry time is the finish or end time long expTime = startTime + (obj.getDurationTime() * super.MILLI_SEC); // check the start time against the availability // case 1: if the list is empty if (reservList_.size() == 0) { acceptReservation(obj, 0, senderID, sendTag, expTime, false); } else { // case 2: if list is not empty, find the available slot int pos = findEmptySlot(startTime, expTime, obj.getNumPE()); // able to find empty slot(s) if (pos > NOT_FOUND) { acceptReservation(obj, pos, senderID, sendTag, expTime, false); } // not able to find any slots. Here pos contains a busy time tag. else { super.replyCreateReservation(senderID, sendTag, NOT_FOUND, pos); } } }
4
private void moveOnY(Vector<Integer> ans, int xDis, int yDis){ if (yDis >= 0){ ans.add(0); if (xDis >= 0){ ans.add(1); ans.add(2); ans.add(3); } else { ans.add(3); ans.add(2); ans.add(1); } } else { ans.add(2); if (xDis >= 0){ ans.add(1); ans.add(0); ans.add(3); } else { ans.add(3); ans.add(0); ans.add(1); } } }
3
public Date getLetzteZahlung() { if (letztezahlung == null) { Date d = null; for (Rechnung r : rechnungCollection) { if (r.getEingang() != null) { if (d == null) { d = r.getEingang(); } else { if (d.before(r.getEingang())) { d = r.getEingang(); } } } } return d; } else { return letztezahlung; } }
5
static public ParseException generateParseException() { jj_expentries.clear(); boolean[] la1tokens = new boolean[57]; if (jj_kind >= 0) { la1tokens[jj_kind] = true; jj_kind = -1; } for (int i = 0; i < 0; i++) { if (jj_la1[i] == jj_gen) { for (int j = 0; j < 32; j++) { if ((jj_la1_0[i] & (1<<j)) != 0) { la1tokens[j] = true; } if ((jj_la1_1[i] & (1<<j)) != 0) { la1tokens[32+j] = true; } } } } for (int i = 0; i < 57; i++) { if (la1tokens[i]) { jj_expentry = new int[1]; jj_expentry[0] = i; jj_expentries.add(jj_expentry); } } int[][] exptokseq = new int[jj_expentries.size()][]; for (int i = 0; i < jj_expentries.size(); i++) { exptokseq[i] = jj_expentries.get(i); } return new ParseException(token, exptokseq, tokenImage); }
9
@SuppressWarnings("unchecked") public ListTag<? extends Tag> getList(String name) { if (!tags.containsKey(name)) return new ListTag<Tag>(name); return (ListTag<? extends Tag>) tags.get(name); }
3
public static boolean controlDirectory(Path p) { return ((p != null) && Files.exists(p, LinkOption.NOFOLLOW_LINKS) && Files.isDirectory(p, LinkOption.NOFOLLOW_LINKS)); }
2
public static void calc(int[] input, int pivot) { int index = -1; int countl = 0; int countr = 0; for (int i = 0; i < input.length; i++) { if (input[i] == pivot) { index = i; } } HashSet<Integer> hs = new HashSet<Integer>(); int j = 0; int k = index + 1; while (j < index) { if (input[j] < pivot && !hs.contains(input[j])) { countl++; hs.add(input[j]); } j++; } while (k < input.length) { if (input[k] > pivot && !hs.contains(input[k])) { countr++; hs.add(input[k]); } k++; } System.out.println("Less than pivot " + countl + " Greater than pivot " + countr); }
8
public void frechetProbabilityPlot(){ this.lastMethod = 7; // Check for suffient data points this.frechetNumberOfParameters = 3; if(this.numberOfDataPoints<4)throw new IllegalArgumentException("There must be at least four data points - preferably considerably more"); // Create instance of Regression Regression min = new Regression(this.sortedData, this.sortedData); // Calculate initial estimates double[] start = new double[3]; start[0] = this.minimum - 0.1*Math.abs(this.minimum); start[1] = this.peakWidth()/3.0; if(start[1]<1.0)start[1] = 2.0; start[2] = 4.0; this.initialEstimates = start; double[] step = {Math.abs(0.3*start[0]), Math.abs(0.3*start[1]), Math.abs(0.3*start[2])}; if(step[0]==0)step[0] = this.range*0.01; double tolerance = 1e-10; // Add constraint; mu<minimum, sigma>0, gamma>0 min.addConstraint(0, +1, minimum); min.addConstraint(1, -1, 0); min.addConstraint(2, -1, 0); // Create an instance of FrechetProbPlotFunc FrechetProbPlotFunc fppf = new FrechetProbPlotFunc(); fppf.setDataArray(this.numberOfDataPoints); // Obtain best probability plot varying mu, sigma and gamma // by minimizing the sum of squares of the differences between the ordered data and the ordered statistic medians min.simplex(fppf, Conv.copy(start), step, tolerance); // Obtain best estimates or first minimisation double[] firstBests = min.getBestEstimates(); double ss = min.getSumOfSquares(); //Calculate new initial estimates double[] start2 = new double[this.frechetNumberOfParameters]; start2[0] = 2.0*firstBests[0] - start[0]; if(start2[0]>minimum)start2[0] = minimum*(1.0 - Math.abs(minimum)*0.05); step[0] = Math.abs(start2[0]*0.1); if(step[0]==0)step[0] = this.range*0.01; start2[1] = 2.0*firstBests[1] - start[1]; if(start2[1]<=0.0)start2[1] = Math.abs(2.0*firstBests[1] - 0.98*start[1]); step[1] = Math.abs(start2[1]*0.1); start2[2] = 2.0*firstBests[2] - start[2]; if(start2[1]<=0.0)start2[2] = Math.abs(2.0*firstBests[2] - 0.98*start[2]); step[2] = Math.abs(start2[2]*0.1); min.simplex(fppf, Conv.copy(start2), step, tolerance); // Get mu, sigma and gamma for best correlation coefficient this.frechetParam = min.getBestEstimates(); double ss2 = min.getSumOfSquares(); if(ss<ss2)this.frechetParam = firstBests; // Calculate Frechet order statistic medians this.frechetOrderMedians = Stat.frechetOrderStatisticMedians(this.frechetParam[0], this.frechetParam[1], this.frechetParam[2], this.numberOfDataPoints); // Regression of the ordered data on the Frechet order statistic medians Regression reg = new Regression(this.frechetOrderMedians, this.sortedData); reg.linear(); // Intercept and gradient of best fit straight line this.frechetLine = reg.getBestEstimates(); // Estimated erors of the intercept and gradient of best fit straight line this.frechetLineErrors = reg.getBestEstimatesErrors(); // Correlation coefficient this.frechetCorrCoeff = reg.getSampleR(); // Initialize data arrays for plotting double[][] data = PlotGraph.data(2,this.numberOfDataPoints); // Assign data to plotting arrays data[0] = this.frechetOrderMedians; data[1] = this.sortedData; data[2] = frechetOrderMedians; for(int i=0; i<this.numberOfDataPoints; i++){ data[3][i] = this.frechetLine[0] + this.frechetLine[1]*frechetOrderMedians[i]; } // Create instance of PlotGraph PlotGraph pg = new PlotGraph(data); int[] points = {4, 0}; pg.setPoint(points); int[] lines = {0, 3}; pg.setLine(lines); pg.setXaxisLegend("Frechet Order Statistic Medians"); pg.setYaxisLegend("Ordered Data Values"); pg.setGraphTitle("Frechet probability plot: gradient = " + Fmath.truncate(this.frechetLine[1], 4) + ", intercept = " + Fmath.truncate(this.frechetLine[0], 4) + ", R = " + Fmath.truncate(this.frechetCorrCoeff, 4)); pg.setGraphTitle2(" mu = " + Fmath.truncate(this.frechetParam[0], 4) + ", sigma = " + Fmath.truncate(this.frechetParam[1], 4) + ", gamma = " + Fmath.truncate(this.frechetParam[2], 4)); // Plot pg.plot(); this.frechetDone = true; this.probPlotDone = true; }
9
public Object getField(Reference ref, Object obj) throws InterpreterException { if (isWhite(ref)) return super.getField(ref, obj); FieldIdentifier fi = (FieldIdentifier) Main.getClassBundle() .getIdentifier(ref); if (fi != null && !fi.isNotConstant()) { Object result = fi.getConstant(); if (currentFieldListener != null) fi.addFieldListener(currentFieldListener); if (result == null) result = getDefaultValue(ref.getType()); return result; } throw new InterpreterException("Field " + ref + " not constant"); }
5
@Override public double distribute(TVC newCon) { Random r = new Random(); Firewall[] firewalls = environment.getFirewalls(); // forget about all links and redistribute connections from scratch for (TVC c : environment.getConnectionsSortedUp()) { int managerFirewallId = r.nextBoolean() ? c.getFirewallId1() : c.getFirewallId2(); firewalls[managerFirewallId].manageConnection(c); } return environment.dispersion(); }
2
private void checkStatusActive(Integer adresse, Integer value) { if(adresse == 0x03 || adresse == 0x83){ String logstring = "[Aktive Beeinträchtigung des Statusregisters]: "; //CARRY if( (value & 0x01) == 0x01){ //Carrybit manuell gesetzt status.setBit(bits.C); PIC_Logger.logger.info(logstring+"Set C"); } else{ //Carrybit gelöscht status.clearBit(bits.C); PIC_Logger.logger.info(logstring+"Clear C"); } //DC BIT if( (value & 0x02) == 0x02){ //DC GESETZT status.setBit(bits.DC); PIC_Logger.logger.info(logstring+"Set DC"); } else{ //DC GELÖSCHT status.clearBit(bits.DC); PIC_Logger.logger.info(logstring+"Clear DC"); } //Z if( (value & 0x04) == 0x04){ //Z GESETZT status.setBit(bits.Z); PIC_Logger.logger.info(logstring+"Set Z"); } else{ //Z GELÖSCHT status.clearBit(bits.Z); PIC_Logger.logger.info(logstring+"Clear Z"); } //RP0 if( (value & 0x20) == 0x20){ //RP0 GESETZT status.setBit(bits.RP0); ram.setBank(Bank.BANK1); PIC_Logger.logger.info(logstring+"Switched to Bank1"); } else{ //RP0 GELÖSCHT status.clearBit(bits.RP0); ram.setBank(Bank.BANK0); PIC_Logger.logger.info(logstring+"Switched to Bank0"); } } }
6
public void render(int x , int y , int startX , int startY , Graphics g) { if(preMode) { diary.draw(); } else { if(music.playing() == false) music.loop(); map.render(0, 0 , startX + x , startY + y , 100 , 100); g.drawString(" " + (float)((timer - elapsedTime) / 1000), 350 , 25); } }
2
public void add(Object o) throws PropertyException { if (o instanceof Event) addEvent((Event)o); else if (o instanceof Note) addNote((Note)o); else throw new PropertyException("Unable to add object of type " + o.getClass().getName() + " to a Family"); }
2
private int choiceLeft() { if (round == 0) return nplayers - getIndex()- npassed+1; else return nplayers - npassed+2; }
1
public int filterRow(byte[] currRow, byte[] prevRow, byte[][] scratchRows, int bytesPerRow, int bytesPerPixel) { int[] filterBadness = new int[5]; for (int i = 0; i < 5; i++) { filterBadness[i] = Integer.MAX_VALUE; } { int badness = 0; for (int i = bytesPerPixel; i < bytesPerRow + bytesPerPixel; i++) { int curr = currRow[i] & 0xff; badness += curr; } filterBadness[0] = badness; } { byte[] subFilteredRow = scratchRows[1]; int badness = 0; for (int i = bytesPerPixel; i < bytesPerRow + bytesPerPixel; i++) { int curr = currRow[i] & 0xff; int left = currRow[i - bytesPerPixel] & 0xff; int difference = curr - left; subFilteredRow[i] = (byte)difference; badness += abs(difference); } filterBadness[1] = badness; } { byte[] upFilteredRow = scratchRows[2]; int badness = 0; for (int i = bytesPerPixel; i < bytesPerRow + bytesPerPixel; i++) { int curr = currRow[i] & 0xff; int up = prevRow[i] & 0xff; int difference = curr - up; upFilteredRow[i] = (byte)difference; badness += abs(difference); } filterBadness[2] = badness; } { byte[] averageFilteredRow = scratchRows[3]; int badness = 0; for (int i = bytesPerPixel; i < bytesPerRow + bytesPerPixel; i++) { int curr = currRow[i] & 0xff; int left = currRow[i - bytesPerPixel] & 0xff; int up = prevRow[i] & 0xff; int difference = curr - (left + up)/2;; averageFilteredRow[i] = (byte)difference; badness += abs(difference); } filterBadness[3] = badness; } { byte[] paethFilteredRow = scratchRows[4]; int badness = 0; for (int i = bytesPerPixel; i < bytesPerRow + bytesPerPixel; i++) { int curr = currRow[i] & 0xff; int left = currRow[i - bytesPerPixel] & 0xff; int up = prevRow[i] & 0xff; int upleft = prevRow[i - bytesPerPixel] & 0xff; int predictor = paethPredictor(left, up, upleft); int difference = curr - predictor; paethFilteredRow[i] = (byte)difference; badness += abs(difference); } filterBadness[4] = badness; } int filterType = 0; int minBadness = filterBadness[0]; for (int i = 1; i < 5; i++) { if (filterBadness[i] < minBadness) { minBadness = filterBadness[i]; filterType = i; } } if (filterType == 0) { System.arraycopy(currRow, bytesPerPixel, scratchRows[0], bytesPerPixel, bytesPerRow); } return filterType; }
9
private boolean checkUpRight(int _row, int _column, int _player) { boolean keepGoing = true; int nbAligned = 0; while (keepGoing == true && nbAligned < nbToAlign) { if (_row - nbAligned < 0 || _column + nbAligned >= column) { keepGoing = false; } else if (gameGrid[_row - nbAligned][_column + nbAligned] != _player) { keepGoing = false; } nbAligned = nbAligned + 1; } return keepGoing; }
5
private int checkDiagonal(byte[][] arr, int startIndex, int mark) { int countOfEmptyField = 0; int countOfBusyField = 0; int emptyIndex = -1; int j; for (int i = 0; i < arr.length; i++) { if (startIndex == 0) { j = i; } else { j = startIndex - i; } if (arr[i][j] == mark) countOfBusyField++; else if (arr[i][j] == GameBoard.EMPTY) { countOfEmptyField++; emptyIndex = i; } } if (countOfEmptyField == 1 && countOfBusyField == 2) return emptyIndex; return -1; }
6
public synchronized void InsertArticle(String name, String author, String years, String url, String introduction) { String insert_article = "INSERT INTO zhangyu_sca.article (name, author, years , url , introduction) values ( '" + name + "','" + author + "' , '" + years + "','" + url + "','" + introduction + "' );"; try { article_ste.executeUpdate(insert_article); } catch (Exception e) { e.printStackTrace(); } }
1
public static boolean checkDungeonBounds(RoomReference reference, Room[][] map, Room room) { if (reference.getX() == 0 && room.hasWestDoor()) return false; if (reference.getX() == map.length - 1 && room.hasEastDoor()) return false; if (reference.getY() == 0 && room.hasSouthDoor()) return false; if (reference.getY() == map[0].length - 1 && room.hasNorthDoor()) return false; return true; }
8
@Override public void init(String[] players, int fieldWidth, int fieldHeight) throws IllegalArgumentException, WrongArgumentException { if(players == null || players.length < 2 || fieldWidth < 5 || fieldHeight < 5 || fieldWidth > 15 || fieldHeight > 15){ throw new IllegalArgumentException("check input arguments: \n"); } for(int i=0; i < players.length - 1; i++){ for(int j=i+1; j < players.length; j++){ if(players[i].equalsIgnoreCase(players[j])){ throw new IllegalArgumentException("check input arguments"); } } } initPlayers(players); initFields(fieldWidth, fieldHeight); }
9
public TreeNode buildTree(int[] inorder, int[] postorder) { if(inorder.length == 0 && postorder.length == 0) return null; TreeNode node = buildTreeRec(inorder, postorder, 0, inorder.length-1, 0, postorder.length-1); return node; }
2
public void onKeyPressed(KeyEvent e) { switch (e.getKeyCode()) { case VK_UP: case VK_W: directions.add(Direction.UP); break; case VK_DOWN: case VK_S: directions.add(Direction.DOWN); break; case VK_RIGHT: case VK_D: directions.add(Direction.RIGHT); break; case VK_LEFT: case VK_A: directions.add(Direction.LEFT); break; } }
8
@Override public NepticalData getData() { Location location = getLocation(); DataModule moduleContext = NSpaceManager.getSpace(location.context()); List<NepticalData> data = moduleContext.getDataAt(location.fragment()); if (data.isEmpty()) { return NepticalData.NULL_DATA; } if (location instanceof CursorLocation) { return data.get(Integer.valueOf(location.name())); } return null; }
2
private void startNextSong() { EIError.debugMsg("startNextSong"); if(playList != null && !stopping) { if(currentSongIndex < playList.size()) { lastSong = playList.get(currentSongIndex); } else { lastSong = null; } GameSong gs = getNextSong(true); if(nextPlayList != null) { // EIError.debugMsg("start nextPlayList"); // nextPlayList.start(); } else if (gs != null) { EIError.debugMsg("next song "+gs.getFilePath()); gs.play(); } } if(nextPlayList != null) { EIError.debugMsg("start nextPlayList"); nextPlayList.start(); } nextPlayList = null; }
6
public void deletePlayerFromPlayers(String userName){ try { cs = con.prepareCall("{call DELETE_PLAYER_FROM_PLAYER(?)}"); cs.setString(1, userName); cs.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } }
1
public void forward(String ip, String message) { if (active) { Iterator<Service> it = services.iterator(); Service service; while (it.hasNext()) { service = it.next(); service.pushMessage(ip, message); } } }
2
@Override public int hashCode() { int result = personId; result = 31 * result + (accountNumber != null ? accountNumber.hashCode() : 0); return result; }
1
@Override public List<Integer> sort(List<Integer> list) { // checking input parameter for null if (list == null) { throw new IllegalArgumentException("ArrayList not specified!"); } int i, j, increment, temp, arraySize = list.size(); // moving forward through array. for (increment = arraySize / 2; increment > 0; increment /= 2) { for (i = increment; i < arraySize; i++) { temp = list.get(i); for (j = i; j >= increment; j -= increment) { // comparing distant elements if (temp < list.get(j - increment)) { list.set(j, list.get(j - increment)); } else { break; } } list.set(j, temp); } } return list; }
5
public Vector<String> findPath() throws ActorNotFoundException, EmptyQueueException { //Check that the actor to start from exists. if(actors.containsKey(startingNode)){ q.enqueue(actors.get(startingNode)); actors.get(startingNode).setVisited(true); } else { throw new ActorNotFoundException("There is no record of an actor called: " + startingNode); } while(!q.isEmpty()){ Actor currentNode; currentNode = q.dequeue(); //Check if the node removed from the queue is the target node. if(currentNode.getName().equals(ENDING_NODE)) { return tracePath(currentNode); } else { for(Movie m : currentNode.getMovieAppearances()){ if(!m.isVisited()){ Vector<Actor> cast = m.getCast(); m.setVisited(true); /*For every actor who has been in a film with the node currently being examined, *check if actor has been visited. If not add it to the queue of nodes to look through. */ for(Actor a : cast){ if(!a.isVisited()){ a.setVisited(true); a.setBaconNumber(currentNode.getBaconNumber() + 1); a.setPrev(currentNode); q.enqueue(a); } } } else { continue; } } } } return null; }
7
public int saveOrder(ArrayList<Order> order, Connection con) throws SQLException { int rowsInserted = 0; int tal = 0; String SQLString1 = "insert into ordre values(?,?,?)"; String SQLString2 = "insert into ordreDetails values(?,?,?,?,?)"; String SQLString3 = "select ordreseq.nextval from dual"; PreparedStatement statement = null; for (int j = 0; j < order.size(); j++) { Order otest = order.get(j); if (otest.getOrderNo() != 0) { tal++; } } try { statement = con.prepareStatement(SQLString3); ResultSet rs = statement.executeQuery(); if (rs.next()) { for (int k = tal; order.size() > k; k++) { Order o = order.get(k); o.setOrderNo(rs.getInt(1)); } } statement = con.prepareStatement(SQLString1); for (int j = tal; j < order.size(); j++) { Order o = order.get(j); statement.setInt(1, o.getOrderNo()); statement.setInt(2, o.getCustomer().getCustomerID()); statement.setInt(3, o.getState()); rowsInserted += statement.executeUpdate(); } if (rowsInserted == order.size() - tal) { rowsInserted = 0; statement = con.prepareStatement(SQLString2); for (int i = tal; i < order.size(); i++) { Order o = order.get(i); for (int j = 0; j < o.getItemlist().size(); j++) { statement.setInt(1, o.getItemlist().get(j).getItemNo()); statement.setInt(2, o.getItemlist().get(j).getItemAmount()); statement.setInt(3, o.getOrderNo()); java.sql.Date sqlDate = new java.sql.Date(o.getDepositumDate().getTime()); java.sql.Date sqlDate2 = new java.sql.Date(o.getorderDate().getTime()); statement.setDate(4, sqlDate); statement.setDate(5, sqlDate2); rowsInserted += statement.executeUpdate(); } } } else { System.out.println("Fejl i OrdreMapper - Part 1"); } } catch (Exception e) { System.out.println("Fejl i OrdreMapper - SaveOrder"); e.printStackTrace(); } return order.get(order.size()-1).getOrderNo(); }
9
public List<GeoIPv4Adress> parse(File file) throws IOException, XMLStreamException { FileInputStream in = new FileInputStream(file); XMLEventReader eventReader = factory.createXMLEventReader(in); while(eventReader.hasNext()) { XMLEvent xmlEvent = eventReader.nextEvent(); switch(xmlEvent.getEventType()) { case XMLStreamConstants.START_DOCUMENT: init(); break; case XMLStreamConstants.START_ELEMENT: processStartElement(xmlEvent.asStartElement()); break; case XMLStreamConstants.CHARACTERS: processCharacters(xmlEvent.asCharacters()); break; case XMLStreamConstants.END_ELEMENT: processEndElement(xmlEvent.asEndElement()); break; case XMLStreamConstants.END_DOCUMENT: cleanup(); break; } } List<GeoIPv4Adress> result = adresses; adresses = null; return result; }
6
private String parseHTML(int dId) { String result = ""; _logger.debug("Filetype = HTML"); MySqlDatabaseHelper databaseHelper = new MySqlDatabaseHelper(); result = (new SourceLoader().loadURL(databaseHelper.loadDocumentURL(dId))); return result; }
0
@Override public int hashCode() { return (username.hashCode() << 5) - 1; }
0
private void renderSprite(double xDiff, double yDiff, double zDiff, int tex, int color) { double xc = (xDiff - x) * 2 - rotXZSin * 0.2; double zc = (zDiff - z) * 2 - rotXZCos * 0.2; double yc = (yDiff - y) * 2 - rotYSin * 5; double zz = zc * rotXZCos + xc * rotXZSin; if(zz < 0.1){ return; } double xx = zc * rotXZSin - xc * rotXZCos; double yy = yc; double xPixel = width/2 + (xx / zz * fov); double yPixel = height/2 + (yy / zz * fov); double xPixel0 = xPixel - fov / zz; double xPixel1 = xPixel + fov / zz; double yPixel0 = yPixel - fov / zz; double yPixel1 = yPixel + fov / zz; int xp0 = (int) xPixel0; int xp1 = (int) xPixel1; int yp0 = (int) yPixel0; int yp1 = (int) yPixel1; if (xp0 < 0) xp0 = 0; if (xp1 > width) xp1 = width; if (yp0 < 0) yp0 = 0; if (yp1 > height) yp1 = height; zz *= 4; for (int yp = yp0; yp < yp1; yp++) { double yPercent = (yp - yPixel0) / (yPixel1 - yPixel0); int yTexture = (int) (yPercent * 16); for (int xp = xp0; xp < xp1; xp++) { double xPercent = (xp - xPixel0) / (xPixel1 - xPixel0); int xTexture = (int) (xPercent * 16); if (zz < zBuffer[xp + yp * width]) { int col = Art.testSprite.pixels[(xTexture + tex % 8 * 16) + (yTexture + (tex / 8) * 16) * 16]; if (col != 0) { pixels[xp + yp * width] = ~(col ^ color); zBuffer[xp + yp * width] = zz; } } } } }
9
public static void printMatrixInSpiral(int [][] input) { int leftTop = 0; int rightTop = input[0].length; int leftBottom = -1; int rightBottom = input.length; int i=0; int j=0; int count =0; while(count<input.length * input[0].length){ while(true){ if(j<rightTop){ System.out.println(" "+input[i][j++]+" "); count++; } else { rightTop--; j--; i++; break; } } while(true) { if(i<rightBottom){ System.out.println(" "+input[i++][j]+" "); count++; } else{ i--; j--; rightBottom--; break; } } while(true) { if(j>leftBottom){ System.out.println(" "+input[i][j--]+" "); count++; } else{ j++; i--; leftBottom++; break; } } while(true) { if(i>leftTop){ System.out.println(" "+input[i--][j]+" "); count++; } else{ i++; j++; leftTop++; break; } } } }
9
public void grabTexture(int var1, boolean var2) { int var3; if((var3 = this.getSlot(var1)) >= 0) { this.selected = var3; } else { if(var2 && var1 > 0 && SessionData.allowedBlocks.contains(Block.blocks[var1])) { this.replaceSlot(Block.blocks[var1]); } } }
4
static Element getElementByTagNameNR(Element e, String tagName) { Node child = e.getFirstChild(); while (child != null) { if (child instanceof Element && child.getNodeName().equals(tagName)) return (Element) child; child = child.getNextSibling(); } return null; }
3
final public boolean replaceChild(Construct child, Construct newCon) { List<Construct> childConstructs = new LinkedList<Construct>(); getAllChildConstructs(childConstructs, child); // Do the construct replacement here, if the replacement // is successful, then we need to cleanup all editors related // to construct we have just replaced if(construct.replaceChild(child, newCon)) { for(Construct constructForEditorDeletion : childConstructs) { WeakReference<ConstructEditor> editor = mBoundEditorStore.get(constructForEditorDeletion); if(editor != null && editor.get() != null) { editor.get().delete(); } } } return true; }
4
protected void readImage() { ix = readShort(); // (sub)image position & size iy = readShort(); iw = readShort(); ih = readShort(); int packed = read(); lctFlag = (packed & 0x80) != 0; // 1 - local color table flag interlace = (packed & 0x40) != 0; // 2 - interlace flag // 3 - sort flag // 4-5 - reserved lctSize = 2 << (packed & 7); // 6-8 - local color table size if (lctFlag) { lct = readColorTable(lctSize); // read table act = lct; // make local table active } else { act = gct; // make global table active if (bgIndex == transIndex) bgColor = 0; } int save = 0; if (transparency) { save = act[transIndex]; act[transIndex] = 0; // set transparent color if specified } if (act == null) { status = STATUS_FORMAT_ERROR; // no color table defined } if (err()) return; decodeImageData(); // decode pixel data skip(); if (err()) return; frameCount++; // create new image to receive frame data image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE); setPixels(); // transfer pixel data to image frames.add(new GifFrame(image, delay)); // add image to frame list if (transparency) { act[transIndex] = save; } resetFrame(); }
7
public AddNewChunkDialog(KlangEditor parent, Chunk curChunk) { super(parent); this.setModalityType(ModalityType.APPLICATION_MODAL); this.setResizable(false); this.setTitle(KlangConstants.KLANGEDITOR_ADDNEWCHUNKDIALOG_TITLE); this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); pnlContent = new JPanel(); pnlContent.setBorder( new EmptyBorder(11,11,11,11) ); pnlContent.setLayout(new BoxLayout(pnlContent, BoxLayout.Y_AXIS)); this.getContentPane().add(pnlContent); pnlChunkName = new JPanel(); FlowLayout f1 = new FlowLayout(); f1.setAlignment(FlowLayout.LEFT); pnlChunkName.setLayout(f1); pnlContent.add(pnlChunkName); lblCurChunkName2 = new KlangLabel(KlangConstants.KLANGEDITOR_ADDNEWCHUNKDIALOG_CURCHUNK + ": " + curChunk.getChunkName()); pnlChunkName.add(lblCurChunkName2); lblChunkName = new KlangLabel(KlangConstants.KLANGEDITOR_ADDNEWCHUNKDIALOG_CHUNKNAMELBL); pnlChunkName.add(lblChunkName); txtfChunkName = new KlangTextField("", 100); pnlChunkName.add(txtfChunkName); pnlTop = new JPanel(); FlowLayout f2 = new FlowLayout(); f2.setAlignment(FlowLayout.LEFT); pnlTop.setLayout(f2); pnlContent.add(pnlTop); lblCurChunkName1 = new KlangLabel(KlangConstants.KLANGEDITOR_ADDNEWCHUNKDIALOG_CURCHUNKTEXT1); pnlTop.add(lblCurChunkName1); bBefore = new JRadioButton(KlangConstants.KLANGEDITOR_ADDNEWCHUNKDIALOG_BEFORE); bAfter = new JRadioButton(KlangConstants.KLANGEDITOR_ADDNEWCHUNKDIALOG_AFTER); bUnder = new JRadioButton(KlangConstants.KLANGEDITOR_ADDNEWCHUNKDIALOG_UNDER); grpbau = new ButtonGroup(); grpbau.add(bBefore); grpbau.add(bAfter); grpbau.add(bUnder); pnlTop.add(bBefore); pnlTop.add(bAfter); pnlTop.add(bUnder); bBefore.setEnabled(false); bAfter.setEnabled(false); bUnder.setEnabled(false); //enable any radio buttons that apply if (curChunk instanceof EditableContainerChunk) { bUnder.setEnabled(true); } if (curChunk.getParentChunk() != null) { if (curChunk.getParentChunk() instanceof EditableContainerChunk) { bBefore.setEnabled(true); bAfter.setEnabled(true); } } if (curChunk.getParentChunk() == null) { if (curChunk.getParentFile() instanceof EditableFileBase) { EditableFileBase efb = (EditableFileBase)curChunk.getParentFile(); if (efb.canAddTopLevelChunks()) { bBefore.setEnabled(true); bAfter.setEnabled(true); } } } //set default if (bBefore.isEnabled()) { bBefore.setSelected(true); } else if (bAfter.isEnabled()) { bAfter.setSelected(true); } else { bUnder.setSelected(true); } pnlButtons = new JPanel(); FlowLayout f5 = new FlowLayout(); f5.setAlignment(FlowLayout.LEFT); pnlButtons.setLayout(f5); pnlContent.add(pnlButtons); bUseBlank = new JRadioButton(KlangConstants.KLANGEDITOR_ADDNEWCHUNKDIALOG_RADBLANK); bUseFile = new JRadioButton(KlangConstants.KLANGEDITOR_ADDNEWCHUNKDIALOG_RADFILE); grpbf = new ButtonGroup(); grpbf.add(bUseBlank); grpbf.add(bUseFile); pnlButtons.add(bUseBlank); pnlFile = new FileBrowseSubPanel(KlangConstants.KLANGEDITOR_ADDNEWCHUNKDIALOG_FILELBL); pnlFile.disableInterface(); pnlContent.add(pnlFile); pnlButtons.add(bUseFile); bUseBlank.setSelected(true); bUseBlank.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { pnlFile.disableInterface(); } }); bUseFile.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { pnlFile.enableInterface(); } }); pnlOKCancel = new JPanel(); FlowLayout f3 = new FlowLayout(); f3.setAlignment(FlowLayout.RIGHT); pnlOKCancel.setLayout(f3); btnOK = new JButton("OK"); btnOK.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { canceled = false; setVisible(false); } }); btnCancel = new JButton("Cancel"); btnCancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { canceled = true; setVisible(false); } }); pnlOKCancel.add(btnOK); pnlOKCancel.add(btnCancel); pnlContent.add(pnlOKCancel); this.pack(); if (parent != null) { //center over parent window this.setLocation(parent.getX() + (parent.getWidth() / 2) - (this.getWidth() / 2), parent.getY() + (parent.getHeight() / 2) - (this.getHeight() / 2)); } this.setVisible(true); }
9
public ScaledQuantity(double value, Unit unit) { super(value, unit); if(!Temperature.class.isInstance(unit)) { throw new RuntimeException("Cannot create ArithmeticQuantity with unit " + unit); } }
1
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (obj.getClass() == this.getClass()) { Matrix m = (Matrix) obj; for (int i = 0; i < m.rows; i++) { for (int j = 0; j < m.columns; j++) { if (this.getElement(j, i) != m.getElement(j, i)) { return false; } } } } return true; }
6
public void loadModels() { ModelList.SortedListModel dataModel = ((ModelList.SortedListModel) m_ModelList.getModel()); int directoryCount = 0; int modelCount = 0; dataModel.clear(); File directory = m_Library.getWorkingDirectory(); File subDirectories[] = directory.listFiles(); if (subDirectories != null) { for (int i = 0; i < subDirectories.length; i++) { if (subDirectories[i].isDirectory() && subDirectories[i].getName().matches( ".*_instances_.*")) { directoryCount++; File[] subDirectoryFiles = subDirectories[i].listFiles(); for (int j = 0; j < subDirectoryFiles.length; j++) { if (subDirectoryFiles[j].getName().matches(".*.elm")) { EnsembleSelectionLibraryModel model = EnsembleSelectionLibraryModel .loadModel(subDirectoryFiles[j].getPath()); // get those Classifier[] objects garbage collected! model.releaseModel(); if (!dataModel.contains(model)) { modelCount++; dataModel.add(model); } } } } } } updateLoadingLabel(modelCount, directoryCount); }
7
@Test public void testGetDescriptionSecondPhone() { Map<String, Object> descriptionSecondPhone = new HashMap<String, Object>(); descriptionSecondPhone.put("name", "Cink Five"); descriptionSecondPhone.put("brandName", "Wiko"); descriptionSecondPhone.put("screenSize", 5); descriptionSecondPhone.put("screenType", ScreenType.RESISTIV); descriptionSecondPhone.put("version", AndroidPhoneVersion.ECLAIR); descriptionSecondPhone.put("id", secondPhone.getId()); descriptionSecondPhone.put("state", State.GOOD); Map<String, Map<Class<? extends IUser>, Integer>> limitsDescription = new HashMap<String, Map<Class<? extends IUser>, Integer>>(); Map<Class<? extends IUser>, Integer> copyLimitsForSecondPhone = new HashMap<Class<? extends IUser>, Integer>(); copyLimitsForSecondPhone.put(Student.class, new Integer(2)); copyLimitsForSecondPhone.put(Teacher.class, new Integer(10)); Map<Class<? extends IUser>, Integer> delayLimitsForSecondPhone = new HashMap<Class<? extends IUser>, Integer>(); delayLimitsForSecondPhone.put(Student.class, new Integer(2)); delayLimitsForSecondPhone.put(Teacher.class, new Integer(14)); Map<Class<? extends IUser>, Integer> durationLimitsForSecondPhone = new HashMap<Class<? extends IUser>, Integer>(); durationLimitsForSecondPhone.put(Student.class, new Integer(14)); durationLimitsForSecondPhone.put(Teacher.class, new Integer(30)); limitsDescription .put(Material.KEY_LIMIT_COPY, copyLimitsForSecondPhone); limitsDescription.put(Material.KEY_LIMIT_DELAY, delayLimitsForSecondPhone); limitsDescription.put(Material.KEY_LIMIT_DURATION, durationLimitsForSecondPhone); descriptionSecondPhone.put("limits", limitsDescription); assertEquals(descriptionSecondPhone, secondPhone.getDescription()); }
8