text
stringlengths
14
410k
label
int32
0
9
public boolean checkWaterHeight (World world, int x, int y) { Tile tile; tile = world.getTile(x, y+1); if (tile.id == Tile.water.id || tile.id == Tile.flowingWater.id) return false; int myheight = getHeight(world, x, y); tile = world.getTile(x+1, y); if (tile.id == Tile.water.id) return false; if (tile.id == Tile.flowingWater.id && getHeight(world, x+1, y) > myheight) return false; tile = world.getTile(x-1, y); if (tile.id == Tile.water.id) return false; if (tile.id == Tile.flowingWater.id && getHeight(world, x-1, y) > myheight) return false; world.setTile(x, y, Tile.air); return true; }
8
public String getNeuronName(Neuron neuron) { for (int i = 0; i < this.neurons.size(); i++) { for (int s = 0; s < this.neurons.get(i).size(); s++) { if (this.neurons.get(i).get(s) == neuron) { return "Neuron" + i + s; } } } throw new IllegalArgumentException( "The given Neuron is not Part of this Perceptron"); }
3
private static UserNotificationBuffer getMonitorFor(long uid) { UserNotificationBuffer rtn = null; if(monitors.containsKey(uid)) { return monitors.get(uid); } else { rtn = new UserNotificationBuffer(uid); monitors.put(uid, rtn); return rtn; } }
1
public void resetStepThrough() { stepThrough = ""; }
0
public static void logError(Exception e) { File dir = new File(System.getProperty("user.dir") + "/Errors"); if(!dir.exists()) { dir.mkdir(); } DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd HH_mm_ss"); Date date = new Date(); File file = new File(dir + "/Error " + dateFormat.format(date) + ".txt"); try { file.createNewFile(); } catch (IOException e1) { e1.printStackTrace(); } StringBuilder error = new StringBuilder(); error.append(e.toString()); error.append(System.getProperty("line.separator")); for(int x = 0; x<e.getStackTrace().length; x++) { error.append(e.getStackTrace()[x]); error.append(System.getProperty("line.separator")); } try { BufferedWriter out = new BufferedWriter(new FileWriter(file)); out.write(error.toString()); out.close(); } catch (IOException e1) { e1.printStackTrace(); } }
4
public List<Triangle> parse(String path) { List<Triangle> result = null; BufferedReader reader = null; try { if (path.startsWith("classpath:")) { path = path.substring("classpath:".length()); reader = new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream(path))); } else { reader = new BufferedReader(new InputStreamReader(new FileInputStream(path))); } result = read(reader); } catch (IOException ex) { ex.printStackTrace(); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result != null ? result : Collections.<Triangle>emptyList(); }
5
private java.awt.image.BufferedImage create_EFFECT_Image(final int WIDTH, final int HEIGHT, final boolean CLICKED) { if (WIDTH <= 0 || HEIGHT <= 0) { return null; } final java.awt.GraphicsConfiguration GFX_CONF = java.awt.GraphicsEnvironment .getLocalGraphicsEnvironment().getDefaultScreenDevice() .getDefaultConfiguration(); final java.awt.image.BufferedImage IMAGE = GFX_CONF .createCompatibleImage(WIDTH, HEIGHT, java.awt.Transparency.TRANSLUCENT); final java.awt.Graphics2D G2 = IMAGE.createGraphics(); G2.setRenderingHint(java.awt.RenderingHints.KEY_ANTIALIASING, java.awt.RenderingHints.VALUE_ANTIALIAS_ON); final int IMAGE_WIDTH = IMAGE.getWidth(); final int IMAGE_HEIGHT = IMAGE.getHeight(); final java.awt.Rectangle BOUNDS = new java.awt.Rectangle( 0, true||CLICKED ? -(int) (IMAGE_HEIGHT * 0.7) : (int) (IMAGE_HEIGHT * 0.6 / 2), IMAGE_WIDTH, true||CLICKED ? (int) (IMAGE_HEIGHT * 1.4) : (int) (IMAGE_HEIGHT * 1.4) ); final java.awt.RadialGradientPaint GRADIENT; if (CLICKED) { GRADIENT = new java.awt.RadialGradientPaint(BOUNDS, EFFECT_FRACTIONS, effectColorsPressed, java.awt.MultipleGradientPaint.CycleMethod.NO_CYCLE); } else { GRADIENT = new java.awt.RadialGradientPaint(BOUNDS, EFFECT_FRACTIONS, effectColors, java.awt.MultipleGradientPaint.CycleMethod.NO_CYCLE); } G2.setPaint(GRADIENT); G2.fill(BOUNDS); G2.dispose(); return IMAGE; }
7
public void openXML(ObjectManager manager, double scale) { manager.clear(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { //Using factory get an instance of document builder DocumentBuilder db = dbf.newDocumentBuilder(); //parse using builder to get DOM representation of the XML file dom = db.parse(fname); } catch (ParserConfigurationException pce) { //pce.printStackTrace(); return; } catch (SAXException se) { //se.printStackTrace(); return; } catch (IOException ioe) { manager.clear(); //ioe.printStackTrace(); return; } //System.out.println("LOADED"); Element docEle = dom.getDocumentElement(); //get a nodelist of elements NodeList nl = docEle.getElementsByTagName("object"); PolygonObject po; if (nl != null && nl.getLength() > 0) { for (int i = 0; i < nl.getLength(); i++) { //System.out.println(((Element)nl.item(i)).getTextContent()); //get the employee element Element object = (Element) nl.item(i); String name = getTextValue(object, "name"); po = new PolygonObject(); po.setName(name); NodeList polys = object.getElementsByTagName("polygon"); Element poly = (Element) polys.item(0); NodeList points = poly.getElementsByTagName("pt"); if (points != null) { for (int p = 0; p < points.getLength(); p++) { //System.out.println(points.item(p).getNodeName()); Element point = (Element) points.item(p); int x = Integer.parseInt(getTextValue(point, "x")); int y = Integer.parseInt(getTextValue(point, "y")); //System.out.println("POINT: " + x * scale + ", " + y * scale); po.addPoint((int) (x * scale), (int) (y * scale)); //po.addPoint(x,y); } } Random gen = new Random(); po.setColor(gen.nextInt(256), gen.nextInt(256), gen.nextInt(256)); po.generatePoly(); manager.addObject(po); //get the Employee object //Employee e = getEmployee(el); //add it to list //myEmpls.add(e); } } }
8
protected void previous() { ParseNode previous=myParser.getPreviousAnswer(); addAnswerToList(previous.getDerivation()); treePanel.setAnswer(previous); treePanel.repaint(); if (previous.getProductions().length>0) statusDisplay.setText("Derived current Strings using "+previous.getProductions()[0]+" production"); else statusDisplay.setText(""); myPreviousCount++; if (myStepCount==myPreviousCount) { myPreviousAction.setEnabled(false); myStepCount=0; myPreviousCount=0; } stepAction.setEnabled(true); progress.setText(null); }
2
public static final Position getByValue(int v) { switch (v) { case 0: return NORTH; case 1: return SOUTH; case 2: return EAST; case 3: return WEST; case 4: return CENTER; default: throw new IllegalArgumentException("No position with value " + v + "exists."); } }
5
public static ClientApp getClientApp() { if(instance == null) instance = new ClientApp(); return instance; }
1
private String readFromStream(InputStream stream) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(stream)); String line = null; boolean first = true; StringBuilder out = new StringBuilder(); while ((line = in.readLine()) != null) { if (first) { first = false; } else { out.append(System.getProperty("line.separator")); } out.append(line); } return out.toString(); }
2
public void setScheduler( Scheduler scheduler ) { this.scheduler = scheduler; }
0
public List<Position> getDestinations(Position start, Player.Orientation orientation, Board board) { List<Position> destinations = new ArrayList<Position>(); int xDest, yDest; if (orientation == Player.Orientation.UP) { xDest = start.getX() + destination.getX(); yDest = start.getY() + destination.getY(); } else { xDest = start.getX() - destination.getX(); yDest = start.getY() - destination.getY(); } Piece piece = board.getPiece(xDest, yDest); if ( piece != null && ( (piece.getPieceType() == null && capture == false) || (piece.getPieceType() != null && !piece.getPlayer().equals(board.getPiece(start).getPlayer()) && capture == true) ) ) { destinations.add(new Position(xDest, yDest)); } return destinations; }
7
public CadastroRevisoes(String entrada, Revista revista) throws FileNotFoundException { this.entrada = entrada; this.revista = revista; File arquivo = new File(entrada); Scanner scanner = new Scanner(arquivo); String cabecalho = scanner.nextLine(); while (scanner.hasNextLine()) { // Obtém todas as linhas do arquivo String linha = scanner.nextLine().trim(); NoncollapsingStringTokenizer token = new NoncollapsingStringTokenizer(linha, ";"); // Divide cada linha em tokens, de acordo com o delimitador ";" while (token.hasMoreTokens()) { // Salva os dados em variáveis int codigo = Integer.parseInt(token.nextToken().trim()); int revisor = Integer.parseInt(token.nextToken().trim()); double originalidade = Double.parseDouble(token.nextToken().replace(',', '.').trim()); double conteudo = Double.parseDouble(token.nextToken().replace(',', '.').trim()); double apresentacao = Double.parseDouble(token.nextToken().replace(',', '.').trim()); Colaborador c = revista.buscaColaborador(revisor); // Trata inconsistencia #8: revisor em revisoes.csv não está cadastrado if(c == null || !(c instanceof Revisor)) { Inconsistencia i = new Inconsistencia("O código " + revisor + " encontrado no cadastro de revisões não corresponde a um revisor cadastrado.", 8); revista.adicionaInconsistencia(i); } else { // Vincula a avaliação de um revisor a um artigo Revisor r = (Revisor)c; Avaliacao avaliacao = new Avaliacao(r); avaliacao.atribuirNota(originalidade,conteudo,apresentacao); Artigo artigo = (revista.getEdicao()).buscaArtigo(codigo); if (artigo == null) { // Trata insconsistencia #9: código do artigo não está cadastrado em artigos submetidos à edição Inconsistencia i = new Inconsistencia("O código " + codigo + " encontrado no cadastro de revisões não corresponde a um artigo cadastrado.", 9); revista.adicionaInconsistencia(i); } else { artigo.adicionaAvaliacao(avaliacao); r.vinculaRevisao(artigo); // Trata inconsistencia #10: revisor não habilitado a revisar artigo sob tema da edição if(revista.getEdicao().getTema() != null) if(!(revista.getEdicao().getTema().contemRevisor(r))){ Inconsistencia i = new Inconsistencia("O revisor " + r.getNome() + " avaliou o artigo " + artigo.getTitulo() + ", porém ele não consta como apto a avaliar o tema." + revista.getEdicao().getTema() + ", desta edição.",10); revista.adicionaInconsistencia(i); } } } } } scanner.close(); // Trata inconsistencia #11: artigos revisados com menos ou mais de 3 avaliações for(Artigo a : revista.getEdicao().getArtigos()){ if(!(a.quantidadeRevisoes())){ Inconsistencia i = new Inconsistencia("O artigo " + "\"" + a.getTitulo() + "\"" + " possui " + a.getQuantidadeRevisoes() + " revisões. Cada artigo deve conter exatamente 3 revisões.", 11); revista.adicionaInconsistencia(i); } } }
9
public int getTotalMovies(){ int movieCount = 0; //Count all movies for(Actor a : actors.values()){ for(Movie m : a.getMovieAppearances()){ if (!m.isVisited()){ movieCount++; m.setVisited(true); } } } //Reset all of the movie flags for(Actor a : actors.values()){ for(Movie m : a.getMovieAppearances()){ if (m.isVisited()){ m.setVisited(false); } } } return movieCount; }
6
@SuppressWarnings("deprecation") void playExecution() { for(ThreadsInformation threadInfo : ThreadsAgent) threadInfo.threadInfo.resume(); }
1
public DirectedCycle(Digraph G) { marked = new boolean[G.V()]; onStack = new boolean[G.V()]; edgeTo = new int[G.V()]; for (int v = 0; v < G.V(); v++) if (!marked[v]) dfs(G, v); }
2
private void processAllParticipants() { user_messages = new HashMap<String,String>(); //reset checks room_bot.current_standup_user = null; room_bot.did_user_speak = false; room_bot.did_user_say_anything = false; HipchatUser next_user = null; StringBuilder sb = new StringBuilder(); while ( (next_user = room_bot.getNextStandupUser()) != null ) { sb.append("Your turn @" + next_user.getMentionName()); hippy_bot.sendMessage(sb.toString(), room_bot.current_room); sb = new StringBuilder(); long start_time = System.currentTimeMillis(); //for tracking timeout //block while we wait for timer to end or user to speak while ( (System.currentTimeMillis() - start_time) < (room_bot.bot_data.max_secs_between_turns*1000L) && !room_bot.did_user_speak ) { //sleep for a few, then check again try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } long end_time = System.currentTimeMillis(); if ( room_bot.did_user_speak ) { //user ended his standup by speaking sb.append("Thanks " + Utils.getFirstName(room_bot.current_standup_user.getName()) + "! "); } else if ( room_bot.did_user_say_anything ) { //user said something but not correct format sb.append(Utils.getFirstName(room_bot.current_standup_user.getName()) + " spoke but didn't say terminating word, burned on a technicality! "); } else { //user timeout sb.append(Utils.getFirstName(room_bot.current_standup_user.getName()) + " must be sleepy! "); } user_time_ran.put(room_bot.current_standup_user.getMentionName(), end_time-start_time); StringBuilder builder = new StringBuilder(); for ( String s : room_bot.current_standup_user_messages) builder.append(s).append(" "); user_messages.put(room_bot.current_standup_user.getMentionName(), builder.toString()); //reset checks room_bot.current_standup_user = null; room_bot.did_user_speak = false; room_bot.did_user_say_anything = false; } //once we get here everyone has gone, display stats sb.append("That's everyone!"); sb.append("\nRuntime stats:"); for ( Map.Entry<String, Long> entry : user_time_ran.entrySet() ) { double run_time = (entry.getValue())/1000.0; sb.append("\n@" + entry.getKey() + ": " + run_time + "s"); } for ( Map.Entry<String, String> entry : room_bot.users_early_standup.entrySet() ) { sb.append("\n@" + entry.getKey() + ": 0s (early standup)"); } //handle user messages for summary createSummary(); room_bot.users_early_standup.clear(); hippy_bot.sendMessage(sb.toString(), room_bot.current_room); room_bot.endStandup(); hippy_bot.sendMessage("/quote SUMMARY:\n" + room_bot.summary, room_bot.current_room); }
9
public final static int parseInt(String value) { if (isInt(value)) return Integer.parseInt(value); return 0; }
1
@Test public void reTest6() { userInput.add("hi"); userInput.add("my name is meng meng"); userInput.add("can you bring me something"); userInput.add("knife"); userInput.add("errorhandling"); userInput.add("errorhandling"); userInput.add("errorhandling"); userInput.add("errorhandling"); userInput.add("handle the error"); userInput.add("handle the error somehow"); userInput.add("handle this error"); userInput.add("no"); userInput.add("i want to go to the canteen"); this.runMainActivityWithTestInput(userInput); assertTrue((nlgResults.get(4).contains("again") || nlgResults.get(4).contains("repeat")) && (nlgResults.get(6).contains("again") || nlgResults.get(6).contains("repeat")) && nlgResults.get(7).contains("rephrase") && nlgResults.get(9).contains("rephrase") && nlgResults.get(10).contains("tools") && nlgResults.get(11).contains("")); }
7
public void BudujTabele(){ current=0; //wysokosc jedenj ramki 22piks HLevel=22; for(int i=0 ; i<ILOSC_POL ; i++) pola[i].setVisible(false); for (int i=0 ; i<Posilek.ILOSC_SKLADNIKOW ; i++){ DeleteAction[i].setValue(0); } for (int i =0 ; i<pos.current ; i++){ skl = BazaObject.IteratorSkladniki.getSkladnik(pos.skladniki[i]); wag = pos.waga[i]; DeleteAction[i].setValue(i); ((WeightTextField) pola[current+1]).setValue(i,pola[current+1]); pola[current].setText(skl.name); pola[current+1].setText(""+wag); pola[current].setBounds(0,HLevel,dlugosc_n,wysokosc); pola[current+1].setBounds(dlugosc_n, HLevel, dlugosc_w, wysokosc); pola[current+2].setText(""+skl.W*wag/100); pola[current+3].setText(""+skl.B*wag/100); pola[current+2].setBounds(dlugosc_n+dlugosc_w,HLevel,dlugosc_m,wysokosc); pola[current+3].setBounds(dlugosc_n+dlugosc_w+dlugosc_m, HLevel, dlugosc_m,wysokosc); pola[current+4].setText(""+skl.T*wag/100); pola[current+4].setBounds(dlugosc_n+dlugosc_w+2*dlugosc_m,HLevel,dlugosc_m,wysokosc); pola[current].setVisible(true); pola[current+1].setVisible(true); pola[current+2].setVisible(true); pola[current+3].setVisible(true); pola[current+4].setVisible(true); HLevel+=wysokosc; current+=5; } if (pos.current<Posilek.ILOSC_SKLADNIKOW) { skladnikiCombo.setBounds(5, HLevel+45, 150, 25); skladnikiCombo.setVisible(true); } else skladnikiCombo.setVisible(false); poleM1.setText("Ogolnie"); poleM1.setBounds(108,HLevel+5,50,25); poleM2.setText(""+pos.macro.W); poleM2.setBounds(158,HLevel+5,26,25); poleM3.setText(""+pos.macro.B); poleM3.setBounds(184,HLevel+5,26,25); poleM4.setText(""+pos.macro.T); poleM4.setBounds(210,HLevel+5,26,25); poleM5.setText(pos.macro.Kcal+" Kcal"); poleM5.setBounds(162,HLevel+30,70,25); poleM1.setEditable(false); poleM2.setEditable(false); poleM3.setEditable(false); poleM4.setEditable(false); poleM5.setEditable(false); MainFrame.updateMainMacro(); System.out.println("===========================BudujTabele()============================="); //System.out.println(SaveChanges.DniInsert[0]); for(Skladnik c: BazaObject.skladniki){ if(c!=null) System.out.println("name="+c.name); } }
6
static public OutputChannels fromInt(int code) { switch (code) { case LEFT_CHANNEL: return LEFT; case RIGHT_CHANNEL: return RIGHT; case BOTH_CHANNELS: return BOTH; case DOWNMIX_CHANNELS: return DOWNMIX; default: throw new IllegalArgumentException("Invalid channel code: "+code); } }
4
@PostConstruct public void init() { httpHandler = new HttpHandler(); try { URL requestUrl = new URL("http://services.brics.dk/java4/cloud" + "/listItems?shopID=" + "195"); Element responseRoot = httpHandler.HttpRequest("GET", requestUrl) .getRootElement(); if (responseRoot == null) { throw new Exception("Response from itemList request was null"); } else { itemList = new ArrayList<Item>(); for (Element itemChild : responseRoot.getChildren()) { Element description = itemChild.getChild("itemDescription", WEBTEKNS); String descriptionStr = ""; for (Element descriptionChild : description.getChildren()) { descriptionChild.setNamespace(null); switch (descriptionChild.getName()) { case "document": descriptionChild.setName("div"); break; case "bold": descriptionChild.setName("b"); break; case "italics": descriptionChild.setName("i"); break; case "list": descriptionChild.setName("ul"); break; case "item": descriptionChild.setName("li"); break; default: break; } descriptionStr += descriptionChild.getValue(); } itemList.add(new Item(itemChild.getChildText("itemID", WEBTEKNS), itemChild.getChildText("itemName", WEBTEKNS), itemChild.getChildText("itemURL", WEBTEKNS), itemChild.getChildText("itemPrice", WEBTEKNS), itemChild.getChildText("itemStock", WEBTEKNS), descriptionStr)); } } } catch (Exception e) { System.out.println("An error occurred: " + e.getMessage()); } }
9
private void jComboBoxPaysItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBoxPaysItemStateChanged if (evt.getStateChange() == ItemEvent.SELECTED){ String test = ((Pays)this.jComboBoxPays.getSelectedItem()).getPays(); this.jTextFieldPays.setText(test); if (this.jComboBoxPays.getSelectedIndex()!=0){ this.jLabelPaysMessage.setText("Modifiez le pays : "); this.jButtonPaysValider.setText("Modifier"); } else{ this.jLabelPaysMessage.setText("Entrez un nouveau Pays : "); this.jButtonPaysValider.setText("Valider"); } } }//GEN-LAST:event_jComboBoxPaysItemStateChanged
2
@Override public Term parseTerm() throws IOException { Term term = new Term(); term.getFactorList().add(parseFactor()); while (curToken.type == DIVIDE || curToken.type == MULTIPLY) { switch (curToken.type) { case DIVIDE: curToken = lexer.getToken(); term.getOpList().add(DIVIDE); term.getFactorList().add(parseFactor()); break; case MULTIPLY: curToken = lexer.getToken(); term.getOpList().add(MULTIPLY); term.getFactorList().add(parseFactor()); break; } } return term; }
4
public List<Region> getRegions(RegionType type) { List<Region> regions = new ArrayList<Region>(); for (Region region : this.mapRegions) { if (region.getType() == type) { regions.add(region); } } return regions; }
2
@Test public void t_gd2gc() /** ** ** Test jauGd2gc function. ** ** Returned: ** status int TRUE = success, FALSE = fail ** ** Called: jauGd2gc, viv, vvd ** ** This revision: 2009 November 6 */ { double e = 3.1, p = -0.5, h = 2500.0; double xyz[] = new double[3]; try { xyz = jauGd2gc( 0, e, p, h ); fail("jauGd2gc should thow exception for illegal parameter"); } catch (JSOFAIllegalParameter e1) { // expected behaviour } catch (JSOFAInternalError e1) { fail("jauGd2gc should thow exception for illegal parameter"); } try { xyz = jauGd2gc( 1, e, p, h ); vvd(xyz[0], -5599000.5577049947, 1e-7, "jauGd2gc", "0/1"); vvd(xyz[1], 233011.67223479203, 1e-7, "jauGd2gc", "1/1"); vvd(xyz[2], -3040909.4706983363, 1e-7, "jauGd2gc", "2/1"); xyz = jauGd2gc( 2, e, p, h); vvd(xyz[0], -5599000.5577260984, 1e-7, "jauGd2gc", "0/2"); vvd(xyz[1], 233011.6722356703, 1e-7, "jauGd2gc", "1/2"); vvd(xyz[2], -3040909.4706095476, 1e-7, "jauGd2gc", "2/2"); xyz = jauGd2gc( 3, e, p, h); vvd(xyz[0], -5598998.7626301490, 1e-7, "jauGd2gc", "0/3"); vvd(xyz[1], 233011.5975297822, 1e-7, "jauGd2gc", "1/3"); vvd(xyz[2], -3040908.6861467111, 1e-7, "jauGd2gc", "2/3"); } catch (JSOFAException e1) { fail("jauGd2gc should not thow exception "); } try { xyz = jauGd2gc( 4, e, p, h ); fail("jauGd2gc should thow exception for illegal parameter"); } catch (JSOFAIllegalParameter e1) { //expected behaviour } catch (JSOFAInternalError e1) { fail("jauGd2gc should thow exception for illegal parameter"); } }
5
public boolean reserve(int theaterID) throws RemoteException{ if(this.lastRequest == -1) this.lastRequest = System.currentTimeMillis(); if(connectionTimout()) return false; ReservationReplyMessage reply; reply = rmiServer.reservationRequest(this.ID, theaterID, reservation); if(reply != null) return reply.getState(); return false; }
3
public String getSkillName() { return skillName; }
0
private void Traversal(TreeNode root,ArrayList<Integer> list) { if(root != null){ list.add(root.val); Traversal(root.left,list); Traversal(root.right,list); } }
1
private JButton generiereNeuenHandKartenKnopf(Karte neueKarte) { JButton handkarte = new JButton(neueKarte.getStadt().toString()); handkarte.setBackground(neueKarte.getStadt().getLand().getFarbe()); handkarte.setForeground(new Color(255, 255, 255)); handkarte.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Spieler aktuellerSpieler = spiel.getAktuellerSpieler(); if (!pruefeZyklus(e.getActionCommand())) { if (aktuellerSpieler.getGelegtCount() > 0) { int answer = JOptionPane.showConfirmDialog(new JPanel(), "Möchtest du diese Karte wirklich auspielen?" , "Karte auspielen", 0); switch (answer) { case 0: for (Karte karte : aktuellerSpieler.getHand()) { if (karte.getStadt().toString().equals(e.getActionCommand())) { spiel.karteAuspielen(karte); aktuellerSpieler.getHand().remove(karte); aktualisiereSpielerInformationen(); verknüpfeSpielerAuslageMitSpiel(); entferneHandKartenKnopf(karte); } } break; } } else { consoleText.append("Noch viel zu lernen du hast, mein junger Padawan\n"); consoleText.append("(Schreib es dir endlich hinter die Ohren,\n das geht nur einmal pro Runde!)\n\n"); } } else { consoleText.append("Warte eben ich hole dir schnell noch mehr Bier! Entweder läufst du im Kreis,\n" + "oder dein Kopf dreht sich wie verrückt!!\n"); consoleText.append("(Du kannst während du eine Route baust,\n jede Stadt nur einmal besuchen!)\n\n"); } } private boolean pruefeZyklus(String actionCommand) { boolean zyklus = false; for (Karte karte : spiel.getAktuellerSpieler().getAuslage()) { if (karte.getStadt().toString().equals(actionCommand)) { zyklus = true; } } return zyklus; } private void entferneHandKartenKnopf(Karte karte) { Component buttonToRemove = null; for (Component comp : handkartenAreal.getComponents()) { if (((JButton) comp).getText().equals(karte.getStadt().toString())) { buttonToRemove = comp; } } handkartenAreal.remove(buttonToRemove); handkartenAreal.revalidate(); handkartenAreal.repaint(); } }); return handkarte; }
9
public final JSONArray optJSONArray(String key) { Object o = opt(key); return o instanceof JSONArray ? (JSONArray)o : null; }
1
public boolean equalsExpr(final Expr other) { return (other != null) && (other instanceof FieldExpr) && ((FieldExpr) other).field.equals(field) && ((FieldExpr) other).object.equalsExpr(object); }
3
public void affiche () { int i = 0; int j = 0; while ( i < tableauDesCaisses.length ) { tableauDesCaisses[i].affiche(); i = i + 1; } System.out.print("Tous les ronchons: "); i = 0; int nbTotalRonchons = 0; int nbTotalRonchonnement = 0; if ( listeDesRonchons.size() == 0 ) { System.out.print("<vide>"); } else { while ( i < listeDesRonchons.size() ) { Client client = listeDesRonchons.get(i); client.afficher(); System.out.print(" ; "); nbTotalRonchons = nbTotalRonchons + 1; nbTotalRonchonnement = nbTotalRonchonnement + client.nombreDeRonchonnements; i = i + 1; } } System.out.println(); System.out.print("Nombre total de ronchons: "); System.out.println(nbTotalRonchons); System.out.print("Nombre total de ronchonnements: "); System.out.println(nbTotalRonchonnement); int maxClientsSortisAffichable = 5; System.out.println("Nombre total de clients sortis: " + listeClientsSortis.size()); System.out.print("Derniers sortis: "); i = 0; if ( listeClientsSortis.size() == 0 ) { System.out.print("<vide>"); } else { if ( listeClientsSortis.size() > maxClientsSortisAffichable ) { System.out.print("... ; "); j = listeClientsSortis.size() - maxClientsSortisAffichable; } while ( i+j < listeClientsSortis.size() && i < maxClientsSortisAffichable ) { Client client = listeClientsSortis.get(i+j); client.afficher(); System.out.print(" ; "); i = i + 1; } } System.out.print("\n"); }
7
@Override public Object getValueAt(int row, int col) { FSE theFSE = (FSE) theData.get(row); switch(col) { case 0: return theFSE.getCode(); case 1: return theFSE.getName(); case 2: return theFSE.getAddress().getShortValue(); case 3: Calendar c = Calendar.getInstance(); c.setTime(c.getTime()); int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); return String.format("%04d", theFSE.getDayOpenHour(dayOfWeek)) + " - " + String.format("%04d", theFSE.getDayCloseHour(dayOfWeek)); } return null; }
4
public ConfigurationDialog(ClientMain parent) { super(parent, I18n.getInstance().getString("cfdTitle"), true); this.setDefaultCloseOperation(DISPOSE_ON_CLOSE); JPanel panel = new JPanel(); panel.setLayout(new BorderLayout(10,10)); panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); panel.setPreferredSize(new Dimension(300, 300)); tabs = new JTabbedPane(); /************************************************** * Settings Tab **************************************************/ JPanel panelSettings = new JPanel(new GridLayout(7, 2, 10, 10)); panelSettings.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); /* * Language */ panelSettings.add(new JLabel(I18n.getInstance().getString("cfdLanguage"))); Set<Locale> langs = I18n.getInstance().getLanguages(); Vector<String> languages = new Vector<String>(); if (langs.size() > 0) { for (Locale lang : langs) { languages.add(lang.toString()); } } cbLanguages = new JComboBox(languages); cbLanguages.setSelectedItem(languages.contains(Config.get("language")) ? Config.get("language") : Locale.ENGLISH.getDisplayLanguage(I18n.getInstance().getLocale())); panelSettings.add(cbLanguages); /* * Default Profile */ panelSettings.add(new JLabel(I18n.getInstance().getString("cfdDefaultProfile"))); cbDefaultProfile = new JComboBox(Config.getProfiles()); cbDefaultProfile.setSelectedItem(Config.getDefaultProfile()); panelSettings.add(cbDefaultProfile); panelSettings.add(new JPanel()); panelSettings.add(new JPanel()); panelSettings.add(new JPanel()); panelSettings.add(new JPanel()); panelSettings.add(new JPanel()); panelSettings.add(new JPanel()); panelSettings.add(new JPanel()); panelSettings.add(new JPanel()); panelSettings.add(new JPanel()); panelSettings.add(new JPanel()); tabs.addTab(I18n.getInstance().getString("cfdSettings"), panelSettings); /************************************************** * Profiles Tab **************************************************/ JPanel panelProfiles = new JPanel(new GridLayout(7, 2, 10, 10)); panelProfiles.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); /** * profile combobox */ panelProfiles.add(new JLabel(I18n.getInstance().getString("cdProfile"))); cbProfile = new JComboBox(Config.getProfiles()); cbProfile.setEditable(true); cbProfile.setSelectedItem(Config.getDefaultProfile()); cbProfile.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Profile profile = (Profile) cbProfile.getSelectedItem(); profileHostAddress.setText(profile.getHost()); profilePortNumber.setText(profile.getPort()); profileUserName.setText(profile.getUserName()); profilePassWord.setText(profile.getPassword()); } }); panelProfiles.add(cbProfile); /** * textfield for host */ panelProfiles.add(new JLabel(I18n.getInstance().getString("cdHost"))); profileHostAddress = new JTextField(Config.getDefaultProfile().getHost()); profileHostAddress.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent arg0) { ConfigurationDialog.this.profileHostAddress.selectAll(); } @Override public void focusLost(FocusEvent e) { ConfigurationDialog.this.profileHostAddress.select(0, 0); } }); panelProfiles.add(profileHostAddress); /** * textfield for the port */ panelProfiles.add(new JLabel(I18n.getInstance().getString("cdPort"))); profilePortNumber = new JTextField(Config.getDefaultProfile().getPort()); profilePortNumber.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent arg0) { ConfigurationDialog.this.profilePortNumber.selectAll(); } @Override public void focusLost(FocusEvent e) { ConfigurationDialog.this.profilePortNumber.select(0, 0); } }); panelProfiles.add(profilePortNumber); /** * textfield for the username */ panelProfiles.add(new JLabel(I18n.getInstance().getString("cdUser"))); profileUserName = new JTextField(Config.getDefaultProfile().getUserName()); profileUserName.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent arg0) { ConfigurationDialog.this.profileUserName.selectAll(); } @Override public void focusLost(FocusEvent e) { ConfigurationDialog.this.profileUserName.select(0, 0); } }); panelProfiles.add(profileUserName); /** * password field */ panelProfiles.add(new JLabel(I18n.getInstance().getString("cdPassWord"))); profilePassWord = new JPasswordField(Config.getDefaultProfile().getPassword()); profilePassWord.addKeyListener(new KeyListener() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE && e.isControlDown()) { profilePassWord.setText(""); } } @Override public void keyReleased(KeyEvent e) { } @Override public void keyTyped(KeyEvent e) { } }); profilePassWord.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent arg0) { ConfigurationDialog.this.profilePassWord.selectAll(); } @Override public void focusLost(FocusEvent e) { ConfigurationDialog.this.profilePassWord.select(0, 0); } }); panelProfiles.add(profilePassWord); /* * New Profile Button */ button = new JButton(I18n.getInstance().getString("cfdAddProfile")); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { } }); panelProfiles.add(button); /* * Delete Profile Button */ button = new JButton(I18n.getInstance().getString("cfdDeleteProfile")); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { } }); panelProfiles.add(button); panelProfiles.add(new JPanel()); panelProfiles.add(new JPanel()); tabs.addTab(I18n.getInstance().getString("cfdProfiles"), panelProfiles); /* * add tabs to panel */ panel.add(tabs, BorderLayout.CENTER); /************************************************** * Buttons **************************************************/ JPanel btnPanel = new JPanel(new GridLayout(1, 3, 10, 10)); btnPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); /* * Save Button */ button = new JButton(I18n.getInstance().getString("cfdSave")); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { ConfigurationDialog.this.save(); ConfigurationDialog.this.dispose(); } }); btnPanel.add(button); /* * Apply Button */ button = new JButton(I18n.getInstance().getString("cfdApply")); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { ConfigurationDialog.this.save(); } }); btnPanel.add(button); /* * Cancel Button */ button = new JButton(I18n.getInstance().getString("cfdCancel")); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { ConfigurationDialog.this.dispose(); } }); btnPanel.add(button); this.getContentPane().add(panel, BorderLayout.CENTER); this.getContentPane().add(btnPanel, BorderLayout.SOUTH); this.pack(); this.setAlwaysOnTop(true); this.setLocationRelativeTo(this.getParent()); this.setVisible(true); this.setResizable(false); }
5
@Override public boolean isHygienicMessage(final CMMsg msg, final int minHygiene, final long adjHygiene) { if(CMSecurity.isDisabled(CMSecurity.DisFlag.HYGIENE)) return false; if((msg.sourceMajor(CMMsg.MASK_MOVE) &&((msg.tool()==null) ||(!(msg.tool() instanceof Ability)) ||((((Ability)msg.tool()).classificationCode()&Ability.ALL_ACODES)!=Ability.ACODE_COMMON_SKILL))) ||((msg.tool() instanceof Social) &&((msg.tool().Name().toUpperCase().startsWith("BATHE")) ||(msg.tool().Name().toUpperCase().startsWith("WASH"))))) return (msg.source().playerStats()!=null)&&(msg.source().soulMate()==null); return false; }
9
static void printSystem ( Fraction[][] matrix ) { int spaces; out.printf( "\n" ); for ( int i = 1; i <= rows; i++ ){ for ( int j =1; j <= columns; j++ ) { if ( j != columns ){ if ( matrix[i][j].getNumerator() != 0 ){ spaces = maxLength - matrix[i][j].length()-2; } else { spaces = maxLength+2; } for ( ; spaces > 0; spaces-- ) { out.printf( " " ); } //if (j!=column) if ( matrix[i][j].equals( one ) ) { //matrix[i][j].output(); out.printf( "X%d + ", j ); } else if ( matrix[i][j].getNumerator() != 0 ) { matrix[i][j].output(); out.printf( "X%d", j ); //if j } }else { out.printf( "= " ); matrix[i][j].output(); out.printf( "\n" ); } } } }
7
public static boolean checking(String person){ String[] dataArray = null; String target; double numOfone = 0; boolean notOne = false; try { BufferedReader csvFile = new BufferedReader(new FileReader("parserResult/coauthor_degree.csv")); while((target = csvFile.readLine())!= null){ dataArray = target.split(","); if(dataArray[0].equals(person)){ break; } } for(int i = 1; i < dataArray.length; i++){ if(dataArray[i].equals("1")){ numOfone++; } else{ notOne = true; } } csvFile.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } double flag = (double)(numOfone/(dataArray.length -1)); if( flag > (1/2) && notOne){ return true; } else{ return false; } }
7
private Point2D scalePoint(Point2D point, Dimension2D size) { Point2D scale = null; try { scale = (Point2D) point.getClass().newInstance(); if (inverted) scale.setLocation(point.getX() * size.getWidth(), (1.0 - point .getY()) * size.getHeight()); else scale.setLocation(point.getX() * size.getWidth(), point.getY() * size.getHeight()); } catch (Throwable e) { System.err.println("BADNESS SCALING THE POINT IN TREEDRAWER!"); System.err.println(e); } return scale; }
2
public boolean[] getThreadStates() { return threadStates; }
0
@Override public boolean insert(DataRow row) { Boolean flaga = false; try { con = DriverManager.getConnection(url, login, password); String stm; String tabelName = row.getTableName(); List<DataCell> cells = row.row; String kolumny = ""; String values = ""; for(DataCell c : cells) { kolumny += c.name + ", "; values += c.value + ", "; } kolumny = kolumny.substring(0, kolumny.length()-2); values = values.substring(0, values.length()-2); stm = "INSERT INTO " + tabelName + "(" + kolumny + ") VALUES (" + values + ")"; pst = con.prepareStatement(stm); pst.executeUpdate(); flaga = true; } catch (SQLException ex) { ErrorDialog errorDialog = new ErrorDialog(true, "Błąd operacji w lokalnej bazie danych: \n" + ex.getMessage(), "LocalDatabaseConnectorPostgre", "insert(DataRow row)", "con, stm, pst"); errorDialog.setVisible(true); } finally { try { if (pst != null) { pst.close(); } if (con != null) { con.close(); } } catch (SQLException ex) { ErrorDialog errorDialog = new ErrorDialog(true, "Błąd operacji w lokalnej bazie danych: \n" + ex.getMessage(), "LocalDatabaseConnectorPostgre", "insert(DataRow row)", "con, stm, pst"); errorDialog.setVisible(true); } } return flaga; }
5
private static SelectorMutableTreeNode generateTreeNode(Object obj){ SelectorMutableTreeNode node = new SelectorMutableTreeNode(obj); for(Method method : obj.getClass().getDeclaredMethods()){ if(method.isAnnotationPresent(CRRCSimEditorNode.class)){ try { Object childObj = method.invoke(obj); if (childObj instanceof List<?>) { for(Object childObjItem : (List)childObj){ node.add(generateTreeNode(childObjItem)); } }else node.add(generateTreeNode(childObj)); } catch (IllegalAccessException ex) { Logger.getLogger(SelectorMutableTreeNode.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalArgumentException ex) { Logger.getLogger(SelectorMutableTreeNode.class.getName()).log(Level.SEVERE, null, ex); } catch (InvocationTargetException ex) { Logger.getLogger(SelectorMutableTreeNode.class.getName()).log(Level.SEVERE, null, ex); } } } return node; }
8
public boolean canStop() { return !(preStop || !isStarted); }
1
public static String edgeTypeToString(EdgeType type){ switch (type) { case NORMAL: return "N"; case ANTI_NORMAL: return "A"; case INNIE: return "I"; case OUTIE: return "O"; } return null; }
4
private BitSet selectABonds(String str) { int n = model.aBonds.size(); if (n == 0) return null; BitSet bs = new BitSet(n); if ("selected".equalsIgnoreCase(str)) { synchronized (model.aBonds) { for (int i = 0; i < n; i++) { if (model.getABond(i).isSelected()) bs.set(i); } } return bs; } String strLC = str.toLowerCase(); if (strLC.indexOf("involve") != -1) { str = str.substring(7).trim(); strLC = str.toLowerCase(); if (strLC.indexOf("atom") != -1) { str = str.substring(4).trim(); if (selectAbondsInvolving(str, bs)) { model.setABondSelectionSet(bs); return bs; } } else { out(ScriptEvent.FAILED, "Unrecognized expression: " + str); return null; } } if (selectFromCollection(str, n, bs)) { model.setABondSelectionSet(bs); return bs; } out(ScriptEvent.FAILED, "Unrecognized expression: " + str); return null; }
8
@Override public void processCas(CAS aCAS) throws ResourceProcessException { JCas jcas = null; try { jcas = aCAS.getJCas(); } catch (CASException e) { throw new ResourceProcessException(e); } String sentenceId = ""; FSIterator<TOP> sentenceIterator = jcas.getJFSIndexRepository().getAllIndexedFS(Sentence.type); if (sentenceIterator.hasNext()) { Sentence sentence = (Sentence)sentenceIterator.next(); sentenceId = sentence.getSentenceId(); } for (Annotation geneEntity : jcas.getAnnotationIndex(GeneEntity.type)) { GeneEntity thisGeneEntity = (GeneEntity)geneEntity; String outputString = sentenceId + "|" + ((Integer)thisGeneEntity.getBegin()).toString() + " " + ((Integer)thisGeneEntity.getEnd()).toString() + "|" + thisGeneEntity.getEntityText() + "\n"; try { mBufferedWriter.write(outputString); mBufferedWriter.flush(); } catch (IOException e) { e.printStackTrace(); } } }
4
@EventHandler public void SilverfishPoison(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.getSilverfishConfig().getDouble("Silverfish.Poison.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if (plugin.getSilverfishConfig().getBoolean("Silverfish.Poison.Enabled", true) && damager instanceof Silverfish && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.POISON, plugin.getSilverfishConfig().getInt("Silverfish.Poison.Time"), plugin.getSilverfishConfig().getInt("Silverfish.Poison.Power"))); } }
6
public void run() { System.out.println("启动消费者线程!"); Random r = new Random(); boolean isRunning = true; try { while (isRunning) { System.out.println("正从队列获取数据..."); String data = queue.poll(2, TimeUnit.SECONDS); if (null != data) { System.out.println("拿到数据:" + data); System.out.println("正在消费数据:" + data); Thread.sleep(r.nextInt(DEFAULT_RANGE_FOR_SLEEP)); } else { // 超过2s还没数据,认为所有生产线程都已经退出,自动退出消费线程。 isRunning = false; } } } catch (InterruptedException e) { e.printStackTrace(); Thread.currentThread().interrupt(); } finally { System.out.println("退出消费者线程!"); } }
3
public Iterator<Integer> getIDIterator() { return laenderMap.keySet().iterator(); }
0
public void moveLeft() { setDirection(-90); for (TetrisBug tb : blocks){ tb.setDirection(-90); } if (rotationPos==0){ if (blocks.get(0).canMove() && blocks.get(2).canMove()) { blocks.get(2).move(); move(); blocks.get(0).move(); blocks.get(1).move(); } } if (rotationPos == 1){ if (canMove() && blocks.get(1).canMove() && blocks.get(2).canMove()){ blocks.get(2).move(); move(); blocks.get(1).move(); blocks.get(0).move(); } } }
8
private static String decodeRawWord(String rawWord) { if (rawWord == null || "".equals(rawWord)) { return rawWord; } char[] cs = rawWord.toCharArray(); boolean quoted = cs[0] == CHAR_QUOTE && cs[cs.length - 1] == CHAR_QUOTE; if (!quoted) { return rawWord; } boolean quoteOn = false; StringBuilder sb = new StringBuilder(); for (int i = 1; i < cs.length - 1; i++) { char c = cs[i]; if (c == CHAR_QUOTE) { if (quoteOn) { sb.append(c); } quoteOn = !quoteOn; } else { sb.append(c); } } return sb.toString(); }
7
@RequestMapping("/lishi") public String lishi(String cardno,String name,String pages,HttpServletRequest request) throws Exception{ Map<Object, Object> map = new HashMap<Object, Object>(); int curPage = 0; List<Logging> loggings= loggingService.findLoggingByNo(cardno); if(loggings != null && loggings.size()>0){ if (pages == null || pages.trim().equals("")) { curPage = 1; } else { curPage = Integer.parseInt(pages); } request.setAttribute("curPage", curPage); map.put("min", (curPage - 1) * page); map.put("max", page); map.put("cardno", cardno); if(!cardno.isEmpty()){ request.setAttribute("cardno", cardno); } List<Logging> l = loggingService.findUserBypage(map); int count =loggingService.countLoggingByNo(cardno); if (count % page == 0) { request.setAttribute("pageNumber", count / page); } else { request.setAttribute("pageNumber", count / page + 1); } request.setAttribute("loggings", l); request.setAttribute("count", count); }else{ request.setAttribute("loggings", null); } request.setAttribute("cardno", cardno); request.setAttribute("name", name); return "lishi"; }
6
public void testStreamTokenizer() { System.out.println("\n*** testStreamTokenizer ***"); try { String string = "()"; MyStreamTokenizer st = CycListParser.makeStreamTokenizer(string); assertEquals(40, st.nextToken()); assertEquals(41, st.nextToken()); assertEquals(st.TT_EOF, st.nextToken()); string = "(1)"; st = CycListParser.makeStreamTokenizer(string); assertEquals(40, st.nextToken()); int token = st.nextToken(); assertEquals(st.TT_WORD, token); assertEquals("1", st.sval); assertEquals(41, st.nextToken()); assertEquals(st.TT_EOF, st.nextToken()); string = "(-10 -2 -1.0 -5.2E05)"; st = CycListParser.makeStreamTokenizer(string); assertEquals(40, st.nextToken()); token = st.nextToken(); assertEquals(st.TT_WORD, token); assertEquals("-10", st.sval); token = st.nextToken(); assertEquals(st.TT_WORD, token); assertEquals("-2", st.sval); token = st.nextToken(); assertEquals(st.TT_WORD, token); assertEquals("-1.0", st.sval); token = st.nextToken(); assertEquals(st.TT_WORD, token); assertEquals("-5.2E05", st.sval); assertEquals(41, st.nextToken()); assertEquals(st.TT_EOF, st.nextToken()); } catch (Exception e) { e.printStackTrace(); fail(); } System.out.println("*** testStreamTokenizer OK ***"); }
1
public void testGet() { YearMonthDay test = new YearMonthDay(); assertEquals(1970, test.get(DateTimeFieldType.year())); assertEquals(6, test.get(DateTimeFieldType.monthOfYear())); assertEquals(9, test.get(DateTimeFieldType.dayOfMonth())); try { test.get(null); fail(); } catch (IllegalArgumentException ex) {} try { test.get(DateTimeFieldType.hourOfDay()); fail(); } catch (IllegalArgumentException ex) {} }
2
public void method346(int i, int j) { i += anInt1442; j += anInt1443; int l = i + j * DrawingArea.width; int i1 = 0; int j1 = myHeight; int k1 = myWidth; int l1 = DrawingArea.width - k1; int i2 = 0; if(j < DrawingArea.topY) { int j2 = DrawingArea.topY - j; j1 -= j2; j = DrawingArea.topY; i1 += j2 * k1; l += j2 * DrawingArea.width; } if(j + j1 > DrawingArea.bottomY) j1 -= (j + j1) - DrawingArea.bottomY; if(i < DrawingArea.topX) { int k2 = DrawingArea.topX - i; k1 -= k2; i = DrawingArea.topX; i1 += k2; l += k2; i2 += k2; l1 += k2; } if(i + k1 > DrawingArea.bottomX) { int l2 = (i + k1) - DrawingArea.bottomX; k1 -= l2; i2 += l2; l1 += l2; } if(k1 <= 0 || j1 <= 0) { } else { method347(l, k1, j1, i2, i1, l1, myPixels, DrawingArea.pixels); } }
6
private void findMinMaxX(int y) { xMin = Integer.MAX_VALUE; xMax = Integer.MIN_VALUE; for (int i = rasterCount; --i >= 0;) { if (yRaster[i] == y) { int x = xRaster[i]; if (x < xMin) { xMin = x; zXMin = zRaster[i]; } if (x > xMax) { xMax = x; zXMax = zRaster[i]; } // if (y == 0) { // } } if (yRaster[i] == -y) { // 0 will run through here too int x = -xRaster[i]; if (x < xMin) { xMin = x; zXMin = -zRaster[i]; } if (x > xMax) { xMax = x; zXMax = -zRaster[i]; } } } }
7
@Override public boolean hasNext() { boolean hasNext = mIterator != null && mIterator.hasNext(); if (!hasNext) { mIterator = null; hasNext = mIndex < mRows.size(); } return hasNext; }
2
public static void main(String[] args) { int n = 200000; int result = 0; int iterations = 0; int counter = 0; boolean[] isPrime = new boolean[n]; Arrays.fill(isPrime, true); for (int i = 2; i * i < n; i++) { if (isPrime[i]) { for (int j = i * i; j < n; j += i) { iterations++; isPrime[j] = false; } } } for (int i = 2; i < n; i++) { if (isPrime[i]) { iterations++; if (counter == 10002) { result = i; break; } counter++; } } System.out.println("Result: " + result); System.out.println("Iterations: " + iterations); }
6
private void debugAddNewUnitToTile(final Game serverGame, Tile tile) { Specification spec = serverGame.getSpecification(); List<ChoiceItem<UnitType>> uts = new ArrayList<ChoiceItem<UnitType>>(); for (UnitType t : spec.getUnitTypeList()) { uts.add(new ChoiceItem<UnitType>(Messages.message(t.toString() + ".name"), t)); } UnitType unitChoice = gui.showChoiceDialog(null, "Select Unit Type", "Cancel", uts); if (unitChoice == null) return; Player player = freeColClient.getMyPlayer(); Player serverPlayer = serverGame.getFreeColGameObject(player.getId(), Player.class); Tile serverTile = serverGame.getFreeColGameObject(tile.getId(), Tile.class); Unit carrier = null; if (!serverTile.isLand() && !unitChoice.isNaval()) { for (Unit u : serverTile.getUnitList()) { if (u.isNaval() && u.getSpaceLeft() >= unitChoice.getSpaceTaken()) { carrier = u; break; } } } ServerUnit serverUnit = new ServerUnit(serverGame, (carrier != null) ? carrier : serverTile, serverPlayer, unitChoice); serverUnit.setMovesLeft(serverUnit.getInitialMovesLeft()); Game game = freeColClient.getGame(); Unit unit = new Unit(game, serverUnit.toXMLElement(DOMMessage.createNewDocument())); if (carrier == null) { tile.add(unit); } else { game.getFreeColGameObject(carrier.getId(), Unit.class).add(unit); } gui.setActiveUnit(unit); player.invalidateCanSeeTiles(); gui.refresh(); }
9
public void keyTyped(KeyEvent e) { if (stage != null) { stage.keyTyped(e); } }
1
public void setTransient(Registry rg) { registry = rg; inventory = null; if(itemType != null) { itemType = rg.getItemManager().getItemType(itemType.getName()); if(itemType.getName().equals("ScrapHammer")) { int x = 9; } if(item == null) { int level = 1; if(itemType.getType().equals("Weapon") || itemType.getType().equals("Armor")) { level = rg.getPlayerManager().getCurrentPlayer().getLevel(); } item = new Item(itemType, level); } item.setTransient(); } else { itemType = null; } if(item != null) { item.setTransient(); } }
6
private static <T extends Comparable<? super T>> void siftDown(T[] array, int start, int end) { int root = start; //While root has at least one child not past the end of the heap while (left_child(root) <= end) { //Find biggest child and swap up: //Start with left child int child = left_child(root); //Biggest so far int biggest = root; //If root is smaller than left child if (array[biggest].compareTo(array[child]) == -1) { biggest = child; } //If right child exists and is bigger than biggest so far if (child+1 <= end && array[biggest].compareTo(array[child+1]) == -1) { biggest = child + 1; } //Check if either of the children was bigger. if (biggest != root) { swap(array, root, biggest); root = biggest; } else { return; } } }
6
public JMenuBar createMenuBar() { menuBar = new JMenuBar(); JMenu file = new JMenu("File"); menuBar.add(file); JMenuItem newMenuItem = new JMenuItem( new AbstractAction("New") { @Override public void actionPerformed(ActionEvent actionEvent) { newFile(); } } ); JMenuItem openMenuItem = new JMenuItem( new AbstractAction("Open") { public void actionPerformed(ActionEvent e) { int returned = fileChooser.showOpenDialog(getFrame()); if (returned == JFileChooser.APPROVE_OPTION) { openFile(fileChooser.getSelectedFile()); } } } ); JMenuItem saveMenuItem = new JMenuItem( new AbstractAction("Save") { public void actionPerformed(ActionEvent e) { int returned = fileChooser.showSaveDialog(getFrame()); if (returned == JFileChooser.APPROVE_OPTION) { try { JTextArea textArea = (JTextArea) getCurrentlySelectedComponent(); BufferedWriter writer = new BufferedWriter(new FileWriter(fileChooser.getSelectedFile())); textArea.write(writer); writer.close(); } catch (IOException e1) { e1.printStackTrace(); } } } } ); JMenuItem closeFileMenuItem = new JMenuItem( new AbstractAction("Close") { @Override public void actionPerformed(ActionEvent e) { tabbedPane.remove(getCurrentTabComponent()); } } ); JMenuItem settingsMenuItem = new JMenuItem( new AbstractAction("Settings") { @Override public void actionPerformed(ActionEvent actionEvent) { new SettingsWindow(WindowConstants.DISPOSE_ON_CLOSE); } } ); JMenuItem quitMenuItem = new JMenuItem( new AbstractAction("Quit") { @Override public void actionPerformed(ActionEvent actionEvent) { Aluminum.getIDE().performShutdown(); } } ); file.add(newMenuItem); file.add(openMenuItem); file.add(saveMenuItem); file.add(closeFileMenuItem); file.addSeparator(); file.add(settingsMenuItem); file.addSeparator(); file.add(quitMenuItem); JMenu edit = new JMenu("Edit"); menuBar.add(edit); JMenuItem cutMenuItem = new JMenuItem( new AbstractAction("Cut") { @Override public void actionPerformed(ActionEvent actionEvent) { if (isEditorActive()) { ((JTextArea) getCurrentlySelectedComponent()).cut(); } } } ); JMenuItem copyMenuItem = new JMenuItem( new AbstractAction("Copy") { @Override public void actionPerformed(ActionEvent actionEvent) { if (isEditorActive()) { ((JTextArea) getCurrentlySelectedComponent()).copy(); } } } ); JMenuItem pasteMenuItem = new JMenuItem( new AbstractAction("Paste") { @Override public void actionPerformed(ActionEvent e) { if (isEditorActive()) { ((JTextArea) getCurrentlySelectedComponent()).paste(); } } } ); JMenuItem selectAllMenuItem = new JMenuItem( new AbstractAction("Select All") { @Override public void actionPerformed(ActionEvent e) { if (isEditorActive()) { ((JTextArea) getCurrentlySelectedComponent()).selectAll(); } } } ); edit.add(cutMenuItem); edit.add(copyMenuItem); edit.add(pasteMenuItem); edit.add(selectAllMenuItem); return menuBar; }
7
public static void nodesToString(Node[][] nodes,BufferedWriter out) throws IOException{ String s=""+NEWLINE; Node node=findConnectedNode(nodes); Node node2=node; s+=node.symbol.value+","+node.constraint.value+NEWLINE; out.write(s); s=""; do{ node2=node2.right; if (node2.connected) s+="\t"+node2.constraint.value; } while(!node2.equals(node)); s+=NEWLINE; out.write(s); s=""; do{ node2=node2.down; if (node2.connected) s+="\t"+node2.symbol.value; } while(!node2.equals(node)); s+=NEWLINE; out.write(s); s=""; do{ node2=node2.right; Node node3=node2; do{ node3=node3.down; s+="\t"+node3.symbol.value; } while(!node3.equals(node2)); s+=NEWLINE; out.write(s); s=""; } while(!node2.equals(node)); s+=NEWLINE; out.write(s); out.flush(); }
6
@Override public int getHeight() { return height; }
0
public void setupGUI() { if(count > 2 && count <=4) frogx=6; if(count>4) frogx=7; // // run[1]=new ImageIcon("NERDY_BIKER.PNG").getImage(); run[2]=new ImageIcon("NERDY_BIKER.PNG").getImage(); run[3]=new ImageIcon("NERDY_BIKER.PNG").getImage(); run[4]=new ImageIcon("NERDY_BIKER.PNG").getImage(); run[5]=new ImageIcon("bulbasaur.PNG").getImage(); run[6]=new ImageIcon("ivysaur.PNG").getImage(); run[7]=new ImageIcon("venusaur.PNG").getImage(); JFrame jf = new JFrame("Don't Die"); Container cp = jf.getContentPane(); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.setResizable(false); jf.setSize(1000, 710); jf.setLocationRelativeTo(null); jf.setLayout(new GridLayout(1,1)); cp.add(this); jf.setVisible(true); jf.addKeyListener(this); }
3
private boolean _jspx_meth_c_forEach_1(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // c:forEach org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_forEach_1 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _jspx_tagPool_c_forEach_var_items.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class); _jspx_th_c_forEach_1.setPageContext(_jspx_page_context); _jspx_th_c_forEach_1.setParent(null); _jspx_th_c_forEach_1.setVar("book"); _jspx_th_c_forEach_1.setItems((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${booksPage}", java.lang.Object.class, (PageContext)_jspx_page_context, null)); int[] _jspx_push_body_count_c_forEach_1 = new int[] { 0 }; try { int _jspx_eval_c_forEach_1 = _jspx_th_c_forEach_1.doStartTag(); if (_jspx_eval_c_forEach_1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("\n"); out.write(" <tr>\n"); out.write(" <th>"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${book.book_ID}", java.lang.String.class, (PageContext)_jspx_page_context, null)); out.write("</th>\n"); out.write(" <th>"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${book.book_Name}", java.lang.String.class, (PageContext)_jspx_page_context, null)); out.write("</th>\n"); out.write(" <th>"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${book.book_Author}", java.lang.String.class, (PageContext)_jspx_page_context, null)); out.write("</th>\n"); out.write(" <th>"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${book.book_Publisher}", java.lang.String.class, (PageContext)_jspx_page_context, null)); out.write("</th>\n"); out.write(" <th>"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${book.book_Price}", java.lang.String.class, (PageContext)_jspx_page_context, null)); out.write("</th>\n"); out.write(" <th><input type=\"button\" name=\"button\" value=\"ShowDetail\" onclick=\"window.location.href='ShowBookDetail.view?bookID="); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${book.book_ID}", java.lang.String.class, (PageContext)_jspx_page_context, null)); out.write("'\"/></th>\n"); out.write(" </tr>\n"); out.write(" "); int evalDoAfterBody = _jspx_th_c_forEach_1.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_forEach_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { return true; } } catch (Throwable _jspx_exception) { while (_jspx_push_body_count_c_forEach_1[0]-- > 0) out = _jspx_page_context.popBody(); _jspx_th_c_forEach_1.doCatch(_jspx_exception); } finally { _jspx_th_c_forEach_1.doFinally(); _jspx_tagPool_c_forEach_var_items.reuse(_jspx_th_c_forEach_1); } return false; }
6
public void tick(){ if(blocksForeground != null){ for(int x = 0; x < blocksForeground.length; x++){ for(int y = 0; y < blocksForeground[x].length; y++){ if(blocksForeground[x][y] != null){ blocksForeground[x][y].tick(); } } } } if(blocksBackground != null){ for(int x = 0; x < blocksBackground.length; x++){ for(int y = 0; y < blocksBackground[x].length; y++){ if(blocksBackground[x][y] != null){ blocksBackground[x][y].tick(); } } } } for(int i = 0; i < entities.size(); i++){ entities.get(i).tick(); } }
9
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
@Override public void add(E e){ int h = Math.abs(e.hashCode()) % table.length; Node<E> n = table[h]; while(n != null && !n.equals(e)){ n = n.next; } if(n == null){ // S'il n'existe pas, on l'ajoute table[h] = new Node<E>(table[h], e); size++; } // sinon, on ne fait rien puisque chaque élément est unique // Si nécessaire, rehachage! if((size/(double)table.length < 0.5 || size/(double)table.length > 1) && size > 10) rehachage(); }
6
public static HashMap<String, Double> sortByValue(HashMap<String, Double> map) { List<Map.Entry<String, Double>> list = new LinkedList<Map.Entry<String, Double>>(map.entrySet()); Collections.sort(list, new Comparator<Map.Entry<String, Double>>() { public int compare(Map.Entry<String, Double> m1, Map.Entry<String, Double> m2) { int out = 0; if (m2.getValue() < m1.getValue()){ out = -1; } if (m2.getValue() > m1.getValue()){ out = 1; } if (m2.getValue() == m1.getValue()){ out = 0; } return out; } }); HashMap<String, Double> result = new LinkedHashMap<String, Double>(); for (Map.Entry<String, Double> entry : list) { result.put(entry.getKey(), entry.getValue()); } return result; }
4
public ErrorSymbol(String message) { super(message); }
0
@Override public boolean branch() { Player player = ctx.players.local(); if (ctx.game.clientState() != Constants.GAME_MAP_LOADED) { return false; } if (player == null || !script.options.getAreaSmall().contains(player)) { return false; } if (!ctx.backpack.isFull()) { return false; } if (ctx.skillingInterface.opened() && ctx.skillingInterface.getAction().equals("Smith")) { return true; } if (!script.options.isSmithing) { //ctx.log.info("SmithTrack branch not smithing"); return true; } if (AnimationMonitor.timeSinceAnimation(LogArtisanWorkshop.ANIMATION_SMITHING) > animationTimelimit) { animationTimelimit = Random.nextInt(2000, 4000); if (Random.nextBoolean()) { animationTimelimit *= 2; } return true; } return false; }
9
public String getType () { switch (getAttributes () & 0x03) { case 0: return "control"; case 1: return "iso"; case 2: return "bulk"; case 3: return "interrupt"; } // "can't happen" return null; }
4
public boolean equals(Board b) { boolean val = true; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (this.board[i][j] != b.get(i, j)) return false; } } return val; }
3
private void processPolyLine(RdpPacket_Localised data, PolyLineOrder polyline, int present, boolean delta) { if ((present & 0x01) != 0) polyline.setX(setCoordinate(data, polyline.getX(), delta)); if ((present & 0x02) != 0) polyline.setY(setCoordinate(data, polyline.getY(), delta)); if ((present & 0x04) != 0) polyline.setOpcode(data.get8()); if ((present & 0x10) != 0) polyline.setForegroundColor(setColor(data)); if ((present & 0x20) != 0) polyline.setLines(data.get8()); if ((present & 0x40) != 0) { int datasize = data.get8(); polyline.setDataSize(datasize); byte[] databytes = new byte[datasize]; for (int i = 0; i < datasize; i++) databytes[i] = (byte) data.get8(); polyline.setData(databytes); } // //logger.info("polyline delta="+delta); // if(//logger.isInfoEnabled()) //logger.info("Line from // ("+line.getStartX()+","+line.getStartY()+") to // ("+line.getEndX()+","+line.getEndY()+")"); // now draw the line surface.drawPolyLineOrder(polyline); }
7
public FSList getAnnotations() { // try reading it from disk String readpath = "/springfield/lisa/data/linkedtv/"+mediaResourceId+"/annotations.xml"; System.out.println("READPATH="+readpath); String body = readFile(readpath); if (body==null) { Response response = HttpHelper.sendRequest("GET", MAGGIE+"&id="+mediaResourceId+"&annotations&curated&renew"); if (response.getStatusCode() != 200) { System.out.println("What? "+response.getStatusCode()); return new FSList(); } else { body = response.toString(); } } else { System.out.println("READING FROM LISA DISK CACHE "+readpath); } //Response response = HttpHelper.sendRequest("GET", MAGGIE+"&id="+mediaResourceId+"&annotations&curated&renew"); this.annotations = new FSList(); try { Document doc = DocumentHelper.parseText(body); List<Node> nodes = doc.selectNodes("//annotations/*"); String presentationUri = doc.selectSingleNode("properties/presentation") == null ? "" : doc.selectSingleNode("properties/presentation").getText(); presentationUri += "annotations"; FSList annotations = new FSList(presentationUri); for (Node annotation : nodes) { Element a = (Element) annotation; FsNode result = new FsNode("unknown","unknown"); result.setName(a.getName()); result.setId(a.attribute("id").getText()); result.setPath(presentationId+"/"+result.getName()+"/"+result.getId()); result.setImageBaseUri(stillsUri); List<Node> properties = a.selectNodes("properties/*"); for (Node property : properties) { //System.out.println("DANIEL2: "+property.getName()+"="+property.getText()); result.setProperty(property.getName(), property.getText()); if (property.getName().equals("locator")) { loadEntityFromProxy(property.getName(),property.getText()); } } annotations.addNode(result); } this.annotations = annotations; return annotations; } catch (DocumentException e) { System.out.println("What? "+e.getMessage()); return new FSList(); } }
7
public void move(long time) { if (state == DeliverState.delivered) return; // upravime podla rychlosti modelu double speed = player.getSpeedBalance() * player.getSendSpeed() * time * 0.001 * force; position += speed; // paksametle okolo odosielania a nevyskocenia z hrany if (position >= 1.0) { position = 1.0; if (player.state == RunState.running && (prevM == null || prevM.state == DeliverState.inbox)) state = DeliverState.inbox; } if (position <= 0.0) position = 0.0; }
6
private long getOffset(Protocol.Section info, long until) { long sizeOfFirst = info.length; long timeDeltaFirst = info.endTime - info.startTime; long timeToSkipFirst = until - info.startTime; System.out.println(timeToSkipFirst + " " + timeDeltaFirst); // long exactStartingPlace = (timeToSkip * sizeOfFirst)/ // timeDelta; double startingPlace = ((double) timeToSkipFirst) / ((double) timeDeltaFirst) * ((double) sizeOfFirst); long offset = (long) startingPlace; if (offset % 2 != 0) offset ++; if (offset < 0) offset = 0; if (offset > info.length) offset = info.length; return offset; }
3
private static Map<Integer, Double> getRankedTagList(BookmarkReader reader, Map<Integer, Double> userMap, double userDenomVal, Map<Integer, Double> resMap, double resDenomVal, boolean sorting, boolean smoothing, boolean topicCreation) { Map<Integer, Double> resultMap = new LinkedHashMap<Integer, Double>(); if (userMap != null) { for (Map.Entry<Integer, Double> entry : userMap.entrySet()) { resultMap.put(entry.getKey(), entry.getValue().doubleValue()); } } if (resMap != null) { for (Map.Entry<Integer, Double> entry : resMap.entrySet()) { double resVal = entry.getValue().doubleValue(); Double val = resultMap.get(entry.getKey()); resultMap.put(entry.getKey(), val == null ? resVal : val.doubleValue() + resVal); } } if (sorting) { Map<Integer, Double> sortedResultMap = new TreeMap<Integer, Double>(new DoubleMapComparator(resultMap)); sortedResultMap.putAll(resultMap); Map<Integer, Double> returnMap = new LinkedHashMap<Integer, Double>(MAX_RECOMMENDATIONS); int i = 0; for (Map.Entry<Integer, Double> entry : sortedResultMap.entrySet()) { if (i++ < MAX_RECOMMENDATIONS) { returnMap.put(entry.getKey(), entry.getValue()); } else { break; } } return returnMap; } return resultMap; /* double size = (double)reader.getTagAssignmentsCount(); double tagSize = (double)reader.getTags().size(); Map<Integer, Double> resultMap = new LinkedHashMap<Integer, Double>(); for (int i = 0; i < tagSize; i++) { double pt = (double)reader.getTagCounts().get(i) / size; Double userVal = 0.0; if (userMap != null && userMap.containsKey(i)) { userVal = userMap.get(i);//Math.exp(userMap.get(i)) / userDenomVal; } Double resVal = 0.0; if (resMap != null && resMap.containsKey(i)) { resVal = resMap.get(i);//Math.exp(resMap.get(i)) / resDenomVal; } if (userVal > 0.0 || resVal > 0.0) { // TODO if (smoothing) { resultMap.put(i, Utilities.getSmoothedTagValue(userVal, userDenomVal, resVal, resDenomVal, pt)); } else { resultMap.put(i, userVal + resVal); } } } if (sorting) { Map<Integer, Double> sortedResultMap = new TreeMap<Integer, Double>(new DoubleMapComparator(resultMap)); sortedResultMap.putAll(resultMap); if (topicCreation) { return sortedResultMap; } else { // otherwise filter Map<Integer, Double> returnMap = new LinkedHashMap<Integer, Double>(MAX_RECOMMENDATIONS); int i = 0; for (Map.Entry<Integer, Double> entry : sortedResultMap.entrySet()) { if (i++ < MAX_RECOMMENDATIONS) { returnMap.put(entry.getKey(), entry.getValue()); } else { break; } } return returnMap; } } return resultMap; */ }
8
public int characterAt(int at) throws JSONException { int c = get(at); if ((c & 0x80) == 0) { return c; } int character; int c1 = get(at + 1); if ((c1 & 0x80) == 0) { character = ((c & 0x7F) << 7) | c1; if (character > 0x7F) { return character; } } else { int c2 = get(at + 2); character = ((c & 0x7F) << 14) | ((c1 & 0x7F) << 7) | c2; if ((c2 & 0x80) == 0 && character > 0x3FFF && character <= 0x10FFFF && (character < 0xD800 || character > 0xDFFF)) { return character; } } throw new JSONException("Bad character at " + at); }
8
public void joinTeam(String userName, String teamName, String matchName){ try { cs = con.prepareCall("{call joinTeam(?,?,?)}"); cs.setString(1, userName); cs.setString(2, teamName); cs.setString(3, matchName); cs.execute(); } catch (SQLException e) { e.printStackTrace(); } }
1
public void onEnable() { // Create any required directories getDataFolder().mkdirs(); // Create/load configuration and customizable messages loadConfiguration(); // Disable plugin if auto-disable is set to true and server is running in online-mode if (getConfig().getBoolean("main.auto-disable") && getServer().getOnlineMode()) { xAuthLog.info("Auto-disabling, server is running in online-mode"); getServer().getPluginManager().disablePlugin(this); return; } if (getConfig().getBoolean("main.check-for-updates")) { Updater updater = new Updater(getDescription().getVersion()); if (updater.isUpdateAvailable()) updater.printMessage(); } File h2File = new File("lib", "h2-" + h2Version + ".jar"); if (!h2File.exists() && getConfig().getBoolean("main.download-library") && !getConfig().getBoolean("mysql.enabled")) { xAuthLog.info("-------------------------------"); xAuthLog.info("Downloading required H2 library.."); downloadLib(h2File); xAuthLog.info("Download complete."); xAuthLog.info(""); xAuthLog.info("Reload the server to enable xAuth."); xAuthLog.info("-------------------------------"); getServer().getPluginManager().disablePlugin(this); return; } // Initialize permissions support //xPermissions.init(); // Initialize database controller dbCtrl = new DatabaseController(this); // Test connection to database if (!dbCtrl.isConnectable()) { xAuthLog.severe("Failed to establish " + dbCtrl.getDBMS() + " database connection!"); // disable (for now, may change in the future) getServer().getPluginManager().disablePlugin(this); return; } xAuthLog.info("Successfully established connection to " + dbCtrl.getDBMS() + " database"); dbCtrl.runUpdater(); // Initialize ALL THE CLASSES plyrMngr = new PlayerManager(this); plyrDtHndlr = new PlayerDataHandler(this); pwdHndlr = new PasswordHandler(this); locMngr = new LocationManager(this); strkMngr = new StrikeManager(this); Player[] players = getServer().getOnlinePlayers(); if (players.length > 0) plyrMngr.handleReload(players); // Initialize listeners new xAuthPlayerListener(this); new xAuthBlockListener(this); new xAuthEntityListener(this); // Register commands getCommand("register").setExecutor(new RegisterCommand(this)); getCommand("login").setExecutor(new LoginCommand(this)); getCommand("logout").setExecutor(new LogoutCommand(this)); getCommand("changepw").setExecutor(new ChangePwdCommand(this)); getCommand("xauth").setExecutor(new xAuthCommand(this)); xAuthLog.info(String.format("v%s Enabled!", getDescription().getVersion())); lol(); }
9
public void merge(int[] array, int p, int q, int r) { int n1 = q - p + 1; int n2 = r - q; int[] leftA = new int[n1]; int[] rightA = new int[n2]; for (int i = 0; i < n1; i++) { leftA[i] = array[p + i]; } for (int j = 0; j < n2; j++) { rightA[j] = array[q + j + 1]; } int i = 0; int j = 0; for (int k = p; k < r + 1; k++) { //copy array if one of side branch is drained if (j > n2 - 1) { array[k] = leftA[i]; i++; } else if (i > n1 - 1) { array[k] = rightA[j]; j++; } else if (leftA[i] <= rightA[j]) { array[k] = leftA[i]; i++; } else if (leftA[i] > rightA[j]) { array[k] = rightA[j]; j++; } } }
7
public Grille (EnvironnementAbs env){ super(env); Border blackline = BorderFactory.createLineBorder(Color.black,1); for(int i= 0 ; i < env.taille_envi;i++){ for(int j= 0 ; j < env.taille_envi;j++){ agent[i][j].setBorder(blackline); } } pan.setBorder(blackline); }
2
public static void main(String args[]) { // Command line arguments if(args.length !=5) { System.out.println("Usage: <inputDataFileName> <NN> <searchFileName> <MM> <DEBUG_VALUE> "); System.exit(0); } try{ String readfile = args[0]; int NNread = Integer.parseInt(args[1]); String searchfile = args[2]; int MMsearch = Integer.parseInt(args[3]); int debug = Integer.parseInt(args[4]); if(NNread<1 || NNread>15){ System.out.println(" Read threads should be between 1 and 15"); System.exit(0); } else if(MMsearch<1 || MMsearch>15){ System.out.println("Search threads should be between 1 and 15"); System.exit(0); } else if(debug<0 || debug>4){ System.out.println("Debug value should be 1 to 4"); System.exit(0); } logger.setDebugVal(debug); inf_populateWorker pop = new populateWorker(readfile, NNread); pop.generateThreads(); inf_resultStore res = new resultStore(); inf_searchWorker search = new searchWorker(searchfile, MMsearch); search.generateSearchThreads(); res.displayData(); } catch(ArrayIndexOutOfBoundsException e){ System.out.println("Invalid Number of Arguments !!"); } catch(NumberFormatException e){ System.out.println("Number Format Exception !! Check your arguments"); } }
9
@Override public boolean equals(Object other) { if (other == null || !(other instanceof MACByteArrayWrapper) || ((MACByteArrayWrapper)other).mac.length != this.mac.length) return false; for (int i = 0; i < this.mac.length; i++) if (((MACByteArrayWrapper)other).mac[i] != this.mac[i]) return false; return true; }
5
public List<Long> sortNodes(){ List<Long> result = new ArrayList<Long>(); for (Long l : nodos) result.add(l); Collections.sort(result); return result; }
1
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(DisAPPMap.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(DisAPPMap.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(DisAPPMap.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(DisAPPMap.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 DisAPPMap().setVisible(true); } }); }
6
public String greetServer(String input) throws IllegalArgumentException { // Verify that the input is valid. if (!FieldVerifier.isValidName(input)) { // If the input is not valid, throw an IllegalArgumentException back to // the client. throw new IllegalArgumentException( "Name must be at least 4 characters long"); } String serverInfo = getServletContext().getServerInfo(); String userAgent = getThreadLocalRequest().getHeader("User-Agent"); // Escape data from the client to avoid cross-site script vulnerabilities. input = escapeHtml(input); userAgent = escapeHtml(userAgent); return "Hello, " + input + "!<br><br>I am running " + serverInfo + ".<br><br>It looks like you are using:<br>" + userAgent; }
1
@Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof DieselLocomotive)) return false; DieselLocomotive other = (DieselLocomotive) obj; if (tankVolume != other.tankVolume) return false; return true; }
4
public void update() { move(); if(walking) animSprite.update(); else animSprite.setFrame(0); if (ya < 0){ animSprite = up; dir = Direction.UP; } else if (ya > 0){ animSprite = down; dir = Direction.DOWN; } if (xa < 0){ animSprite = left; dir = Direction.LEFT; } else if (xa > 0){ animSprite = right; dir = Direction.RIGHT; } }
5
public boolean hitTank(Tank t){ if(this.isLive&& t.isLive() && this.getRect().intersects(t.getRect())&& (this.isMyMissile != t.isMytank())){ if(t.isMytank()){ t.setBlood(t.getBlood() - 20); if(t.getBlood() <= 0){ t.setLive(false); } }else t.setLive(false); this.setLive(false); tc.explosions.add(new Explosion(x,y,this.tc)); return true; } return false; }
6
public Object nextValue() throws JSONException { char c = this.nextClean(); String string; switch (c) { case '"': case '\'': return this.nextString(c); case '{': this.back(); return new JSONObject(this); case '[': this.back(); return new JSONArray(this); } /* * Handle unquoted text. This could be the values true, false, or * null, or it can be a number. An implementation (such as this one) * is allowed to also accept non-standard forms. * * Accumulate characters until we reach the end of the text or a * formatting character. */ StringBuffer sb = new StringBuffer(); while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { sb.append(c); c = this.next(); } this.back(); string = sb.toString().trim(); if ("".equals(string)) { throw this.syntaxError("Missing value"); } return JSONObject.stringToValue(string); }
7
public static boolean isInputPressed(String command) { int[] checked = inputs.get(command); if (checked == null) { return false; } for (int i = 0; i < checked.length; i++) { if (container.getInput().isKeyPressed(checked[i])) { return true; } else if (checked[i] == Input.MOUSE_LEFT_BUTTON || checked[i] == Input.MOUSE_RIGHT_BUTTON) { if (container.getInput().isMousePressed(checked[i])) { return true; } } } return false; }
6
@Override public int posicionFichaY(int nivel) { return nivel == 1 ? 260 : nivel == 2 ? 233 : nivel == 3 ? 206 : nivel == 4 ? 179 : nivel == 5 ? 152 : nivel == 6 ? 125 : nivel == 7 ? 98 : nivel == 8 ? 71 : 0; }
8
private void insertTeam() { TeamBO teamBO = ServiceLocator.getBean(TeamBO.class); CountryBO countryBO = ServiceLocator.getBean(CountryBO.class); BufferedImage imBuff = null; InputStream is = InsertImageTest.class.getResourceAsStream("/flags/mexico_fmf.png"); try { imBuff = ImageIO.read(is); } catch (IOException e) { e.printStackTrace(); } if (imBuff != null) { Country country = (Country) countryBO.findByIdentifier(9); Team team = new Team("mexico", "El tri", imBuff, country, 1929, 0, ""); teamBO.insertRecord(team); } }
2
public static ListNode reverseKGroup(ListNode head, int k) { ListNode H = new ListNode(-1); H.next = head; if(head == null) { return head; } if(head.next == null) { return head; } if(k < 2) { return head; } int count = 0; ListNode startNode = H; ListNode fastNode = head; ListNode slowNode = head; ListNode currentNode = head; while(currentNode != null) { count++; if(count == k) { startNode.next = currentNode; startNode = slowNode; fastNode = fastNode.next; slowNode.next = currentNode.next; while(fastNode != currentNode) { ListNode tmp = fastNode.next; fastNode.next = slowNode; slowNode = fastNode; fastNode = tmp; } fastNode = currentNode.next; currentNode.next = slowNode; slowNode = fastNode; currentNode = fastNode; count = 0; }else { currentNode = currentNode.next; } } return H.next; }
6