method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
e623db32-d581-4107-af3b-62b273618152
4
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpRequest) { servingFromCache = false; HttpRequest req = (HttpRequest) msg; ReferenceCountUtil.retain(req); requestsQueue.add(req); HttpResponse response = cachedResponse(req); if (response != null) { logger.info("Serving response from cache for uri: " + req.getUri()); servingFromCache = true; ctx.channel().writeAndFlush(response); return; } } if (servingFromCache && msg instanceof HttpContent) { return; } ctx.fireChannelRead(msg); }
8f035759-dc1e-4ead-96ef-7192e2908e94
7
@Override public void update(final Observable the_arg0, final Object the_arg1) { if (my_level > my_last_speed_up) { final int time = my_timer.getDelay(); my_timer.setDelay((int) (time * SPEED_RATIO)); my_last_speed_up = my_level; } if (the_arg1 instanceof Integer) { final int lines = (Integer) the_arg1; my_lines += lines; if (lines == 1) { my_score += SINGLE_LINE; } else if (lines == 2) { my_score += DOUBLE_LINE; } else if (lines == TRIPLE) { my_score += TRIPLE_LINE; } else if (lines == QUADRUPLE) { my_score += TETRIS; } } if (the_arg1 instanceof Boolean) { my_score += BASE_SCORE; } }
329a8eea-6ff8-48cc-807c-c509656dddf2
1
public static void falsepositive(DMatrix[] pointset){ for(int i = 0; i < pointset.length; i++){ System.out.println("NN法" + i + "番目クラス偽陽性"); } }
5acd362f-92c0-4fd9-9639-7377b54028ca
6
public void unloadLinked(Game game) { ready = false; if (!droppable) { onUse(game); return; } Pickup pick; try { pick = (Pickup) link.newInstance(); } catch (InstantiationException | IllegalAccessException ex) { return; } if (pick != null) { List<Floor> possible = game.getNeighbours(game.getPlayer().x(), game.getPlayer().y()); while (true) { int len = possible.size(); if (len == 0) { add(1); return; } int pos = new Random().nextInt(len); if (!possible.get(pos).set(pick)) { possible.remove(pos); } else { break; } } game.addLiving(pick); game.getPlayer().addStatus("You dropped", name()); } }
ce334cd9-b7a1-4c8d-b587-ec97ceb92ec9
2
public static String noSpaces(String str) { String lines[] = str.split("\n"); StringBuilder sb = new StringBuilder(); for (String line : lines) sb.append(line.trim().replaceAll("\\s", "") + "\n"); if (lines.length == 1) sb.deleteCharAt(sb.length() - 1); return sb.toString(); }
4ad29ff2-0319-4fdd-9057-33d08225b77a
3
@Override public void keyPressed(int key, char character, GUIComponent component) { switch (key) { case (Keyboard.KEY_ESCAPE) : this.deactivate(); break; case (Keyboard.KEY_RIGHT) : nextSlide(); break; case (Keyboard.KEY_LEFT) : previousSlide(); break; } }
6512bda3-e212-4a32-a4c4-bec43ef47c9c
5
public static double computeAP(int[] positions, int R){ int d = positions.length; double sum1 = 0; int sum2; for(int i = 0; i < d; i++){ if(positions[i] == 1){ sum2 = 0; for(int j = 0; j < i+1; j++){ if(positions[j] == 1){ sum2 += 1; } } sum1 += (double)sum2/(i+1); } } return sum1 == 0 ? 0 : sum1 / R; }
516cb16d-9350-4964-8c04-a5830a242293
4
private static Camera restorecam() { Class<? extends Camera> ct = camtypes.get(Utils.getpref("defcam", "border")); if (ct == null) return (new BorderCam()); String[] args = (String[]) Utils.deserialize(Utils.getprefb("camargs", null)); if (args == null) args = new String[0]; try { return (makecam(ct, args)); } catch (ClassNotFoundException e) { return (new BorderCam()); } }
9e599c36-5f41-4a6d-9b43-d8a9c929903f
4
static void decodeHorizontal(BitStream in, BitStream out, G4State s, Code code) throws IOException { int rl = 0; do { rl = s.white ? findWhite(in, code) : findBlack(in, code); if (rl >= 0) { if (rl < 64) { addRun(rl + s.longrun, s, out); s.white = !s.white; s.longrun = 0; } else { s.longrun += rl; } } else { addRun(rl, s, out); } } while (rl >= 64); out.close(); }
49806d56-a6f3-4749-813e-c53e6075dc1d
7
public void setup(MasterFrame parent, int myNum){ this.parent = parent; this.myNum = myNum; try { Field field = Color.class.getField(color); myColor = (Color) field.get(null); } catch (Exception e) { e.printStackTrace(); } if(myColor == null) System.out.println("color: " + color); myPanel = new JPanel(); panelName = new JLabel(name + "(type: " + myNum + ")"); panelName.setBounds(20 + (200 * myNum), 580, 200, 50); jComps = new Vector<JComponent>(); jNames = new Vector<JLabel>(); for(int i = 0; i < xmlComps.size(); i++){ XMLComponent xmlc = xmlComps.get(i); if(xmlc.type == 0){ JTextField tempTextField = new JTextField(); tempTextField.setBounds(150, 30 * i, 25, 20); jComps.add(tempTextField); JLabel tempLabel = new JLabel(xmlc.name); tempLabel.setBounds(10, 30 * i, 130, 20); jNames.add(tempLabel); } if(xmlc.type == 1){ JCheckBox tempCheckBox = new JCheckBox(); tempCheckBox.setBounds(150, 30 * i, 25, 20); jComps.add(tempCheckBox); JLabel tempLabel = new JLabel(xmlc.name); tempLabel.setBounds(10, 30 * i, 130, 20); jNames.add(tempLabel); } } activeBtn = new JButton("Activate"); activeBtn.setBounds(10, (jComps.size() * 30), 170, 20); activeBtn.addActionListener(new ActionListener(){ @Override public void actionPerformed (ActionEvent event) { activate(); } }); //Container content = myFrame.getContentPane(); myPanel.setVisible(true); for(JLabel jl : jNames){ myPanel.add(jl); } for(JComponent jc : jComps){ myPanel.add(jc); } myPanel.add(activeBtn); myPanel.setBounds(10 + (200 * myNum), 630, 200, (jComps.size() * 30) + 60); //myPanel.setLocationRelativeTo(null); myPanel.setLayout(null); parent.getContent().add(myPanel); parent.getContent().add(panelName); parent.repaint(); }
2dd35dcb-e360-4db8-b884-6d2b096f758e
7
public static void main(String[] args) { File testFile = new File(System.getProperty("user.home") + File.separator + "Desktop" + File.separator + "newFile.txt"); if (!testFile.exists()) { try { testFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } PrintWriter writer = null; try { writer = new PrintWriter(new BufferedWriter(new FileWriter(testFile, true))); writer.println("Drew Hoener: Hello: There"); } catch (IOException e) { e.printStackTrace(); } finally { if (writer != null) { writer.close(); } } BufferedReader reader; try { reader = new BufferedReader(new FileReader(testFile)); String s; while ((s = reader.readLine()) != null) { for (String s1 : s.split(":")) System.out.println(s1); } } catch (IOException e) { } }
56e0c2d7-fca7-46e8-95e6-6f900fb92a45
3
public boolean waitEncryptedDeck(RSAService rsaService, final PublicKey pubKey) throws IOException, InterruptedException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException { Notification not = new Notification(); encryptedDeck = null; final Subscription encSub = elvin.subscribe(NOT_TYPE + " == '" + ENCRYPT_DECK_REQUEST + "' && " + GAME_ID + " == '" + gameHost.getID() + "' && " + REQ_USER + " == '" + user.getID() + "'"); encSub.addListener(new NotificationListener() { public void notificationReceived(NotificationEvent e) { byte[] tmpBytes = (byte[]) e.notification.get(ENCRYPTED_DECK); try { encryptedDeck = (EncryptedDeck) Passable .readObject(tmpBytes); if (!sigServ.validateSignature(encryptedDeck, pubKey)) { // sig failed! callCheat(SIGNATURE_FAILED); encryptedDeck = null; } } catch (Exception e1) { e1.printStackTrace(); } // notify the waiting thread that a message has arrived synchronized (encSub) { encSub.notify(); } } }); synchronized (encSub) { // wait until received reply encSub.wait(); } // construct the notification to send if (encryptedDeck == null) { encSub.remove(); return false; } // encrypt and shuffle the deck EncryptedDeck encDeck = rsaService.encryptEncDeck(encryptedDeck); encDeck.shuffleDeck(); // sign the deck sigServ.createSignature(encDeck); not.set(NOT_TYPE, ENCRYPT_DECK_REPLY); not.set(GAME_ID, gameHost.getID()); not.set(REQ_USER, user.getID()); not.set(ENCRYPTED_DECK, encDeck.writeObject()); elvin.send(not); encSub.remove(); return true; }
e0689735-589d-463e-8e61-44c82f6b3451
4
static void dedupProcess() throws IOException{ int memoryPolicy = 5; resultRecord.println("Total " + storageLoad() + " entries added into the index"); File[] incomingFile = null; incomingFile = new File(outputpath).listFiles(); int cacheSizeControl = 0; // int sampleNum = (int) ((Math.log(2)+Math.log(10000))/2/0.0001/Math.pow(expectRaio,2)); resultRecord.println("Pick out " + sampleNumPerSeg + " samples per segment for estimation"); System.out.println("Pick out " + sampleNumPerSeg + " samples persegment for estimation"); // int sampleNumPerSeg = sampleNum/incomingFile.length; // samples per segment for(int i = 1; i <=incomingFile.length; i++){ sampleTotal+=sampleNumPerSeg; File file = null; file = new File(outputpath+"/Segment_"+ i); hashRecord = new String[segsize*1024/chunksize]; // System.out.println("The seg size is: "+ segsize); // System.out.println("The chunk size is: "+ chunksize); // System.out.println("The hashrecord array size is: "+ (segsize*1024/chunksize)); uniqueRecord = new int[segsize*1024/chunksize]; sampledRecord = new int[segsize*1024/chunksize]; containerTrack = new long[segsize*1024/chunksize]; cacheSizeControl++; if(cacheSizeControl==memoryPolicy ){ //cache size control containerRecord.clear(); cache.clear(); cacheSizeControl=0; } dedupProcess_v2 dP = new dedupProcess_v2(index,indexSize, M,cache,chunksize, segsize, hashRecord, uniqueRecord,sampledRecord,containerTrack,storageFileFolder,bf, bloomfilterRecord, file,containerRecord,estimateBase,sampleNumPerSeg,segAmount,consecutiveDedup,sampleRate); dP.dedup(); total += dP.getTotal(); dup += dP.getDup(); /* * periodically output statistics (every 'segAmount' segments, we do one time's dedup) */ if(consecutiveDedup=true && i%segAmount == 0){ nodeQue.add(new Node(total,dup,(double)1/sampleRate,index.size(),(double)dup/total,(double)dup/(index.size()),sampleTotal)); resultRecord.println(); resultRecord.println("The culmulative segments are: " + i + "\nCurrent data amount is: "+total+ "\nThe duplicates are: "+dup+ "\nThe current index size is: " + index.size()+ "\nThe deduplication rate is : " + (double)dup/total*100 +"%"+ "\nThe estimated dedup rate is: " + getEstimateRatio()*100 +" %"); resultRecord.println(); resultRecord.println("####The dedup efficiency is: " + (double)dup/(index.size())+" dup/index entry slot"); } totalChunkNum += dP.getTotalChunkNum(); dP.storageWrite(); // System.out.println("The current cache size is: " + dP.getCacheSize()); } resultRecord.println("The current index size is: " + index.size()); System.out.println("The current index size is: " + index.size()); // System.out.println("The current BloomFilter size is: " + bf.size()); resultRecord.println("The total data is: "+total+"\nThe duplicates are: "+dup+ "\nThe deduplication rate is : " + (double)dup/total*100 +"%"); System.out.println("The total data is: "+total+"\nThe duplicates are: "+dup+ "\nThe sampling rate is: " + sampleRate + "\nThe deduplication rate is : " + (double)dup/total*100 +"%"); measuredRatio = (double)dup/total; estiRatio = getEstimateRatio(); resultRecord.println("The estimated dedup rate is: " + getEstimateRatio()*100 +" %"); System.out.println("The estimated dedup rate is: " + getEstimateRatio()*100 +" %"); nodeQue.add(new Node(total,dup,(double)1/sampleRate,index.size(),(double)dup/total,(double)dup/(index.size()),sampleTotal)); matlabStatistic(); indexStatistic(); }
237de322-0162-4073-b88d-03cdf39375d3
8
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line = ""; StringBuilder out = new StringBuilder(); while ((line = in.readLine()) != null && line.length() != 0) { int times = Integer.parseInt(line); for (int i = 0; i < times; i++) { int n = Integer.parseInt(in.readLine().trim()); int nbars = Integer.parseInt(in.readLine().trim()); int[] l = readInts(in.readLine()); boolean can[] = new boolean[n + 1], pos = n == 0; can[0] = true; for (int j = 0; j < l.length && !pos; j++) for (int k = n - l[j]; k >= 0; k--) { can[k + l[j]] |= can[k]; if (can[n]) { pos = true; break; } } out.append(pos ? "YES\n" : "NO\n"); } } System.out.print(out); }
4ffe569e-80cc-4b60-8c64-0c1815ad7476
6
public static String escape(String string) { StringBuilder sb = new StringBuilder(string.length()); for (int i = 0, length = string.length(); i < length; i++) { char c = string.charAt(i); switch (c) { case '&': sb.append("&amp;"); break; case '<': sb.append("&lt;"); break; case '>': sb.append("&gt;"); break; case '"': sb.append("&quot;"); break; case '\'': sb.append("&apos;"); break; default: sb.append(c); } } return sb.toString(); }
8885d075-694a-4c9d-84c0-6bd2ca9e5aa9
5
private static void method342(int color, int x, int alpha, int y, int height) { if (x < Graphics2D.topX || x >= Graphics2D.bottomX) { return; } if (y < Graphics2D.topY) { height -= Graphics2D.topY - y; y = Graphics2D.topY; } if (y + height > Graphics2D.bottomY) { height = Graphics2D.bottomY - y; } int srcAlpha = 256 - alpha; int destRed = (color >> 16 & 0xff) * alpha; int destGreen = (color >> 8 & 0xff) * alpha; int destBlue = (color & 0xff) * alpha; int step = x + y * Graphics2D.width; for (int j3 = 0; j3 < height; j3++) { int j2 = (Graphics2D.pixels[step] >> 16 & 0xff) * srcAlpha; int k2 = (Graphics2D.pixels[step] >> 8 & 0xff) * srcAlpha; int l2 = (Graphics2D.pixels[step] & 0xff) * srcAlpha; int destColor = (destRed + j2 >> 8 << 16) + (destGreen + k2 >> 8 << 8) + (destBlue + l2 >> 8); Graphics2D.pixels[step] = destColor; step += Graphics2D.width; } }
54b2a33d-40cf-4859-aba0-529fbc5dfb6d
9
@Override public boolean okMessage(final Environmental myHost, final CMMsg msg) { if(!(affected instanceof MOB)) return super.okMessage(myHost,msg); final MOB mob=(MOB)affected; if((msg.amITarget(mob)) &&(CMath.bset(msg.targetMajor(),CMMsg.MASK_MALICIOUS)) &&(msg.targetMinor()==CMMsg.TYP_CAST_SPELL) &&(msg.tool() instanceof Ability) &&((((Ability)msg.tool()).classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_SPELL) &&(invoker!=null) &&(!mob.amDead()) &&(CMLib.dice().rollPercentage()<35)) { mob.location().show(mob,null,CMMsg.MSG_OK_VISUAL,L("The ward around <S-NAME> inhibits @x1!",msg.tool().name())); return false; } return super.okMessage(myHost,msg); }
0db82805-d6c9-4d1d-99ed-a0f60bc5aa5c
9
/** @see org.lateralgm.joshedit.FindDialog.FindNavigator#findNext() */ @Override public void findNext() { if (FindDialog.wrap.isSelected() && joshText.caret.row == joshText.getLineCount() - 1) { joshText.caret.col = 0; joshText.caret.row = 0; } // TODO: I have no idea how multiline regexp search will be handled. String ftext = tFind.getText(); if (ftext.length() == 0) { return; } if (FindDialog.regex.isSelected()) { Pattern p; try { p = Pattern.compile(ftext, Pattern.CASE_INSENSITIVE); } catch (PatternSyntaxException pse) { System.out.println("Shit man, your expression sucks"); return; } lastResult = joshText.code.findNext(p, joshText.caret.row, joshText.caret.col + (joshText.sel.isEmpty()? 0 : 1)); if (lastResult != null) { selectFind(lastResult); } return; } String[] findme = ftext.split("\r?\n"); //$NON-NLS-1$ lastResult = joshText.code.findNext(findme, joshText.caret.row, joshText.caret.col + (joshText.sel.isEmpty()? 0 : 1)); if (lastResult != null) { selectFind(lastResult); } return; }
62346f0b-8351-4147-8e2f-29d56bf2207d
0
public CheckResultMessage check32(int day) { return checkReport.check32(day); }
e9945803-2ba6-45ff-871d-231dc58c87b5
3
private void initValidColors(){ String colors = "123456789"; validColors = new ArrayList<Character>(); //initialize with all colors available for(int i = 0; i < colors.length(); i++) validColors.add(colors.charAt(i)); //check to make sure no other Cell in the Clique already has this color for(Clique clique : cliques) for(Cell cell : clique.getCells()) validColors.remove(Character.valueOf(cell.getColor())); //no-op if not present }
4004e5a6-d0de-4233-997b-62cc11e51901
7
public boolean addFrame(BufferedImage im) { if ((im == null) || !started) { return false; } boolean ok = true; try { if (!sizeSet) { // use first frame's size setSize(im.getWidth(), im.getHeight()); } image = im; getImagePixels(); // convert to correct format if necessary analyzePixels(); // build color table & map pixels if (firstFrame) { writeLSD(); // logical screen descriptior writePalette(); // global color table if (repeat >= 0) { // use NS app extension to indicate reps writeNetscapeExt(); } } writeGraphicCtrlExt(); // write graphic control extension writeImageDesc(); // image descriptor if (!firstFrame) { writePalette(); // local color table } writePixels(); // encode and write pixel data firstFrame = false; } catch (IOException e) { ok = false; } return ok; }
be8120f6-5dc5-48d4-87ab-c2b3790b02c4
0
public String getName() { return Name; }
45b9843f-4d1b-449f-aa5d-4f71d04a5ef7
3
public void render(Graphics g) { // Graphics2D makes it look pretty Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // fill in a green background g.setColor(new Color(140, 230, 0)); g.fillRect(xMin-20, yMin-20, xMax+40, yMax+125); // draw the bounds box g.setColor(Color.red); g.drawRect(xMin, yMin, xMax, yMax); // draw beaker g2.setColor(Color.black); BasicStroke thick = new BasicStroke(3.0f); g2.setStroke(thick); g2.drawLine(xMin, yMin, xMin, yMin+yMax); g2.drawLine(xMin+xMax, yMin, xMin+xMax, yMin+yMax); g2.drawLine(xMin, yMin+yMax, xMin+xMax, yMin+yMax); // use a normal sized line (this is needed if the last stroke was abnormal, ie dotted) g2.setColor(Color.black); BasicStroke normalStroke = new BasicStroke(); g2.setStroke(normalStroke); // call render method of all molecules for(Molecule mole : getMolecules()) // if(mole instanceof Air) mole.render(g2); // use a dotted line type stroke g2.setColor(Color.black); BasicStroke dashed = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, new float[]{10.0f}, 0.0f); g2.setStroke(dashed); // draw the midline fixOutOfBounds(); g2.setColor(new Color(0,0,0, (int)(255.0*(100-perm)/100))); // the line is more transparent if it is more permeabile g2.drawLine(xMin, yMid, xMin+xMax, yMid); g2.setColor(new Color(0,0,0, 255)); // draw water background g2.setColor(new Color(0, 100, 200, 150)); g2.fillRect(xMin, yMid+2, xMax, yMax-(yMid-yMin)-2); // draw the flame int transparency = (int)(255.0*(temp-minTemp)/(maxTemp-minTemp)); if(transparency > 255) transparency = 255; else if(transparency < 0) transparency = 0; g2.setStroke(normalStroke); g2.setColor(new Color(255, 0, 0, transparency)); // red g2.fillOval((xMin+xMax+xMin)/2-15, yMin+yMax+10, 30, 75); g2.setColor(new Color(255, 165, 0, transparency)); // orange g2.fillOval((xMin+xMax+xMin)/2-10, yMin+yMax+25+10, 20, 50); g2.setColor(Color.black); // black g2.fillRect((xMin+xMax+xMin)/2-10, yMin+yMax+75, 20, 30); // draw the barrel of the bunsen burner // draw text information g2.setColor(Color.black); g2.drawString(getState(), xMin, yMin+yMax+20); // g2.drawString(pres+" mmHG", xMin, yMin+yMax+40); // g2.drawString(temp+" K", xMin, yMin+yMax+60); // g2.drawString((int)(perm*100)/100+" % perm", xMin, yMin+yMax+80); }
5a0e8feb-1df4-49d4-9604-7a91f5e9d89e
8
private void untidy(double di, double wa){ for (int i=0;i<w;i++) for (int j=0;j<h;j++){ double d = r.nextDouble(); if (d<di){ net[i][j]=DIRTY; anet[i][j]=CLEAN; }else if (d<di+wa){ net[i][j]=WALL; anet[i][j]=CLEAN; } if (i==0 || j==0 || i==w-1 || j==h-1){ net[i][j]=WALL; } } }
539936fe-77ed-4dfe-99c3-5b136e94fd05
3
public String findSavedGameSize() { File file; file = new File("Saved_Games.txt"); Scanner scanner; String line; try { scanner = new Scanner(file); while(scanner.hasNextLine()) { line = scanner.nextLine(); if(line.equals(user.getUsername())) { scanner.nextLine(); return scanner.nextLine(); } } scanner.close(); } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(null, "Could not load puzzle. Contact system administrator.", "Error", JOptionPane.ERROR_MESSAGE); } return ""; }
70476d03-c933-4c16-b0dd-1cdc373e3166
1
private static ArrayList<String> loadLines(String fileName) throws IOException { System.out.println("Reading file"); BufferedReader br = new BufferedReader(new FileReader(fileName)); ArrayList<String> ret = new ArrayList<String>(); String line; while ((line = br.readLine()) != null) { ret.add(line); } System.out.println("... Read file."); return ret; }
a2ada55c-f1f2-439f-9aa3-5d48f73fb65e
6
public void updateUser() throws SQLException { String query = "" + "UPDATE user " + "SET Email = ?, Name = ?, Surname = ?, Type = ? "; if (u.getPassword() != null && !u.getPassword().equals("")) { query += ", Password = ? "; } query += "WHERE userID = ? "; PreparedStatement ps = c.prepareStatement(query); ps.setString(1, u.getEmail()); ps.setString(2, u.getName()); ps.setString(3, u.getSurname()); if (u.getType().equals("admin")) { ps.setInt(4, 1); } else if (u.getType().equals("user")) { ps.setInt(4, 0); } if (u.getPassword() != null && !u.getPassword().equals("")) { ps.setString(5, StrVal.sha256(u.getPassword())); ps.setInt(6, u.getUserID()); } else { ps.setInt(5, u.getUserID()); } ps.executeUpdate(); }
64d1ebfa-a1c2-4a28-ac84-84af1bfa889f
6
public void atualizar() { jComboBoxEstadoUF.removeAllItems(); jComboBoxCidade.removeAllItems(); jComboBairro.removeAllItems(); jComboBoxDDD.removeAllItems(); jComboBoxTelefone.removeAllItems(); jComboBoxCelular.removeAllItems(); jComboBoxEstadoUF.addItem("Todos"); for (Estado estado : listaView.getCidadaoComboBox().getEstados()) { jComboBoxEstadoUF.addItem(estado); } jComboBoxCidade.addItem("Todos"); for (Cidade cidade : listaView.getCidadaoComboBox().getCidades()) { jComboBoxCidade.addItem(cidade); } jComboBairro.addItem("Todos"); for (Bairro bairro : listaView.getCidadaoComboBox().getBairros()) { jComboBairro.addItem(bairro); } jComboBoxDDD.addItem("Todos"); for (DDD ddd : listaView.getCidadaoComboBox().getDDDs()) { jComboBoxDDD.addItem(ddd); } jComboBoxTelefone.addItem("Todos"); for (Telefone telefone : listaView.getCidadaoComboBox().getTelefones()) { jComboBoxTelefone.addItem(telefone); } jComboBoxCelular.addItem("Todos"); for (Celular celular : listaView.getCidadaoComboBox().getCelulares()) { jComboBoxCelular.addItem(celular); } }
ec1d235e-7b21-4060-b631-378764686fba
6
public void tryToGetData(){ try { byte[] receiveData = new byte[1024]; DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); boolean allreadyingame = false; for(ServerSideClient client:clients){ if(client != null && receivePacket.getAddress() == client.getAddress() && receivePacket.getPort() == client.getPort()) allreadyingame = true; } if(allreadyingame == false) this.addClient(receivePacket); DataInputStream inputStream = new DataInputStream(new ByteArrayInputStream(receivePacket.getData())); handlePacket(inputStream.readInt(),inputStream,receivePacket); } catch (IOException e) { e.printStackTrace(); } }
930310bc-861d-4b54-b387-14ad77ed7eb2
5
private boolean checkQualifier(QualifiedValue<?> value, Enum<?>... qualifiers) { boolean contained = true; for (Enum<?> qualifier : qualifiers) { if (!value.getQualifiers().contains(qualifier)) { contained = false; break; } } return contained; }
be70851b-11eb-469f-ad38-a7d0cd61eff7
7
public ArrayList<DuplicateMusicObject> getDuplicatesOnContent() { ArrayList<MusicObject> allMusic = getAllSongs(); ArrayList<MusicObject> temp = null; HashMap <String,ArrayList<MusicObject>> byteDuplicates = new HashMap<String,ArrayList<MusicObject>>(); for (MusicObject song : allMusic) { if (byteDuplicates.containsKey(song.getMD5String())) { temp = byteDuplicates.remove(song.getMD5String()); } else { temp = new ArrayList<MusicObject>(); } temp.add(song); byteDuplicates.put(song.getMD5String(), temp); } // Remove non-duplicates ArrayList <String>keys = new ArrayList<String>(); keys.addAll(byteDuplicates.keySet()); for (String key : keys) { if (byteDuplicates.get(key).size() == 1) { byteDuplicates.remove(key); } } allMusic.clear(); System.gc(); ArrayList<DuplicateMusicObject> dupList = new ArrayList<DuplicateMusicObject>(); // Normalize this back to an array for (ArrayList<MusicObject> musicArr : byteDuplicates.values()) { DuplicateMusicObject dup = new DuplicateMusicObject(); for (MusicObject music : musicArr) { if (!dup.hasDuplicates()) { dup.setDuplicateCriteria("Duplicate Content - " + music.getMD5String()); } dup.addID(music); } dupList.add(dup); } return dupList; }
f3b4aacc-d264-4e90-bbd1-5da07f40922a
1
public Vector3f getVector3f( String name ) { Vector3f result = vector3fHashMap.get( name.toLowerCase() ); if ( result != null ) return result; return new Vector3f( 0, 0, 0 ); }
2712fdb1-2940-4ced-a9fe-81ad2662b6f6
3
private void playUser(Scanner sc){ System.out.println("There are "+m.count()+" marbles in the pile."); System.out.println("How many marbles do you want to remove?"); try{ m.remove(sc.nextInt()); player = false; } catch(Marbles.NotValid e){ System.err.println(e.getMessage()); } catch(Marbles.EmptyPile e){ System.err.println(e.getMessage()); } catch(java.util.InputMismatchException e){ System.err.println("Not a number"); } }
1ac527a7-9f6c-4fb7-8bfc-741c0c2237a2
9
public RequeteRaster() throws SQLException { srids=RequeteUnion.getSrids(); tableaux=FenetreRaster.getTableauTailles(); for(int fg=0;fg<tableaux.size();fg++){ String test34[][]=tableaux.get(fg); String taillePixels=test34[fg][1]; taillePixel.add(taillePixels); String nomCouche=test34[fg][0]; nomCouches.add(nomCouche); } System.out.println("Dernier srid size: "+taillePixel.size()); for(int i=0;i<srids.size();i++){ System.out.println("Dernier srdi: "+srids.get(i)); } //shapes=ConnexionTraitement.getArrayy(); this.setNomBase(ConnexionBaseDonnees.getNomBase()); this.setHote(ConnexionBaseDonnees.getHote()); this.setPort(ConnexionBaseDonnees.getPort()); this.setNomUtilisateur(ConnexionBaseDonnees.getUser()); this.setMotDePasse(ConnexionBaseDonnees.getPswd()); //System.out.println("Test"); Connection con = null; try{ Class.forName("org.postgresql.Driver"); con = DriverManager.getConnection("jdbc:postgresql://"+this.getHote()+":"+this.getPort()+"/"+this.getNomBase(),this.getNomUtilisateur(),this.getMotDePasse()); for(int j=0;j<taillePixel.size();j++){ if (con!=null){ Statement st = con.createStatement(); //st.execute("ALTER TABLE batiments DROP COLUMN surface_total "); System.out.println(nomCouches.get(j)); /* st.execute("CREATE TABLE "+nomCouches.get(j)+"2 as SELECT ST_BUFFER(geom_"+nomCouches.get(j)+",0.0) as geom_"+nomCouches.get(j)+" from "+nomCouches.get(j)+""); st.execute("CREATE TABLE "+nomCouches.get(j)+"_union as SELECT ST_UNION(geom_"+nomCouches.get(j)+") as geom_"+nomCouches.get(j)+" from "+nomCouches.get(j)+"2"); st.execute("ALTER TABLE "+nomCouches.get(j)+"_union ADD COLUMN gid serial primary key"); */ st.execute("DROP TABLE if exists "+nomCouches.get(j)+"_raster"); st.execute("CREATE TABLE "+nomCouches.get(j)+"_raster as SELECT ST_asraster("+srids.get(j)+","+taillePixel.get(j)+",-"+taillePixel.get(j)+") as rast from "+nomCouches.get(j)+"_unionraster"); System.out.println("CREATE TABLE "+nomCouches.get(j)+"_raster as SELECT ST_asraster("+srids.get(j)+","+taillePixel.get(j)+",-"+taillePixel.get(j)+") as rast from "+nomCouches.get(j)+"_unionraster"); st.execute("ALTER TABLE "+nomCouches.get(j)+"_raster ADD COLUMN rid serial primary key"); st.execute("DROP TABLE "+nomCouches.get(j)+"_unionraster"); // stmt = con.createStatement(); // // String query = "select SUM(surfpalu) from "+shapes.get(j)+" as sum"; // ResultSet rs = stmt.executeQuery(query); // while (rs.next()) { // // // String coffeeName = rs.getString("abc"); // // int test = rs.getInt("sum"); // this.setSurfaceTotale(rs.getDouble("sum")); // //float test = rs.getFloat("sum"); // //float price = rs.getFloat("PRICE"); // // int sales = rs.getInt("SALES"); // // int total = rs.getInt("TOTAL"); // System.out.println("surface totalefeneraster pour:"+ shapes.get(j)+" "+this.getSurfaceTotale()); // } // // st.execute("ALTER TABLE "+shapes.get(j)+" DROP COLUMN surfpalu"); nomRaster.add(nomCouches.get(j)); srids1.add(srids.get(j)); //System.out.println("Base de donn�es "+database+" cr�e"); if(!nomCouches2.contains(nomCouches.get(j))){ System.out.println("srids11111 "+ nomCouches.get(j)); System.out.println("srids11111 "+ srids.get(j)); nomCouches2.add(nomCouches.get(j)); srids1.add(srids.get(j)); } if(!shapes1.contains(nomCouches.get(j))){ shapes1.add(nomCouches.get(j)); // srids1.add(srids.get(ff)); } if(!nomRaster2.contains(nomCouches.get(j)+"_raster")){ nomRaster2.add(nomCouches.get(j)+"_raster"); } if(!taillePixel2.contains(taillePixel.get(j))){ taillePixel2.add(taillePixel.get(j)); } } } } catch (Exception b){ b.printStackTrace(); JOptionPane.showMessageDialog(this,"Erreur : "+b,"Titre : exception",JOptionPane.ERROR_MESSAGE); } ConnexionRaster.getArrayy().remove(nomRaster); ConnexionRaster.getGeomms().remove(srids1); DensitePopulation.getNomCouches2().removeAll(nomRaster); DensitePopulation.getSrids1().removeAll(srids1); nomCouches = new ArrayList<String>(); shapes = new ArrayList<String>(); srids = new ArrayList<String>(); tableaux.removeAll(tableaux); RequeteUnion.getSrids().removeAll(RequeteUnion.getSrids()); // ZFenetre.getVisualiserRaster().setEnabled(true); }
6be5b536-c3ae-40f5-a174-51ba3e28377c
5
public static Set<RepairedCell> readTruth(String fileRoute) { File file = new File(fileRoute); Set<RepairedCell> truth = new HashSet<RepairedCell>(); if(!file.exists()){ System.out.println(fileRoute+"文件不存在,无法测试!"); return truth; } try { FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String line = null; while (null != (line = br.readLine())) { String[] paras = line.split(","); RepairedCell cell = null; if(paras.length==2){ cell = new RepairedCell(Integer.parseInt(paras[0]),paras[1],""); }else{ cell = new RepairedCell(Integer.parseInt(paras[0]),paras[1],paras[2]); } truth.add(cell); } br.close(); fr.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return truth; }
6187b10d-8664-433f-a4ef-d6df010e54d8
3
public boolean setType(int n) { if ((n != NetworkSimulator.TIMER_INTERRUPT) && (n != NetworkSimulator.FROM_LAYER_5) && (n != NetworkSimulator.FROM_LAYER_3)) { type = -1; return false; } type = n; return true; }
6053fdb3-3e7b-4fc9-beb9-c2dde441b9c1
8
public String getInitialFilePath() { StringBuilder initialFilePath = new StringBuilder(); String userHome = System.getProperty("user.home"); if(userHome != null) { initialFilePath.append(userHome); } String osName = System.getProperty("os.name").toUpperCase(); String fileSeparator = System.getProperty("file.separator"); // Currently not appending anything after the user home // If it is Linux or some other OS. // With so many Linux distributions it is hard to guess // where the pictures folder might be. // TODO: Search for a pictures folder using a 'smart' fashion. if(osName != null) { if(osName.contains("WIN") && (osName.contains("7") || osName.contains("8"))) { initialFilePath.append(fileSeparator +"Music"+ fileSeparator); } else if(osName.contains("WIN") && osName.contains("XP")) { initialFilePath.append(fileSeparator +"My Music"+ fileSeparator); } else if(osName.contains("MAC")) { initialFilePath.append(fileSeparator +"Music"+ fileSeparator); } } return initialFilePath.toString(); }
98538a97-af03-4309-ae87-c204de9ccaf3
9
public void handleConf(CSTAEvent event) { if ((event == null) || (event.getEventHeader().getEventClass() != 5) || (event.getEventHeader().getEventType() != this.pdu)) { return; } if (this.pdu == 30) { this.enable = ((CSTAQueryDndConfEvent) event.getEvent()) .isDoNotDisturb(); } this.device.replyAddrPriv = event.getPrivData(); this.device.replyTermPriv = event.getPrivData(); Vector<TSEvent> eventList = new Vector<TSEvent>(); this.device.updateDNDState(this.enable, eventList); if (eventList.size() > 0) { Vector<?> observers = this.device.getAddressObservers(); for (int j = 0; j < observers.size(); j++) { TsapiAddressMonitor callback = (TsapiAddressMonitor) observers .elementAt(j); callback.deliverEvents(eventList, false); } Vector<?> terminalObservers = this.device.getTerminalObservers(); for (int j = 0; j < terminalObservers.size(); j++) { TsapiTerminalMonitor callback = (TsapiTerminalMonitor) terminalObservers .elementAt(j); callback.deliverEvents(eventList, false); } } }
efade2cc-604b-42ac-878c-ebcccd30090b
3
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final TabelOutletSize other = (TabelOutletSize) obj; if (!Objects.equals(this.kodeSize, other.kodeSize)) { return false; } return true; }
956bf31b-1c11-4e59-982a-a0df42eb8af3
0
public String getSeqID() { return seqID; }
d9bfe8bf-7380-4d36-908d-080f556fd3cf
4
public void generationControlee(){ int nbP; int nbA; Date date = new Date(); TachePeriodique tacheP; Tache tacheA; //Tache apériodique Scanner sc = new Scanner(System.in); //Stockage du nombre de tache a générer System.out.println("Nombre de taches périodiques controlées à générer : "); nbP = sc.nextInt(); System.out.println("Nombre de tâches apériodiques à générer : "); nbA = sc.nextInt(); try { //Création du fichier PrintWriter fichier = new PrintWriter (new FileWriter("../data/txt/GENERATION_CONTROLEE - " + date.toString() + ".txt")); //Pour chaque tache périodique for(int i = 0; i < nbP; i++){ System.out.println("Date de réveil :"); int ri = sc.nextInt(); System.out.println("Durée d'éxecution maximale :"); int Ci = sc.nextInt(); System.out.println("Période d'activation :"); int Pi = sc.nextInt(); System.out.println("Délai critique :"); int Di = sc.nextInt(); tacheP = new TachePeriodique(ri, Ci, Pi, Di); //On écrit la tache dans le fichier fichier.print(tacheP.toString()+"\n"); } //Pour chaque tache apériodique (s'il y en a) for(int i = 0; i < nbA; i++){ System.out.println("Date de réveil :"); int ri = sc.nextInt(); System.out.println("Durée d'éxecution maximale :"); int Ci = sc.nextInt(); tacheA = new Tache(ri, Ci); //On écrit la tache dans le fichier fichier.print(tacheA.toString()+"\n"); } fichier.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //Fermeture du flux d'entrée clavier sc.close(); }
58ff7723-e87d-413d-acae-21c5ef52b2cc
0
public VueListe getVueListe() { return panelListe; }
f7a7c0d9-f3a0-4616-9e04-820d64476952
4
private static boolean isBSTHelper(TreeNode<Integer> t, int max, int min) { if (t == null) { return true; } if (t.data > max || t.data < min) { return false; } /* * current data is the max value of left subtree and min value of right * subtree */ return isBSTHelper(t.left, t.data, min) && isBSTHelper(t.right, max, t.data); }
940cd3cd-948d-433b-b2f9-3d9c1f0da2f2
8
protected static void processRoomRelinks(List<String> reLinkTable, String areaName, Map<String, Room> areaHashedRoomSet, Map<String, Room> hashedRoomSet) { // try to re-link olde room links if(reLinkTable!=null) { for(int r=0;r<reLinkTable.size();r++) { final String link=reLinkTable.get(r); String nextLink=""; if(r<(reLinkTable.size()-1)) nextLink=reLinkTable.get(r+1); final int s1=link.indexOf('/'); final int s2=link.lastIndexOf('/'); final String sourceRoomID=link.substring(0,s1); synchronized(("SYNC"+sourceRoomID).intern()) { final int direction=CMath.s_int(link.substring(s1+1,s2)); final String destRoomID=link.substring(s2+1); final Room sourceRoom=getRoom(areaHashedRoomSet,hashedRoomSet,areaName,sourceRoomID); final Room destRoom=getRoom(areaHashedRoomSet,hashedRoomSet,areaName,destRoomID); if((sourceRoom==null)||(destRoom==null)) Log.errOut("Import","Relink error: "+sourceRoomID+"="+sourceRoom+"/"+destRoomID+"="+destRoom); else { sourceRoom.rawDoors()[direction]=destRoom; if(((!hashedRoomSet.containsValue(sourceRoom))) &&((nextLink.length()==0)||(!nextLink.startsWith(sourceRoomID+"/")))) CMLib.database().DBUpdateExits(sourceRoom); } } } } }
4e7dd3ad-80f0-4180-9349-6f00aecd8a55
3
public Vec3D getIntermediateWithYValue(Vec3D var1, double var2) { double var4 = var1.xCoord - this.xCoord; double var6 = var1.yCoord - this.yCoord; double var8 = var1.zCoord - this.zCoord; if(var6 * var6 < 1.0000000116860974E-7D) { return null; } else { double var10 = (var2 - this.yCoord) / var6; return var10 >= 0.0D && var10 <= 1.0D?createVector(this.xCoord + var4 * var10, this.yCoord + var6 * var10, this.zCoord + var8 * var10):null; } }
adfae6a6-4416-4a3f-87e6-6b473ecab386
4
private void switchInputStream() throws IOException { if(getInputStream() != null) getInputStream().close(); if(filenames.isEmpty()) throw new IOException("All files in the playlist were marked as bad"); if(random) current = (int)(Math.random() * filenames.size()); else current = (current + 1) % filenames.size(); try { Fluid.log("Playing: " + filenames.get(current), 1); setInputStream(new FileInputStream((String)filenames.get(current))); } catch(IOException e) { filenames.remove(current); throw e; } }
51e10b13-cf40-4cc2-8caa-37d12bcd651e
1
public void shrink() { if (c.length == length) { return; } char[] newc = new char[length]; System.arraycopy(c, 0, newc, 0, length); c = newc; }
33937dc9-3107-4187-a702-bfe6c718d1b3
9
private void updatePatch(final MeshPatch old, final float time) { if (! (old.updateMesh || old.updateRoads || old.updateDirt)) return ; final int x = old.x, y = old.y ; final boolean init = old.inceptTime == TIME_INIT ; final MeshPatch patch = init ? old : new MeshPatch() ; if (init) { old.inceptTime = TIME_DONE ; } else { patch.previous = old ; patch.inceptTime = time ; patch.x = x ; patch.y = y ; patches[x / patchSize][y / patchSize] = patch ; } ///I.say("Updating patch: "+x+"/"+y+", incept: "+patch.inceptTime) ; if (old.updateMesh) { patch.meshes = TerrainMesh.genMeshes( x, y, x + patchSize, y + patchSize, Habitat.BASE_TEXTURES, heightVals, typeIndex, varsIndex ) ; animate(patch.meshes, Habitat.SHALLOWS) ; animate(patch.meshes, Habitat.OCEAN ) ; old.updateMesh = false ; } else { patch.meshes = new TerrainMesh[old.meshes.length] ; for (int i = old.meshes.length ; i-- > 0 ;) { patch.meshes[i] = TerrainMesh.meshAsReference(old.meshes[i]) ; } } if (old.updateRoads) { patch.roadsMesh = TerrainMesh.genMesh( x, y, x + patchSize, y + patchSize, Habitat.ROAD_TEXTURE, heightVals, pavingMask ) ; old.updateRoads = false ; } else patch.roadsMesh = TerrainMesh.meshAsReference(old.roadsMesh) ; if (old.updateDirt) { patch.dirtMesh = TerrainMesh.genMesh( x, y, x + patchSize, y + patchSize, Habitat.SQUALOR_TEXTURE, heightVals, squalorMask ) ; old.updateDirt = false ; } else patch.dirtMesh = TerrainMesh.meshAsReference(old.dirtMesh) ; }
84142186-06f0-4866-bf6c-24f6b815ac0f
3
public void test_04() { System.out.println("\n\nSuffixIndexerNmer: Add & overlap test"); String fastqFileName = "tests/short.fastq"; // Create indexer SuffixIndexerNmer<DnaAndQualitySequence> seqIndexNmer = new SuffixIndexerNmer<DnaAndQualitySequence>(new DnaQualSubsequenceComparator(true), 15); // Add & overlap (join) all sequences from a file for( Fastq fastq : new FastqFileIterator(fastqFileName, FastqVariant.FASTQ_ILLUMINA) ) { String seq = fastq.getSequence(); if( seq.indexOf('N') < 0 ) { // Create sequence and add it to indexer String qual = fastq.getQuality(); DnaAndQualitySequence bseq = new DnaAndQualitySequence(seq, qual, FastqVariant.FASTQ_ILLUMINA); seqIndexNmer.add(bseq); boolean joined = seqIndexNmer.overlap(bseq); // Try to find the best overlap if( !joined ) seqIndexNmer.add(bseq); // Nothing found? => add sequence } } // Sanity check seqIndexNmer.sanityCheck(); }
70707f67-4381-4135-af89-841f4af318a4
8
@Override public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge, PlotRenderingInfo plotState) { // if the axis is not visible, don't draw it... if (!isVisible()) { return new AxisState(cursor); } // calculate the adjusted data area taking into account the 3D effect... // this assumes that there is a 3D renderer, all this 3D effect is a // bit of an ugly hack... CategoryPlot plot = (CategoryPlot) getPlot(); Rectangle2D adjustedDataArea = new Rectangle2D.Double(); if (plot.getRenderer() instanceof Effect3D) { Effect3D e3D = (Effect3D) plot.getRenderer(); double adjustedX = dataArea.getMinX(); double adjustedY = dataArea.getMinY(); double adjustedW = dataArea.getWidth() - e3D.getXOffset(); double adjustedH = dataArea.getHeight() - e3D.getYOffset(); if (edge == RectangleEdge.LEFT || edge == RectangleEdge.BOTTOM) { adjustedY += e3D.getYOffset(); } else if (edge == RectangleEdge.RIGHT || edge == RectangleEdge.TOP) { adjustedX += e3D.getXOffset(); } adjustedDataArea.setRect(adjustedX, adjustedY, adjustedW, adjustedH); } else { adjustedDataArea.setRect(dataArea); } if (isAxisLineVisible()) { drawAxisLine(g2, cursor, adjustedDataArea, edge); } // draw the category labels and axis label AxisState state = new AxisState(cursor); if (isTickMarksVisible()) { drawTickMarks(g2, cursor, adjustedDataArea, edge, state); } state = drawCategoryLabels(g2, plotArea, adjustedDataArea, edge, state, plotState); state = drawLabel(getLabel(), g2, plotArea, dataArea, edge, state); return state; }
85d7a22d-3f78-42d4-b17b-80ce86a93614
2
public static String getUrlFileType(String url){ if(url.endsWith(FileType.jpg.getType())){ return FileType.jpg.getType(); } else if(url.endsWith(FileType.jpg.getType())){ return FileType.png.getType(); } log.warn("System could not analyze this url's file type: " + url); return null; }
5718b067-0e8d-4cff-9b27-a772d718a6ea
9
public static void main(String[] args) { //System.setProperty("webdriver.chrome.driver", "/L/tmp/chromedriver"); Options options = new Options(); options.addOption("c", "config", true, "Path ot config to use"); options.addOption("d", "driver", true, "Driver to use"); options.addOption("o", "output", true, "Directory to store output at"); options.addOption("u", "url", true, "The url to test"); CommandLineParser parser = new GnuParser(); CommandLine commandLine; WebDriver driver = null; String configPath = null; String url = null; String outputdir = null; try { commandLine = parser.parse(options, args); if (commandLine.hasOption("config")) configPath = commandLine.getOptionValue("config"); else configPath = "config.properties"; if (commandLine.hasOption("output")) outputdir = commandLine.getOptionValue("output"); else outputdir = "."; if (!commandLine.hasOption("driver")) throw new Exception("You have to specify driver"); String drv = commandLine.getOptionValue("driver"); if (drv.equals("firefox")) driver = new FirefoxDriver(); else if (drv.equals("chrome")) driver = new ChromeDriver(); else if (drv.equals("htmlunit")) driver = new HtmlUnitDriver(); else throw new Exception("Driver " + drv + " is not supported yet");//TODO: more specific exception? if (!commandLine.hasOption("url")) throw new IOException("You have to specify url"); url = commandLine.getOptionValue("url"); Config.init(configPath); new WebPageTester(driver, outputdir).run(url); } catch (Exception e) { System.err.println("Something bad has happened:"); e.printStackTrace(); } finally { if (driver != null) driver.quit(); } }
1cdda6d6-31e5-4088-8aa6-ce3f90518315
7
public static void main(String[]args){ String Train = args[0]; //String Test = args[1]; //Naive naive = new Naive(); topwords naive = new topwords(); try { naive.train(Train); } catch (IOException e) { e.printStackTrace(); } //naive.test(Test); List<Map.Entry<String, Double>> folder = new ArrayList<Map.Entry<String, Double>>(naive.pMap2.entrySet()); Collections.sort(folder, new Comparator<Map.Entry<String, Double>>() { public int compare(Map.Entry<String, Double> e1, Map.Entry<String, Double> e2) { if (!e1.getValue().equals(e2.getValue())) { if (e2.getValue() > e1.getValue()) return 1; else return -1; } else return (e1.getKey()).toString().compareTo(e2.getKey().toString()); } }); for(int i = 0; i < 20; i++){ System.out.printf(folder.get(i).getKey() + " %.04f" + "\n", folder.get(i).getValue()); } System.out.printf("\n"); folder = new ArrayList<Map.Entry<String, Double>>(naive.pMap1.entrySet()); Collections.sort(folder, new Comparator<Map.Entry<String, Double>>() { public int compare(Map.Entry<String, Double> e1, Map.Entry<String, Double> e2) { if (!e1.getValue().equals(e2.getValue())) { if (e2.getValue() > e1.getValue()) return 1; else return -1; } else return (e1.getKey()).toString().compareTo(e2.getKey().toString()); } }); for(int i = 0; i < 20; i++){ System.out.printf(folder.get(i).getKey() + " %.04f" + "\n", folder.get(i).getValue()); } }
9635b809-26b2-4c6c-969b-942fe7e2cf4a
5
public static void main(String[] args) { //Please input the value of "String[] args" from the settings of Java application. Class<?> c; ArrayList classList = null; try { c = Class.forName(args[0]); TypeDesc desc = new TypeDesc(); for(String name : args){ desc.printType(c, 0, TypeDesc.basic); classList = desc.getClassList(); } for(int i = 0; i < classList.size(); i++){ printAllMembers((Class<?>) classList.get(i)); } } catch (ClassNotFoundException e) { System.out.println("unknown class:" + args[0]); } }
db175825-dd6e-48d0-9331-da1e4849ca74
8
@Override public double calculateFractalWithoutPeriodicity(Complex pixel) { iterations = 0; double temp = 0; Complex tempz = new Complex(pertur_val.getPixel(init_val.getPixel(pixel))); Complex tempz2 = new Complex(init_val2.getPixel(pixel)); Complex[] complex = new Complex[3]; complex[0] = tempz;//z complex[1] = new Complex(pixel);//c complex[2] = tempz2;//z2 Complex zold = new Complex(); Complex zold2 = new Complex(); if(parser.foundS()) { parser.setSvalue(new Complex(complex[0])); } if(parser2.foundS()) { parser2.setSvalue(new Complex(complex[0])); } if(parser.foundP()) { parser.setPvalue(new Complex()); } if(parser2.foundP()) { parser2.setPvalue(new Complex()); } for(; iterations < max_iterations; iterations++) { if((temp = complex[0].distance_squared(zold)) <= convergent_bailout) { Object[] object = {iterations, complex[0], temp, zold, zold2}; return out_color_algorithm.getResult(object); } zold2.assign(zold); zold.assign(complex[0]); function(complex); if(parser.foundP()) { parser.setPvalue(new Complex(zold)); } if(parser2.foundP()) { parser2.setPvalue(new Complex(zold)); } } Object[] object = {complex[0], zold}; return in_color_algorithm.getResult(object); }
ca601f69-82f5-4b72-b342-583f7517f014
0
private void jButtonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOKActionPerformed ctrlP.chercher(); }//GEN-LAST:event_jButtonOKActionPerformed
89cdeeb2-04ca-4872-814a-c00aa2b02f7c
9
@Override public void run() { if(workflow.getContext() == null) { workflow.setContext(new Context()); } if (AzotConfig.GLOBAL.DEBUG) { System.out.println("Reading " + workflowFile + "..."); } final List<Variable> contextVariables = workflow.getContext().getVariables(); for (final Variable contextVariable : contextVariables) { String value = VariableHelper.substituteVariables(contextVariable.getValue(), inheritedVariables); value = VariableHelper.substituteVariables(value, contextVariables); if (AzotConfig.GLOBAL.DEBUG) { System.out.println("Reading variable: ${" + contextVariable.getId() + "} = " + value + " (overwrite=" + contextVariable.isOverwrite() + ")"); } contextVariable.setValue(value); } // Add inherited variables which are not already present into context variables for (final Variable inheritVariable : inheritedVariables) { Variable existingContextVariable = VariableHelper.exist(inheritVariable.getId(), contextVariables); if (existingContextVariable == null) { contextVariables.add(inheritVariable); } else { if(!existingContextVariable.isOverwrite()) { existingContextVariable.setValue(inheritVariable.getValue()); if (AzotConfig.GLOBAL.DEBUG) { System.out.println("Setting variable: ${" + existingContextVariable.getId() + "} = " + existingContextVariable.getValue()); } } } } if (AzotConfig.GLOBAL.VERBOSE) { System.out.println("Starting workflow '" + workflow.getName() + "'"); } new WorkflowEngine(workflow).start(); }
51b19196-b2b3-4a85-a1b7-730619936202
9
public void render(int bufp, float[][] buf, long nsamples, float buf2, boolean add) { //public void render(ByteBuffer buf, long nsamples, float buf2, boolean add) { //System.out.println("Rendering " + nsamples + " samples..."); long todo = nsamples; int bufpp = 0; while (todo != 0) { if (tickd == 0) { tick(); } //StereoSample[] src = instance.mixbuf; //[instance.SRcFrameSize - tickd]; bufpp = instance.SRcFrameSize - tickd; //System.out.printf("%d %d \n", bufp, bufpp); float[][] src = instance.mixbuf; long nread = Math.min(todo, tickd); if (buf2 == 0) { if (!add) { for(int i = 0; i < nread; i++) { buf[bufp + i][0] = src[bufpp + i][0]; //src[i][0] = 0.5f; buf[bufp + i][1] = src[bufpp + i][1]; } //memcpy(buf, src, nread * sizeof(StereoSample)); //System.out.println("Write buffer" + todo); } else { for (int i = 0; i < nread; i++) { //buf[i*2+0] = src[i].l; //buf[i*2+1] = src[i].r; } } //buf += 2 * nread; bufp += nread; //System.out.printf("bufp %d nread %d \n", bufp, nread); } else { if (!add) { for (int i = 0; i < nread; i++) { //buf[i] = src[i].l; //buf2[i] = src[i].r; } } else { for (int i = 0; i < nread; i++) { //buf[i] += src[i].l; //buf2[i] += src[i].r; } } //buf += nread; //buf2 += nread; } todo -= nread; tickd -= nread; } //System.out.printf("todo %d tickd %d bufp %d \n", todo, tickd, bufp); }
ede62c49-7b55-4ad5-b0ee-e725310ad9dc
3
private final static Map<String, InstrumentType> buildMap() { final Map<String, InstrumentType> map_ = new HashMap<>(); try { for (final Field f : InstrumentType.class.getFields()) { final InstrumentType t = (InstrumentType) f.get(null); for (final String key : t.keys) { map_.put(key, t); } map_.put(f.getName().toLowerCase(), t); } } catch (final Exception e) { return null; } return map_; }
01f31a21-985c-4db9-a93f-3d2d2602ac72
8
@Override public int castingQuality(MOB mob, Physical target) { if(mob!=null) { final Room R=mob.location(); if(R!=null) { if((R.domainType()&Room.INDOORS)>0) return Ability.QUALITY_INDIFFERENT; if((R.domainType()==Room.DOMAIN_OUTDOORS_CITY) ||(R.domainType()==Room.DOMAIN_OUTDOORS_SPACEPORT) ||(CMLib.flags().isWateryRoom(R)) ||(R.domainType()==Room.DOMAIN_OUTDOORS_AIR)) return Ability.QUALITY_INDIFFERENT; if(!mob.isInCombat()) return Ability.QUALITY_INDIFFERENT; } } return super.castingQuality(mob,target); }
e734acab-9f25-4fb0-91e7-bf7c5e80636c
5
public void remove() { Connection conn = null; PreparedStatement ps = null; try { conn = iConomy.getiCoDatabase().getConnection(); ps = conn.prepareStatement("DELETE FROM " + Constants.SQLTable + "_BankRelations WHERE bank_id = ? AND account_name = ?"); ps.setInt(1, this.BankId); ps.setString(2, this.AccountName); ps.executeUpdate(); } catch (Exception e) { return; } finally { if (ps != null) try { ps.close(); } catch (SQLException ex) { } if (conn != null) try { conn.close(); } catch (SQLException ex) { } } }
9542a5a2-5515-4c55-a827-0b3a060d35a4
7
public int minPathSum(int[][] grid) { // Start typing your Java solution below // DO NOT write main() function int m = grid.length; if (m == 0) return 0; int n = grid[0].length; if (n == 0) return 0; int[][] res = new int[m][]; int i = 0, j = 0; for (i = 0; i < m; i++) res[i] = new int[n]; res[m - 1][n - 1] = grid[m - 1][n - 1]; for (i = m - 2; i >= 0; i--) res[i][n - 1] = res[i + 1][n - 1] + grid[i][n - 1]; for (i = n - 2; i >= 0; i--) res[m - 1][i] = res[m - 1][i + 1] + grid[m - 1][i]; for (i = m - 2; i >= 0; i--) { for (j = n - 2; j >= 0; j--) { res[i][j] = grid[i][j] + Math.min(res[i + 1][j], res[i][j + 1]); } } return res[0][0]; }
a536a381-7a7e-458b-a049-f06697ca5ddc
8
private boolean processAsCommand(String input) { input = input.trim(); if (!input.startsWith(":")) return false; input = input.substring(1).trim(); String[] parts = input.split("\\s+"); if (parts.length == 0) System.out.println("missing command!"); else if ("context".startsWith(parts[0])) cmdContext(parts); else if ("generation".startsWith(parts[0])) cmdGeneration(parts); else if ("output".startsWith(parts[0])) cmdOutput(parts); else if ("reset".startsWith(parts[0])) context.reset(); else if ("set".startsWith(parts[0])) cmdSet(parts); else if ("unset".startsWith(parts[0])) cmdUnset(parts); else System.out.println("unknown command: " + parts[0]); return true; }
4d27435b-c009-471c-b924-082e24bb0c11
4
public List<List<Point>> mutation(List<List<Point>> nextGen) { Random random = new Random(); for (int i = 0; i < nextGen.size(); i++) { int minInCircles = getMinInCircles(nextGen.get(i)); for (int j = 0; j < nextGen.get(i).size(); j++) { if (circleContainMin(nextGen.get(i).get(j), minInCircles)) { if (circleEmpty(nextGen.get(i).get(j))) { int ranEmerg1 = random.nextInt(incidents.size()); int ranEmerg2 = random.nextInt(incidents.size()); Point newPoint = new Point((incidents.get(ranEmerg1).x + incidents.get(ranEmerg2).x) / 2, (incidents.get(ranEmerg1).y + incidents.get(ranEmerg2).y) / 2); nextGen.get(i).set(j, newPoint); } else { nextGen.get(i).set(j, getNewPoint(nextGen.get(i).get(j))); } j = nextGen.get(i).size(); } } } return nextGen; }
38c741b0-2d73-498a-b566-108346326edb
5
public synchronized ArrayList<Intron> introns() { if (introns == null) { introns = new ArrayList<Intron>(); Exon exBefore = null; for (Exon ex : sortedStrand()) { if (exBefore != null) { // Create intron Intron intron; int rank = introns.size() + 1; // Find intron start and end int start, end; if (isStrandPlus()) { start = exBefore.getEnd() + 1; end = ex.getStart() - 1; } else { start = ex.getEnd() + 1; end = exBefore.getStart() - 1; } int size = end - start + 1; if (size > 0) { // Add intron to list intron = new Intron(this, start, end, strand, id + "_intron_" + rank, exBefore, ex); intron.setRank(rank); introns.add(intron); } } exBefore = ex; } } return introns; }
5e1d379d-14a4-4936-9f6c-5cf9ccb90b2c
1
public Object display(int size) { // TODO Auto-generated method stub if(size==0) return this.head.getElement(); else return this.head.getNext().getElement(); }
302e735a-981a-4a9f-8da7-7b2c9561ba50
2
private static int readn(InputStream in, byte buf[], int c) throws IOException { int i = 0; while (i < c) { int n = in.read(buf, i, c - i); if (n == -1) return i; i += n; } return c; }
03d1a3fd-8085-4f74-a9ce-50f0b961274d
6
@SuppressWarnings("rawtypes") private void configRowMapper(Method method) { MongoMapper mapper = method.getAnnotation(MongoMapper.class); Class<? extends BeanMapper> mapperType = AutoDetectBeanMapper.class; if (mapper != null) { mapperType = mapper.value(); } if (AutoDetectBeanMapper.class.equals(mapperType)) { Class<?> type = method.getReturnType(); if (ClassHelper.isTypeList(type)) { type = ClassHelper.getReturnGenericType(method); } beanMapper = (BeanMapper<?>) ReflectUtils.newInstance(mapperType, new Class[] { Class.class }, new Object[] { type }); } else { beanMapper = (BeanMapper) ReflectUtils.newInstance(mapperType); } }
2cb6195d-b33d-464d-9a07-5b734f0dfa8a
1
public final double getTotalAfterDiscount() { double total = 0.0; for (LineItem item : lineItems) { total += item.getDiscount(); } return total; }
e84e87ef-63d3-4fac-8660-4e8ed82ccbfe
6
public static void ex7() throws NumberFormatException, IOException{ System.out.print("Dimensió del array => "); int dim=Integer.parseInt(stdin.readLine()); int[] array=new int[dim]; for(int i=0; i<dim; i++){ array[i]=(int)(Math.random()*10); System.out.print(array[i]+" , "); } boolean creixent=true; boolean decre=true; for(int i=0; i<dim-1; i++){ if(array[i]>array[i+1]){creixent=false;} if(array[i]<array[i+1]){decre=false;} } if(creixent==true){System.out.println("El array esta ordenat de forma creixent");} else if(decre==true){System.out.println("El array esta ordenat de forma decreixent");} else{System.out.println("El array no segueix cap patro de ordre");} }
b0c6b2c6-c02d-44b0-9329-efbb6504d796
3
public void setup(Main p) { con = new File(p.getDataFolder(), "config.yml"); config = p.getConfig(); if (!p.getDataFolder().exists()) { p.getDataFolder().mkdir(); } loc = new File(p.getDataFolder(), ".yml"); if (!loc.exists()) { try { loc.createNewFile(); } catch (IOException e) { Bukkit.getServer().getLogger().severe(ChatColor.RED + "Could not create data.yml!"); } } data = YamlConfiguration.loadConfiguration(loc); }
da4b4a5a-1f7b-4c88-a34f-91dda8f36a18
4
public void testConstructor_int_int() throws Throwable { YearMonth test = new YearMonth(1970, 6); assertEquals(ISO_UTC, test.getChronology()); assertEquals(1970, test.getYear()); assertEquals(6, test.getMonthOfYear()); try { new YearMonth(Integer.MIN_VALUE, 6); fail(); } catch (IllegalArgumentException ex) {} try { new YearMonth(Integer.MAX_VALUE, 6); fail(); } catch (IllegalArgumentException ex) {} try { new YearMonth(1970, 0); fail(); } catch (IllegalArgumentException ex) {} try { new YearMonth(1970, 13); fail(); } catch (IllegalArgumentException ex) {} }
f96df67f-514b-4e84-8d76-d8842e048650
3
@SuppressWarnings("unchecked") @Override public T mapper(DBObject o) { T result = (T) ReflectUtils.newInstance(clazz); if (result == null) { return result; } Map<String, Object> resultMap = o.toMap(); for (Entry<String, Object> entry : resultMap.entrySet()) { String key = entry.getKey(); Object val = entry.getValue(); Method writeMethod = writeMethods.get(key); try { writeMethod.invoke(result, convert(val, key)); } catch (Exception e) { throw new DataAccessException("映射数据失败:", e); } } return result; }
5b962bbf-fb21-45d5-9582-288e99ff9e81
5
private void createD(String in1, String out) { DFlipFlop d = new DFlipFlop(); // Connect the first input // Check if the in wire is an input if (stringToInput.containsKey(in1)) { Wire inWire = new Wire(); stringToInput.get(in1).connectOutput(inWire); d.connectInput(inWire); } // Check if the in wire is an output else if (stringToOutput.containsKey(in1)) { Wire inWire = new Wire(); stringToOutput.get(in1).connectOutput(inWire); d.connectInput(inWire); } // Check if the in wire is just a wire already known to the circuit else if (stringToWire.containsKey(in1)) d.connectInput(stringToWire.get(in1)); else MainFrame.showError("Error, the wire " + in1 + " isn't in the circuit"); // Connect the output // Check if the in wire is an output if (stringToOutput.containsKey(out)) { Wire outWire = new Wire(); stringToOutput.get(out).connectInput(outWire); d.connectOutput(outWire); } // Check if the in wire is just a wire already known to the circuit else if (stringToWire.containsKey(out)) d.connectOutput(stringToWire.get(out)); else MainFrame.showError("Error, the wire " + out + " isn't in the circuit"); flipflops.add(d); }
95dc5ef2-0503-4350-8825-2141d48299d5
0
@Override public void endAddSubContainer(Container c) { containerStack.remove(containerStack.size() - 1); AbstractPreferencesPanel.addSingleItemCentered((JComponent) c, getCurrentContainer()); }
7e1f407d-4187-4644-9766-a05270fd827a
2
private static void printTerrainTable(ArrayList<ParkerPaulTaxable> taxables) { double totalTaxes = 0.00; // total taxes for items double minTaxes = -1.00; // min taxes for items double maxTaxes = 0.00; // max taxes for items int count = 0; // count of items printTerrainHeader(); for (ParkerPaulTaxable taxable : taxables) { if ((taxable instanceof ParkerPaulTerrain)) { // accumulate footer values double tax = taxable.getTax(); // tax for item totalTaxes += tax; minTaxes = getMinTax(minTaxes, tax); maxTaxes = Math.max(maxTaxes, tax); count++; // print info for item printTerrainInfo((ParkerPaulTerrain) taxable, count); } } printFooter(totalTaxes, minTaxes, maxTaxes, count); }
0ff257a2-84f9-4270-a88c-22bb1b936ba9
2
public static void main(String [] args) { String[] paths = new String[]{ "samples/testseq100000.gif", "samples/testseq100007.gif", "samples/testseq100136.gif", "samples/testseq100192.gif", }; try { for (String path : paths) { System.out.println(path); // start the timer so we can print sub times Timer timer = new Timer(); BufferedImage image = ImageIO.read(new File(path)); timer.print("image load"); Collection<Circle> circles = CircleDetection.detect(image); timer.print("circle detection"); PopUp.show(CircleAdder.combine(image, circles), path); timer.print("popup"); System.out.printf("Detected: %d circles. %n%n", circles.size()); } } catch (IOException e) { e.printStackTrace(); } }
6735a291-3d38-42c7-b6d8-971890cfb62c
9
public void readCommand() throws InvalidComException, IncorrectNumException{ if (command[0].equals("addplayer")) { comAddplayer(true); } else if (command[0].equals("removeplayer")) { comRemoveplayer(); } else if (command[0].equals("editplayer")) { comEditplayer(); } else if (command[0].equals("resetstats")) { comResetstats(); } else if (command[0].equals("displayplayer")) { comDisplayplayer(); } else if (command[0].equals("rankings")) { comRankings(); } else if (command[0].equals("startgame")) { comStartgame(); } else if (command[0].equals("exit")) { comExit(); } else if (command[0].equals("addaiplayer")){ comAddplayer(false); } else { throw new InvalidComException(); } }
1b11116c-9474-468b-8867-12a90faf1b1d
8
public void finishLoadingGeography() { Vector<VTD> features = featureCollection.features; System.out.println(features.size()+" precincts loaded."); getMinMaxXY(); System.out.println("Initializing wards..."); featureCollection.initFeatures(); dlbl.setText("Setting min and max coordinates..."); getMinMaxXY(); resetZoom(); dlbl.setText("Initializing ecology..."); try { //featureCollection.initEcology(); addEcologyListeners(); } catch (Exception ex) { System.out.println("init ecology ex: "+ex); ex.printStackTrace(); } System.out.println("resize ex1"); try { featureCollection.ecology.resize_population(); //featureCollection.loadDistrictsFromProperties(""); } catch (Exception ex) { System.out.println("resize ex: "+ex); ex.printStackTrace(); } System.out.println("filling combo boxes..."); fillComboBoxes(); mapPanel.invalidate(); mapPanel.repaint(); System.out.println("resize ex2"); try { featureCollection.ecology.resize_population(); //featureCollection.loadDistrictsFromProperties(""); } catch (Exception ex) { System.out.println("resize ex2: "+ex); ex.printStackTrace(); } setDistrictColumn(project.district_column); //featureCollection.loadDistrictsFromProperties(project.district_column); System.out.println("resize ex3"); try { featureCollection.ecology.resize_population(); //featureCollection.loadDistrictsFromProperties(""); } catch (Exception ex) { System.out.println("resize ex3: "+ex); ex.printStackTrace(); } mapPanel.featureCollection = featureCollection; mapPanel.invalidate(); mapPanel.repaint(); //featureCollection.ecology.mapPanel = mapPanel; //featureCollection.ecology.statsPanel = panelStats; addEcologyListeners(); System.out.println("resize ex4"); try { featureCollection.ecology.resize_population(); //featureCollection.loadDistrictsFromProperties(""); } catch (Exception ex) { System.out.println("resize ex3: "+ex); ex.printStackTrace(); } dlg.setVisible(false); System.out.println("Ready."); geo_loaded = true; System.out.println("resize_population start0 "+ (featureCollection.ecology.population == null ? "null" : featureCollection.ecology.population.size())); setEnableds(); System.out.println("resize_population start1 "+ (featureCollection.ecology.population == null ? "null" : featureCollection.ecology.population.size())); project.demographic_columns.clear(); setDemographicColumns(); /* System.out.println("resize_population start2 "+ (featureCollection.ecology.population == null ? "null" : featureCollection.ecology.population.size())); project.election_columns.clear(); setElectionColumns(); System.out.println("resize_population start3 "+ (featureCollection.ecology.population == null ? "null" : featureCollection.ecology.population.size())); project.election_columns_2.clear(); setElectionColumns2(); System.out.println("resize_population start4 "+ (featureCollection.ecology.population == null ? "null" : featureCollection.ecology.population.size())); project.election_columns_3.clear(); setElectionColumns3(); System.out.println("resize_population start5 "+ (featureCollection.ecology.population == null ? "null" : featureCollection.ecology.population.size())); project.substitute_columns.clear(); setSubstituteColumns(); */ System.out.println("resize ex5"); try { featureCollection.ecology.resize_population(); //featureCollection.loadDistrictsFromProperties(""); } catch (Exception ex) { System.out.println("resize ex3: "+ex); ex.printStackTrace(); } }
015e40b2-6b1b-4cca-957c-2261612601f4
8
public static Stella_Object lookupDeferredQueryOption(Stella_Object queryoroptions, Keyword key, Surrogate coercetotype) { { PropertyList options = null; PropertyList deferredoptions = null; Stella_Object value = null; Stella_Object coercedvalue = null; boolean processeddeferredoptionP = false; { Surrogate testValue000 = Stella_Object.safePrimaryType(queryoroptions); if (Surrogate.subtypeOfP(testValue000, Logic.SGT_STELLA_PROPERTY_LIST)) { { PropertyList queryoroptions000 = ((PropertyList)(queryoroptions)); options = queryoroptions000; } } else if (Surrogate.subtypeOfP(testValue000, Logic.SGT_LOGIC_QUERY_ITERATOR)) { { QueryIterator queryoroptions000 = ((QueryIterator)(queryoroptions)); options = queryoroptions000.options; } } else { { OutputStringStream stream000 = OutputStringStream.newOutputStringStream(); stream000.nativeStream.print("`" + testValue000 + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace())); } } } deferredoptions = ((PropertyList)(options.lookup(Logic.KWD_DEFERRED_OPTIONS))); if (deferredoptions != null) { value = deferredoptions.lookup(key); if (value == null) { value = options.lookup(key); } else { processeddeferredoptionP = true; } if (value != null) { if (coercetotype != null) { coercedvalue = Stella_Object.coerceOptionValue(value, coercetotype); if (coercedvalue == null) { { OutputStringStream stream001 = OutputStringStream.newOutputStringStream(); { Object old$PrintreadablyP$000 = Stella.$PRINTREADABLYp$.get(); try { Native.setBooleanSpecial(Stella.$PRINTREADABLYp$, true); stream001.nativeStream.println("PARSING ERROR: Illegal `" + key + "' value: `" + value + "'."); Logic.helpSignalPropositionError(stream001, Logic.KWD_ERROR); } finally { Stella.$PRINTREADABLYp$.set(old$PrintreadablyP$000); } } throw ((ParsingError)(ParsingError.newParsingError(stream001.theStringReader()).fillInStackTrace())); } } else { value = coercedvalue; } } if (processeddeferredoptionP) { deferredoptions.removeAt(key); options.insertAt(key, value); } } } return (value); } }
4ae00955-13d4-4be5-9c13-b46016906843
7
public void stateChanged(String s) { if (s.equals(VisibleTimer.START)) { enableEdits(false); String answerList[] = new String[answers.length]; for (int i = 0; i < answerList.length; i++) answerList[i] = answers[i].getAnswer(); model.broadcastQuestion(question.getText(), answerList); if (!timer.isActive()) model.resetClickers(); } else if (s.equals(VisibleTimer.PAUSE) || s.equals(VisibleTimer.CANCEL)) enableEdits(true); else if (s.equals(VisibleTimer.SUBMIT) || s.equals(VisibleTimer.EXPIRED)) { stats = new GClickerStats(this, model); model.resetClickers(); enableEdits(true); } }
c04684cd-c285-4e42-b672-26d9980d0809
0
public MealyNondeterminismDetector() { }
6b4e534d-572b-4a41-88fc-e3c7bd3cfa37
9
public void update(Graphics g) { Dimension dim = getSize(); Insets insets = getInsets(); g.setColor(getBackground()); int x = insets.left; int y = insets.top; int w = dim.width - insets.left - insets.right; int h = dim.height - insets.top - insets.bottom; g.fillRect(x, y, w, h); float scale = w / (upperBound - lowerBound); if (type == ABSORPTION) { float leftEdge = 0; float rightEdge = 0; float start = 0; float end = 0; if (lowerBound < Photon.MIN_VISIBLE_FREQ) { leftEdge = (Photon.MIN_VISIBLE_FREQ - lowerBound) * scale; start = Photon.MIN_VISIBLE_FREQ; } else { leftEdge = x; start = lowerBound; } if (upperBound > Photon.MAX_VISIBLE_FREQ) { rightEdge = dim.width - insets.right - (upperBound - Photon.MAX_VISIBLE_FREQ) * scale; end = Photon.MAX_VISIBLE_FREQ; } else { rightEdge = w; end = upperBound; } int min = (int) ((start - Photon.MIN_VISIBLE_FREQ) / ZONE_WIDTH); int max = (int) ((end - Photon.MIN_VISIBLE_FREQ) / ZONE_WIDTH); int del = (int) ((rightEdge - leftEdge) / (max - min - 1)); float x1 = 0; Graphics2D g2 = (Graphics2D) g; g2.setPaint(new GradientPaint(leftEdge - del, 0, getBackground(), leftEdge, 0, Photon.COLOR[0])); g2.fillRect((int) (leftEdge - del), y, del, h); for (int i = min; i < max - 1; i++) { x1 = leftEdge + del * (i - min); g2.setPaint(new GradientPaint(x1, 0, Photon.COLOR[i], x1 + del, 0, Photon.COLOR[i + 1])); g2.fillRect((int) x1, y, del, h); } g2.setPaint(new GradientPaint(x1 + del, 0, Photon.COLOR[6], x1 + del * 2, 0, getBackground())); g2.fillRect((int) (x1 + del), y, del, h); } g.setColor(Color.gray); float d = (float) w / (float) ntick; for (int i = 0; i <= ntick; i++) { g.drawLine((int) (x + i * d), y + h, (int) (x + i * d), y + h - 5); } if (!lineMap.isEmpty()) { if (type == ABSORPTION) { synchronized (lineMap) { g.setColor(Color.black); for (Float a : lineMap.keySet()) { x = (int) (a * scale); g.drawLine(x, insets.top, x, dim.height - insets.bottom); } } } else { synchronized (lineMap) { for (Float a : lineMap.keySet()) { g.setColor(getColor(a)); x = (int) (a * scale); g.drawLine(x, insets.top, x, dim.height - insets.bottom); } } } } }
bbf7512f-14dc-478d-8b30-054089ac82a3
2
public int promptRemoveDirectoryFromPath(String directory,Exception e) { if (e instanceof NullPointerException) { return jopDependency.showConfirmDialog(null, String.format("Couldn't match the following path with any environment variables. Do you wish to remove it?\n%s", directory), "Remove invalid directory from path enviroment", JOptionPane.YES_NO_OPTION); } else if (e instanceof IOException) { return jopDependency.showConfirmDialog(null, String.format("The following path is invalid. Do you wish to remove it?\n%s", directory), "Remove invalid directory from path enviroment", JOptionPane.YES_NO_OPTION); } return 0; }
15645ff0-fd66-457a-8350-02c3bfa03314
1
public void test_append_Printer_nullParser() { DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder(); bld.appendLiteral('Y'); DateTimePrinter p = bld.toPrinter(); try { DateTimeFormatterBuilder bld2 = new DateTimeFormatterBuilder(); bld2.append(p, (DateTimeParser) null); fail(); } catch (IllegalArgumentException ex) { // expected } }
a12f4e6c-b85c-4730-aa38-2e82bac5f756
2
@Override public void Execute(Session mSession, String[] Arguments) { if (Arguments.length == 0) { mSession.SendAlert("You didn't specify a plugin to destroy!", null); return; } if (Grizzly.GrabPluginHandler().DestructPlugin(mSession, Arguments[0])) { mSession.GrabActor().Speak("*Disables the plugin " + Arguments[0] + "*", true); } }
335044e4-2d9b-44e3-a967-405c774d8ad1
5
private static void processClientChoice(int choice) { String testName; String studentName; String studentSurname; switch (choice) { case 1: listTests(); break; case 2: System.out.println("Enter test name:"); testName = input.nextLine(); listQuestions(testName); break; case 3: System.out.println("Enter test name"); testName = input.nextLine(); System.out.println("Enter student name"); studentName = input.nextLine(); System.out.println("Enter student surname"); studentSurname = input.nextLine(); showTestResult(testName, studentName, studentSurname); break; case 4: System.out.println("Enter test name"); testName = input.nextLine(); System.out.println("Enter student name"); studentName = input.nextLine(); System.out.println("Enter student surname"); studentSurname = input.nextLine(); assignTestAndSaveTestResult(testName, studentName, studentSurname); break; case 0: isExit = true; break; default: logger.error("WRONG NUMBER! TRY AGAIN!"); } }
2c8710c1-cdea-437c-aad7-35b4b0c0fb0e
6
public static void main(String args[]) { 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(Gui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Gui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Gui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Gui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Gui().setVisible(true); } }); }
a6c5e35e-df67-4f47-993b-4d0a821d59c7
9
public boolean findPath(int X, int Y, ArrayList<Point> path, Hashtable<Point, Boolean> cache) { Point p = new Point(X, Y); if (cache.containsKey(p)) return cache.get(p); // already visit the cell if (X == 0 && Y == 0) return true; // already find a path boolean success = false; if (X >= 1 && isFree(X - 1, Y)) success = findPath(X-1, Y, path, cache); if (!success && Y >= 1 && isFree(X, Y - 1)) success = findPath(X, Y-1, path, cache); if (success) path.add(p); cache.put(p, success); return success; }
71d2b450-662f-4b8f-96e4-25f9aa650bc0
5
@Override public void actionPerformed(final ActionEvent e) { if (e.getSource() == bHint) { ArrayList<Integer> moves = client.getAIMove(); int pcx = moves.get(0); int pcy = moves.get(1); int pct = moves.get(2); String pcc = "any"; if (moves.get(3) == 0) { pcc = "RED"; } else if (moves.get(3) == 1) { pcc = "BLUE"; } else if (moves.get(3) == 0) { pcc = "GREEN"; } else if (moves.get(3) == 0) { pcc = "YELLOW"; } JOptionPane.showMessageDialog(null, "Place color: " + pcc + " type:" + pct + " on: (" + pcx + "," + pcy + ")"); } }
b7a2e326-3608-4854-b333-9caa2a5af01a
8
private void favorite(HttpServletRequest request, HttpServletResponse response,UserBean user) throws ServletException, IOException { List<String> errors = new ArrayList<String>(); FavoriteForm form = new FavoriteForm(request); if (!form.isPresent() && form.getFavoriteId() == null) { outputList(response,form,null,user); return; } errors.addAll(form.getValidationErrors()); if (errors.size() != 0) { outputList(response,form,errors,user); return; } try { FavoriteBean bean; if(form.isPresent() && form.getButton().equals("Add Favorite")) { bean = new FavoriteBean(); bean.setId(user.getId()); bean.setUrl(form.getUrl()); bean.setComments(form.getComments()); bean.setCount(0); hw8DAO.create(bean); outputList(response,form,errors,user); } else if(form.isPresent() && form.getButton().equals("Logout")) { HttpSession session = request.getSession(); session.removeAttribute("user"); login(request,response); } else { hw8DAO.updateCount(Integer.parseInt(form.getFavoriteId())); outputList(response,form,errors,user); } } catch (MyDAOException e) { errors.add(e.getMessage()); outputList(response,form,errors,user); } }
84e6db74-a317-40ca-a5b0-5270a0a36849
5
private void rotateRight(Node u) { int hookType; if (root == u) hookType = 0; else if (u == u.parent.left) hookType = -1; else hookType = 1; Node nodesLeft = u.left; Node leftsRight = nodesLeft.right; nodesLeft.right = u; if (hookType == 0) root = nodesLeft; else { nodesLeft.parent = u.parent; if (hookType == -1) u.parent.left = nodesLeft; else u.parent.right = nodesLeft; } u.left = leftsRight; if (leftsRight != null) leftsRight.parent = u; u.parent = nodesLeft; }
15d35887-e2d4-4417-af98-2809c6e016a0
3
public int getTotalBlocksPlaced(String playerName) { int totalBlocksPlaced = 0; try { ResultSet rs = _sqLite.query("SELECT total(blocks_placed) " + "AS total_blocks_placed " + "FROM player, login " + "WHERE player.playername = '" + playerName + "' " + "AND player.id = login.id_player;"); if (rs.next()) { try { totalBlocksPlaced = rs.getInt("total_blocks_placed"); } catch (SQLException e) { e.printStackTrace(); } } } catch (SQLException e) { e.printStackTrace(); } return totalBlocksPlaced; }
35c1de83-b0af-44cb-9859-ddb8ef76e1d8
1
public static void main(String args[]){ Deal deal=new Deal(); PrestataireDeService p = new PrestataireDeService(); p.setIdUser(2); deal.setDescriptif("un descriptif test"); deal.setCategorie("mm"); deal.setTypeDeal("Produit"); deal.setDateDebut("27/02/2013"); deal.setPrixInitial(111.2); deal.setPrixPromotionnel(11.8); deal.setPrestataireDeService(p); DealDAO dealDAO =new DealDAO(); // //test ajout réussi dealDAO.AjouterDeal(deal); deal.setIdDeal(5); // test update réussi deal.setTypeDeal("Service"); deal.setDateFin("28-02-2014"); dealDAO.ModifierDeal(deal); //test delete réussi // System.out.println(dealDAO.SupprimerDeal(deal)); // List<Deal> l = dealDAO.ListerDeals(); // // for (int i=0; i< l.size();i++) // { // System.out.println(l.get(i).getCategorie()+" "+l.get(i).getTypeDeal()); // } // System.out.println(dealDAO.RechercheParId(5).getDateDebut()); // System.out.println(dealDAO.SupprimerDeal(deal)); List<Deal> l = dealDAO.rechercherParCategorie("vêtement"); System.out.println(l.size()); for (int i=0; i< l.size();i++) { System.out.println(l.get(i).getDateFin()+" "+l.get(i).getTypeDeal()); } }
03bf9589-13f9-4d04-898e-3aa65373c263
3
public void fromJSONObject(JSONObject o) { try { setFirstName((String) o.remove(KEY_FIRST_NAME)); setLastName((String) o.remove(KEY_LAST_NAME)); setID((String) o.remove(KEY_ID)); setPoints(Utils.numToInt(o.remove(KEY_POINTS))); String id = (String) o.remove(KEY_WEEKLY_PICK_ID); Contestant c = null; GameData g = GameData.getCurrentGame(); if (id.equals(Contestant.NULL_ID)) { c = new Contestant(); c.setNull(); } else { c = g.getContestant(id); } setWeeklyPick(c); id = (String) o.remove(KEY_ULT_PICK_ID); if (id.equals(Contestant.NULL_ID)) { c = new Contestant(); c.setNull(); } else { c = g.getContestant(id); } setUltimatePick(c); setUltimatePoints(Utils.numToInt(o.remove(KEY_WIN_PICK_POINTS))); setNumBonusAnswer(((Number) o.remove(KEY_NUM_BONUS_ANSWER)).intValue()); } catch (InvalidFieldException e) { System.out.println("Warning: InvalidFieldException in fromJSONObject"); e.printStackTrace(); } }
94e8e40d-b604-48bd-a9c5-ab117c618f4b
0
protected void _setConfigFile(File config_file) { this.config_file = config_file; }
eef5d401-af03-48b3-9dbc-95f5ede71794
6
protected boolean ist_angrenzendes_Land_verschieben(Land frage_Land, Spieler aktuellerSpieler, List<Land> gepruefte_laender){ for (int i=0;i<angrenzendeLaender.length; i++){ if (angrenzendeLaender[i]==frage_Land) return true; } gepruefte_laender.add(this); boolean ist_angrenzend=false; for (int i=0;i<angrenzendeLaender.length; i++){ if ((angrenzendeLaender[i].gib_besitzer()==aktuellerSpieler) && (!(gepruefte_laender.contains(angrenzendeLaender[i]))) && (ist_angrenzend==false)){ ist_angrenzend = angrenzendeLaender[i].ist_angrenzendes_Land_verschieben(frage_Land, aktuellerSpieler, gepruefte_laender); } } return ist_angrenzend; }
5856b4d4-e923-451c-a64b-a61eb4a546fa
0
public void setTotal(double total) { this.total = total; }
b9af7bfb-2e12-42ce-aef6-8b8639008737
0
public Location(int row, int col) { this.row = row; this.col = col; }
6466f794-e748-47b2-b6f6-681ecbef2653
6
public void reserveRoundTripTicket() { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.out.println("Where is your MySQL JDBC Driver?"); e.printStackTrace(); } PreparedStatement ps = null; Connection con = null; ResultSet rs; try { con = DriverManager.getConnection("jdbc:mysql://mysql2.cs.stonybrook.edu:3306/mlavina", "mlavina", "108262940"); if (con != null) { con.setAutoCommit(false); String sql = "SELECT max(ResrNo) FROM reservation;"; ps = con.prepareStatement(sql); try { ps.execute(); rs = ps.getResultSet(); int resrNo = -1; if (rs.next()) { resrNo = rs.getInt(1) + 1; } sql = "Insert into passenger (Id, AccountNo) values (?,?) ON DUPLICATE KEY UPDATE Id=Id;"; ps = con.prepareStatement(sql); ps.setInt(1, personID); ps.setInt(2, accountNo); ps.execute(); sql = "INSERT INTO Reservation VALUES (?, ?, ?, ?, ?,?); "; double fare = selectedFlight.fare + selectedReturnFlight.fare; ps = con.prepareStatement(sql); ps.setInt(1, resrNo); ps.setTimestamp(2, new java.sql.Timestamp(new Date().getTime())); ps.setDouble(3, (fare * .10)); ps.setDouble(4, fare); ps.setInt(5, employeeSSN); ps.setInt(6, accountNo); ps.execute(); sql = "INSERT INTO Includes VALUES (?, ?, ?, ?, ?);"; ps = con.prepareStatement(sql); ps.setInt(1, resrNo); ps.setString(2, selectedFlight.airlineID); ps.setInt(3, selectedFlight.flightNo); ps.setInt(4, selectedFlight.legNo); ps.setDate(5, new java.sql.Date(selectedReturnFlight.deptTime.getTime())); ps.execute(); sql = "INSERT INTO Includes VALUES (?, ?, ?, ?, ?);"; ps = con.prepareStatement(sql); ps.setInt(1, resrNo); ps.setString(2, selectedReturnFlight.airlineID); ps.setInt(3, selectedReturnFlight.flightNo); ps.setInt(4, selectedReturnFlight.legNo); ps.setDate(5, new java.sql.Date(selectedReturnFlight.deptTime.getTime())); ps.execute(); sql = "INSERT INTO ReservationPassenger VALUES(?, ?, ?, ?, ?, ?);"; ps = con.prepareStatement(sql); ps.setInt(1, resrNo); ps.setInt(2, personID); ps.setInt(3, accountNo); ps.setString(4, ("" + seatNo)); ps.setString(5, selectedFlight.seatClass); ps.setString(6, mealPreference); ps.execute(); con.commit(); } catch (Exception e) { con.rollback(); } } } catch (Exception e) { System.out.println(e); } finally { try { con.setAutoCommit(true); con.close(); ps.close(); } catch (Exception e) { e.printStackTrace(); } } }