text
stringlengths
14
410k
label
int32
0
9
static long Evclid(long a, long b) { long mult = a * b; while (a != 0 && b != 0) { if (a >= b) { a = a % b; } else { b = b % a; } } long NOK = (mult / (a + b)); return NOK; // Одно - ноль }
3
public void add() throws IOException, JSONException, NullPointerException { try{ long StartTime = System.currentTimeMillis(); String keyvalue = null; if(Table == null) { System.err.println("Table name not set"); } else if(ColumnFamily == null) { System.err.println("Column family not set"); } else if(Qualifier == null) { System.err.println("Qualifier not set"); } else if(Value == null) { System.err.println("Value not set"); } else{ keyvalue = read(Table); if(keyvalue.contains(ColumnFamily)) { String DBloc = getDBloc(); FileWriter fstream = new FileWriter(DBloc+"/"+Table+"/"+ColumnFamily+"/"+Qualifier,true); BufferedWriter out = new BufferedWriter(fstream); JSONObject obj = new JSONObject(); obj.put(Key, Value); out.write(obj+"\n"); out.close(); System.out.println("Value added to store"); } else{ System.err.println("Column family does not exist"); } } long endTime = System.currentTimeMillis(); System.out.println("Time Taken : "+(endTime-StartTime)+" ms"); } catch(Exception e) { e.printStackTrace(); } }
6
private static void readUnifiedNums(String str, int off, int[] values) throws NumberFormatException { while (str.charAt(off) == ' ' || str.charAt(off) == '-') off++; int end = str.indexOf(CONTEXT_MARK_DELIMETER, off); if (end > 0) { values[0] = Integer.parseInt(str.substring(off, end).trim()); } else throw new NumberFormatException("Missing comma."); off = end + 1; end = str.indexOf(' ', off); if (end > 0) { values[1] = Integer.parseInt(str.substring(off, end).trim()); } else throw new NumberFormatException("Missing middle space."); off = end + 1; while (str.charAt(off) == ' ' || str.charAt(off) == '+') off++; end = str.indexOf(CONTEXT_MARK_DELIMETER, off); if (end > 0) { values[2] = Integer.parseInt(str.substring(off, end).trim()); } else throw new NumberFormatException("Missing second comma."); off = end + 1; end = str.indexOf(' ', off); if (end > 0) { values[3] = Integer.parseInt(str.substring(off, end).trim()); } else throw new NumberFormatException("Missing final space."); values[1] += values[0] - 1; values[3] += values[2] - 1; }
8
@BeforeClass public static void setUpClass() { }
0
double residualCapacityTo(int vertex) { if (vertex == v) return flow; // backward edge else if (vertex == w) return capacity - flow; // forward edge else throw new IllegalArgumentException(); }
2
public String genKeywords(){ if(keywords.size() > 0){ StringBuffer impKeywords = new StringBuffer(); Iterator<String> i = this.keywords.iterator(); while(i.hasNext()) { impKeywords.append(i.next()); if(i.hasNext()) impKeywords.append(","); } return impKeywords.toString(); } return null; }
3
public static Iterator allDirectSupercollections(LogicObject self, boolean performfilteringP) { if (Stella_Object.isaP(self, Logic.SGT_LOGIC_DESCRIPTION)) { Description.deriveDeferredSatelliteRules(((Description)(self))); } { Iterator directlylinkedobjects = Logic.allDirectlyLinkedObjects(self, Logic.SGT_PL_KERNEL_KB_SUBSET_OF, ((Boolean)(Logic.$REVERSEPOLARITYp$.get())).booleanValue()); if (!performfilteringP) { return (directlylinkedobjects); } { Cons directsupers = Stella.NIL; Cons equivalents = LogicObject.allEquivalentCollections(self, true); if (!(equivalents.rest == Stella.NIL)) { { LogicObject e = null; Cons iter000 = equivalents; for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) { e = ((LogicObject)(iter000.value)); { LogicObject parent = null; Iterator iter001 = LogicObject.allDirectSupercollections(e, false); while (iter001.nextP()) { parent = ((LogicObject)(iter001.value)); if ((!equivalents.memberP(parent)) && (!directsupers.memberP(parent))) { directsupers = Cons.cons(parent, directsupers); } } } } } } else { directsupers = ((Cons)(directlylinkedobjects.consify())); } return (Logic.mostSpecificCollections(directsupers).allocateIterator()); } } }
7
public static void main(String args[]) { Servidor servidor = new Servidor(PUERTO); Cliente cliente = null; String ip = ""; try { servidor.conectar(); System.out.println("Conectado"); while (servidor.estaConectado()) { cliente = new Cliente(servidor.escuchar(),servidor); cliente.setIp(cliente.socket.getInetAddress().getHostAddress()); ip = cliente.getIp(); //if(servidor.existeIp(ip)){ // cliente.getSalida().println("/server " + ip); // cliente.getSalida().println("/server Ya existe un equipo con esta direccion"); //} //else{ // cliente.start(); //} cliente.start(); } } catch (IOException ioe) { ioe.printStackTrace(); } }
2
public SkiPass getFirstHalfDaySkiPass(Date currentDate) { if (currentDate == null) { throw new IllegalArgumentException("Current date is null"); } Calendar calendar = new GregorianCalendar(); calendar.setTime(currentDate); calendar.set(Calendar.HOUR_OF_DAY, 9); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); Date activationDate = calendar.getTime(); calendar.add(Calendar.HOUR_OF_DAY, 4); Date expirationDate = calendar.getTime(); if (expirationDate.before(currentDate)) { return null; } else { return system.createSkiPass("HOURLY", activationDate, expirationDate, 0); } }
2
public void newArray(final Type type){ int typ; switch(type.getSort()) { case Type.BOOLEAN: typ = Opcodes.T_BOOLEAN; break; case Type.CHAR: typ = Opcodes.T_CHAR; break; case Type.BYTE: typ = Opcodes.T_BYTE; break; case Type.SHORT: typ = Opcodes.T_SHORT; break; case Type.INT: typ = Opcodes.T_INT; break; case Type.FLOAT: typ = Opcodes.T_FLOAT; break; case Type.LONG: typ = Opcodes.T_LONG; break; case Type.DOUBLE: typ = Opcodes.T_DOUBLE; break; default: typeInsn(Opcodes.ANEWARRAY, type); return; } mv.visitIntInsn(Opcodes.NEWARRAY, typ); }
8
public void shoot() { if (readyToFire) { Projectile p = new Projectile(centerX + 50, centerY - 25); projectiles.add(p); } }
1
public void paint(Graphics2D g) { if(animated) g.drawImage(game.bitmapFact.getEntityImage(name + animFrame), drawX, drawY, null); else g.drawImage(game.bitmapFact.getEntityImage(name), drawX, drawY, null); if(game.getDevMode()) g.drawRect(drawX, drawX, getBounds().width, getBounds().height); }
2
public static LinkedList<String> computeDifference(LinkedList<String> A, LinkedList<String> B) { LinkedList<String> diff = new LinkedList<String>(); for(int i =0; i<A.size(); i++) { String item = A.get(i); if(!B.contains(item)) { diff.add(item); } } return diff; }
2
public static void main(String[] args) throws Exception { HashMap<String, Integer> barcodeMap = getBarcodeToSampleMap(); HashMap<String, Integer> expectedMap = getExpectedSubjectID(); System.out.println("got " + expectedMap.size()); BufferedReader reader = new BufferedReader(new FileReader(new File( ConfigReader.getIanNov2015Dir() + File.separator + "behavbugs_noindex_l001_r2_001" + File.separator + "mcsmm" + File.separator + "mcsmm.behavbugsn" ))); int numPassed = 0; int numNotFound =0; for(String s= reader.readLine(); s != null && s.trim().length() >0; s= reader.readLine()) { String key = new StringTokenizer(s).nextToken(); if( ! key.startsWith("@")) throw new Exception("Incorrect line " + key); String sequence = reader.readLine(); for( int x=0; x < 2; x++) { String nextLine = reader.readLine(); if( nextLine == null) throw new Exception("No"); } Integer expectedFromBarcode = barcodeMap.get(sequence); if( expectedFromBarcode != null) { Integer expectedFromSeq = expectedMap.get(key); if(expectedFromSeq == null) throw new Exception("Could not find " + key); if( ! expectedFromBarcode.equals(expectedFromSeq)) throw new Exception("Mismatch " + key + " " + expectedFromBarcode + " " + expectedFromSeq); numPassed++; } else { numNotFound++; } if( (numPassed + numNotFound) % 10000== 0) System.out.println("passed " + numPassed + " skipped "+ numNotFound); } System.out.println("passed " + numPassed + " skipped "+ numNotFound); System.out.println("global pass"); }
9
private JTable initTable() { JTable table = null; if (numberOfUsers == 3) { titels = new Object[4]; titels[0] = ""; inhalt = new Object[20][4]; } if (numberOfUsers == 4) { titels = new Object[5]; titels[0] = ""; inhalt = new Object[15][5]; } if (numberOfUsers == 5) { titels = new Object[6]; titels[0] = ""; inhalt = new Object[12][6]; } if (numberOfUsers == 6) { titels = new Object[7]; titels[0] = ""; inhalt = new Object[10][7]; } for (int i = 0; i < inhalt.length; i++) { inhalt[i][0] = i + 1; } for (int i = 0; i < userList.size(); i++) { titels[i + 1] = userList.get(i).getName(); } TableModel model = new DefaultTableModel(inhalt, titels) { public boolean isCellEditable(int row, int col) { return false; } }; DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer(); rightRenderer.setHorizontalAlignment(JLabel.RIGHT); table = new JTable(model); for (int i = 0; i < table.getColumnCount(); i++) { table.getColumnModel().getColumn(i).setCellRenderer(rightRenderer); } for (int i = 1; i <= numberOfUsers; i++) { setColumnWidth(table, i, 75); } setColumnWidth(table, 0, 30); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); return table; }
8
public static File getLauncherDir() { File dir = null; File root = new File(System.getProperty("user.home", ".") + "/"); final String appName = "mclauncher"; switch (SystemUtils.getSystemOS()) { case linux: case solaris: dir = new File(root, "." + appName + "/"); break; case macosx: dir = new File(root, "Library/Application Support/" + appName); break; case windows: final String applicationData = System.getenv("APPDATA"); if (applicationData != null) { root = new File(applicationData); } dir = new File(root, '.' + appName + '/'); break; default: dir = new File(root, appName + '/'); break; } if (dir != null && !dir.exists() && !dir.mkdirs()) { throw new RuntimeException( "The working directory could not be created: " + dir); } return dir; }
8
public Account getNewAccount() { return new HumanAccount(); }
0
private void parsejButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_parsejButtonMouseClicked // long startTime = System.currentTimeMillis(); if (selectedCheckboxCount == 0) { JOptionPane.showMessageDialog(null, "至少要选择一个语言", "信息提示", JOptionPane.ERROR_MESSAGE); return; } String function = ""; if (funcbuttonGroup.getSelection() != null) { function = funcbuttonGroup.getSelection().getActionCommand(); } ControllerJFrame.showNoticeMessageJFrame(); NoticeMessageJFrame.noticeMessage("开始转换,请耐心等待。。。。"); String msg = null; if ("PARSE_ALL".equals(function)) {//全部转换 //配置文件 String configFilePath = configFilejTextField.getText(); //输出路径 String outputPath = outputjTextField.getText(); initNeedParseLangList(); funcMap.entrySet().stream().forEach((entry) -> { String currentFunction = entry.getKey(); String excelFileName = entry.getValue(); ConfigParserDispatch.transformSingleExcel(currentFunction, configFilePath + "/" + excelFileName, outputPath); }); } else {//转换某一个配置项 //配置文件 String configFilePath = configFilejTextField.getText(); //输出路径 String outputPath = outputjTextField.getText(); if (function.isEmpty()) { msg = "请选择解析内容 "; } else if (configFilePath.isEmpty()) { msg = "请选择待解析文件(xls) "; } else if (outputPath.isEmpty()) { msg = "请选择输出路径"; } if (msg != null && !msg.isEmpty()) { JOptionPane.showMessageDialog(null, msg, "信息提示", JOptionPane.ERROR_MESSAGE); System.exit(0); } initNeedParseLangList(); ConfigParserDispatch.transformSingleExcel(function, configFilePath, outputPath); } }//GEN-LAST:event_parsejButtonMouseClicked
8
public void paintShape(Graphics2D g2) { Dimension dim = label.getPreferredSize(); // System.out.println(dim); if (dim.width > 0 && dim.height > 0) { label.setBounds(0, 0, dim.width, dim.height); g2.translate(getX(), getY()); g2.scale((image.getWidth() + 2 * xGrow) / dim.width, (image.getHeight() + 2 * yGrow) / dim.height); label.paint(g2); } }
2
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(TaskInput.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(TaskInput.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(TaskInput.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TaskInput.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 TaskInput(gui).setVisible(true); } }); }
6
public String KonversiKwitansi (double doubleAngka){ String [] bil ={"","satu","dua","tiga","empat","lima","enam","tujuh","delapan","sembilan","sepuluh","sebelas"}; String x=" "; int intAngka = (int) doubleAngka; if (doubleAngka<12){ x = " " + bil[intAngka]; } else if(doubleAngka<20){ x = KonversiKwitansi(doubleAngka-10) + " belas"; } else if(doubleAngka<100){ x = KonversiKwitansi(doubleAngka/10) + " puluh" + KonversiKwitansi(doubleAngka%10); } else if(doubleAngka<200){ x = " seratus" + KonversiKwitansi(doubleAngka-100); } else if(doubleAngka<1000){ x = KonversiKwitansi(doubleAngka/100) + " ratus" + KonversiKwitansi(doubleAngka%100); } else if(doubleAngka<2000){ x = " seribu"+ KonversiKwitansi(doubleAngka-1000); } else if(doubleAngka<1000000){ x = KonversiKwitansi(doubleAngka/1000) + " ribu" + KonversiKwitansi (doubleAngka%1000); } else if(doubleAngka<1000000000){ x = KonversiKwitansi(doubleAngka/1000000)+ " juta" + KonversiKwitansi (doubleAngka%1000000); } else { x = KonversiKwitansi(doubleAngka/1000000000) + " milyat" + KonversiKwitansi(doubleAngka%1000000000); } return x; }
8
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { MOB target=mob; if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB)) target=(MOB)givenTarget; if(target==null) return false; if(target.fetchEffect(ID())!=null) { mob.tell(target,null,null,L("<S-NAME> already <S-HAS-HAVE> a camel's back.")); return false; } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; // now see if it worked final boolean success=proficiencyCheck(mob,0,auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?"":L("^S<S-NAME> chant(s) thirstily.^?")); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); beneficialAffect(mob,target,asLevel,0); mob.location().show(mob,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> grow(s) a camelback hump!")); target.tell(L("You feel quenched!")); } } else return beneficialWordsFizzle(mob,target,L("<S-NAME> chant(s) thirstily, but nothing more happens.")); // return whether it worked return success; }
9
void setSelectionForeground () { if (!instance.startup) { tabFolder1.setSelectionForeground(selectionForegroundColor); } // Set the selection foreground item's image to match the foreground color of the selection. Color color = selectionForegroundColor; if (color == null) color = tabFolder1.getSelectionForeground (); TableItem item = colorAndFontTable.getItem(SELECTION_FOREGROUND_COLOR); Image oldImage = item.getImage(); if (oldImage != null) oldImage.dispose(); item.setImage (colorImage(color)); }
3
protected <R> R openStatement(final Connection db, JdbcCallback<R> callback, Sql sql) { PreparedStatement stmt = null; try { stmt = db.prepareStatement(sql.toSql()); return callback.connected(stmt); } catch (SQLException e) { throw new RuntimeException(e); } finally { if(stmt != null) { try { stmt.close(); } catch (SQLException e) { //ignore } } } }
3
public void renderMiniMapResources(Graphics g, int mx, int my, int cx, int cy, int w, int h, int x, int y, String resourceName) { HashMap<String, Resource> rs = new HashMap<String, Resource>(resources); Resource resource = null; int[] xy = null; try { for (String key : rs.keySet()) { resource = (Resource) rs.get(key); if (resource.getResourceType().getName().equals(resourceName) || resourceName.equals("")) { xy = registry.getBlockManager().getMiniMapPosition(mx, my, cx, cy, w, h, resource.getMapX() / this.gameController.getBlockWidth(), resource.getMapY() / this.gameController.getBlockHeight()); if ((xy[0] > mx && xy[0] < mx + w) && (xy[1] > my + 1 && xy[1] < my + h)) { renderMiniMapResource(g, xy[0], xy[1]); } } } } catch (Exception e) { } }
8
public static void main (String args[]) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(reader.readLine()); int currentOperation; int currentNumber; boolean isQueue; StringTokenizer st; for (int i=0; i<t; i++) { isQueue = true; int n = Integer.parseInt(reader.readLine()); //LinkStack stack = new LinkStack(); ArrayStack stack = new ArrayStack(); for (int j=0; j<n; j++) { st = new StringTokenizer(reader.readLine()); if (isQueue) { currentOperation = Integer.parseInt(st.nextToken()); currentNumber = Integer.parseInt(st.nextToken()); if (currentOperation == 1) { stack.enQueue(currentNumber); } else { isQueue = stack.deQueue(currentNumber); } } } System.out.println(isQueue ? "Queue" : "Stack"); } }
5
protected void detect() { monitor.println("\nDerivation length: " + length); AbstractWorker workerPool[] = new AbstractWorker[workers]; startTime = System.currentTimeMillis(); Job j = new Job(length, newStackFrame(dfa.startState)); // have one worker hand out a predefined number of jobs AbstractWorker dealer = newWorker("dealer"); dealer.setDealer(true); dealer.go(j, true); monitor.println("Jobs: " + jobs.size()); long sentences = 0; if (jobs.size() > 0 && !monitor.canceling()) { for (int i = 0; i < workers; i++) { workerPool[i] = newWorker(("" + i)); workerPool[i].start(); } for (int i = 0; i < workers; i++) { while (workerPool[i].isAlive() && !monitor.canceling()) { try { workerPool[i].join(); } catch (InterruptedException e) { return; } } sentences += workerPool[i].sentences; } } if (monitor.canceling()) { monitor.println("Aborted"); } else { monitor.println("Done"); } monitor.println("Sentences: " + sentences); int parsed = 0; for (Relation<Symbol, SymbolString> r : possibleAmbiguities) { parsed += r.size(); } monitor.println("Parsed: " + parsed); monitor.println("Ambiguities found: " + ambiguities.size()); monitor.println("Ambiguous nonterminals: " + ambiguities.m.size()); monitor.println("Time: " + (System.currentTimeMillis() - startTime)); }
9
@Override public boolean isFull() { for (int i = 0; i < buffer.length; ++i) { if (buffer[i] == null) { return false; } } return true; }
2
static public Direction getDirectionFromString(String str) { if (str.equals("UP")) { return UP; } else if (str.equals("DOWN")) { return DOWN; } else if (str.equals("LEFT")) { return LEFT; } else if (str.equals("RIGHT")) { return RIGHT; } else if (str.equals("NONE")) { return NONE; } else { assert false : "String discribing direction unknown : " + str; return null; } }
5
public boolean searchMatrix(int[][] matrix, int target) { // Note: The Solution object is instantiated only once and is reused by each test case. if(matrix==null || matrix.length==0) return false; int low = 0, high = matrix.length-1; while(low<high){ int mid = (low+high)/2; if(matrix[mid][0]==target){ return true; } else if(matrix[mid][0]>target){ high = mid-1; } else if(matrix[mid+1][0]>target){ low = mid; break; } else{ low = mid+1; } } int row = low; low = 0; high = matrix[0].length-1; while(low<=high){ int mid = (low+high)/2; if(matrix[row][mid]==target) return true; else if(matrix[row][mid]>target){ high = mid-1; } else{ low = mid+1; } } return false; }
9
private void applyGamma(Delta currentDelta, ASTNode node, Environment currentEnv, Stack<ASTNode> currentControlStack){ ASTNode rator = valueStack.pop(); ASTNode rand = valueStack.pop(); if(rator.getType()==ASTNodeType.DELTA){ Delta nextDelta = (Delta) rator; //Delta has a link to the environment in effect when it is pushed on to the value stack (search //for 'RULE 2' in this file to see where it's done) //We construct a new environment here that will contain all the bindings (single or multiple) //required by this Delta. This new environment will link back to the environment carried by the Delta. Environment newEnv = new Environment(); newEnv.setParent(nextDelta.getLinkedEnv()); //RULE 4 if(nextDelta.getBoundVars().size()==1){ newEnv.addMapping(nextDelta.getBoundVars().get(0), rand); } //RULE 11 else{ if(rand.getType()!=ASTNodeType.TUPLE) EvaluationError.printError(rand.getSourceLineNumber(), "Expected a tuple; was given \""+rand.getValue()+"\""); for(int i = 0; i < nextDelta.getBoundVars().size(); i++){ newEnv.addMapping(nextDelta.getBoundVars().get(i), getNthTupleChild((Tuple)rand, i+1)); //+ 1 coz tuple indexing starts at 1 } } processControlStack(nextDelta, newEnv); return; } else if(rator.getType()==ASTNodeType.YSTAR){ //RULE 12 if(rand.getType()!=ASTNodeType.DELTA) EvaluationError.printError(rand.getSourceLineNumber(), "Expected a Delta; was given \""+rand.getValue()+"\""); Eta etaNode = new Eta(); etaNode.setDelta((Delta)rand); valueStack.push(etaNode); return; } else if(rator.getType()==ASTNodeType.ETA){ //RULE 13 //push back the rand, the eta and then the delta it contains valueStack.push(rand); valueStack.push(rator); valueStack.push(((Eta)rator).getDelta()); //push back two gammas (one for the eta and one for the delta) currentControlStack.push(node); currentControlStack.push(node); return; } else if(rator.getType()==ASTNodeType.TUPLE){ tupleSelection((Tuple)rator, rand); return; } else if(evaluateReservedIdentifiers(rator, rand, currentControlStack)) return; else EvaluationError.printError(rator.getSourceLineNumber(), "Don't know how to evaluate \""+rator.getValue()+"\""); }
9
@Override public void run() { if (Updater.this.url != null && (Updater.this.read() && Updater.this.versionCheck(Updater.this.versionName))) { // Obtain the results of the project's file feed if ((Updater.this.versionLink != null) && (Updater.this.type != UpdateType.NO_DOWNLOAD)) { String name = Updater.this.file.getName(); // If it's a zip file, it shouldn't be downloaded as the plugin's name if (Updater.this.versionLink.endsWith(".zip")) { final String[] split = Updater.this.versionLink.split("/"); name = split[split.length - 1]; } Updater.this.saveFile(updateFolder, name, Updater.this.versionLink); } else { Updater.this.result = UpdateResult.UPDATE_AVAILABLE; } } }
6
public void addPoly(List<Position> coords, String tooltip) { Polygon shape = new Polygon(coords); shape.setAltitudeMode(WorldWind.RELATIVE_TO_GROUND); shape.setAttributes(attrPoly); if (tooltip != null) { shape.setValue(AVKey.HOVER_TEXT, "hover: " + tooltip); shape.setValue(AVKey.ROLLOVER_TEXT, "rollover: " + tooltip); } addRenderable(shape); }
1
private Object openInputGUI(final Component component, String title, final int tapes) { // TODO Auto-generated method stub JPanel panel; JTextField[] fields; //for FA, PDA if (tapes==0) { panel = new JPanel(new GridLayout(3, 1)); fields = new JTextField[1]; for (int i = 0; i < 1; i++) { panel.add(new JLabel(title + " ")); panel.add(fields[i] = new JTextField()); } } else { panel = new JPanel(new GridLayout(tapes*2+1, 2)); fields = new JTextField[tapes]; for (int i = 0; i < tapes; i++) { panel.add(new JLabel(title + " "+(i+1))); panel.add(fields[i] = new JTextField()); } } int result = JOptionPane.showOptionDialog(component, panel, title, JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); if (result != JOptionPane.YES_OPTION && result != JOptionPane.OK_OPTION) return null; if (tapes==0) { String input = fields[0].getText(); return input; } else { String[] input = new String[tapes]; for (int i = 0; i < tapes; i++) input[i] = fields[i].getText(); return input; } }
7
private List<Repository> getRepositories(final String organizationName) throws IOException { try { return repoListCache.get(organizationName, new Callable<List<Repository>>() { @Override public List<Repository> call() throws IOException { logger.log(Level.INFO, "Getting and caching list of repositories for {0}.", organizationName); RepositoryService repositoryService = new RepositoryService(connectToGitHub()); List<Repository> repositories = repositoryService.getOrgRepositories(organizationName); if (repositories == null) { // Callable must return a value or throw an exception - can't return null throw new IllegalArgumentException(); } return repositories; } }); } catch (ExecutionException e) { if (e.getCause() instanceof IOException) { throw (IOException)e.getCause(); } // Callable should only throw an IOException. If we get here, something fishy is going on... throw new IllegalStateException(e.getCause()); } }
3
private void initComponents() { JMenuBar menuBar1 = new JMenuBar(); JMenu menu1 = new JMenu(); JMenuItem menuItem1 = new JMenuItem(); pauseButton = new JButton(); JButton stopButton = new JButton(); JButton screenshotButton = new JButton(); JButton resetButton = new JButton(); JLabel runTimeLabel = new JLabel(); timeLabel = new JLabel(); JScrollPane infoPane = new JScrollPane(); infoTable = new JTable(); setTitle("BBStatistics"); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); setResizable(false); final Container contentPane = getContentPane(); contentPane.setLayout(new GridBagLayout()); ((GridBagLayout)contentPane.getLayout()).columnWidths = new int[] {6, 56, 6, 56, 6, 56, 6, 56, 4, 0}; ((GridBagLayout)contentPane.getLayout()).rowHeights = new int[] {6, 20, 24, 36, 4, 0}; ((GridBagLayout)contentPane.getLayout()).columnWeights = new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0E-4}; ((GridBagLayout)contentPane.getLayout()).rowWeights = new double[] {0.0, 0.0, 0.0, 0.0, 0.0, 1.0E-4}; //======== menuBar1 ======== { //======== menu1 ======== { menu1.setText("Options"); //---- menuItem1 ---- menuItem1.setText("Stuff"); menu1.add(menuItem1); } menuBar1.add(menu1); } setJMenuBar(menuBar1); //---- pauseButton ---- pauseButton.setText("Pause"); pauseButton.setMaximumSize(new Dimension(54, 18)); pauseButton.setMinimumSize(new Dimension(54, 18)); contentPane.add(pauseButton, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 2, 2), 0, 0)); pauseButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (pauseButton.getText().equalsIgnoreCase("pause")) { pauseButton.setText("Play"); Context.get().getScriptHandler().pause(); } else if (pauseButton.getText().equalsIgnoreCase("play")) { pauseButton.setText("Pause"); Context.get().getScriptHandler().resume(); } } }); //---- stopButton ---- stopButton.setText("Stop"); contentPane.add(stopButton, new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 2, 2), 0, 0)); stopButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { StatisticsHandler.setStop(true); dispose(); } }); //---- screenshotButton ---- screenshotButton.setText("Screenshot"); contentPane.add(screenshotButton, new GridBagConstraints(5, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 2, 2), 0, 0)); screenshotButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent a) { final BufferedImage image = new BufferedImage(contentPane.getWidth(), contentPane.getHeight(), BufferedImage.TYPE_INT_RGB); final Graphics2D g2d = image.createGraphics(); contentPane.paint(g2d); StatisticsHandler.setScreenshot(image); StatisticsHandler.setUploadImage(true); } }); //---- resetButton ---- resetButton.setText("Reset"); resetButton.setEnabled(false); contentPane.add(resetButton, new GridBagConstraints(7, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 2, 2), 0, 0)); //---- runTimeLabel ---- runTimeLabel.setText("Run time:"); runTimeLabel.setFont(new Font("Arial", Font.BOLD, 13)); contentPane.add(runTimeLabel, new GridBagConstraints(1, 2, 2, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 2, 2), 0, 0)); //---- timeLabel ---- timeLabel.setText(""); timeLabel.setFont(new Font("Arial", Font.PLAIN, 12)); contentPane.add(timeLabel, new GridBagConstraints(3, 2, 5, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 2, 2), 0, 0)); infoPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); infoPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER); infoPane.setEnabled(false); infoPane.setPreferredSize(new Dimension(300, 71)); //---- infoTable ---- infoTable.setFont(new Font("Arial", Font.PLAIN, 11)); infoTable.setModel(new DefaultTableModel( new Object[][] { {"Ranged", "0", "0", "0"}, {"Profit", "0", "0", null}, {"Tickets", "0", "0", null}, }, new String[] { "Title", "Amount", "Hourly", "Levels" } )); TableColumnModel cm = infoTable.getColumnModel(); for (int i = 0; i < 4; i++) cm.getColumn(i).setResizable(false); infoTable.setEnabled(false); infoPane.setViewportView(infoTable); contentPane.add(infoPane, new GridBagConstraints(1, 3, 7, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 2, 2), 0, 0)); pack(); setVisible(true); setLocationRelativeTo(getOwner()); }
3
public void addZombieAtCanvasLocation(int canvasX, int canvasY) { // FIRST MAKE SURE THE ENTIRE INTERSECTION IS INSIDE THE LEVEL if ((canvasX - 17.5) < 0) return; if ((canvasY - 17.5) < 0) return; if ((canvasX + 17.5) > viewport.levelWidth) return; if ((canvasY + 17.5) > viewport.levelHeight) return; // AND ONLY ADD THE INTERSECTION IF IT DOESN'T OVERLAP WITH // AN EXISTING INTERSECTION for(Zombie z : level.zombies) { double distance = calculateDistanceBetweenPoints(z.x-viewport.x, z.y-viewport.y, canvasX, canvasY); if (distance < 17.5) return; } // LET'S ADD A NEW INTERSECTION int intX = canvasX + viewport.x; int intY = canvasY + viewport.y; Zombie newZombie = new Zombie(intX, intY); level.zombies.add(newZombie); view.getCanvas().repaint(); }
6
public double getMeasure(String measureName) { if (measureName.equals("measureExtraArcs")) { return measureExtraArcs(); } if (measureName.equals("measureMissingArcs")) { return measureMissingArcs(); } if (measureName.equals("measureReversedArcs")) { return measureReversedArcs(); } if (measureName.equals("measureDivergence")) { return measureDivergence(); } if (measureName.equals("measureBayesScore")) { return measureBayesScore(); } if (measureName.equals("measureBDeuScore")) { return measureBDeuScore(); } if (measureName.equals("measureMDLScore")) { return measureMDLScore(); } if (measureName.equals("measureAICScore")) { return measureAICScore(); } if (measureName.equals("measureEntropyScore")) { return measureEntropyScore(); } return 0; } // getMeasure
9
static public Object getLowestDegreeVertex(mxAnalysisGraph aGraph, Object[] omitVertex) { Object[] vertices = aGraph.getChildVertices(aGraph.getGraph().getDefaultParent()); int vertexCount = vertices.length; int lowestEdgeCount = Integer.MAX_VALUE; Object bestVertex = null; List<Object> omitList = null; if (omitVertex != null) { omitList = Arrays.asList(omitVertex); } for (int i = 0; i < vertexCount; i++) { if (omitVertex == null || !omitList.contains(vertices[i])) { int currEdgeCount = aGraph.getEdges(vertices[i], null, true, true, true, true).length; if (currEdgeCount == 0) { return vertices[i]; } else { if (currEdgeCount < lowestEdgeCount) { lowestEdgeCount = currEdgeCount; bestVertex = vertices[i]; } } } } return bestVertex; };
6
public void swap(String name, String name2) { int one; String oneTemp = ""; for(one = 1; one< getCount(); one++){ if(get(one).endsWith(name)){ oneTemp = get(one); list.remove(one); break; } } int two; String twoTemp = ""; for(two = 0; two< getCount(); two++){ if(get(two).endsWith(name)){ twoTemp = get(two); list.remove(two); break; } } list.put(two, oneTemp); list.put(one, twoTemp); }
4
private void newPassword() { JPasswordField cPass = new JPasswordField(); JPasswordField nPass = new JPasswordField(); JPasswordField qPass = new JPasswordField(); JOptionPane.showConfirmDialog(null, cPass, "Enter current password", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); JOptionPane.showConfirmDialog(null, nPass, "Enter new password", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); JOptionPane.showConfirmDialog(null, qPass, "Enter new password again", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if(Arrays.equals(nPass.getPassword(), qPass.getPassword())) { try { if(opr.updateOperator(cPass.getPassword(), nPass.getPassword())) { textArea.append("[" + getDate() + "] Password has successfully been changed.\n"); } } catch (DALException e) { e.printStackTrace(); } } }
3
public ArrayList<Actor> getObjectsInRect(Rectangle rect, Class<? extends Actor> actorClass) { ArrayList<Actor> objectsAtPosition = new ArrayList<>(); for (Actor actor : actorList) { if(actor.getClass().isAssignableFrom(actorClass)) continue; if(actor.getRect().intersects(rect)) objectsAtPosition.add(actor); } return objectsAtPosition; }
4
public int longestValidParentheses_4(String s) { // DP solution, take advantage of the computed DP value, it is the distance to the index we want to look at int [] DP = new int[s.length()]; int res = 0; for(int i = 0; i < DP.length; ++i){ if(s.charAt(i) == ')' && i > 0){ int j = i - 1 - DP[i-1]; if(j >= 0 && s.charAt(j) == '('){ DP[i] = DP[i-1] + 2; if(j - 1 >= 0) DP[i] += DP[j-1]; res = Math.max(res, DP[i]); } } } return res; }
6
public boolean generate(World world, Random random, int x, int y, int z){ for (int l = 0; l < 64; ++l){ int i1 = x + random.nextInt(8) - random.nextInt(8); int j1 = y + random.nextInt(4) - random.nextInt(4); int k1 = z + random.nextInt(8) - random.nextInt(8); if (world.isAirBlock(i1, j1, k1) && this.block.canBlockStay(world, i1, j1, k1)){ world.setBlock(i1, j1, k1, this.block); } } return true; }
3
public static void main (String[] args) throws IOException { File file = new File("C:/1.txt"); BufferedReader in = new BufferedReader(new FileReader(file)); String line; int sum = 0; while ((line = in.readLine()) != null) { String[] lineArray = line.split("\n"); if (lineArray.length > 0) { //Process line of input Here sum += Integer.parseInt(line); } } System.out.println(sum); }
2
String anonymizeString(String input,String nameToBeAnonymized) { //extract name terms String nameTerms[] = nameToBeAnonymized.split(" "); String textTerms[] = input.split(" "); String output = null; //go through input, replace name term sequences with substitute boolean lastTermWasName = false; for(int i = 0; i < textTerms.length;i++) { boolean foundName = false; for(int j = 0; j < nameTerms.length;j++) { String processedTextTerm = textTerms[i].toLowerCase().replaceAll("[,.:;]+", ""); //System.out.println(processedTextTerm); if(processedTextTerm.compareTo(nameTerms[j].toLowerCase()) == 0) { foundName = true; } } if((foundName == true) && (anonymize == true)) { if(lastTermWasName == false) { if(output == null) { output = anonymousSubstituteName; } else { output = output + " " + anonymousSubstituteName; } } lastTermWasName = true; } else { if(output == null) { output = textTerms[i]; } else { output = output + " " + textTerms[i]; } lastTermWasName = false; } } return output; }
8
private Map<String, int[]> generateRewardTable(GemEventReward rewards) { ArrayList<Integer> levels = new ArrayList<Integer>(rewards.getLevels()); Collections.sort(levels); Map<String, int[]> table = new HashMap<String, int[]>(); boolean hasBonusGem = false; Iterator<Integer> levelIter = levels.iterator(); // scan rewards for bonus gems so the column can be eliminated if // there are none while (!hasBonusGem && levelIter.hasNext()) { if (rewards.getBonusGems(levelIter.next()) > 0) { hasBonusGem = true; } } if (hasBonusGem) { String bonusGemKey = "Bonus Gem"; // there is at least one bonus gem, so make a table column table.put(bonusGemKey, new int[levels.size()]); Iterator<Integer> levelIterator = levels.iterator(); int i = 0; while (levelIterator.hasNext()) { table.get(bonusGemKey)[i++] = rewards .getBonusGems(levelIterator.next()); } } for (int level : levels) { Map<String, Integer> levelRewards = rewards.getRewards(level); for (String item : levelRewards.keySet()) { // iterate over item names and for new items, add new entry if (!table.containsKey(item)) { // item hasn't been found yet, so add an entry in the map table.put(item, new int[levels.size()]); } table.get(item)[levels.indexOf(level)] = levelRewards.get(item); } } return table; }
8
public void writeLine(String s) throws IOException { for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); switch (c) { case '\\': super.write("\\\\"); break; case '\t': super.write("\\t"); break; case '\n': super.write("\\n"); break; case '\r': super.write("\\r"); break; case '\f': super.write("\\f"); break; default: if ((c < 0x0020) || (c > 0x007E)) { String hexChar = Integer.toHexString(c); super.write("\\u"); super.write(Integer.toHexString((c >> 12) & 0xF)); super.write(Integer.toHexString((c >> 8) & 0xF)); super.write(Integer.toHexString((c >> 4) & 0xF)); super.write(Integer.toHexString(c & 0xF)); } else write(c); } } newLine(); }
8
static final public Map<String, Object> asNestedMap(Map<? extends Object, ? extends Object> flattenMap){ Map<String, Object> nestedPropMap = new HashMap<>(); Map<String, Map<String,Object>> mapByPath = new HashMap<>(); for (Map.Entry entry : flattenMap.entrySet()){ Object keyObj = entry.getKey(); String key = (keyObj instanceof String)?(String)keyObj:keyObj.toString(); Object val = entry.getValue(); Object propVal = val; Map<String, Object> childPropMap = null; if (key.indexOf('.') != -1) { String[] names = key.split("\\."); int lastIdx = names.length - 1; for (int i = lastIdx; i >= 0; i--) { String propName = names[i]; // the mapByPath key (TODO: need to optimize this) String mapByPathKey = String.join(".",Arrays.copyOfRange(names, 0, i)); // if i == 0, then, we take the base propMap Map<String, Object> propMap = (i == 0)?nestedPropMap:mapByPath.get(mapByPathKey); boolean newPropMap = false; // create the propMap if needed if (propMap == null) { propMap = new HashMap<>(); mapByPath.put(mapByPathKey, propMap); newPropMap = true; } // put the value propMap.put(propName, propVal); // determine if we need set childPropMap for next iteration if (newPropMap){ propVal = propMap; }else{ break; } } }else{ nestedPropMap.put(key,val); } } return nestedPropMap; }
9
public void refreshImg(RefreshEvent event) { WorldModel wm = (WorldModel)event.getSource(); int win = wm.getWin(); switch (win) { case -1: this.imgButton.setImg(GraphicalGameView.loseImg); break; case 0: this.imgButton.setImg(GraphicalGameView.stoicImg); break; case 1: this.imgButton.setImg(GraphicalGameView.winImg); break; default: throw new AssertionError(); } }
3
@Test(expected = ImpossibleSolutionException.class) public void test_singular_matrix_solve() throws ImpossibleSolutionException,UnsquaredMatrixException, ElementOutOfRangeException{ int height=2; int width=2; System.out.print("Testing singular matrix solve method...\n\t"); try{ test_matrix = new LinearEquationSystem(height,width); }catch(UnsquaredMatrixException e){ throw e; } try{ test_matrix.setValueAt(0,0,0.0f); test_matrix.setValueAt(0,1,0.0f); test_matrix.setValueAt(1,0,0.0f); test_matrix.setValueAt(1,1,0.0f); }catch(ElementOutOfRangeException e){ throw e; } try{ test_matrix.solve(); }catch(ImpossibleSolutionException e){ System.out.println(e.toString()); throw e; } }
3
public static void main(String[] args) { for(char c = 0; c < 128; c++) if(Character.isLowerCase(c)) System.out.println("value: " + (int)c + " character: " + c); }
2
private ArrayList<Worker> jobWorkers(String job, Day day, ArrayList<String> workersWorking) { ArrayList<Worker> workersForJob = new ArrayList<Worker>(); for (Worker worker : this.workerIndices.get(this .numForName(day.getNameOfDay()))) { Day workerDay = worker.getDayWithName(day .getNameOfDay()); if (workerDay.getJobs().contains(job) && !workersWorking.contains(worker .getName())) { workersForJob.add(worker); } } return workersForJob; }
3
public static final int StateUpdateShortRep(int index) { return index < 7 ? 9 : 11; }
1
@SuppressWarnings("unchecked") protected T findOneResult(String namedQuery, Map<String, Object> parameters) { T result = null; try { Query query = manager.createNamedQuery(namedQuery); // Method that will populate parameters if they are passed not null and empty if (parameters != null && !parameters.isEmpty()) { populateQueryParameters(query, parameters); } result = (T) query.getSingleResult(); } catch (NoResultException e) { // TODO trocar isso aqui para log System.out.println("No result found for named query: " + namedQuery); } catch (Exception e) { // TODO trocar isso aqui para log System.out.println("Error while running query: " + e.getMessage()); e.printStackTrace(); } return result; }
4
public String toString() { return "waiting for user to start the game"; }
0
public boolean leaveMessage(Info info) { String message = info.getMessage(); String sender = info.getSender(); String channel = info.getChannel(); String stripped = message.substring( message.indexOf(" ") ).trim( ); int breakpt = stripped.indexOf( ' ' ); String who = stripped.substring( 0, breakpt ).trim( ); //check for abuse. Thank you HackBastard if( System.currentTimeMillis() > nextReset ) { sentMessages = new HashMap<String, Integer>(); nextReset = System.currentTimeMillis() + 1000*60*60*24; } if( sentMessages.get( who ) == null ) { sentMessages.put(who, 1); } else { int newTot = sentMessages.get(who) + 1; if( newTot > 25 ) { info.sendMessage( "Your request is denied. " + who + " has a full mailbox. This will reset sometime in the next 24 hours. Blame the <censored> who abused me and forced Entomo to put this in just so I can be started back up."); return true; } sentMessages.put(who, newTot ); } //now, onto the work of if( who.toLowerCase().equals(info.getBot().getName().toLowerCase()) ) { info.sendMessage("That would be me, dingleberry."); return true; } else if( who.toLowerCase().equals("jane") ) { info.sendMessage("No. I'm not speaking to her."); return true; } else if( who.toLowerCase().contains("beerwench") ) { info.sendMessage("Sorry, no. She scares me. Did you know she has a gun?"); return true; } else if( who.toLowerCase().contains("Teksura")) { List<String> stooges = Arrays.asList( "Teksura" ); if( Utils.isPresent(info, stooges) ) { info.sendAction( "points at Tek. \"I've been instructed to convey the following message, 'Just send him a fucking query if you want him to get the message before next month.'\"" ); info.sendMessage( "Try this: /msg Teksura " + stripped.substring( breakpt ) ); return true; } } String what = "( " + Utils.getRealTime(info) + ": In " + channel + " | From " + sender + " | To " + who + ") " + stripped.substring( breakpt ); messages.putMessage( who, what ); info.sendMessage( "Message saved." ); try { FileWriter out = new FileWriter("messages/"+ sender +".archive", true); out.write( what + Utils.NEWLINE ); out.close(); } catch(Exception e) { e.printStackTrace(); } return false; }
9
public int getMossaMinAvvicinando(){ int minAvv = 16; if(desmosse!=null) //Trovo il minimo tra i vmax for(DescrittoreMossa dm : desmosse) if(dm!=null && dm.getAvvicinando()<minAvv && dm.getAvvicinando()!= -1) minAvv = dm.getAvvicinando(); //Restituisco il vmin se è valido return minAvv!=16?minAvv:-1; }
6
public BTXEvent next() throws IOException { ParseEventData cur = eventStack; if (cur == null) { // If there's nothing left in the stack, we're at the end of the file! return BTXEvent.EOF; } if (cur.attrsLeft > 0) { cur.attrsLeft--; cur.curAttr = BTXHelp_0.readAttribute(f); return BTXEvent.ATTRIBUTE; } if (cur.objsLeft == 0) { // Out of children and done with the current object! eventStack = eventStack.par; return eventStack == null ? BTXEvent.EOF : BTXEvent.END_OBJECT; } else { // cur.objsLeft > 0 // Start reading a new object eventStack.curAttr = null; // Clear last curAttr // (don't need to do this really, but we should) cur.objsLeft--; eventStack = new ParseEventData(eventStack, // push it to the top of the stack BTXHelp_0.readString(f), // Name BTXHelp_0.read32BitUnsigned(f), // Attribute count BTXHelp_0.read32BitUnsigned(f)); // Object count return BTXEvent.START_OBJECT; } }
4
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; EdgeMarker other = (EdgeMarker) obj; if (_source == null) { if (other._source != null) return false; } else if (!_source.equals(other._source)) return false; if (_target == null) { if (other._target != null) return false; } else if (!_target.equals(other._target)) return false; return true; }
9
private boolean canHaveAsTeleporter(Position pos) { return pos != null && grid.getElementsOnPosition(pos).isEmpty(); }
1
public TileColor getLeft(TileColor top){ TileColor[] whiteL = {red,blue,orange,green}; TileColor[] blueL = {red,yellow,orange,white}; TileColor[] redL = {blue,white,green,yellow}; TileColor[] L = {}; if(top.equals(white)){ L = whiteL; } else if(top.equals(blue)){ L = blueL; } else if(top.equals(red)){ L = redL; } else if(top.equals(yellow)){ L = flip(whiteL); } else if(top.equals(green)){ L = flip(blueL); } else if(top.equals(orange)){ L = flip(redL); } int i = find(this,L) - 1; i = i == -1 ? 3 : i; if(i == -2) return null; return L[i]; }
8
private void delete(File file) throws Exception { File[] inners = file.listFiles(); if (null != inners && inners.length > 0) { for (File inner : inners) { delete(inner); } } if (!file.delete()) { throw newIOException(file); } }
4
public void begin() { started = System.currentTimeMillis(); }
0
private void order(int start, int end) { if(start >= end) return; int separatorPos = divide(start, end); order(start, separatorPos - 1); order(separatorPos + 1, end); }
1
private static String LoadShader(String fileName) { StringBuilder shaderSource = new StringBuilder(); BufferedReader shaderReader = null; final String INCLUDE_DIRECTIVE = "#include"; try { shaderReader = new BufferedReader(new FileReader("./res/shaders/" + fileName)); String line; while((line = shaderReader.readLine()) != null) { if(line.startsWith(INCLUDE_DIRECTIVE)) { shaderSource.append(LoadShader(line.substring(INCLUDE_DIRECTIVE.length() + 2, line.length() - 1))); } else shaderSource.append(line).append("\n"); } shaderReader.close(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } return shaderSource.toString(); }
3
private void setParameterValue(final PreparedStatement ps, final List<Object[]> argsList, int idx) throws SQLException { Object[] args = argsList.get(idx); if (args != null) { for (int index = 0; index < args.length; index++) { Object arg = args[index]; JdbcUtils.setParameterValue(ps, index + 1, arg); } } }
2
public ItemEditor(int ID) { setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); System.setProperty("resources", System.getProperty("user.dir") + "/resources"); this.ID = ID; setTitle("Item Editor"); setBounds(100, 100, 600, 500); getContentPane().setLayout(new BorderLayout()); contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); getContentPane().add(contentPanel, BorderLayout.CENTER); contentPanel.setLayout(null); JSplitPane splitPane = new JSplitPane(); splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT); splitPane.setBounds(0, 0, 584, 429); contentPanel.add(splitPane); JPanel panel = new JPanel(); splitPane.setLeftComponent(panel); panel.setLayout(null); JLabel lblName = new JLabel("Name:"); lblName.setBounds(10, 38, 46, 14); panel.add(lblName); nameText = new JTextField(); nameText.setBounds(66, 35, 86, 20); panel.add(nameText); nameText.setColumns(10); IDText = new JTextField(ID + ""); IDText.setEditable(false); IDText.setBounds(66, 11, 86, 20); panel.add(IDText); IDText.setColumns(10); stackableCheck = new JCheckBox("Stackable"); stackableCheck.setBounds(10, 59, 91, 23); panel.add(stackableCheck); JLabel lblPrice = new JLabel("Price:"); lblPrice.setBounds(10, 115, 46, 14); panel.add(lblPrice); priceSpinner = new JSpinner(); priceSpinner.setModel(new SpinnerNumberModel(new Integer(0), new Integer(0), null, new Integer(1))); priceSpinner.setBounds(76, 113, 59, 20); panel.add(priceSpinner); usableCheck = new JCheckBox("Usable"); usableCheck.setBounds(10, 85, 86, 23); panel.add(usableCheck); JLabel lblWeaponType = new JLabel("Weapon Type:"); lblWeaponType.setBounds(162, 38, 86, 14); panel.add(lblWeaponType); wepTypeCombo = new JComboBox<String>(); wepTypeCombo.setModel(new DefaultComboBoxModel<String>(new String[] {"Melee", "Magic", "Ranged"})); wepTypeCombo.setBounds(258, 34, 86, 22); panel.add(wepTypeCombo); JLabel lblVigorCost = new JLabel("Vigor Cost:"); lblVigorCost.setBounds(10, 140, 71, 14); panel.add(lblVigorCost); vigorSpinner = new JSpinner(); vigorSpinner.setModel(new SpinnerNumberModel(new Float(0), new Float(0), null, new Float(1))); vigorSpinner.setBounds(76, 138, 59, 20); panel.add(vigorSpinner); JLabel lblWeaponName = new JLabel("Weapon Name:"); lblWeaponName.setBounds(162, 63, 86, 14); panel.add(lblWeaponName); JLabel lblDamage = new JLabel("Damage:"); lblDamage.setBounds(10, 165, 53, 14); panel.add(lblDamage); damageSpinner = new JSpinner(); damageSpinner.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); damageSpinner.setBounds(76, 163, 59, 20); panel.add(damageSpinner); JLabel lblResistance = new JLabel("Resistance:"); lblResistance.setBounds(354, 38, 71, 14); panel.add(lblResistance); JLabel lblCrush = new JLabel("Crush:"); lblCrush.setBounds(354, 64, 46, 14); panel.add(lblCrush); crushSpinner = new JSpinner(); crushSpinner.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); crushSpinner.setBounds(410, 61, 46, 20); panel.add(crushSpinner); JLabel lblThrust = new JLabel("Thrust:"); lblThrust.setBounds(354, 90, 46, 14); panel.add(lblThrust); thrustSpinner = new JSpinner(); thrustSpinner.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); thrustSpinner.setBounds(410, 87, 46, 20); panel.add(thrustSpinner); JLabel lblSlash = new JLabel("Slash:"); lblSlash.setBounds(354, 116, 46, 14); panel.add(lblSlash); slashSpinner = new JSpinner(); slashSpinner.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); slashSpinner.setBounds(410, 113, 46, 20); panel.add(slashSpinner); JLabel lblMagic = new JLabel("Magic:"); lblMagic.setBounds(354, 165, 46, 14); panel.add(lblMagic); magicSpinner = new JSpinner(); magicSpinner.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); magicSpinner.setBounds(410, 163, 46, 20); panel.add(magicSpinner); JLabel lblHead = new JLabel("Head:"); lblHead.setBounds(466, 64, 46, 14); panel.add(lblHead); headSpinner = new JSpinner(); headSpinner.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); headSpinner.setBounds(522, 61, 46, 20); panel.add(headSpinner); JLabel lblBody = new JLabel("Body:"); lblBody.setBounds(466, 90, 46, 14); panel.add(lblBody); bodySpinner = new JSpinner(); bodySpinner.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); bodySpinner.setBounds(522, 87, 46, 20); panel.add(bodySpinner); crippleSpinner = new JSpinner(); crippleSpinner.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); crippleSpinner.setBounds(522, 113, 46, 20); panel.add(crippleSpinner); JLabel lblCripple = new JLabel("Cripple:"); lblCripple.setBounds(466, 116, 46, 14); panel.add(lblCripple); JLabel lblSpells = new JLabel("Spells:"); lblSpells.setBounds(162, 90, 46, 14); panel.add(lblSpells); JLabel lblId = new JLabel("ID:"); lblId.setBounds(10, 15, 46, 14); panel.add(lblId); JLabel lblItemType = new JLabel("Item Type:"); lblItemType.setBounds(164, 15, 84, 14); panel.add(lblItemType); itemTypeCombo = new JComboBox<String>(); itemTypeCombo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { tabbedPane.setEnabledAt(0, false); tabbedPane.setEnabledAt(1, false); tabbedPane.setEnabledAt(2, false); tabbedPane.setEnabledAt(3, false); switch(itemTypeCombo.getSelectedIndex()) { case(0): tabbedPane.setEnabledAt(0, true); tabbedPane.setSelectedIndex(0); break; case(1): tabbedPane.setEnabledAt(1, true); tabbedPane.setSelectedIndex(1); break; case(2): tabbedPane.setEnabledAt(2, true); tabbedPane.setSelectedIndex(2); break; case(3): tabbedPane.setEnabledAt(3, true); tabbedPane.setSelectedIndex(3); toggleAmmo(); break; } updateID(); } }); itemTypeCombo.setModel(new DefaultComboBoxModel<String>(new String[] {"Pocket", "Armor", "Weapon", "Ammo"})); itemTypeCombo.setBounds(258, 10, 86, 22); panel.add(itemTypeCombo); weaponNameCombo = new JComboBox<String>(); weaponNameCombo.setModel(buildWeaponList()); weaponNameCombo.setBounds(258, 59, 86, 22); panel.add(weaponNameCombo); tabbedPane = new JTabbedPane(JTabbedPane.TOP); splitPane.setRightComponent(tabbedPane); JPanel pocketPanel = new JPanel(); tabbedPane.addTab("Pocket", null, pocketPanel, null); pocketPanel.setLayout(null); consumableCheck = new JCheckBox("Consumable"); consumableCheck.setBounds(8, 9, 97, 23); pocketPanel.add(consumableCheck); JButton effectButton = new JButton("Add Effect"); effectButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ConsumableEditor consumableEditor = new ConsumableEditor(Integer.parseInt(IDText.getText())); if(consumableEditor.getEffects() != null) effectTextArea.setText(consumableEditor.getEffects()); } }); effectButton.setBounds(8, 41, 95, 25); pocketPanel.add(effectButton); JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(8, 73, 213, 75); pocketPanel.add(scrollPane); effectTextArea = new JTextArea(); scrollPane.setViewportView(effectTextArea); tabbedPane.setEnabledAt(0, true); JPanel armorPanel = new JPanel(); tabbedPane.addTab("Armor", null, armorPanel, null); armorPanel.setLayout(null); JLabel lblArmorSlot = new JLabel("Armor Slot:"); lblArmorSlot.setBounds(12, 13, 60, 14); armorPanel.add(lblArmorSlot); armorSlotCombo = new JComboBox<String>(); armorSlotCombo.setModel(buildSlotList(1)); armorSlotCombo.setBounds(84, 11, 86, 20); armorPanel.add(armorSlotCombo); JLabel lblStability = new JLabel("Stability:"); lblStability.setBounds(12, 40, 46, 14); armorPanel.add(lblStability); stabilitySpinner = new JSpinner(); stabilitySpinner.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); stabilitySpinner.setBounds(84, 38, 39, 20); armorPanel.add(stabilitySpinner); tabbedPane.setEnabledAt(1, false); JPanel weaponPanel = new JPanel(); tabbedPane.addTab("Weapon", null, weaponPanel, null); weaponPanel.setLayout(null); JLabel lblWeaponSlot = new JLabel("Weapon Slot:"); lblWeaponSlot.setBounds(12, 13, 70, 14); weaponPanel.add(lblWeaponSlot); weaponSlotCombo = new JComboBox<String>(); weaponSlotCombo.setModel(buildSlotList(2)); weaponSlotCombo.setBounds(94, 11, 86, 20); weaponPanel.add(weaponSlotCombo); JLabel lblSkill = new JLabel("Skill:"); lblSkill.setBounds(12, 40, 46, 14); weaponPanel.add(lblSkill); skillSpinner = new JSpinner(); skillSpinner.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); skillSpinner.setBounds(94, 38, 39, 20); weaponPanel.add(skillSpinner); tabbedPane.setEnabledAt(2, false); JPanel ammoPanel = new JPanel(); tabbedPane.addTab("Ammo", null, ammoPanel, null); ammoPanel.setLayout(null); JLabel lblBreakChance = new JLabel("Break Chance:"); lblBreakChance.setBounds(8, 41, 75, 14); ammoPanel.add(lblBreakChance); breakSpinner = new JSpinner(); breakSpinner.setModel(new SpinnerNumberModel(new Float(0), new Float(0), new Float(1), new Float(1))); breakSpinner.setBounds(95, 39, 41, 20); ammoPanel.add(breakSpinner); JLabel lblAmmoType = new JLabel("Ammo Type:"); lblAmmoType.setBounds(8, 68, 75, 14); ammoPanel.add(lblAmmoType); ammoTypeCombo = new JComboBox<ProjectileType>(); ammoTypeCombo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { toggleAmmo(); } }); ammoTypeCombo.setModel(new DefaultComboBoxModel<ProjectileType>(ProjectileType.values())); ammoTypeCombo.setBounds(95, 64, 97, 22); ammoPanel.add(ammoTypeCombo); JLabel lblAmmoName = new JLabel("Ammo Name:"); lblAmmoName.setBounds(8, 95, 75, 14); ammoPanel.add(lblAmmoName); ammoText = new JTextField(); ammoText.setBounds(95, 93, 86, 20); ammoPanel.add(ammoText); ammoText.setColumns(10); JLabel lblSpeed = new JLabel("Speed:"); lblSpeed.setBounds(8, 122, 46, 14); ammoPanel.add(lblSpeed); speedSpinner = new JSpinner(); speedSpinner.setModel(new SpinnerNumberModel(new Float(0), new Float(0), null, new Float(1))); speedSpinner.setBounds(95, 120, 41, 20); ammoPanel.add(speedSpinner); piercingCheck = new JCheckBox("Piercing"); piercingCheck.setBounds(8, 145, 97, 23); ammoPanel.add(piercingCheck); JLabel lblDistance = new JLabel("Distance:"); lblDistance.setBounds(200, 14, 54, 14); ammoPanel.add(lblDistance); distanceSpinner = new JSpinner(); distanceSpinner.setModel(new SpinnerNumberModel(new Float(0), new Float(0), null, new Float(1))); distanceSpinner.setBounds(266, 11, 41, 20); ammoPanel.add(distanceSpinner); JLabel lblDamage_1 = new JLabel("Damage:"); lblDamage_1.setBounds(200, 42, 54, 14); ammoPanel.add(lblDamage_1); ammoDamageSpinner = new JSpinner(); ammoDamageSpinner.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); ammoDamageSpinner.setBounds(266, 39, 41, 20); ammoPanel.add(ammoDamageSpinner); JLabel lblRadius = new JLabel("Diameter:"); lblRadius.setBounds(200, 69, 54, 14); ammoPanel.add(lblRadius); diameterSpinner = new JSpinner(); diameterSpinner.setModel(new SpinnerNumberModel(new Float(0), new Float(0), null, new Float(1))); diameterSpinner.setBounds(266, 66, 41, 20); ammoPanel.add(diameterSpinner); multiCheck = new JCheckBox("Multi"); multiCheck.setBounds(200, 92, 97, 23); ammoPanel.add(multiCheck); movingCheck = new JCheckBox("Moving"); movingCheck.setBounds(200, 119, 97, 23); ammoPanel.add(movingCheck); JLabel lblDuration = new JLabel("Duration:"); lblDuration.setBounds(200, 150, 54, 14); ammoPanel.add(lblDuration); durationSpinner = new JSpinner(); durationSpinner.setModel(new SpinnerNumberModel(new Float(0), new Float(0), null, new Float(1))); durationSpinner.setBounds(266, 147, 41, 20); ammoPanel.add(durationSpinner); JLabel lblAreaTexture = new JLabel("Area Texture:"); lblAreaTexture.setBounds(319, 14, 69, 14); ammoPanel.add(lblAreaTexture); areaTextureText = new JTextField(); areaTextureText.setBounds(400, 11, 86, 20); ammoPanel.add(areaTextureText); areaTextureText.setColumns(10); JLabel lblWeaponSlot_1 = new JLabel("Weapon Slot:"); lblWeaponSlot_1.setBounds(8, 14, 75, 14); ammoPanel.add(lblWeaponSlot_1); ammoWeaponSpinner = new JSpinner(); ammoWeaponSpinner.setModel(new SpinnerNumberModel(0, 0, 7, 1)); ammoWeaponSpinner.setBounds(95, 12, 41, 20); ammoPanel.add(ammoWeaponSpinner); tabbedPane.setEnabledAt(3, false); splitPane.setDividerLocation(200); { JPanel buttonPane = new JPanel(); buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT)); getContentPane().add(buttonPane, BorderLayout.SOUTH); { JButton okButton = new JButton("OK"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { updateID(); save(); dispose(); } }); okButton.setActionCommand("OK"); buttonPane.add(okButton); getRootPane().setDefaultButton(okButton); } { JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { dispose(); } }); cancelButton.setActionCommand("Cancel"); buttonPane.add(cancelButton); } } if(ID != 0) load(); setModalityType(ModalityType.APPLICATION_MODAL); setVisible(true); }
6
* * @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 CycConstant makeCycConstant(String name) throws UnknownHostException, IOException, CycApiException { String constantName = name; if (constantName.startsWith("#$")) { constantName = constantName.substring(2); } CycConstant cycConstant = getConstantByName(name); if (cycConstant != null) { return cycConstant; } String command = wrapBookkeeping("(ke-create-now \"" + constantName + "\")"); Object object = converseObject(command); if (object instanceof CycConstant) { cycConstant = (CycConstant) object; } else { throw new CycApiException("Cannot create new constant for " + name); } CycObjectFactory.addCycConstantCache(cycConstant); return cycConstant; }
3
@Override public String runMacro(HTTPRequest httpReq, String parm, HTTPResponse httpResp) throws HTTPServerException { if(!CMProps.getBoolVar(CMProps.Bool.MUDSTARTED)) return "false;"; if(!initialized) { initialize(); } if((httpReq.getHeader("upgrade")!=null) &&("websocket".equalsIgnoreCase(httpReq.getHeader("upgrade"))) &&(httpReq.getHeader("connection")!=null) &&(httpReq.getHeader("connection").toLowerCase().indexOf("upgrade")>=0)) { final HTTPException exception = new HTTPException(HTTPStatus.S101_SWITCHING_PROTOCOLS); try { final String key = httpReq.getHeader("sec-websocket-key"); final String tokenStr = key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; final MessageDigest cript = MessageDigest.getInstance("SHA-1"); cript.reset(); cript.update(tokenStr.getBytes("utf8")); final String token = B64Encoder.B64encodeBytes(cript.digest()); httpResp.setStatusCode(101); exception.getErrorHeaders().put(HTTPHeader.Common.CONNECTION, HTTPHeader.Common.UPGRADE.toString()); exception.getErrorHeaders().put(HTTPHeader.Common.UPGRADE, httpReq.getHeader("upgrade")); exception.getErrorHeaders().put(HTTPHeader.Common.SEC_WEBSOCKET_ACCEPT, token); if(httpReq.getHeader("origin")!=null) exception.getErrorHeaders().put(HTTPHeader.Common.ORIGIN, httpReq.getHeader("origin")); final StringBuilder locationStr = new StringBuilder("ws://"+httpReq.getHost()); if(httpReq.getClientPort() != 80) locationStr.append(":").append(httpReq.getClientPort()); locationStr.append(httpReq.getUrlPath()); exception.getErrorHeaders().put(HTTPHeader.Common.SEC_WEBSOCKET_LOCATION, locationStr.toString()); final SipletProtocolHander newHandler = new SipletProtocolHander(); exception.setNewProtocolHandler(newHandler); } catch (Exception e) { Log.errOut(e); throw new HTTPServerException(e.getMessage()); } throw new HTTPServerException(exception); } return processRequest(httpReq); }
9
public String toString() { String listArray = ""; for(int index = 0; index < manyItems; index++) { listArray += String.valueOf(data[index])+ ","; } /* WONG VERSION for(int index = 0; index < data.length; index++) { listArray += String.valueOf(data[index]) + "\n"; } */ return "{"+ listArray + "}"; }
1
public void siteUnreachable(String site) { lock.lock(); try { for(Map.Entry<Address,Rsp<T>> entry : rsps.entrySet()) { Address member=entry.getKey(); if(!(member instanceof SiteAddress)) continue; SiteAddress addr=(SiteAddress)member; if(addr.getSite().equals(site)) { Rsp<T> rsp=entry.getValue(); if(rsp != null && rsp.setUnreachable()) { lock.lock(); try { if(!(rsp.wasReceived() || rsp.wasSuspected())) num_received++; } finally { lock.unlock(); } } } } if(responsesComplete()) { complete(this.rsps); corrDone(); } } finally { lock.unlock(); } }
8
@Override public void executeTask() { try { sendingSocket = new DatagramSocket(SENDING_PORT); sendingSocket.setBroadcast(true); client = new Client(); client.setCurrentIP(InetAddress.getLocalHost().getHostAddress()); client.setHostname(InetAddress.getLocalHost().getHostName()); client.setReceivingPort(ServerReceiverServlet.LISTENING_PORT); client.setUsername("Client " + client.getHostname()); client.SERVER_COMMAND = COMMAND_TYPE.REGISTER_NODE; buffer = client.toBytes(); String defGateway = DCServer.GetDefaultGateway(); String ipPiece = defGateway.substring(0, defGateway.length() - 1); String[] ipPieces = defGateway.split("\\."); ipPiece = ipPieces[0] + "." + ipPieces[1] + "."; for (int i = 0; i < 255; i++) { for (int j = 0; j < 255; j++) { String builtIP = ipPiece + Integer.toString(i) + "." + Integer.toString(j); dataGram = new DatagramPacket(buffer, buffer.length); dataGram.setPort(ServerReceiverServlet.LISTENING_PORT); dataGram.setAddress(InetAddress.getByName(builtIP)); sendingSocket.send(dataGram); } } sendingSocket.close(); } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // String userInput = // SynchedInOut.getInstance().postMessageForUserInput("Network scan finished. Scan again? (y/n): "); // // if(userInput.equalsIgnoreCase("y")) { // executeTask(); // } stopTask(); }
5
@Override protected Control createContents(Composite parent) { Composite container = new Composite(parent, SWT.NONE); container.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE)); container.setLayout(null); txtBalance = formToolkit.createText(container, "New Text", SWT.NONE); txtBalance.setBounds(89, 10, 76, 21); txtBalance.setToolTipText("Total Balance"); txtBalance.setText(""); Label lblBalance = new Label(container, SWT.NONE); lblBalance.setBackground(SWTResourceManager .getColor(SWT.COLOR_WIDGET_FOREGROUND)); lblBalance.setBounds(10, 13, 73, 15); formToolkit.adapt(lblBalance, true, true); lblBalance.setText("Balance"); txtComputedRisk = new Text(container, SWT.BORDER); txtComputedRisk.setBounds(89, 91, 76, 21); formToolkit.adapt(txtComputedRisk, true, true); txtHighscore = new Text(container, SWT.BORDER); txtHighscore.setBounds(89, 37, 76, 21); formToolkit.adapt(txtHighscore, true, true); txtStartingBet = new Text(container, SWT.BORDER); txtStartingBet.setText("25"); txtStartingBet.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent arg0) { Integer i = new Integer(txtStartingBet.getText()); if (i > 0) { strategy.setStartingBet(i); } } }); txtStartingBet.setBounds(89, 64, 76, 21); formToolkit.adapt(txtStartingBet, true, true); lblHighestBalance = new Label(container, SWT.NONE); lblHighestBalance.setText("Highscore"); lblHighestBalance.setBackground(SWTResourceManager .getColor(SWT.COLOR_WIDGET_FOREGROUND)); lblHighestBalance.setBounds(10, 40, 73, 15); formToolkit.adapt(lblHighestBalance, true, true); lblStarting = new Label(container, SWT.NONE); lblStarting.setText("Starting Bet"); lblStarting.setBackground(SWTResourceManager .getColor(SWT.COLOR_WIDGET_FOREGROUND)); lblStarting.setBounds(10, 67, 73, 15); formToolkit.adapt(lblStarting, true, true); lblTotalRisk = new Label(container, SWT.NONE); lblTotalRisk.setText("Total Risk"); lblTotalRisk.setBackground(SWTResourceManager .getColor(SWT.COLOR_WIDGET_FOREGROUND)); lblTotalRisk.setBounds(10, 94, 73, 15); formToolkit.adapt(lblTotalRisk, true, true); txtNormalRisk = new Text(container, SWT.BORDER); txtNormalRisk.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent arg0) { int risk = new Integer(txtNormalRisk.getText()); if (risk > 1) { // strategy.setNormalRisk(risk); } } }); txtNormalRisk.setText("200"); txtNormalRisk.setBounds(318, 10, 76, 21); formToolkit.adapt(txtNormalRisk, true, true); txtLossRisk = new Text(container, SWT.BORDER); txtLossRisk.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent arg0) { int risk = new Integer(txtLossRisk.getText()); if (risk > 1) { // strategy.setLossRisk(risk); } } }); txtLossRisk.setText("10"); txtLossRisk.setBounds(318, 37, 76, 21); formToolkit.adapt(txtLossRisk, true, true); txtMultiplier = new Text(container, SWT.BORDER); txtMultiplier.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent arg0) { Float mul = new Float(txtMultiplier.getText()); if (mul >= 2 && mul <= 4) { // strategy.setMultiplier(mul); } } }); txtMultiplier.setText("2"); txtMultiplier.setBounds(318, 64, 76, 21); formToolkit.adapt(txtMultiplier, true, true); txtBadStreak = new Text(container, SWT.BORDER); txtBadStreak.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent arg0) { Integer mul = new Integer(txtBadStreak.getText()); if (mul > 6) { // strategy.setBadStreak(mul); } } }); txtBadStreak.setText("13"); txtBadStreak.setBounds(318, 91, 76, 21); formToolkit.adapt(txtBadStreak, true, true); lblNormalRisk = new Label(container, SWT.NONE); lblNormalRisk.setText("Normal Risk"); lblNormalRisk.setBackground(SWTResourceManager .getColor(SWT.COLOR_WIDGET_FOREGROUND)); lblNormalRisk.setBounds(239, 16, 73, 15); formToolkit.adapt(lblNormalRisk, true, true); lblLossRisk = new Label(container, SWT.NONE); lblLossRisk.setText("Loss Risk"); lblLossRisk.setBackground(SWTResourceManager .getColor(SWT.COLOR_WIDGET_FOREGROUND)); lblLossRisk.setBounds(239, 43, 73, 15); formToolkit.adapt(lblLossRisk, true, true); lblMultiplier = new Label(container, SWT.NONE); lblMultiplier.setText("Multiplier"); lblMultiplier.setBackground(SWTResourceManager .getColor(SWT.COLOR_WIDGET_FOREGROUND)); lblMultiplier.setBounds(239, 70, 73, 15); formToolkit.adapt(lblMultiplier, true, true); lblBadStreak = new Label(container, SWT.NONE); lblBadStreak.setText("Bad Streak"); lblBadStreak.setBackground(SWTResourceManager .getColor(SWT.COLOR_WIDGET_FOREGROUND)); lblBadStreak.setBounds(239, 97, 73, 15); formToolkit.adapt(lblBadStreak, true, true); startButton = new Button(container, SWT.NONE); startButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (strategy.running) { strategy.running = false; updateStartButton("Start"); } else { strategy.start(); updateStartButton("Stop"); } } }); startButton.setBounds(92, 135, 220, 54); formToolkit.adapt(startButton, true, true); startButton.setText("Start"); Button btnReset = new Button(container, SWT.NONE); btnReset.addMouseListener(new MouseAdapter() { @Override public void mouseDown(MouseEvent e) { //strategy.highscore = 0; txtHighscore.setText("0"); updateHighscore(0); } }); btnReset.setBounds(318, 150, 75, 25); formToolkit.adapt(btnReset, true, true); btnReset.setText("Reset"); return container; }
7
public void redo() { revising = true; if (!TEXT_FUTURE.isEmpty()) { String restoreText = TEXT_FUTURE.pop(); TEXT_HISTORY.push(restoreText); textLower.setText(restoreText); // gui.TEXT_HISTORY.tailMap(fromKey) } }
1
public static List<Player> getNearbyPlayers(Location l, int range) { List<Player> players = new ArrayList<Player>(); for (Entity e : getNearbyEntities(l, range)) { if (e instanceof Player) { players.add((Player) e); } } return players; }
2
protected void initialize() {}
0
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Article other = (Article) obj; if (!Objects.equals(this.id, other.id)) { return false; } if (!Objects.equals(this.name, other.name)) { return false; } if (!Objects.equals(this.ordersCollection, other.ordersCollection)) { return false; } if (Float.floatToIntBits(this.price) != Float.floatToIntBits(other.price)) { return false; } if (!Objects.equals(this.description, other.description)) { return false; } return true; }
7
public int getDestinationEnd() { return this._destinationEnd; }
0
public void purgeOperation() { try { Iterator iterator = mapTtl.keySet().iterator(); String key = null; Date expTime; Date currentTime = new Date(); while (iterator.hasNext()) { key = (String) iterator.next(); expTime = (Date) mapTtl.get(key); if(expTime==null) { continue; } if (expTime.before(currentTime)) { mapTtl.remove(key); map.remove(key); while(true) { if(hardCache.remove(key)==false) { break; } } expired++; } Thread.yield(); } } catch (Exception e) { logger.log(Level.WARNING, "Error: " + e, e); } }
6
public static TreeNode lowestCommonAncestor(TreeNode root, TreeNode a, TreeNode b) { TreeNode left = null; TreeNode right = null; if (root == null || root == a || root == b) { return root; } left = lowestCommonAncestor(root.left, a, b); right = lowestCommonAncestor(root.right, a, b); if (left != null && right != null) { return root; } if (left == null) { return right; } if (right == null) { return left; } return null; }
7
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(dlgConfiguration.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(dlgConfiguration.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(dlgConfiguration.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(dlgConfiguration.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { dlgConfiguration dialog = new dlgConfiguration(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); }
6
public static float getFovX() { return fovX; }
0
@Override public void changedMostRecentDocumentTouched(DocumentRepositoryEvent e) { calculateEnabledState(e.getDocument()); }
0
public Rank getFourthRank() { return (ranks.size() < 4 ? Rank.Null : ranks.get(3)); }
1
public boolean isChar(int token) { return (token == 0x09 || token == 0x0A || token == 0x0D || token >= 0x20 && token <= 0xFF); }
4
@Test public void testGetHig() { System.out.println("getHig"); assertEquals(3.0, new Cylinder(3,1,2.8).getHig(), 0.00001); }
0
public void exitRoutine() { boolean exit = true ; TGlobal.config.setDirectInt( "mainWidth", this.getWidth() ) ; TGlobal.config.setDirectInt( "mainHeight", this.getHeight() ) ; // ask - save data ? if ( TGlobal.projects.isProjectChanged() ) { int result = JOptionPane.showConfirmDialog( null, "Project has changed - exit without saving files ?", "Exit Question/Warning", JOptionPane.YES_NO_OPTION ) ; if ( result != JOptionPane.YES_OPTION ) { exit = false ; } } if ( exit ) { // save the configuration try { // save the current project TGlobal.config.setLastProject( TGlobal.projects.getCurrentProject().getProjectFile()) ; TGlobal.config.save() ; } catch ( Exception e ) { JOptionPane.showMessageDialog( null, "could not save the current configuration", "save configuration", JOptionPane.ERROR_MESSAGE ) ; } System.exit( 0 ) ; } }
4
@Override public BMPImage apply(BMPImage image) { Filter grey = new Grey(); image = grey.apply(image); BMPImage filteredImage = new BMPImage(image); BMPImage.BMPColor[][] bitmap = image.getBitMap(); BMPImage.BMPColor[][] filteredBitmap = filteredImage.getBitMap(); for(int i = 1; i <= filteredImage.getHeight(); i++) { for(int j = 1; j <= filteredImage.getWidth(); j++) { int y = (int) (-bitmap[i - 1][j - 1].red - 2*bitmap[i - 1][j].red - bitmap[i - 1][j + 1].red + bitmap[i + 1][j - 1].red + 2*bitmap[i + 1][j].red + bitmap[i + 1][j + 1].red); int x = (int) (-bitmap[i - 1][j - 1].red - 2*bitmap[i][j - 1].red - bitmap[i + 1][j - 1].red + bitmap[i - 1][j + 1].red + 2*bitmap[i][j + 1].red + bitmap[i + 1][j + 1].red); int r = (int)Math.sqrt(x*x + y*y); if(r < 0) r = 0; if(r > 255) r = 255; filteredBitmap[i][j].red = r; filteredBitmap[i][j].green = r; filteredBitmap[i][j].blue = r; } } return filteredImage; }
4
public boolean handleRightClick(Point clickPoint) { HUD hud = null; boolean doUpdate = !gameController.getIsMasterPaused(); //start from the top and work our way down to "layer" the huds for (int i = (huds.size() - 1); i >= 0; i--) { hud = huds.get(i); if (doUpdate || hud.getName().equals("Pause") || hud.getName().equals("Tutorial") || hud.getName().equals("Credits")) { if (hud.handleRightClick(clickPoint)) { return true; } } } return false; }
6
@Override public boolean containsValue(Object value) { String key = (String) value; boolean res = false; for (Map.Entry<String, String> e : entries) { if (key == null) { if (e.getValue() == null) { res = true; break; } } else if (key.equalsIgnoreCase(e.getValue())) { res = true; break; } } return res; }
4
public void print() { // check if read in if(!treeHeader.isHeaderOK()){ int badMagic = treeHeader.getMagic(); log.error("Error reading B+ tree header: bad magic = " + badMagic); return; } // print B+ tree header treeHeader.print(); // print B+ tree node and leaf items - recursively if(rootNode != null) rootNode.printItems(); }
2
public void signAndSaveMessage(String message) { // die Nachricht als Byte-Array byte[] msg = message.getBytes(); Signature rsaSig = null; byte[] signature = null; try { // als Erstes erzeugen wir das Signatur-Objekt rsaSig = Signature.getInstance("SHA1withRSA"); // zum Signieren benoetigen wir den privaten Schluessel (hier: RSA) rsaSig.initSign(keyPair.getPrivate()); // Daten fuer die kryptographische Hashfunktion (hier: SHA1) liefern rsaSig.update(msg); // Signatur durch Verschluesselung des Hashwerts (mit privatem RSA-Schluessel) erzeugen signature = rsaSig.sign(); } catch (NoSuchAlgorithmException ex) { showErrorAndExit("Keine Implementierung fuer SHA1withRSA!", ex); } catch (InvalidKeyException ex) { showErrorAndExit("Falscher Schluessel!", ex); } catch (SignatureException ex) { showErrorAndExit("Fehler beim Signieren der Nachricht!", ex); } // der oeffentliche Schluessel vom Schluesselpaar PublicKey pubKey = keyPair.getPublic(); // wir benoetigen die Default-Kodierung byte[] pubKeyEnc = pubKey.getEncoded(); System.out .println("Der Public Key wird in folgendem Format gespeichert: " + pubKey.getFormat()); try { // eine Datei wird erzeugt und danach die Nachricht, die Signatur // und der oeffentliche Schluessel darin gespeichert DataOutputStream os = new DataOutputStream(new FileOutputStream( fileName)); os.writeInt(msg.length); os.write(msg); os.writeInt(signature.length); os.write(signature); os.writeInt(pubKeyEnc.length); os.write(pubKeyEnc); os.close(); } catch (IOException ex) { showErrorAndExit("Fehler beim Schreiben der signierten Nachricht.", ex); } // Bildschirmausgabe System.out.println("Erzeugte SHA1/RSA-Signatur: "); for (int i = 0; i < signature.length; ++i) { System.out.print(toHexString(signature[i]) + " "); } System.out.println(); }
5
private boolean versionCheck(String title) { if (type != UpdateType.NO_VERSION_CHECK) { String version = plugin.getDescription().getVersion(); if (title.split(" v").length == 2) { String remoteVersion = title.split(" v")[1].split(" ")[0]; // Get // the // newest // file's // version // number int remVer = -1, curVer = 0; try { remVer = calVer(remoteVersion); curVer = calVer(version); } catch (NumberFormatException nfe) { remVer = -1; } if (hasTag(version) || version.equalsIgnoreCase(remoteVersion) || curVer >= remVer) { // We already have the latest version, or this build is // tagged for no-update result = Updater.UpdateResult.NO_UPDATE; return false; } } else { // The file's name did not contain the string 'vVersion' plugin.getLogger() .warning( "The author of this plugin (" + plugin.getDescription().getAuthors() .get(0) + ") has misconfigured their Auto Update system"); plugin.getLogger() .warning( "Files uploaded to BukkitDev should contain the version number, seperated from the name by a 'v', such as PluginName v1.0"); plugin.getLogger().warning( "Please notify the author of this error."); result = Updater.UpdateResult.FAIL_NOVERSION; return false; } } return true; }
6
* * @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 CycObject converseCycObject(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 { return (CycObject) response[1]; } } else { throw new ConverseException(command, response); } }
2
public void actionPerformed(ActionEvent ae) { double x = 0.0, y = 0.0; Double d; try { d = new Double(eastings.getText()); x = d.doubleValue(); } catch (NumberFormatException nfe) { eastings.setText("0"); x = 0.0; } try { d = new Double(northings.getText()); y = d.doubleValue(); } catch (NumberFormatException nfe) { northings.setText("0"); y = 0.0; } DPoint p0 = new DPoint(x, y); String pfxs = prefix.getSelectedItem(); DPoint dp = osni.GridSquareToOffset(pfxs.charAt(0)); dp.offsetBy(p0); DPoint p = osni.GridToLongitudeAndLatitude(dp); DPoint osgbPoint = osgb.LatitudeAndLongitudeToGrid(p); String str; if (osgbPoint.getX() >= 0.0 && osgbPoint.getY() >= 0.0) { str = new String(osgb.GridToGridSquare(osgbPoint)); osgbPrefix.setForeground(Color.blue); osgbPrefix.setText(str); } else { osgbPrefix.setForeground(Color.red); osgbPrefix.setText("NO GRID SQUARE"); } double osgbX = osgbPoint.getX() % 100000.0; if (osgbX < 0.0) osgbX += 100000.0; str = myFormat.format(osgbX); osgbEastings.setText(str); double osgbY = osgbPoint.getY() % 100000.0; if (osgbY < 0.0) osgbY += 100000.0; str = myFormat.format(osgbY); osgbNorthings.setText(str); str = pfxs + " " + myFormat.format(p0.getX()) + " " + myFormat.format(p0.getY()); gridinput.setText(str); }
6
public static URI loadResourceAsUri(String resourcePath) { URI resourceAsURI = null; if(resourcePath.startsWith("/")){ try { resourceAsURI = loadResourceAsURL(resourcePath).toURI(); } catch (URISyntaxException e) { e.printStackTrace(); } return resourceAsURI; }else{ System.err.println("A resource path must(!) begin with a \"/\""); return resourceAsURI; } }
2
public void test_09() { // Create pvalues ScoreList pvlist = new ScoreList(); int max = 1000; for (int i = 0; i < max; i++) { double quantile = ((double) i) / max; pvlist.add(quantile); } // Test for (int i = 0; i < max; i++) { double quantile = ((double) i) / max; double pval = pvlist.cdf(quantile); Assert.assertEquals(quantile, pval); // Make sure they match } }
2
public Projectile(float x, float y, boolean goingUp, boolean friendly) { super(TextureManager.loadTexture(friendly ? PROJECTILE_TEX : PROJECTILE_TEX_ENEMY), "none", x, y, PROJECTILE_WIDTH, PROJECTILE_HEIGHT); if(goingUp) { this.velocity.y = PROJECTILE_VEL; } else { this.velocity.y = -PROJECTILE_VEL; } this.friendly = friendly; if(!friendly) { this.velocity.y /= 2.0f; } this.entName = ENT_NAME + ":" + (friendly ? FRIENDLY : HOSTILE); }
4
@Override public boolean equals(Object other) { if (other == this) return true; if (other == null || other.getClass() != this.getClass()) return false; final Position pos = (Position) other; return this.xCoordinate == pos.xCoordinate && this.yCoordinate == pos.yCoordinate; }
4