text
stringlengths
14
410k
label
int32
0
9
public String getValue() { return value; }
0
static Implementation getImplementation( String baseName, String algorithm, String provider) throws NoSuchProviderException { if (provider == null) { Provider[] prov = Security.getProviders(); // // search every provider looking for the algorithm we want. // for (int i = 0; i != prov.length; i++) { // // try case insensitive // Implementation imp = getImplementationFromProvider(baseName, algorithm.toUpperCase(), prov[i]); if (imp != null) { return imp; } imp = getImplementationFromProvider(baseName, algorithm, prov[i]); if (imp != null) { return imp; } } } else { Provider prov = Security.getProvider(provider); if (prov == null) { throw new NoSuchProviderException("Provider " + provider + " not found"); } // // try case insensitive // Implementation imp = getImplementationFromProvider(baseName, algorithm.toUpperCase(), prov); if (imp != null) { return imp; } return getImplementationFromProvider(baseName, algorithm, prov); } return null; }
6
private boolean jj_3_71() { if (jj_scan_token(OR)) return true; return false; }
1
@Override public void endElement(String uri, String localName, String qName) { switch (localName) { case TagConstants.ARTIFICIAL_FLOWER_TAG: case TagConstants.NATURAL_FLOWER_TAG: case TagConstants.CUT_FLOWER_TAG: floralComposition.addFlower(currentFlower); currentFlower = null; break; case TagConstants.FLOWER_BASKET_TAG: case TagConstants.PACKAGING_PAPER_TAG: floralComposition.setFlowerPackaging(currentFlowerPackaging); currentFlowerPackaging = null; break; default: currentTag = ""; } }
5
public void setSelectedItem(Object item) { if ((selected != null && !selected.equals(item)) || (selected == null && item != null)) { // YUCK from useing generics + old SWING stuff selected = (T)item; fireContentsChanged(this, -1, -1); } }
4
public void testPropertyCompareToMonthOfYear() { MonthDay test1 = new MonthDay(TEST_TIME1); MonthDay test2 = new MonthDay(TEST_TIME2); assertEquals(true, test1.monthOfYear().compareTo(test2) < 0); assertEquals(true, test2.monthOfYear().compareTo(test1) > 0); assertEquals(true, test1.monthOfYear().compareTo(test1) == 0); try { test1.monthOfYear().compareTo((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.monthOfYear().compareTo(dt2) < 0); assertEquals(true, test2.monthOfYear().compareTo(dt1) > 0); assertEquals(true, test1.monthOfYear().compareTo(dt1) == 0); try { test1.monthOfYear().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} }
2
public void fin() { total = System.nanoTime() - then; nm = new String[nw.size()]; prt = new long[pw.size()]; for(int i = 0; i < pw.size(); i++) { nm[i] = nw.get(i); prt[i] = pw.get(i); } hist[i] = this; if(++i >= hist.length) i = 0; pw = null; nw = null; }
2
public List<Booking> getBookingsOfRenter(String authToken, String renterID) throws AccessException{ if(authToken != "abcd1234") throw new AccessException("Access denied"); Renter r = this.getRenterByID(authToken, renterID); try{ List<Booking> b = r.getBookings(); if(b == null || b.size() == 0) throw new BusinessException("No bookings found"); } catch(BusinessException be){ System.out.println(be); } return r.getBookings(); }
4
public String getName() { return s; }
0
@Override public void keyTyped(KeyEvent e) { }
0
public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) { ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); ArrayList<Integer> row = new ArrayList<Integer>(); if (root == null) { return result; } TreeIterator iterator = new TreeIterator(root); while (iterator.hasNext()) { TreeNode current = iterator.next(); if (current == null) { result.add(row); row = new ArrayList<Integer>(); } else { row.add(current.val); } } return result; }
3
public static void main(String[] args) throws Exception { // the first row and last column were manually removed... File inFile = new File( ConfigReader.getBigDataScalingFactorsDir() + File.separator + "MouseDonors" + File.separator + "otu_table_edited.txt"); File outFile = new File( ConfigReader.getBigDataScalingFactorsDir() + File.separator + "MouseDonors" + File.separator + "otu_table_mouseOnlyAllSamples.txt"); OtuWrapper.transpose(inFile.getAbsolutePath(), outFile.getAbsolutePath(), false); OtuWrapper wrapper = new OtuWrapper(outFile); HashMap<String, MetadataParserFileLine> metaMap = MetadataParserFileLine.parseMetadata(); HashSet<String> excludedSamples = new HashSet<String>(); for(MetadataParserFileLine mpfl : metaMap.values()) if( mpfl.getEnv_package().indexOf("human") != -1) excludedSamples.add(mpfl.getSample()); HashSet<String> excludedOtus = new HashSet<String>(); for(int x=0; x < wrapper.getOtuNames().size(); x++) { String otuName = wrapper.getOtuNames().get(x); if( wrapper.getCountForTaxaExcludingTheseSamples(x, excludedSamples) < 0.1 ) excludedOtus.add(otuName); } wrapper = new OtuWrapper(outFile, excludedSamples, excludedOtus); wrapper.writeUnnormalizedDataToFile( new File(ConfigReader.getBigDataScalingFactorsDir() + File.separator + "MouseDonors" + File.separator + "otu_table_mouseOnlyAllSamplesTaxaAsColumns.txt")); wrapper.writeNormalizedDataToFile( new File(ConfigReader.getBigDataScalingFactorsDir() + File.separator + "MouseDonors" + File.separator + "otu_table_mouseOnlyAllSamplesTaxaAsColumnsNorm.txt")); wrapper.writeLoggedDataWithTaxaAsColumns( new File(ConfigReader.getBigDataScalingFactorsDir() + File.separator + "MouseDonors" + File.separator + "otu_table_mouseOnlyAllSamplesTaxaAsColumnsLogNorm.txt")); wrapper.writeRankedSpreadsheet(ConfigReader.getBigDataScalingFactorsDir() + File.separator + "MouseDonors" + File.separator + "otu_table_mouseOnlyAllSamplesTaxaAsColumnsRanked.txt"); BufferedWriter writer = new BufferedWriter(new FileWriter( new File( ConfigReader.getBigDataScalingFactorsDir() + File.separator + "MouseDonors" + File.separator + "otu_table_mouseOnlyAllSamplesTaxaAsColumnsPlusMetaData.txt"))); writer.write("sample\tinoculum"); for(String s: wrapper.getOtuNames()) writer.write("\t" + s); writer.write("\n"); for(int x=0; x < wrapper.getSampleNames().size(); x++) { String sampleName = wrapper.getSampleNames().get(x); writer.write(sampleName + "\t"); MetadataParserFileLine mpfl = metaMap.get(sampleName); if( mpfl == null) throw new Exception("No"); writer.write(mpfl.getInnoculum()); for( int y=0; y < wrapper.getOtuNames().size(); y++) writer.write("\t" + wrapper.getDataPointsUnnormalized().get(x).get(y)); writer.write("\n"); } writer.flush(); writer.close(); }
8
private void readDataFromTextFile() throws IOException { //read each data line or until end of file reached String line; if ((line = in.readLine()) != null){ dataVersion = line; } for (int i=0; i<DATA_SIZE; i++){ if ((line = in.readLine()) == null) { break; } data[i] = line; } }//end of ADataClass::readDataFromTextFile
3
private HttpRespons send(String urlString, String method, Map<String, String> parameters, Map<String, String> propertys) throws IOException { HttpURLConnection urlConnection = null; if (method.equalsIgnoreCase("GET") && parameters != null) { StringBuffer param = new StringBuffer(); int i = 0; for (String key : parameters.keySet()) { if (i == 0) param.append("?"); else param.append("&"); param.append(key).append("=").append(parameters.get(key)); i++; } urlString += param; } URL url = new URL(urlString); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod(method); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setUseCaches(false); if (propertys != null) for (String key : propertys.keySet()) { urlConnection.addRequestProperty(key, propertys.get(key)); } if (method.equalsIgnoreCase("POST") && parameters != null) { StringBuffer param = new StringBuffer(); for (String key : parameters.keySet()) { param.append("&"); param.append(key).append("=").append(parameters.get(key)); } urlConnection.getOutputStream().write(param.toString().getBytes()); urlConnection.getOutputStream().flush(); urlConnection.getOutputStream().close(); } return this.makeContent(urlString, urlConnection); }
9
public static ListNode detectCycle(ListNode head) { if (head == null || head.next == null || head.next.next == null) return null; ListNode oneStep = head.next; ListNode twoStep = head.next.next; ListNode ecounterPoint = null; while (twoStep != null) { if (oneStep == twoStep) { ecounterPoint = oneStep; break; } if (twoStep.next == null || twoStep.next.next == null) return null; twoStep = twoStep.next.next; oneStep = oneStep.next; } ListNode startPoint = null; ListNode newHead = head; while (true) { if (ecounterPoint == newHead) { startPoint = ecounterPoint; break; } newHead = newHead.next; ecounterPoint = ecounterPoint.next; } return startPoint; }
9
static String normalize(String address){ if(address==null){ return "localhost"; } else if(address.length()==0 || address.equals("*")){ return ""; } else{ return address; } }
3
public boolean confirmPossibleMaterialLocation(int resource, Room room) { if(room==null) return false; final Integer I=Integer.valueOf(resource); final boolean isMaterial=(resource&RawMaterial.RESOURCE_MASK)==0; final int roomResourceType=room.myResource(); if(((isMaterial&&(resource==(roomResourceType&RawMaterial.MATERIAL_MASK)))) ||(I.intValue()==roomResourceType)) return true; final List<Integer> resources=room.resourceChoices(); if(resources!=null) for(int i=0;i<resources.size();i++) { if(isMaterial&&(resource==(resources.get(i).intValue()&RawMaterial.MATERIAL_MASK))) return true; else if(resources.get(i).equals(I)) return true; } return false; }
9
private void addVarOp(int op, int varIndex) { switch (op) { case Token.SETCONSTVAR: if (varIndex < 128) { addIcode(Icode_SETCONSTVAR1); addUint8(varIndex); return; } addIndexOp(Icode_SETCONSTVAR, varIndex); return; case Token.GETVAR: case Token.SETVAR: if (varIndex < 128) { addIcode(op == Token.GETVAR ? Icode_GETVAR1 : Icode_SETVAR1); addUint8(varIndex); return; } // fallthrough case Icode_VAR_INC_DEC: addIndexOp(op, varIndex); return; } throw Kit.codeBug(); }
7
public int checkWin(Player player){ int playerHandValue = player.getHand(1).isBust() ? 0 : player.getHand(1).getValues().get(0); int dealerHandValue = dealer.getHand(1).isBust() ? 0 : dealer.getHand(1).getValues().get(0); if(playerHandValue > dealerHandValue){ return 1; } else if(playerHandValue < dealerHandValue){ return 2; } else{ return 3; } }
4
public Event get_next_double_cpu() { Event out = null; double min = Double.MAX_VALUE; if (tempoCPU1 < min) { min = tempoCPU1; out = Event.CPU1; } if (tempoCPU2 < min) { min = tempoCPU2; out = Event.CPU2; } if (tempoArrivo < min) { min = tempoArrivo; out = Event.ARRIVAL; } if (tempoIO < min) out = Event.IO; return out; }
4
public Component getRendererComponent(SubGraph sd) { sgbck=sd; final SubGraph mysd = new SubGraph(sd.graph); mysd.vertices = new HashSet<Vertex>(sd.vertices); mysd.edges = new HashSet<Edge>(sd.edges); mysd.label = sd.label; String txt = ""; txt = "<HTML><BODY>"; if (mysd.label != null && !mysd.label.equals("")) { txt += "<B>" + mysd.label + ": </B><BR>"; } if (mysd.vertices != null && mysd.vertices.size() > 0) { txt = txt + "<B>V: </B> {"; for (Vertex v : mysd.vertices) { txt = txt + v.getLabel() + ", "; } txt = txt.substring(0, txt.length() - 2) + "}"; } if (mysd.edges != null && mysd.edges.size() > 0) { txt += "<BR><B>E: </B> {"; for (Edge e : mysd.edges) { txt = txt + e.source.getLabel() + "-"+ e.target.getLabel() + ", "; } txt = txt.substring(0, txt.length() - 2) + "}"; } txt = txt + "</BODY></HTML>"; JLabel l = new JLabel(txt) { @Override public void setForeground(Color fg) { super.setForeground(fg); if (fg== GCellRenderer.SELECTED_COLOR) showOnGraph(mysd); } }; l.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { showOnGraph(mysd); } } ); return l; }
9
@Override public String toString() { if (type == VariableType.ARRAYLIST) { StringBuilder str = new StringBuilder(); str.append("["); for (Value val : (ArrayList<Value>) value) { str.append(val.toString()); if (!val.equals(((ArrayList<Value>) value).get(((ArrayList<Value>) value).size() - 1))) { str.append(" "); } } str.append("]"); return str.toString(); } else if (type == VariableType.BOOLEAN) { if ((Boolean) this.value) return "true"; else return "false"; } else return this.value.toString(); }
5
private static void myMenu(BufferedReader br, ServiceInterface obj, Scanner cs) throws IOException { // TODO Auto-generated method stub System.out.println("1 Update"); System.out.println("0 Logout"); int val = cs.nextInt(); if (val == 0) showMenu(br, obj, cs); else if (val == 1) update(br, obj, cs); else System.out.println("Wrong choice"); }
2
public static List<String> getAvailableLanguages () { List<String> result = new ArrayList<String>(); result.add(""); for (String language : Locale.getISOLanguages()) { String fileName = MESSAGE_BASENAME + "_" + language + ".properties"; URL url = MessageUtils.class.getClassLoader().getResource(CONFIG_DIR + fileName); try { url.getFile(); result.add(new Locale(language).getLanguage()); } catch (NullPointerException e) { // Do nothing } } return result; }
2
public static void main(String[] args) { // TODO Auto-generated method stub String s = "Hello a olleH"; String str = "aaaa aabaa bbb samaaiaaksl iiii aisk"; String1 strObj = new String1(); String palindromeWords=""; String wordswithVowelInMid=""; if(strObj.isPalindrome(s)) System.out.println("Yes, "+s+" is a Palindrome."); Scanner scnr = new Scanner(System.in); String original = scnr.nextLine(); String reverse = ""; for (int i = original.length(); i <= 0; i--) { reverse = reverse + original.charAt(i); } System.out.println(reverse); String[] strArr= str.split(" "); for (int i = 0; i < strArr.length; i++) { if (strObj.isPalindrome(strArr[i])) { palindromeWords +=strArr[i]+" "; } else { } if (strObj.hasVowelInMid(strArr[i])) { wordswithVowelInMid +=strArr[i]+" "; } } System.out.println("Palindrome Words: "+palindromeWords); System.out.println("Words with Vowel in Middle: "+wordswithVowelInMid); }
5
public EsteTest() { }
0
public void updateDisplay() { if (this.stock != null) { this.setTitle("Edit stock \"" + this.stock.getName() + "\""); this.txfName.setText(this.stock.getName()); this.cbxType.setSelectedItem(stock.getType()); this.txfCapacity.setText(stock.getCapacity() + ""); this.txfMaxTrays.setText(stock.getMaxTraysPerStorageUnit() + ""); this.txfUnitsPerRow.setText(stock.getStorageUnitsPerRow() + ""); } else { this.setTitle("New stock"); this.txfName.setText("New stock"); this.cbxType.setSelectedItem(StockType.SEMI); this.txfCapacity.setText("64"); this.txfMaxTrays.setText("16"); this.txfUnitsPerRow.setText("8"); } }
1
private boolean isDragOk(final java.io.PrintStream out, final java.awt.dnd.DropTargetDragEvent evt) { boolean ok = false; // Get data flavors being dragged java.awt.datatransfer.DataFlavor[] flavors = evt.getCurrentDataFlavors(); // See if any of the flavors are a file list int i = 0; while (!ok && i < flavors.length) { // BEGIN 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added. // Is the flavor a file list? final DataFlavor curFlavor = flavors[i]; if (curFlavor.equals(java.awt.datatransfer.DataFlavor.javaFileListFlavor) || curFlavor.isRepresentationClassReader()) { ok = true; } // END 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added. i++; } // end while: through flavors // If logging is enabled, show data flavors if (out != null) { if (flavors.length == 0) { log(out, "FileDrop: no data flavors."); } for (i = 0; i < flavors.length; i++) { log(out, flavors[i].toString()); } } // end if: logging enabled return ok; } // end isDragOk
7
@Override public void run() { long previousTime = System.currentTimeMillis(); long currentTime = previousTime; if( soundSystem == null ) { errorMessage( "SoundSystem was null in method run().", 0 ); cleanup(); return; } // Start out asleep: snooze( 3600000 ); while( !dying() ) { // Perform user-specific source management: soundSystem.ManageSources(); // Process all queued commands: soundSystem.CommandQueue( null ); // Remove temporary sources every ten seconds: currentTime = System.currentTimeMillis(); if( (!dying()) && ((currentTime - previousTime) > 10000) ) { previousTime = currentTime; soundSystem.removeTemporarySources(); } // Wait for more commands: if( !dying() ) snooze( 3600000 ); } cleanup(); // Important! }
5
static int lowestBoard(Circuit circuit) { int ypos = 0; StringReader sr = new StringReader(circuit.toString()); StreamTokenizer st = new StreamTokenizer(sr); st.parseNumbers(); try { while (st.nextToken() != -1) { if (st.ttype == -3 && st.sval.equals("Board") && st.nextToken() == -3) { st.nextToken(); st.nextToken(); int current = (int) st.nval; if (current > ypos) { ypos = current; } } } } catch (IOException e) { System.err.println("Um.. something bad happened AdvChip.lowestBoard.. input:" + circuit); } return ypos + 168; }
6
Space[] won() { int n = numToWin - 1; if (lastSpaceMoved == null) return null; int[] pos = lastSpaceMoved.getPos(); for (int i = 0, rowInd = pos[0]; i <= n; i++, rowInd = pos[0] - i) for (int j = 0, colInd = pos[1]; j <= n; j++, colInd = pos[1] - j) { boolean outOfBounds = rowInd < 0 || colInd < 0 || rowInd + n >= rows || colInd + n >= cols; if (outOfBounds) continue; ExpBoard_C sub = new ExpBoard_C(this, rowInd, colInd, new int[] { i, j }); Space[] winningSet = sub.subWon(); if (winningSet != null) { for (Space sp : winningSet) sp.setPos(sp.getRow() + rowInd, sp.getCol() + colInd); return winningSet; } } return null; }
9
static String[] getPortForwarding(Session session){ java.util.Vector foo=new java.util.Vector(); synchronized(pool){ for(int i=0; i<pool.size(); i++){ PortWatcher p=(PortWatcher)(pool.elementAt(i)); if(p.session==session){ foo.addElement(p.lport+":"+p.host+":"+p.rport); } } } String[] bar=new String[foo.size()]; for(int i=0; i<foo.size(); i++){ bar[i]=(String)(foo.elementAt(i)); } return bar; }
3
public void renderSlot(int id, float x, float y, int mx, int my, boolean[] buttons, boolean selected) { super.renderSlot(id, x, y, mx, my, buttons, selected); String n = file.getName(); if(file.isDirectory() && !file.getName().endsWith(File.separator)) n+=File.separator; if(!FontRenderer.drawStringInBounds(replacementTxt == null ? n: replacementTxt, x+22, y+20/2f-8, !isMouseOver(x,y,w,h,mx, my) ? 0xFFFFFF: 0xFFFF00,x,y,x+500,y+h)) { FontRenderer.drawString("[..]", x+500-16f, y+20/2f-8, !isMouseOver(x,y,w,h,mx, my) ? 0xFFFFFF: 0xFFFF00); } Textures.render(textID, x+2, y+2, 16, 16); }
6
private static double[][] normalizeDensity(double[][] unNormDensity){ // The number of gridlines across the density domain int numGridLines = getNumGridlines(); int iter = 0; // How many normalization cycles have been performed double threshold = Math.pow(10, -8); // The maximum acceptable error double densityDomainSize = Settings.getMaximumRange() - Settings.getMinimumRange(); double[][] normDens = unNormDensity; while (iter < 1000) { // Zero negative points for (int i1 = 0; i1 < numGridLines; i1++) { for (int i2 = 0; i2 < numGridLines; i2++) { if (normDens[i1][i2] < 0.0) { normDens[i1][i2] = 0.0; } } } // Sum over probability density over interval double integralSum = 0.0; for (int i1 = 0; i1 < numGridLines; i1++) { for (int i2 = 0; i2 < numGridLines; i2++) { integralSum += normDens[i1][i2] * Math.pow(Settings.discretization, 2); } } // Return if error is under threshold if (Math.abs(integralSum - 1) < threshold) { return (normDens); } // Modify density so that it integrates to 1 double normalizeConstant = (integralSum - 1) / Math.pow(densityDomainSize, 2); for (int i1 = 0; i1 < numGridLines; i1++) { for (int i2 = 0; i2 < numGridLines; i2++) { normDens[i1][i2] -= normalizeConstant; } } iter++; } // Settle for the current approximation return normDens; } //end normalizeDensity
9
public boolean Salvar(Produto obj){ try{ if(obj.getId() == 0){ PreparedStatement comando = bd.getConexao() .prepareStatement("INSERT INTO produtos (nome,descricao," + "valor_uni_Compra,valor_uni_Venda,ativo) VALUES (?,?,?,?,1)"); comando.setString(1, obj.getNome()); comando.setString(2, obj.getDescricao()); comando.setDouble(3, obj.getValorUnidadeCompra()); comando.setDouble(4,obj.getValorUnidadeVenda()); comando.executeUpdate(); //busca do id do produto PreparedStatement comando2 = bd.getConexao() .prepareStatement("Select max(id) FROM produtos WHERE ativo = 1"); ResultSet consulta = comando2.executeQuery(); consulta.first(); //setando o estoque com o novo id PreparedStatement comando3 = bd.getConexao() .prepareStatement("INSERT INTO estoques (id,quantidade) " + "VALUES (?,?)"); comando3.setInt(1,consulta.getInt("max(id)")); comando3.setInt(2, obj.getEstoque().getQuantidade()); comando3.executeUpdate(); comando.getConnection().commit(); comando2.getConnection().commit(); comando3.getConnection().commit(); return true; }else{ PreparedStatement comando = bd.getConexao() .prepareStatement("UPDATE produtos SET nome = ?,descricao " + "= ?,valor_uni_Compra = ?,valor_uni_Venda =? WHERE id =?"); comando.setString(1, obj.getNome()); comando.setString(2, obj.getDescricao()); comando.setDouble(3, obj.getValorUnidadeCompra()); comando.setDouble(4, obj.getValorUnidadeVenda()); comando.setInt(5, obj.getId()); comando.executeUpdate(); PreparedStatement comando2 = bd.getConexao() .prepareStatement("UPDATE estoques SET quantidade = ? " + "WHERE id = ?"); comando2.setInt(1, obj.getEstoque().getQuantidade()); comando2.setInt(2, obj.getEstoque().getId()); comando.getConnection().commit(); comando2.getConnection().commit(); return true; } }catch(SQLException ex){ new ErroValidacaoException(ex.getMessage()); return false; } }
2
public boolean similar(Object other) { if (!(other instanceof JSONArray)) { return false; } int len = this.length(); if (len != ((JSONArray)other).length()) { return false; } for (int i = 0; i < len; i += 1) { Object valueThis = this.get(i); Object valueOther = ((JSONArray)other).get(i); if (valueThis instanceof JSONObject) { if (!((JSONObject)valueThis).similar(valueOther)) { return false; } } else if (valueThis instanceof JSONArray) { if (!((JSONArray)valueThis).similar(valueOther)) { return false; } } else if (!valueThis.equals(valueOther)) { return false; } } return true; }
8
public static void stopMusic() { if(BATTLE_TYPE.equals("WILD")) { if(!Mechanics.isLegendary(enemy[0])) wildMusic.stop(); else fatefulMusic.stop(); } else if(BATTLE_TYPE.equals("TRAINER")) { if(b1.trainer.type==Trainer.TrainerType.JAVA) javaMusic.stop(); else trainerMusic.stop(); } else if(BATTLE_TYPE.equals("SUPER")) { eliteMusic.stop(); } else if(BATTLE_TYPE.equals("GYM")) gymMusic.stop(); else if(BATTLE_TYPE.equals("RIVAL")) rivalMusic.stop(); }
7
public static void main(String[] args) throws Exception { String languagesList = (args.length>0) ? args[0] : "en"; String dirName = (args.length>1) ? args[1].replace( '\\', '/' ) : ""; if(dirName.length() > 0 && !dirName.endsWith( "/" )){ dirName += '/'; } String[] languages = languagesList.split(","); for(int i = 0; i < languages.length; i++){ String language = languages[i]; String filename = dirName + language+"wiktionary-latest-pages-articles.xml"; File file = new File(filename); BookGenerator generator = (BookGenerator)Class.forName( BookGenerator.class.getName()+"_" + language ).newInstance(); generator.start(file); generator.save(language); generator.createPackage( language ); } }
5
public synchronized void mouseMoved(MouseEvent e) { // this event is from re-centering the mouse - ignore it if (isRecentering && centerLocation.x == e.getX() && centerLocation.y == e.getY()) { isRecentering = false; } else { int dx = e.getX() - mouseLocation.x; int dy = e.getY() - mouseLocation.y; mouseHelper(MOUSE_MOVE_LEFT, MOUSE_MOVE_RIGHT, dx); mouseHelper(MOUSE_MOVE_UP, MOUSE_MOVE_DOWN, dy); if (isRelativeMouseMode()) { recenterMouse(); } } mouseLocation.x = e.getX(); mouseLocation.y = e.getY(); }
4
public void readHistory(DataInput input) { try { int unused = input.readInt(); // VERSION = 1 int commandCount = input.readInt(); if (directoryCombo == null) { directoryCombo = new JComboBox(); } for (int i = 0; i < commandCount; ++i) { String nextString = input.readUTF(); int itemCount = directoryCombo.getItemCount(); boolean containsIt = false; for (int j = 0; j < itemCount; ++j) { if (directoryCombo.getItemAt(j).toString().trim().equals(nextString)) { containsIt = true; } } if (!containsIt) { directoryCombo.addItem(nextString); } } } catch (IOException e) { // NYI } }
6
protected DateTimeField getField(int index, Chronology chrono) { switch (index) { case 0: return chrono.year(); case 1: return chrono.monthOfYear(); default: throw new IndexOutOfBoundsException(); } }
2
public static String doubleToString(double d) { if (Double.isInfinite(d) || Double.isNaN(d)) { return "null"; } // Shave off trailing zeros and decimal point, if possible. String string = Double.toString(d); if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) { while (string.endsWith("0")) { string = string.substring(0, string.length() - 1); } if (string.endsWith(".")) { string = string.substring(0, string.length() - 1); } } return string; }
7
private double hilb_index(double x, double y, int lvl){ if (lvl==0) return x; if ( x<0.5 && y<0.5 ) return hilb_index(y*2, x*2, lvl-1)*0.25; if ( x<0.5 && y>=0.5) return 0.25 + hilb_index(x*2, y*2-1, lvl-1)*0.25; if (x>=0.5 && y<0.5) return 0.75 + hilb_index(1-y*2, 2-x*2, lvl-1)*0.25; if (x>=0.5 && y>=0.5) return 0.5 + hilb_index(x*2-1, y*2-1, lvl-1)*0.25; throw new RuntimeException("hilb-index: coordinate is invalid"); }
9
private boolean jj_2_62(int xla) { jj_la = xla; jj_lastpos = jj_scanpos = token; try { return !jj_3_62(); } catch(LookaheadSuccess ls) { return true; } finally { jj_save(61, xla); } }
1
private boolean overlaps(Piece pi, int x0, int y0) { if( pi.w() + x0 > w() ){ return true; } if( pi.h() + y0 > h() ){ return true; } for( int x = 0 ; x < pi.w() ; x++ ){ for( int y = 0 ; y < pi.h() ; y++ ){ if( pi.contains(x, y) ){ if( _board[x+x0][y+y0] != null ){ return true; } } } } return false; }
6
public int I(Privacy p) { switch (p) { case PUBLIC: return 0; case PROTECTED: return 1; } return 2; }
2
public void start(){ try { //ServerSocket serverSocket = new ServerSocket(port); while(true){ if(shutdown){ break; } Socket socket = getServerSocket().accept(); Request request = new Request(socket); Response response = new Response(socket); // >> SessionCookie determineSession(request, response); // << SessionCookie // >> File Handling if(request.getPath().startsWith("/public/")){ request.getPath().replace("../", ""); request.getPath().replace("/..", ""); byte[] content = getFileReader().getFileContent(request.getPath()); if(content.length == 0){ response.setStatus(Response.STATUS_NOT_FOUND); }else{ response.setBinContent(content); response.setContentType(getFileReader().getContentType(request.getPath())); } }else{ // << File Handling for(ThinServerAction action:actions){ if(request.getRequestProcessState().stopProcessing()){ break; } if(action.mapActionPath(request)){ action.doAction(request, response); } } } if(response.getBinContent().length > 0){ OutputStream outputstream = socket.getOutputStream(); outputstream.write(response.getBinResponse()); outputstream.flush(); outputstream.close(); }else{ PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream())); writer.println(response.getResponse()); writer.println("\r\n"); writer.flush(); writer.close(); } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
9
public boolean next() throws IOException { while (true) { if (count == df) return false; final int docCode = freqStream.readVInt(); if (currentFieldOmitTermFreqAndPositions) { doc += docCode; freq = 1; } else { doc += docCode >>> 1; // shift off low bit if ((docCode & 1) != 0) // if low bit is set freq = 1; // freq is one else freq = freqStream.readVInt(); // else read freq } count++; if (deletedDocs == null || !deletedDocs.get(doc)) break; skippingDoc(); } return true; }
6
@Override public int castingQuality(MOB mob, Physical target) { if(mob!=null) { if(target instanceof MOB) { final Room R=((MOB)target).location(); boolean found=false; if(R!=null) for(int r=0;r<R.numInhabitants();r++) { final MOB M=R.fetchInhabitant(r); if((M!=null)&&(M!=mob)&&(M!=target)&&(CMLib.flags().isHidden(M))) { found=true; break;} } if(!found) return Ability.QUALITY_INDIFFERENT; } } return super.castingQuality(mob,target); }
9
@EventHandler public void onVehicleExit(VehicleExitEvent event) { if (event.getExited() != null && event.getExited() instanceof Player) { Player player = (Player) event.getExited(); if (this.manager.isRoutePlayer(player)) { event.setCancelled(true); } } }
3
public void addEdge(int from, int to, String edgeValueToken) throws IOException { if (maxVertexId < from) maxVertexId = from; if (maxVertexId < to) maxVertexId = to; /* If the from and to ids are same, this entry is assumed to contain value for the vertex, and it is passed to the vertexProcessor. */ if (from == to) { if (vertexProcessor != null && edgeValueToken != null) { VertexValueType value = vertexProcessor.receiveVertexValue(from, edgeValueToken); if (value != null) { addVertexValue(from % numShards, preIdTranslate.forward(from), value); } } return; } int preTranslatedIdFrom = preIdTranslate.forward(from); int preTranslatedTo = preIdTranslate.forward(to); addToShovel(to % numShards, preTranslatedIdFrom, preTranslatedTo, (edgeProcessor != null ? edgeProcessor.receiveEdge(from, to, edgeValueToken) : null)); }
7
@Override public void run() { AudioInputStream audioIn = null; try { audioIn = AudioSystem.getAudioInputStream(getClass() .getResource(track)); } catch (UnsupportedAudioFileException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { clip = AudioSystem.getClip(); } catch (LineUnavailableException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { clip.open(audioIn); } catch (LineUnavailableException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } clip.start(); }
5
public static void refreshConnectionToTrackingServer() { System.setProperty("java.rmi.server.hostname", currentPeerInfo.getIp()); int trackingServerPort = PeerConfig.getTrackingServerPort(); String trackingServerIp = PeerConfig.getTrackingServerIp(); while(true) { try { trackingServerRMIObjectHandle = (TrackingServer) Naming .lookup("rmi://" + trackingServerIp + ":" + trackingServerPort + "/" + RMIConstants.TRACKING_SERVER_SERVICE); } catch (MalformedURLException e) { try { Thread.sleep(2000); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } continue; } catch (RemoteException e) { try { Thread.sleep(2000); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } continue; } catch (NotBoundException e) { try { Thread.sleep(2000); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } continue; } break; } }
7
@Override public Solution search(Puzzle puzzle) { fringe.add(new Node(puzzle.getInitialState(), null, null)); while (!fringe.isEmpty()) { Node selectedNode = fringe.poll(); if (puzzle.getGoalTest().isGoalState(selectedNode.getState())) { return new Solution(selectedNode, getNodeExpanded()); } closedList.add(selectedNode); LinkedList<Node> expansion = selectedNode.expandNode(); for (Node n : expansion) { if (!closedList.contains(n) && !fringe.contains(n)) fringe.add(n); } } return new Solution(null, getNodeExpanded()); }
5
public static void main(String[] args) { // 1,new A() System.out.println("***new init***"); @SuppressWarnings("unused") A a = new A(); // 2,Class.forname("package-path.class-name") System.out.println("***Class.forname init***"); try { Class<?> clazz =Class.forName(A.class.getName()); try { clazz.newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } // 3,ClassLoader loader = Thread.currentThread().getContextClassLoader(); System.out.println("***ClassLoader init***"); ClassLoader loader = Thread.currentThread().getContextClassLoader(); try { Class<?> clazz =loader.loadClass(A.class.getName()); try { clazz.newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } }
8
public void run() { synchronized (this) { try { this.wait(MainServerApp.initializationTime); }catch(Exception e){} } while(true){ synchronized (monitor) { while(registeredThreads != MainServerApp.numberOfThreads) { try { monitor.wait(); } catch (InterruptedException e){ } } } MSCandidate looser = new MSCandidate(null, null, -1); looser.nrOfVotes = 1000000000; for (MSCandidate c: candidatesBank.getTempCandidatesList()) { if(looser.nrOfVotes > c.nrOfVotes) looser = c; } for (MSCandidate c: candidatesBank.getTempCandidatesList()) c.nrOfVotes = 0; looserIndex = looser.Id; candidatesBank.remove(looser); MainServerApp.time=new Date().getTime()+MainServerApp.roundTime; synchronized(monitor){ registeredThreads = 0; monitor.notifyAll(); } } }
7
public static Figure getFigure(int figureId) { Figure figure = null; switch (figureId) { case Figure.FIGURE_ID_I: figure = new FigureI(); break; case Figure.FIGURE_ID_T: figure = new FigureT(); break; case Figure.FIGURE_ID_O: figure = new FigureO(); break; case Figure.FIGURE_ID_L: figure = new FigureL(); break; case Figure.FIGURE_ID_J: figure = new FigureJ(); break; case Figure.FIGURE_ID_S: figure = new FigureS(); break; case Figure.FIGURE_ID_Z: figure = new FigureZ(); break; default: figure = null; break; } return figure; }
7
public boolean within(MouseEvent e, int x, int y, int width, int height) { if (e.getX() > x && e.getX() < x + width && e.getY() > y && e.getY() < y + height) { return true; } return false; }
4
public static boolean isValidVector(Vector3f vector) { if (vector == null) return false; if (Float.isNaN(vector.x) || Float.isNaN(vector.y) || Float.isNaN(vector.z)) return false; if (Float.isInfinite(vector.x) || Float.isInfinite(vector.y) || Float.isInfinite(vector.z)) return false; return true; }
7
public void testWithField2() { Partial test = createHourMinPartial(); try { test.withField(null, 6); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20); }
1
public boolean hasPermission(CommandSender sender) { if (sender instanceof Player) { return sender.isOp() || (permissionNode != null && sender.hasPermission("getperms." + permissionNode)); } return true; }
3
@Override public void execute(Object parent) { mxIGraphModel model = graph.getModel(); // Moves the vertices to build a circle. Makes sure the // radius is large enough for the vertices to not // overlap model.beginUpdate(); try { // Gets all vertices inside the parent and finds // the maximum dimension of the largest vertex double max = 0; Double top = null; Double left = null; List<Object> vertices = new ArrayList<Object>(); int childCount = model.getChildCount(parent); for (int i = 0; i < childCount; i++) { Object cell = model.getChildAt(parent, i); if (!isVertexIgnored(cell)) { vertices.add(cell); mxRectangle bounds = getVertexBounds(cell); if (top == null) { top = bounds.getY(); } else { top = Math.min(top, bounds.getY()); } if (left == null) { left = bounds.getX(); } else { left = Math.min(left, bounds.getX()); } max = Math.max(max, Math.max(bounds.getWidth(), bounds .getHeight())); } else if (!isEdgeIgnored(cell)) { if (isResetEdges()) { graph.resetEdge(cell); } if (isDisableEdgeStyle()) { setEdgeStyleEnabled(cell, false); } } } int vertexCount = vertices.size(); double r = Math.max(vertexCount * max / Math.PI, radius); // Moves the circle to the specified origin if (moveCircle) { left = x0; top = y0; } circle(vertices.toArray(), r, left.doubleValue(), top.doubleValue()); } finally { model.endUpdate(); } }
8
public void update(long elapsedTime) { ShipV2 player = (ShipV2)map.getPlayer(); JTabbedPane tabbelShipMenu = menu.tabbedShipMenu; //JPanel sliderMenu = ((JPanel)menu.tabbedShipMenu.getComponent(0)); //menu.updateShipSliders(sliderMenu); /* don't plan on doing this now // player is dead! start map over if (player.getState() == Creature.STATE_DEAD) { map = resourceManager.reloadMap(); return; }*/ // get keyboard/mouse input checkInput(elapsedTime); checkCollisions(elapsedTime); player.update(elapsedTime); map.updateSpriteV2(elapsedTime); //updateLasers(); // not worrying about lasers right now // update other sprites //ListIterator i = (ListIterator) map.getSprites(); LinkedList<Sprite>sprites = map.getSprites(); for (int i = 0; i < sprites.size(); i++) { Sprite sprite = (Sprite)sprites.get(i); if (sprite instanceof Creature) { Creature creature = (Creature)sprite; if (creature.getState() == Creature.STATE_DEAD) { sprites.remove(i); } else { updateCreature(creature, elapsedTime); } } // normal update sprite.update(elapsedTime); } }
3
@EventHandler(priority = EventPriority.HIGH) public void onPlayerRespawn(PlayerRespawnEvent event) { try { // first try to get our "default" home ArrayList<HashMap<String, Object>> results = DatabaseManager.accessQuery( "select * from homes where owner=? and name=?;", event.getPlayer().getName(), "default"); // if we don't have a "default" home, get the first one if(results.size() != 1) { // grab our first home results = DatabaseManager.accessQuery( "select * from homes where owner=? order by id limit 1;", event.getPlayer().getName()); if(results.size() != 1){ // we don't have a home, cancel it! return; } } // we DO have a home! // make a location Location location = new Location( Bukkit.getServer().getWorld((String)results.get(0).get("world")), (Float)results.get(0).get("x"), (Float)results.get(0).get("y"), (Float)results.get(0).get("z")); // take us there! event.setRespawnLocation(location); } catch(Exception e) { // ignore if something goes wrong! } }
3
public void loadPreview() { if (selectedCard != null) { if (selectedCard instanceof HeroFrontCard) { creator = new CreatorTabHeroFront(frame, (HeroFrontCard)selectedCard); ImageIcon ii = new ImageIcon(creator.getImage(214, 300)); preview.setIcon(ii); } if (selectedCard instanceof HeroBackCard) { creator = new CreatorTabHeroBack(frame, (HeroBackCard)selectedCard); ImageIcon ii = new ImageIcon(creator.getImage(214, 300)); preview.setIcon(ii); } if (selectedCard instanceof BackCard) { creator = new CreatorTabCardBack(frame, (BackCard)selectedCard); ImageIcon ii = new ImageIcon(creator.getImage(214, 300)); preview.setIcon(ii); } if (selectedCard instanceof HeroCard) { creator = new CreatorTabHeroCard(frame, (HeroCard)selectedCard); ImageIcon ii = new ImageIcon(creator.getImage(214, 300)); preview.setIcon(ii); } if (selectedCard instanceof VillainFrontCard) { creator = new CreatorTabVillainFront(frame, (VillainFrontCard)selectedCard); ImageIcon ii = new ImageIcon(creator.getImage(214, 300)); preview.setIcon(ii); } if (selectedCard instanceof VillainCard) { creator = new CreatorTabVillainCard(frame, (VillainCard)selectedCard); ImageIcon ii = new ImageIcon(creator.getImage(214, 300)); preview.setIcon(ii); } if (selectedCard instanceof EnvironmentCard) { creator = new CreatorTabEnvironmentCard(frame, (EnvironmentCard)selectedCard); ImageIcon ii = new ImageIcon(creator.getImage(214, 300)); preview.setIcon(ii); } } }
8
private final void loadImages() throws IOException { // RenderableObjects BufferedImage mainMenuSheet = ImageIO.read(Images.class.getResource(imageDir + "/mainMenu.png")); BufferedImage saveManagerSheet = ImageIO.read(Images.class.getResource(imageDir + "/saveManager.png")); // Map textures BufferedImage terrainSheet = ImageIO.read(Images.class.getResource(imageDir + "/terrain.png")); // GUI textures BufferedImage guiSheet = ImageIO.read(Images.class.getResource(imageDir + "/gui.png")); // object textures BufferedImage itemSheet = ImageIO.read(Images.class.getResource(imageDir + "/items.png")); // Sprites BufferedImage playerSheet = ImageIO.read(Images.class.getResource(imageDir + "/player.png")); BufferedImage preySheet = ImageIO.read(Images.class.getResource(imageDir + "/prey.png")); terrain = new BufferedImage[6]; for (int i = 1; i < 6; i++) terrain[i] = getCroppedImage(terrainSheet, 50, i * 50, 50, 50); terrain[0] = getCroppedImage(terrainSheet, 0, 0, 50, 50); GUI = new BufferedImage[4]; GUI[0] = getCroppedImage(guiSheet, 0, 0, 800, 100); GUI[1] = getCroppedImage(guiSheet, 0, 120, 30, 30); GUI[2] = getCroppedImage(guiSheet, 30, 120, 30, 30); GUI[3] = getCroppedImage(guiSheet, 60, 120, 12, 5); objects = new BufferedImage[10][10]; for (int x = 0; x < 10; x++) for (int y = 0; y < 10; y++) objects[x][y] = getCroppedImage(itemSheet, x * 30, y * 30, 30, 30); mainMenu = new BufferedImage[5]; for (int i = 0; i < 5; i++) mainMenu[i] = getCroppedImage(mainMenuSheet, 0, 100 * i, 300, 100); saveManager = new BufferedImage[8]; for (int i = 0; i < 5; i++) saveManager[i] = getCroppedImage(saveManagerSheet, 0, 100 * i, 150, 100); saveManager[5] = getCroppedImage(saveManagerSheet, 0, 500, 50, 50); saveManager[6] = getCroppedImage(saveManagerSheet, 50, 500, 50, 50); saveManager[7] = getCroppedImage(saveManagerSheet, 100, 500, 25, 50); player = new BufferedImage[4][4]; for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) player[i][j] = getCroppedImage(playerSheet, 50 * i, 50 * j, 50, 50); prey = new BufferedImage[4][4]; for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) prey[i][j] = getCroppedImage(preySheet, 50 * i, 50 * j, 50, 50); }
9
@Override public boolean isCellEditable(int rowIndex, int columnIndex) { switch (COLUMNS.values()[columnIndex]) { case ID: return false; case FIRSTNAME: case LASTNAME: case BIRTH: case EMAIL: return true; default: throw new IllegalArgumentException("columnIndex"); } }
5
private boolean jj_3R_33() { if (jj_3R_77()) return true; return false; }
1
public void test_01() { initSnpEffPredictor("testCase"); String fileName = "./tests/vcf.vcf"; VcfFileIterator vcf = new VcfFileIterator(fileName, genome); vcf.setCreateChromos(true); for (VcfEntry vcfEntry : vcf) { for (Variant seqChange : vcfEntry.variants()) { System.out.println(seqChange); String seqChangeStr = "chr" + seqChange.getChromosomeName() + ":" + seqChange.getStart() + "_" + seqChange.getReference() + "/" + seqChange.getChange(); Assert.assertEquals(seqChangeStr, seqChange.getId()); } } }
2
public long getSumOfMostCommonValues(int[] result) { if (result == null || result.length == 0) return 0; quickSort(0, result.length - 1, result); int maxCount = 1; int count = 0; int base = result[0]; int number = base; for (int i : result) { if (base == i) count++; else { if (count > maxCount) { maxCount = count; number = base; base = i; } count = 1; } } return maxCount * number; }
5
private URL getURL(String filename) { URL url = null; try { url = this.getClass().getResource(filename); } catch (Exception e) { } return url; }
1
public void setVisible(boolean visible) { if(frame == null) { hud = new HUDManager(model); flyups = new FlyUpsManager(); options = new OptionsManager(model); buildGUI(); } frame.setVisible(visible); }
1
protected void paintComponent(Graphics g) { super.paintComponent(g); // Paints the background if (image == null) { return; } if (scale == 0.0) { initializeParams(); } if (isHighQualityRendering()) { Rectangle rect = getImageClipBounds(); if (rect == null || rect.width == 0 || rect.height == 0) { // no part of image is displayed in the panel return; } BufferedImage subimage = image.getSubimage(rect.x, rect.y, rect.width, rect.height); Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, INTERPOLATION_TYPE); g2.drawImage(subimage, Math.max(0, originX), Math.max(0, originY), Math.min((int)(subimage.getWidth() * scale), getWidth()), Math.min((int)(subimage.getHeight() * scale), getHeight()), null); } else { g.drawImage(image, originX, originY, getScreenImageWidth(), getScreenImageHeight(), null); } //Draw navigation image if (isNavigationImageEnabled()) { g.drawImage(navigationImage, 0, 0, getScreenNavImageWidth(), getScreenNavImageHeight(), null); drawZoomAreaOutline(g); } }
7
public void showHelpAndExit() { List<String> names = new ArrayList<>(mOptions.keySet()); int cmdWidth = 0; Collections.sort(names); System.out.println(); System.out.println(BundleInfo.getDefault().getAppBanner()); System.out.println(); if (mHelpHeader != null) { System.out.println(mHelpHeader); System.out.println(); } System.out.println(AVAILABLE_OPTIONS); System.out.println(); for (String name : names) { CmdLineOption option = mOptions.get(name); int width = 5 + name.length(); if (option.takesArgument()) { width += 1 + option.getArgumentLabel().length(); } if (width > cmdWidth) { cmdWidth = width; } } for (String name : names) { CmdLineOption option = mOptions.get(name); StringBuilder builder = new StringBuilder(); String[] allNames = option.getNames(); String prefix = Platform.isWindows() ? "/" : "-"; //$NON-NLS-1$ //$NON-NLS-2$ String description; if (allNames[allNames.length - 1].equals(name)) { description = option.getDescription(); } else { description = MessageFormat.format(REFERENCE_DESCRIPTION, prefix, allNames[allNames.length - 1]); } builder.append(" "); //$NON-NLS-1$ builder.append(prefix); builder.append(name); if (option.takesArgument()) { builder.append('='); builder.append(option.getArgumentLabel()); } builder.append(TextUtility.makeFiller(cmdWidth - builder.length(), ' ')); System.out.print(TextUtility.makeNote(builder.toString(), TextUtility.wrapToCharacterCount(description, 75 - cmdWidth))); } if (mHelpFooter != null) { System.out.println(); System.out.println(mHelpFooter); } System.out.println(); System.exit(0); }
9
*/ public void removeAll () { checkWidget (); if (itemsCount == 0) return; setRedraw (false); setFocusItem (null, false); for (int i = 0; i < itemsCount; i++) { items [i].dispose (false); } items = new CTableItem [0]; selectedItems = new CTableItem [0]; int oldCount = itemsCount; itemsCount = topIndex = 0; anchorItem = lastClickedItem = null; lastSelectionEvent = null; int[] eventData = new int[5]; eventData[0] = ACC.DELETE; eventData[1] = 0; eventData[2] = oldCount; eventData[3] = 0; eventData[4] = 0; getAccessible().sendEvent(ACC.EVENT_TABLE_CHANGED, eventData); ScrollBar vBar = getVerticalBar (); if (vBar != null) { vBar.setMaximum (1); vBar.setVisible (false); } if (columns.length == 0) { horizontalOffset = 0; ScrollBar hBar = getHorizontalBar (); if (hBar != null) { hBar.setMaximum (1); hBar.setVisible (false); } } setRedraw (true); }
5
@Override public boolean onCommand(CommandSender cs, Command cmd, String label, String[] args) { if (cs instanceof Player) { final Player player = (Player) cs; if (Lobby.started && !Game.started) { if (DatabaseHandler.hasPass(player)) { if (!Lobby.forcedTraitors.contains(player) && !Lobby.forcedDetectives.contains(player)) { if (!(Lobby.forcedDetectives.size() >= TIMV.config.getInt("MaxDetectives"))) { Lobby.forcedDetectives.add(player); player.sendMessage(MessagesHandler.convert("Detective.Success")); } else { player.sendMessage(MessagesHandler.convert("Detective.TooMany")); } } else { player.sendMessage(MessagesHandler.convert("Detective.AlreadyMatched")); } } else { player.sendMessage(MessagesHandler.convert("NoPasses")); } } else { player.sendMessage(MessagesHandler.convert("Detective.OnlyInLobby")); } } else { cs.sendMessage(MessagesHandler.noPlayer()); } return true; }
7
public TreeNode buildTree(Vector<Integer> v ,int sta, int end){ if(end - sta < 0 ) return null; int mid = (sta + end)/2; TreeNode node = new TreeNode(v.get(mid)); node.left = buildTree(v,sta,mid-1); node.right = buildTree(v,mid+1,end); return node; }
1
@Test public void testSolve() throws ParseurException { SolutionState solutionState = null; try{ solutionState = tournee.solve(MAX_TIME_SEC * 1000); } catch (Exception e) { e.printStackTrace(); fail(); } if (solutionState == SolutionState.OPTIMAL_SOLUTION_FOUND || solutionState == SolutionState.SOLUTION_FOUND) { this.verifierHoraires(); } else { fail("Impossible de résoudre le problème en moins de "+MAX_TIME_SEC+" secondes."); } }
3
@Override public void start(Stage primaryStage) { this.stage = primaryStage; root = new StackPane(); Button btn = new Button(); btn.setText("Say 'Hello World'"); btn.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { System.out.println("Hello World!"); } }); //root.getChildren().add(btn); Group mazeGroup = new Group(); //root.getChildren().add(mazeGroup); VBox guiBox = new VBox(); guiBox.setAlignment(Pos.TOP_CENTER); MenuBar menu = new MenuBar(); Menu file = new Menu("File"); MenuItem openMazeFile = new MenuItem("Open Maze File"); openMazeFile.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent t) { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Open Maze File"); // System.out.println(pic.getId()); fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Maze File", "*.maze")); File file = fileChooser.showOpenDialog(stage); if (file != null) { try ( InputStream fStream = new FileInputStream(file); InputStream buffer = new BufferedInputStream(fStream); ObjectInput input = new ObjectInputStream(buffer);) { MazeGridDataContainer mgd = (MazeGridDataContainer) input.readObject(); MazeGrid mgrid = mgd.reconstructMazeGrid(); mazeCentered.getChildren().clear(); mazeGrid = mgrid; mazeCentered.getChildren().add(mgrid.getGridGroup()); slider.adjustValue(mgrid.getSideCount()); mazeName = file.getName(); } catch (IOException | ClassNotFoundException ex) { Logger.getLogger(MazeFramework.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(null, ex.getMessage(), ex.getClass().getName(), JOptionPane.ERROR_MESSAGE); } } } }); MenuItem saveMazeFile = new MenuItem("Save Maze File"); saveMazeFile.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent t) { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Save Maze"); fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Maze File", "*.maze")); // System.out.println(pic.getId()); File file = fileChooser.showSaveDialog(stage); if (file != null) { if (mazeGrid != null) { try (OutputStream outputFile = new FileOutputStream(file.getAbsolutePath() + ".maze"); OutputStream buffer = new BufferedOutputStream(outputFile); ObjectOutput output = new ObjectOutputStream(buffer);) { output.writeObject(mazeGrid.toDataContainer()); } catch (IOException ex) { Logger.getLogger(MazeFramework.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(null, ex.getMessage(), ex.getClass().getName(), JOptionPane.ERROR_MESSAGE); } } } } }); file.getItems().addAll(openMazeFile, saveMazeFile); Menu options = new Menu("Cells per row"); CustomMenuItem cells = new CustomMenuItem(); slider = new Slider(5, 50, 10); slider.setShowTickLabels(true); slider.setShowTickMarks(true); slider.setOnMouseDragged(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent t) { mazeCentered.getChildren().clear(); MazeGrid mg = new MazeGrid(null, (int) (slider.getValue()), 500); mazeGrid = mg; mazeCentered.getChildren().add(mg.getGridGroup()); } }); cells.setContent(slider); options.getItems().addAll(cells); Menu execution = new Menu("Execution"); noDiagonal = new CheckMenuItem("Diagonal Movement"); MenuItem execute = new MenuItem("Execute"); MenuItem benchmark = new MenuItem("Benchmark"); execute.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent t) { execute(); } }); benchmark.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent t) { benchmark(); } }); execution.getItems().addAll(noDiagonal, execute, benchmark); menu.getMenus().addAll(file, options, execution); mazeCentered = new FlowPane(); mazeCentered.setAlignment(Pos.CENTER); MazeGrid mg = new MazeGrid(null, 10, 500); mazeGrid = mg; mazeCentered.getChildren().add(mg.getGridGroup()); guiBox.getChildren().add(menu); guiBox.getChildren().add(mazeCentered); root.getChildren().add(guiBox); Scene scene = new Scene(root, 500, 520); primaryStage.setTitle("Maze Framework"); // primaryStage.setResizable(false); primaryStage.setScene(scene); primaryStage.show(); }
5
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success) { invoker=mob; final CMMsg msg=CMClass.getMsg(mob,null,this,verbalCastCode(mob,null,auto),auto?"":L("^S<S-NAME> summon(s) help from the Java Plane.^?")); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); final String[] choices={"Dog","Orc","Tiger","Troll","Chimp","BrownBear","Goblin","LargeBat","GiantScorpion","Rattlesnake","Ogre"}; final int num=(mob.phyStats().level()+(getXLEVELLevel(mob)+(2*getX1Level(mob))))/3; for(int i=0;i<num;i++) { final MOB newMOB=CMClass.getMOB(choices[CMLib.dice().roll(1,choices.length,-1)]); newMOB.addNonUninvokableEffect(CMClass.getAbility("Prop_ModExperience")); newMOB.setLocation(mob.location()); newMOB.basePhyStats().setRejuv(PhyStats.NO_REJUV); newMOB.recoverCharStats(); newMOB.recoverPhyStats(); newMOB.recoverMaxState(); newMOB.resetToMaxState(); newMOB.bringToLife(mob.location(),true); CMLib.beanCounter().clearZeroMoney(newMOB,null); newMOB.location().showOthers(newMOB,null,CMMsg.MSG_OK_ACTION,L("<S-NAME> appears!")); newMOB.setStartRoom(null); // keep before postFollow for Conquest newMOB.setVictim(mob.getVictim()); CMLib.commands().postFollow(newMOB,mob,true); if(newMOB.amFollowing()!=mob) newMOB.setFollowing(mob); if(newMOB.getVictim()!=null) newMOB.getVictim().setVictim(newMOB); hasFought=false; beneficialAffect(mob,newMOB,asLevel,0); } } } else return beneficialWordsFizzle(mob,null,L("<S-NAME> call(s) for magical help, but chokes on the words.")); // return whether it worked return success; }
7
public void active(int speed){ if( dir==DirKey.Up ){ this.y = this.y - speed; } else if( dir==DirKey.Down ){ this.y = this.y + speed; } else if( dir==DirKey.Left ){ this.x = this.x - speed; } else if( dir==DirKey.Right ){ this.x = this.x + speed; } }
4
private void ensureColumnBounds(Sheet sheet) { if (gotBounds) { return; } Iterator<Row> iter = sheet.rowIterator(); firstColumn = (iter.hasNext() ? Integer.MAX_VALUE : 0); endColumn = 0; while (iter.hasNext()) { Row row = iter.next(); short firstCell = row.getFirstCellNum(); if (firstCell >= 0) { firstColumn = Math.min(firstColumn, firstCell); endColumn = Math.max(endColumn, row.getLastCellNum()); } } if (maxColumns > 0 && endColumn > maxColumns){ endColumn = maxColumns; } gotBounds = true; }
6
public static void init() { //Configurations for file properties using Properties properties = new Properties(); FileInputStream propFile; try { propFile = new FileInputStream("test.properties"); properties.load(propFile); } catch (IOException e) { e.printStackTrace(); Assert.fail(e.getMessage()); } @SuppressWarnings("unchecked") Enumeration<String> e = (Enumeration<String>) properties.propertyNames(); while (e.hasMoreElements()) { String key = e.nextElement(); System.setProperty(key, properties.getProperty(key)); //Reporter.log(key + " - " + properties.getProperty(key), 2, true); } //Configurations for file properties using WebDriver driver; switch (System.getProperty("test.browser")) { case "firefox": driver = new FirefoxDriver(); break; case "chrome": System.setProperty("webdriver.chrome.driver", "chromedriver.exe"); driver = new ChromeDriver(); break; case "chrome_hub": DesiredCapabilities capability = DesiredCapabilities.chrome(); try { driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability); } catch (MalformedURLException e1) { e1.printStackTrace(); throw new AssertionError("Unexpected error during remote WebDriver setup"); } break; default: throw new AssertionError("Unsupported browser: " + System.getProperty("test.browser")); } //Configurations for synchronization driver.manage().timeouts().implicitlyWait( Integer.parseInt(System.getProperty("test.timeout")), TimeUnit.SECONDS ); //Configurations for synchronization Driver.set(driver); }
6
public void incUtteranceWords(String[] units, Boolean[] stresses, Boolean[] boundaries, boolean[] trusts) { // If we're not using trusts, ignore the trusts passed Boolean[] wordsTrusts; if (!useTrust || trusts == null) { wordsTrusts = null; } else { wordsTrusts = SegUtil.wordsTrusts(trusts, boundaries); } // Get slices of the stresses and units in this utterance Object[][] wordsUnits = SegUtil.slicesFromAllBoundaries(units, boundaries); Object[][] wordsStresses = SegUtil.slicesFromAllBoundaries(stresses, boundaries); // Each element of the outer array represents units/stresses for a single word for (int i = 0; i < wordsUnits.length; i++) { // Reward if no trust info was provided or if trusted if (wordsTrusts == null || wordsTrusts[i]) { rewardWord(((String[]) wordsUnits[i]), ((Boolean[]) wordsStresses[i])); } } }
5
@EventHandler public void GhastConfusion(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getZombieConfig().getDouble("Ghast.Nausea.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if (damager instanceof Fireball) { Fireball a = (Fireball) event.getDamager(); LivingEntity shooter = a.getShooter(); if (plugin.getGhastConfig().getBoolean("Ghast.Nausea.Enabled", true) && shooter instanceof Ghast && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, plugin.getGhastConfig().getInt("Ghast.Nausea.Time"), plugin.getGhastConfig().getInt("Ghast.Nausea.Power"))); } } }
7
public static Song interpret(String string) { Song song = new Song("Imported Song", Instrument.BELL, 100); for (int i = 0; i < string.length(); i++) { char character = string.charAt(i); Action act = Action.getActionFor(character); if (act != null) { if (string.length() > i + 2) { char next = string.charAt(i + 1); switch (next) { case '/': case '\\': char chord = string.charAt(i + 2); Action nextAct = Action.getActionFor(chord); if (nextAct != null) { song.appendAction(new Chord(act, nextAct)); i += 2; continue; } break; default: break; } } song.appendAction(new Note(act)); } } return song; }
6
public static HashMap<String, ArrayList<HashMap<String, Object>>> bundle(ArrayList<HashMap<String, Object>> flatData) { HashMap<String, ArrayList<HashMap<String, Object>>> bigBox = new HashMap<String, ArrayList<HashMap<String, Object>>>(); ArrayList<HashMap<String, Object>> experiments = new ArrayList<HashMap<String, Object>>(); ArrayList<HashMap<String, Object>> weathers = new ArrayList<HashMap<String, Object>>(); ArrayList<HashMap<String, Object>> soils = new ArrayList<HashMap<String, Object>>(); ArrayList<String> foundWeathers = new ArrayList<String>(); ArrayList<String> foundSoils = new ArrayList<String>(); for (HashMap<String, Object> item : flatData) { if (item.containsKey("weather")) { HashMap<String, Object> w_ref = (HashMap<String, Object>) item.get("weather"); if (w_ref.containsKey("wst_id")) { String wst_id = (String) w_ref.get("wst_id"); if (! foundWeathers.contains(wst_id)) { foundWeathers.add(wst_id); weathers.add(w_ref); } } } if (item.containsKey("soil")) { HashMap<String, Object> s_ref = (HashMap<String, Object>) item.get("soil"); if (s_ref.containsKey("soil_id")) { String soil_id = (String) s_ref.get("soil_id"); if (! foundSoils.contains(soil_id)) { foundSoils.add(soil_id); soils.add(s_ref); } } } item.remove("weather"); item.remove("soil"); experiments.add(item); } bigBox.put("experiments", experiments); bigBox.put("soils", soils); bigBox.put("weathers", weathers); return bigBox; }
7
public int GetStopBusStop() { //get the person stop bus stop return stopBustop; }
0
protected RoomnumberSet getLocations() { final Vector<Physical> items=makeVector(); final RoomnumberSet homes=(RoomnumberSet)CMClass.getCommon("DefaultRoomnumberSet"); final RoomnumberSet set=(RoomnumberSet)CMClass.getCommon("DefaultRoomnumberSet"); Room R=null; for(final Environmental E : items) { R=CMLib.map().getStartRoom(E); if(R==null) R=CMLib.map().roomLocation(E); if(R==null) continue; if((E instanceof Item) &&(((Item)E).owner() instanceof MOB) &&(!((MOB)((Item)E).owner()).isMonster())) continue; if(CMLib.law().getLandTitle(R)!=null) homes.add(CMLib.map().getExtendedRoomID(R)); else set.add(CMLib.map().getExtendedRoomID(R)); } if(set.roomCountAllAreas()>0) return set; return homes; }
8
private boolean lahdeSuuntaan(ArrayList<Merkki> merkit, Suunta suunta, Merkki merkki, int askel, ArrayList<Laatu> jono) { if (merkki.getLaatu() == (jono.get(askel))) { if (askel + 1 == jono.size()) { return true;//paatepiste } for (Merkki seuraava : merkit) { if (seuraava.equals(merkki)) { continue; } if ((seuraava.getX() == (merkki.getX() + suunta.getXmuutos())) && (seuraava.getY() == (merkki.getY() + suunta.getYmuutos()))) { askel++; if (lahdeSuuntaan(merkit, suunta, seuraava, askel, jono)) { return true;//paluupolku paatepisteelta } askel--; } } } return false; }
7
public Method findGetMethod(Field field) { if(field == null) return null; if(getFieldDetailStore().isGetMethodPresentFor(field)) { return getFieldDetailStore().getMethodOf(field); } String getterName = createMethodName("get", field.getName()); try { Method getMethod = getInspectedClass().getDeclaredMethod(getterName); getFieldDetailStore().addSetMethod(field,getMethod); return getMethod; } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { System.err.println("<Classinspect> Did not find GET method <" + getterName + ">. Trying to find <is> method variant"); return findIsMethod(field); } return null; }
4
StringWriter getResult() { try { is.close(); } catch (IOException e) { System.err.println("Unable to close input stream in StreamReader"); } /** * * the StringWriter is closed in {@link #doExec(String[])} after storing its string result. */ return sw; }
1
private void handleKeyPressed(KeyPressedEvent event) { if (event.getCharacter() != 0 && event.getKeyCode() != KeyCode.KEY_BACK && event.getKeyCode() != KeyCode.KEY_ESC) { this.tbv.addChar(event.getCharacter()); return; } switch (event.getKeyCode()) { case KeyCode.KEY_BACK: this.tbv.back(); break; case KeyCode.KEY_LEFT: this.tbv.left(); break; case KeyCode.KEY_RIGHT: this.tbv.right(); break; case KeyCode.KEY_UP: this.tbv.up(); break; case KeyCode.KEY_DOWN: this.tbv.down(); break; } }
8
protected void getMods() { if(modPath != null){ File file = new File(modPath); modDir = file.list(new FilenameFilter() { @Override public boolean accept(File current, String name) { File mfile = new File(current, name); if(name.endsWith(".zip") || mfile.isDirectory()) return true; else return false; } }); //con.log("Log",Arrays.toString(modDir)); getModCount(); getCurrentMods(); } }
3
@Test public void delMinReturnsCorrectOrderWithManyIdenticalElements() { Random r = new Random(); int[] expected = new int[100]; for (int i = 0; i < 100; i++) { int randomInteger = r.nextInt(4); h.insert(new Vertex(0, randomInteger)); expected[i] = randomInteger; } Arrays.sort(expected); int[] actual = new int[100]; for (int i = 0; i < 100; i++) { actual[i] = h.delMin().getDistance(); } assertArrayEquals(expected, actual); }
2
public JButton getButtonOK(){ return buttonOK; }
0
void scoreDnaAndQualitySequence(String seq1, String seq2, int start, int threshold, int result) { // Overlapping with DnaAndQualitySequence DnaAndQualitySequence s1 = new DnaAndQualitySequence(seq1); DnaAndQualitySequence s2 = new DnaAndQualitySequence(seq2); DnaQualSubsequenceComparator compartor = new DnaQualSubsequenceComparator(true, threshold); int idx1 = (start >= 0 ? start : 0); int idx2 = (start >= 0 ? 0 : -start); int score = compartor.score(s1, idx1, s2, idx2); assertEquals(result, score); }
2
private boolean expr_sempred(ExprContext _localctx, int predIndex) { switch (predIndex) { case 0: return precpred(_ctx, 13); case 1: return precpred(_ctx, 12); case 2: return precpred(_ctx, 11); case 3: return precpred(_ctx, 10); case 4: return precpred(_ctx, 9); case 5: return precpred(_ctx, 8); case 6: return precpred(_ctx, 7); case 7: return precpred(_ctx, 6); } return true; }
8
@Override public BeerResponse getBeer(String beerId) { BeerReadOnly beerReadOnly = barService.getBeer(beerId); return new BeerResponse(beerReadOnly); }
0
public String toString() //Displays the rank and suit of the card as a string { String suitName; String rankName; if (suit == SPADES) suitName = "spades"; else if (suit == CLUBS) suitName = "clubs"; else if (suit == HEARTS) suitName = "hearts"; else suitName = "diamonds"; if (rank == 1 || rank > 10) //If the rank is something other than a 1, 11, 12 or 13... { if (rank == ACE) rankName = "ace"; else if (rank == JACK) rankName = "jack"; else if (rank == QUEEN) rankName = "queen"; else rankName = "king"; } else rankName = rank + ""; return ("the suit is " + suitName + " and the rank is " + rankName + "."); //Displays the suit name and the card's rank }
8