method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
05f403a5-744b-4af9-a0fc-82bfbf37b2fe
8
@Override public boolean equals(Object o) { if (this == o){ return true; } if (!(o instanceof Position)){ return false; } Position p = (Position) o; if (point == null) { if (p.point != null) return false; } else if (!point.equals(p.point)) return false; if (room == null) { if (p.room != null) return false; } else if (!room.equals(p.room)) return false; return true; }
9fa526ed-7a95-4a29-8222-ce55d80ede8d
2
public static HttpServletRequest login(HttpServletRequest request) { Models.DatabaseModel.User user = new Models.DatabaseModel.User(); String username = request.getParameter("username"); String password = request.getParameter("password"); if(validLoginParameters(username, password)){ user.findUser(username, password); } if (user.getID() > 0) { request.getSession().setAttribute("user", user); request.setAttribute("view", "homepage.jsp"); } else { request.getSession().invalidate(); request.setAttribute("view", "error404.jspf"); } return request; }
f52d2a94-481a-4dc7-ad52-1f4d0c864f2e
9
public FloatElement[] getSortedSimilarWords(String word) throws Exception{ int index = model1.index(word); FloatElement[] similarWords = new FloatElement[model1.sizeOfVocabulary]; for (int i=0; i<model1.sizeOfVocabulary; i++){ float pmi1 = 0; float pmi2 = 0; float similarity = Float.NEGATIVE_INFINITY; try { pmi2 = model2.getPMI(index, i); //if (pmi2 < BASE_PMI) pmi2 = BASE_PMI; } catch (Exception e) { // if not exist in the smaller window try { pmi1 = model1.getPMI(index, i); if (REMOVE_NON_FREQUENT_WORDS && model1.getFrequency(i) < model1.FREQUENCY_LIMIT) similarity = 0; // exclude rarely appearing words else{ //similarity = 0; similarity = combinedPMI(pmi1, BASE_PMI); /* if (model1.getCoOccurrence(index, i) > 10) similarity = combinedPMI(pmi1, BASE_PMI); else similarity = pmi1; // + CORPUS_PMI_DELTA; */ } } catch (Exception e2) { // TODO Auto-generated catch block similarity = 0; } } if (similarity == Float.NEGATIVE_INFINITY){ try { pmi1 = model1.getPMI(index, i); if (REMOVE_NON_FREQUENT_WORDS && model1.getFrequency(i) < model1.FREQUENCY_LIMIT) similarity = 0; // exclude rarely appearing words else similarity = combinedPMI(pmi1, pmi2); } catch (Exception e) { // TODO Auto-generated catch block //throw new Exception("Error in program! The two words " + word + " " + model1.vocabulary[i] + " do not co-occur in the bigger window but co-occur in the smaller window"); similarity = 0; } } FloatElement element = new FloatElement(model1.vocabulary[i], similarity); similarWords[i] = element; } Arrays.sort(similarWords); return similarWords; }
2930f92f-8ff1-48bf-aa4a-e9c924313dcd
4
private boolean memeChecker(String currentText) { boolean isAMeme = false; for (String currentMeme : memeList) { if (currentMeme.equalsIgnoreCase(currentText)) { isAMeme = true; } } for (int loopCount = 0; loopCount < memeList.size(); loopCount++) { if (memeList.get(loopCount).equalsIgnoreCase(currentText)) { isAMeme = true; } } return isAMeme; }
405ddfa3-22a4-4ac8-a8d5-988739bf88dd
8
@SuppressWarnings("resource") public TestRecord getMedicalTest(DataSource ds) { while (true) { System.out.print("Back = 0. Enter name or health care number of patient: "); Scanner s = new Scanner(System.in); String patient_info = s.nextLine(); try { int option = Integer.parseInt(patient_info); if (option == 0) { return null; } } catch (Exception e) { } ResultSet rs = ds.checkRecord(patient_info); Vector<TestRecord> records = ds.getRecordList(rs); int isExist = records.size(); System.out.println("size: " + isExist); if (isExist == 0) { System.out.println("Nothing."); continue; } else { Helper.printRecords(records); if (isExist > 1) { while(true){ System.out.print("Enter test id: "); int id = new Scanner(System.in).nextInt(); for(TestRecord t : records){ if(t.getTest_id() == id){ return t; } } } } else { return records.listIterator(0).next(); } } } }
b7a7a965-0756-4df4-b0ee-81eea6485087
4
public void bringToFront(int index) { /* illegal index or bring the first node */ if (index >= numElements || index <= 0) { return; } int currentIndex = 0; SingleNode cursor = head; while (cursor != null) { if (currentIndex == index - 1) { /* node to be moved to the front */ SingleNode temp = cursor.next; cursor.next = cursor.next.next; temp.next = head; head = temp; return; } cursor = cursor.next; currentIndex++; } }
39ba5362-972f-4d96-b128-22765499bc2d
0
public long getType() { return this._type; }
fbfbc5e2-88f1-449b-a54f-f2da1def0167
0
public Integer getPassRate() { return this.passRate; }
c3ef122e-9a7c-49e3-8320-798845869992
6
public void startGame(int numPlayers) { removeAllPanels(); GameController game = new GameController(numPlayers); ViewController view = new ViewController(game, frame); ControlController control = new ControlController(game, playerKeyCodes); if (soundActive) { SoundController sound = new SoundController(game); if(isChristmas) sound.setBgFile("sounds/christmas.wav"); } //added for compliance with assignment game2 = game; if (numPlayers == 1){ frame.addMouseListener(new MouseListener(){ @Override public void mouseClicked(MouseEvent e) { switch (e.getButton()){ case MouseEvent.BUTTON1: game2.getPlayer(1).moveLeft(); break; case MouseEvent.BUTTON2: game2.getPlayer(1).rotatePiece(); break; case MouseEvent.BUTTON3: game2.getPlayer(1).moveRight(); break; } } @Override public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } }); } game.startGame(); }
82692e9f-8425-40c4-8d8f-fa480d791ca3
4
private Msg xxrecv (int flags_) { Msg msg_ = null; // If there is a prefetched message, return it. if (prefetched) { msg_ = prefetched_msg ; prefetched = false; prefetched_msg = null; return msg_; } // DEALER socket doesn't use identities. We can safely drop it and while (true) { msg_ = fq.recv (); if (msg_ == null) return msg_; if ((msg_.flags () & Msg.identity) == 0) break; } return msg_; }
e9dbea9e-1d5c-459f-820a-35164586c19e
6
public Vertex<V, E> next() { this.previousVertex = this.nextVertex; Vertex<V, E> currentVertex = null; Iterator<Edge<V, E>> curEdgeIter = null; Vertex<V, E> unvisitedVertex = null; while (!this.edgeIters.isEmpty()) { currentVertex = this.edgeIters.peek().getKey(); curEdgeIter = this.edgeIters.peek().getValue(); unvisitedVertex = this.nextUnvisitedVertex(currentVertex, curEdgeIter); if (unvisitedVertex != null) { this.setNextVertex(unvisitedVertex); break; } else { vertexTimings.get(currentVertex)[1] = ++time; this.edgeIters.pop(); } } if (this.edgeIters.isEmpty()) { Vertex<V, E> v = this.nextUnvisitedVertex(); if (v != null && vertexTimings.get(v)[0] == -1) this.setNextVertex(v); else this.nextVertex = null; } if (this.verbose) System.out.println(this.currentStateInfo()); return this.previousVertex; }
c838c944-d6b7-409e-9392-e879283f61f1
3
@RequestMapping(value = "/{contactId}", method = RequestMethod.DELETE, produces = "application/json") public ResponseEntity<?> delete(@PathVariable("contactId") int contactId, @RequestParam(required = false) String searchFor, @RequestParam(required = false, defaultValue = DEFAULT_PAGE_DISPLAYED_TO_USER) int page, Locale locale) { try { contactService.delete(contactId); } catch (AccessDeniedException e) { return new ResponseEntity<Object>(HttpStatus.FORBIDDEN); } if (isSearchActivated(searchFor)) { return search(searchFor, page, locale, "message.delete.success"); } return createListAllResponse(page, locale, "message.delete.success"); }
62252a62-463c-410f-baa2-d0fd70a6e396
0
public final void setLineIncrement(double increment) { incrementWidth = increment; parametersToNumbers.put("lineIncrement", new Double(increment)); }
fe6f92b0-0124-4369-a8de-d9517cf662e1
7
@Override public void init() { /* 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(HMPView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(HMPView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(HMPView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(HMPView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the applet */ try { java.awt.EventQueue.invokeAndWait(new Runnable() { public void run() { initComponents(); } }); } catch (Exception ex) { ex.printStackTrace(); } }
6d11977f-73de-43bc-b5fa-d30d0b296649
8
public static void GUI(){ //Every player's action list default values for (int i = 0; i < 5; i++){ for (int j = 0; j < 12; j++){ actionAll[i][j] = -1; } } raam = new JFrame("Raam"); raam.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); raam.setSize(1280, 800); raam.setLayout(null); //actionCard-ide icon-id for (int i = 0; i < 24; i++){ actionCards[i] = new ImageIcon((String)("src/img/action" + i + ".png")); } iconsFromFolder(threatCards, "src/img/spaceAlertPictures/threats/external"); iconsFromFolder(threatCards_v, "src/img/spaceAlertPictures/threats/external/v"); iconsFromFolder(inthreatCards, "src/img/spaceAlertPictures/threats/internal"); iconsFromFolder(inthreatCards_v, "src/img/spaceAlertPictures/threats/internal/v"); iconsFromFolder(sthreatCards, "src/img/spaceAlertPictures/threats/sExternal"); iconsFromFolder(sthreatCards_v, "src/img/spaceAlertPictures/threats/sExternal/v"); iconsFromFolder(sinthreatCards, "src/img/spaceAlertPictures/threats/sInternal"); iconsFromFolder(sinthreatCards_v, "src/img/spaceAlertPictures/threats/sInternal/v"); iconsFromFolder(playerIcons, "src/img/spaceAlertPictures/players"); iconsFromFolder(glowIcons, "src/img/spaceAlertPictures/glow"); iconsFromFolder(tokenIcons, "src/img/spaceAlertPictures/Token"); for (int i = 0; i < 5; i++) { glows[i] = new JLabel(glowIcons[i]); glows[i].setBounds(-100, -100, 50, 80); raam.add(glows[i]); } bg = new JLabel(icon1); nextPage = new JLabel(new ImageIcon("src/img/nextPage.png")); nextPage.setBounds(710 + 9*55, 630, 30, 30); nextPage.addMouseListener(new PageListener()); raam.add(nextPage); previousPage = new JLabel(new ImageIcon("src/img/previousPage.png")); previousPage.setBounds(710, 630, 30, 30); previousPage.addMouseListener(new PageListener()); raam.add(previousPage); //lane-id vasakule for (int i = 0; i < 4; i++){ lane[i] = new JLane(icon2, i, 15, 4, new int[]{8, 11}); raam.add(lane[i]); lane[i].setBounds(5 + i*55, 5, 50, 588); } //slotid alla int phase = 1; for (int i = 0; i < 12; i++){ if (i == 3 || i == 7) phase += 1; action.add(i, new ActionSlot(icon6, phase, i)); } updateField(); raam.add(new JLabel()); raam.add(bg); bg.setBounds(230, 5, 800, 588); raam.setVisible(true); }
6a96c135-3758-458d-a581-993d1d9cdf9e
4
public java.lang.Object get(int field$) { switch (field$) { case 0: return names; case 1: return name; case 2: return favorite_number; case 3: return favorite_color; default: throw new org.apache.avro.AvroRuntimeException("Bad index"); } }
1eb1c61e-2074-4520-8905-65e08c05fe78
3
@Override public void run() { try { byte[] dlen = new byte[4]; System.out.println(socket.getRemoteSocketAddress() + " connected."); in = new DataInputStream(socket.getInputStream()); out = new DataOutputStream(socket.getOutputStream()); while (true) { in.readFully(dlen); ArrayReader r = new ArrayReader(dlen); int len = r.readInt(); byte[] packet = new byte[len]; in.readFully(packet); server.handlePacket(packet, this); } } catch (IOException ex) { ex.printStackTrace(); } for (File f : lockedFiles) f.endEdit(this); System.out.println(socket.getRemoteSocketAddress() + " disconnected."); }
ce98fb95-5ec2-4fc7-acdd-f41864efe85f
3
public void drawGrid(Game game, Graphics2D g2d, int[] screen) { int hexWidth = screen[0]/8; int hexHeight = hexWidth/8*9; g2d.setColor(COLORS[1]); boolean off = false; g2d.translate(-hexWidth*2+hexWidth/2,-hexHeight/9*7); for(int y = 0; y < game.grid.getHeight(); y++) { int leftOffset = 0; if(off) { off = false; leftOffset = -hexWidth/2; } else { off = true; } for(int x = 0; x < game.grid.getWidth(); x++) { Tile tile = game.grid.getTile(x,y); drawTile(tile,g2d,hexWidth*x+leftOffset,hexHeight/9*7*y,hexWidth,hexHeight,game.menu); } } g2d.translate(hexWidth*2-hexWidth/2,hexHeight/9*7); }
64a0da58-63fb-4988-89c7-4fe3084b61d2
6
public void paint(Graphics g){ Graphics2D g2d = (Graphics2D)g; at.setToTranslation(x, y); if(ax>0 && !isLanding) at.rotate(Math.toRadians(-angle), 3.5, 8); else if(ax>0 && isLanding) at.rotate(Math.toRadians(-angleDown), 3.5, 8); else if(ax<0 && !isLanding) at.rotate(Math.toRadians(angle), 3.5, 8); else at.rotate(Math.toRadians(angleDown), 3.5, 8); g2d.drawImage(arrow, at, null); }
5366778f-ac25-4449-8dcd-b173524204a4
3
protected Position<Entry<K, V>> treeSearch(K key, Position<Entry<K, V>> p) throws InvalidPositionException, BoundaryViolationException { if (p == null) return null; else { K currentK = key(p); int comp = this.comp.compare(key, currentK); if (comp < 0) return treeSearch(key, left(p)); else if (comp > 0) return treeSearch(key, right(p)); else return p; } }
5aeda940-512c-4817-93de-fb8073419e68
8
private void scrapeBasketball() { PGsPlaying = new ArrayList<BasketballPlayer>(); SGsPlaying = new ArrayList<BasketballPlayer>(); SFsPlaying = new ArrayList<BasketballPlayer>(); PFsPlaying = new ArrayList<BasketballPlayer>(); CentersPlaying = new ArrayList<BasketballPlayer>(); Elements script = doc.select("script"); Element playerScript = script.get(1); String playerInfo = playerScript.data(); String[] semiColon = playerInfo.split("\\{"); String players = semiColon[14]; String [] playerStrings = players.split("\\["); //For every player in the HTML Document, divide into commas to get the Name and Salary attributes; //Add that player to the ArrayList based upon their type. int lastInteger = (playerStrings.length - 1); for(int i = 0;i < playerStrings.length;i++){ //Need to not include the first or last if(i != 0 && i != lastInteger){ String[] playerData = playerStrings[i].split(","); String position = playerData[0].replaceAll("^\"|\"$", ""); //Remove the quotes from the position String playerName = playerData[1].replaceAll("^\"|\"$", ""); //Remove the quotes from the name int salary = Integer.parseInt(playerData[5].replaceAll("^\"|\"$","")); switch(position.toUpperCase()){ case "SG": FantasyApp.log.debug("Adding SG"); SGsPlaying.add(new BasketballPlayer(playerName, salary)); break; case "PG": FantasyApp.log.debug("Adding PG"); PGsPlaying.add(new BasketballPlayer(playerName, salary)); break; case "SF": FantasyApp.log.debug("Adding SF"); SFsPlaying.add(new BasketballPlayer(playerName, salary)); break; case "PF": FantasyApp.log.debug("Adding PF"); PFsPlaying.add(new BasketballPlayer(playerName, salary)); break; case "C": FantasyApp.log.debug("Adding Center"); CentersPlaying.add(new BasketballPlayer(playerName, salary)); break; } FantasyApp.log.debug("Position: "+position+" Name: "+playerName+" Salary: "+salary); } } FantasyApp.log.info("The website FanDuel was scraped sucessfully"); }
777774c6-fc59-407a-870a-b11d935f8fcb
0
public void setX2Coordinate(double x) { this.x2Coordinate=x; }
1e274f5a-a2f9-48e5-aed3-a42365540cc7
5
@Override public void recieveMouseEvent(int mouseX, int mouseY){ if (mouseX < 800){ int newX = -1; int newY = -1; int cx = Boot.getPlayer().getX(); int cy = Boot.getPlayer().getY(); newX = cx + (mouseX / Standards.TILE_SIZE) - 12; newY = cy + ((Standards.W_HEIGHT - mouseY) / Standards.TILE_SIZE) - 12; if (Mouse.isButtonDown(0)){ if (PointMath.distance2Points(newX, newY, cx, cy) < 3){ Boot.getWorldObj().getTileAtCoords(newX, newY).setTileID(ID, metadata); } } if (Mouse.isButtonDown(1)){ if (PointMath.distance2Points(newX, newY, cx, cy) < 3){ int meta = Boot.getWorldObj().getTileAtCoords(newX, newY).getMetadata(); Boot.getWorldObj().getTileAtCoords(newX, newY).setMetadata(meta + 1); } } } }
0a0ee226-26ab-451a-a46f-c586e96f2016
3
@Override public Paciente listById(int codigo) { Connection con = null; PreparedStatement pstm = null; ResultSet rs = null; Paciente p = new Paciente(); try { con = ConnectionFactory.getConnection(); pstm = con.prepareStatement(LISTBYID); pstm.setInt(1, codigo); rs = pstm.executeQuery(); while (rs.next()) { p.setCodigo(rs.getInt("codigo")); p.setNome(rs.getString("nome")); p.setDataNascimento(rs.getDate("data_nascimento")); p.setTelefone(rs.getString("telefone")); p.setCelular(rs.getString("celular")); p.setRg(rs.getString("rg")); p.setEndereco(rs.getString("endereco")); p.setCidade(rs.getString("cidade")); p.setEstado(rs.getString("estado")); Convenio c = new Convenio(); c.setCodigo(rs.getInt("convenio.codigo")); c.setNome(rs.getString("convenio.nome")); p.setConvenio(c); } System.out.println(p.getCodigo()); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Erro ao listar(id) paciente: " + e.getMessage()); } finally { try { ConnectionFactory.closeConnection(con, pstm, rs); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, "Erro ao fechar conexão do listar paciente: " + ex.getMessage()); } } return p; }
8be1d5cf-b349-454e-b6ea-11d242ffc199
6
private static int getNumberOfMappers() { // default TODO change to 6 before submission int cores = conf.Constants.NUMBER_OF_CORES; File cpuInfo = new File("/proc/cpuinfo"); //check if AFS /proc/cpuinfo exists if(!cpuInfo.exists()){ Logger.errLog("NO CPUINFO FILE. Using default value of 6 cores."); return cores; } try{ BufferedReader in = new BufferedReader(new FileReader(cpuInfo)); String line = in.readLine(); while (line != null) { if(line.contains("cpu cores")){ for(char s: line.toCharArray()){ if(Character.isDigit((char)s)){ in.close(); return Integer.parseInt(s+""); } } } line = in.readLine(); } in.close(); Logger.log("constant NOT DETECTED"); return cores; } catch(Exception e){ return cores; } }
8e137f6f-baa0-4405-8466-4c5f6c0e77fa
7
public int getTableNumber(int i, int j) { int n = trainSet.getNbrOfVariables(); int tableCounter = 0; for (int l = 0; l < n - 1; l++) { for (int l2 = l+1; l2 < n; l2++) { if (j<i) { if (l==j && l2==i) { return tableCounter; } } else if (l==i && l2==j) { return tableCounter; } tableCounter++; } } return -1; }
4721b119-d7e2-4408-9f1b-39dec1560376
1
private void decreaseLife(int value){ this.life_delay -= value; if(life_delay <= 0){ this.life -= 1; life_delay += 100; } }
e3738db3-0a4d-4231-9171-261f3ee73209
5
public void sendMoveStatus() throws GameOverException { if (game) { if (isAttack) { sendAttackMessage(isSecondPlayerInMove); if (player1.getHealth() <= 0) { game = false; sendGameOverMessage(1); throw new GameOverException(); } else if (player2.getHealth() <= 0) { game = false; sendGameOverMessage(2); throw new GameOverException(); } isAttack = false; } else sendGameStateToPlayers(false, MessageType.S_LINE_MOVE); try { Thread.sleep(1000); } catch (InterruptedException e) { // logger.error("Interrupted while sleep", e); } } }
2e8914af-6c83-49df-b757-54b76960c7b5
4
public void COMForce() { if (myToggles.get(COM)) { for (HashMap<String, Mass> massList : springies.getMassMaps()) { int xTotal = 0; int yTotal = 0; for (Mass m : massList.values()) { xTotal += m.x; yTotal += m.y; } int xCOM = xTotal / massList.size(); int yCOM = yTotal / massList.size(); for (Mass m : massList.values()) { Vec2 force = new Vec2((float) (xCOM - m.x), (float) (yCOM - m.y)); force.normalize(); force = force.mul((float) (myCMMag / Math.pow( Math.sqrt(Math.pow(xCOM - m.getX(), 2) + Math.pow(yCOM - m.y, 2)), myCMExp))); m.applyForce(force); } } } }
0b57fd5f-82ce-4a78-8681-9510fbb40a5d
8
public void buildAssociations(Instances instances) throws Exception { // can associator handle the data? getCapabilities().testWithFail(instances); m_errorMessage = null; m_targetSI.setUpper(instances.numAttributes() - 1); m_target = m_targetSI.getIndex(); Instances inst = new Instances(instances); inst.setClassIndex(m_target); inst.deleteWithMissingClass(); if (inst.attribute(m_target).isNominal()) { m_targetIndexSI.setUpper(inst.attribute(m_target).numValues() - 1); m_targetIndex = m_targetIndexSI.getIndex(); } else { m_targetIndexSI.setUpper(1); // just to stop this SingleIndex from moaning } if (m_support <= 0) { throw new Exception("Support must be greater than zero."); } m_numInstances = inst.numInstances(); if (m_support >= 1) { m_supportCount = (int)m_support; m_support = m_support / (double)m_numInstances; } m_supportCount = (int)Math.floor((m_support * m_numInstances) + 0.5d); // m_supportCount = (int)(m_support * m_numInstances); if (m_supportCount < 1) { m_supportCount = 1; } m_header = new Instances(inst, 0); if (inst.attribute(m_target).isNumeric()) { if (m_supportCount > m_numInstances) { m_errorMessage = "Error: support set to more instances than there are in the data!"; return; } m_globalTarget = inst.meanOrMode(m_target); } else { double[] probs = new double[inst.attributeStats(m_target).nominalCounts.length]; for (int i = 0; i < probs.length; i++) { probs[i] = (double)inst.attributeStats(m_target).nominalCounts[i]; } m_globalSupport = (int)probs[m_targetIndex]; // check that global support is greater than min support if (m_globalSupport < m_supportCount) { m_errorMessage = "Error: minimum support " + m_supportCount + " is too high. Target value " + m_header.attribute(m_target).value(m_targetIndex) + " has support " + m_globalSupport + "."; } Utils.normalize(probs); m_globalTarget = probs[m_targetIndex]; /* System.err.println("Global target " + m_globalTarget); System.err.println("Min support count " + m_supportCount); */ } m_ruleLookup = new HashMap<HotSpotHashKey, String>(); double[] splitVals = new double[m_header.numAttributes()]; byte[] tests = new byte[m_header.numAttributes()]; m_head = new HotNode(inst, m_globalTarget, splitVals, tests); // m_head = new HotNode(inst, m_globalTarget); }
c6e53675-2c33-45d1-a474-55d646d5353c
5
final void method1337(int i) { anInt2300++; ((Class174) this).anInt2298 = Class70.cosineTable[anInt2302 << 259569763]; long l = (long) ((Class174) this).anInt2291; long l_10_ = (long) ((Class174) this).anInt2290; long l_11_ = (long) ((Class174) this).anInt2294; ((Class174) this).anInt2299 = (int) Math.sqrt((double) (l_10_ * l_10_ + (l * l - -(l_11_ * l_11_)))); if (((Class174) this).anInt2304 == 0) ((Class174) this).anInt2304 = 1; if ((((Class174) this).anInt2289 ^ 0xffffffff) != i) { if (((Class174) this).anInt2289 == 1) { ((Class174) this).aLong2301 = (long) (((Class174) this).anInt2299 * 8 / ((Class174) this).anInt2304); ((Class174) this).aLong2301 *= ((Class174) this).aLong2301; } else if (((Class174) this).anInt2289 == 2) ((Class174) this).aLong2301 = (long) (8 * ((Class174) this).anInt2299 / ((Class174) this).anInt2304); } else ((Class174) this).aLong2301 = 2147483647L; if (aBoolean2308) ((Class174) this).anInt2299 *= -1; }
bacb40b3-abf8-497f-bb1e-e57f689c4b44
6
private CardPower isFourOfKind(int[] valueCounts) { int highCard = -1; int kickerCard = -1; for (int i = valueCounts.length - 1; i >= 0; i--) { if (valueCounts[i] == 4) { highCard = i; break; } } if (highCard >= 0) { for (int i = valueCounts.length - 1; i >= 0; i--) { if (i != highCard && valueCounts[i] > 0) { kickerCard = i; return new CardPower().add(7).add(highCard).add(kickerCard); } } } return null; }
42816634-3f1a-4794-b673-2ffc76e37d77
9
public void handle(String target,Request baseRequest,HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException { response.setContentType("application/json;charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); ProxyRequest req = mapper.readValue(request.getReader(), ProxyRequest.class); DefaultHttpClient client = new DefaultHttpClient(); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DAY_OF_YEAR, 1); Date cookieExpiry = calendar.getTime(); BasicCookieStore cookieStore = new BasicCookieStore(); for( String cookieName : req.cookies.keySet() ) { System.out.println(cookieName + " : " + req.cookies.get(cookieName)); BasicClientCookie cookie = new BasicClientCookie(cookieName, req.cookies.get(cookieName)); cookie.setDomain("betaspike.appspot.com"); cookie.setPath("/"); cookie.setExpiryDate(cookieExpiry); cookieStore.addCookie(cookie); } client.setCookieStore(cookieStore); HttpUriRequest loginReq = null; if( req.method.equals("POST") ) { HttpPost loginReqP = new HttpPost(req.url); loginReqP.setEntity(new StringEntity(req.body)); loginReq = loginReqP; } else if( req.method.equals("GET") ){ loginReq = new HttpGet(req.url); } System.out.println( "XsrfToken: " + req.xsrfToken ); if( req.xsrfToken != null ) { loginReq.setHeader( "X-XsrfToken", req.xsrfToken ); } loginReq.setHeader("Accept-Encoding", "gzip"); loginReq.setHeader("User-Agent", "Nemesis (gzip)"); if( req.contentType != null ) { loginReq.setHeader( "Content-Type", req.contentType ); } HttpResponse respx = client.execute(loginReq); Header[] lheaders = loginReq.getAllHeaders( ); for( int i = 0; i < lheaders.length; ++i ) { System.out.println(lheaders[i].getName() + ": " + lheaders[i].getValue()); } InputStream inStream = null; if( respx.getEntity().getContentEncoding() != null ) { if( respx.getEntity().getContentEncoding().getValue().equals("gzip") ) { inStream = new GZIPInputStream(respx.getEntity().getContent()); } else { System.out.println( "Unknown Encoding!" ); } } else { inStream = respx.getEntity().getContent(); } ProxyResponse resp = new ProxyResponse( ); resp.body = CharStreams.toString(new InputStreamReader(inStream, Charsets.UTF_8)); List<Cookie> cookies = cookieStore.getCookies(); for( int i = 0; i < cookies.size(); ++i ) { resp.cookies.put(cookies.get(i).getName(), cookies.get(i).getValue()); System.out.println(cookies.get(i).toString()); } resp.statusCode = respx.getStatusLine().getStatusCode(); mapper.writeValue(response.getWriter(), resp); }
4b1a17d2-b672-4e30-bfd2-a4b33d50dacf
4
private void ResetFinanceTables() { if(table_FinanceData != null) { while(table_FinanceData.getRowCount() > 0) { ((DefaultTableModel) table_FinanceData.getModel()).removeRow(0); } } if(table_FinanceDetails != null) { while(table_FinanceDetails.getRowCount() > 0) { ((DefaultTableModel) table_FinanceDetails.getModel()).removeRow(0); } } }
362d3fe1-6829-4562-9ee2-9a4351053674
5
@Override protected void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.fill(new Rectangle(getPreferredSize())); drawBackground(g2, board); for (int row = HIDDEN_LINES; row < board.getHeight(); row++) { for (int col = 0; col < board.getWidth(); col++) { if (board.getSquare(row, col) != null) paintBlock(g2, new Point(col * SQUARE_SIZE, (row - HIDDEN_LINES) * SQUARE_SIZE), getSquareColor(board.getSquare(row, col))); } } if (board.fallingBlock != null) { for (SquarePos pos : board.fallingBlock.getBlocks()) { int xPos = pos.x * SQUARE_SIZE + SQUARE_SIZE * board.fallingBlock.position.x; int yPos = pos.y * SQUARE_SIZE + SQUARE_SIZE * (board.fallingBlock.position.y - HIDDEN_LINES); paintBlock(g2, new Point(xPos, yPos), getSquareColor(board.fallingBlock.poly.color)); } } }
d9ab58f4-7a1a-47d7-9af1-9197253b9cec
9
private void traverseGrid(final String prevString, final int currentx, final int currenty, boolean[][] visited) { if (currentx < 0 || currentx >= this.getWidth() || currenty < 0 || currenty >= this.getHeight() || visited[currentx][currenty]) return; visited[currentx][currenty] = true; String currentString = prevString + this.get(currentx, currenty).getUp(); if (this.wordDict.hasWord(currentString)) this.foundWords.add(currentString); if (this.wordDict.hasPrefix(currentString)) for (int dx=-1; dx<=1; dx++) for (int dy=-1; dy<=1; dy++) this.traverseGrid(currentString, currentx + dx, currenty + dy, visited); visited[currentx][currenty] = false; }
16fba31f-d63a-495d-b7e8-ffa981cbc345
5
private String getCombinedList() { StringBuilder total = new StringBuilder(); for ( int i = 0; i < javaVariables.size(); i++ ) { StringBuilder list = new StringBuilder(); switch ( databaseType ) { case H2: case ORACLE: list.append( sqlVariables.get( i ) ); } list.append( makeSpace( 35, list.toString() ) ); if( javaVariables.get( i ).equals("systimestamp")) { list.append( "= " + javaVariables.get( i ) + "" ); } else { list.append( "= #{" + javaVariables.get( i ) + "}" ); } if ( i != javaVariables.size() - 1 ) { list.append( " ," ); list.append( "\n" ); } total.append( TAB + TAB + TAB + list ); } return total.toString(); }
83da9a5c-4861-42d3-8786-deb3404959d6
8
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { MOB target=mob; if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB)) target=(MOB)givenTarget; if(target.fetchEffect(this.ID())!=null) { mob.tell(target,null,null,L("<S-NAME> already <S-HAS-HAVE> sonar.")); return false; } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,null,this,verbalCastCode(mob,target,auto),auto?L("<T-NAME> gain(s) sonar capability!"):L("^S<S-NAME> incant(s) softly, and <S-HIS-HER> ears become capable of sonar!^?")); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); beneficialAffect(mob,target,asLevel,0); } } else beneficialVisualFizzle(mob,null,L("<S-NAME> incant(s) softly and listen(s), but the spell fizzles.")); return success; }
26e50524-2561-46aa-a4d1-534bcded3897
0
public AffineTransform getCoordTransform() { return coordTransform; }
4f139758-1472-4364-bec9-440f1aa5c19c
0
@Override public void requestFocus() {}
c9ed6c38-7f33-4556-9c5e-ce98d0b43b31
7
private void makeResult() { if (mode == ADD_MODE) { TProjectData pData = project.getProjectData() ; TProjectFileList liste = pData.getAvailableLangs() ; int keysBefore = pData.getRowCount() ; // insert a file, if available String str = filenameField.getText() ; if ((str != null) && (str.length() > 0)) { File file = new File(project.getWorkingDirectory(), str) ; languageFile = liste.createFileHandle(file) ; if (languageFile != null) { pData.addNewLanguage( languageFile ) ; } } else // try to insert with language, country, variant settings { languageFile = project.getProjectData().addNewLanguage( langField.getText(), countryField.getText(), variantField.getText(), project.getWorkingDirectory() ) ; } // try to load already available data if (languageFile.getFileHandle().exists()) { pData.loadSingleFile( languageFile, liste.getSize() - 1 ) ; } int keysAfter = pData.getRowCount() ; int newKeys = keysAfter - keysBefore ; if (newKeys > 0) { JOptionPane.showMessageDialog(this, "<" +newKeys +"> new keys found!", "new keys", JOptionPane.CLOSED_OPTION); } } else // EDIT { // no special things to do } // insert the encoding - for both edit and add mode if (languageFile != null) { languageFile.setDefaultFileEncoding( encCombo.getSelectedItem().toString() ) ; languageFile.setSaveWithEscapeSequence( escapeCB.isSelected() ); } }
a499addb-d51f-464f-b6fb-6010c1c737e1
9
private static int[][] calcFrom(char[][] grid, int N, int M) { int[][] from = new int[N][M]; from[0][0] = 1; for (int i = 1; i < M; i++) { if (grid[0][i] == '#' || from[0][i-1] == -1) from[0][i] = -1; else from[0][i] = from[0][i-1] + 1; } for (int i = 1; i < N; i++) { for (int j = 0; j < M; j++) if (grid[i][j] == '#') from[i][j] = -1; else { from[i][j] = -1; if (from[i-1][j] >= 0) from[i][j] = from[i-1][j] + 1; if (j > 0 && from[i][j-1] >= 0) from[i][j] = Math.max(from[i][j], from[i][j-1] + 1); } } return from; }
14aa4657-a9d5-40eb-b9d0-3cefce075215
5
public void runSimulation() throws VehicleException, SimulationException, IOException { this.log.initialEntry(this.carPark, this.sim); for (int time = 0; time <= Constants.CLOSING_TIME; time++) { // queue elements exceed max waiting time if (!this.carPark.queueEmpty()) { this.carPark.archiveQueueFailures(time); } // vehicles whose time has expired if (!this.carPark.carParkEmpty()) { // force exit at closing time, otherwise normal boolean force = (time == Constants.CLOSING_TIME); this.carPark.archiveDepartingVehicles(time, force); } // attempt to clear the queue if (!this.carPark.carParkFull()) { this.carPark.processQueue(time, this.sim); } // new vehicles from minute 1 until the last hour if (newVehiclesAllowed(time)) { this.carPark.tryProcessNewVehicles(time, this.sim); } // Log progress this.log.logEntry(time, this.carPark); chartData.add(carPark.getStatus(time)); // System.out.printf("%s\n",carPark.getStatus(time)); } this.log.finalise(this.carPark); }
333234f5-912a-49f4-8ab6-a97445799e17
6
private boolean isLinkInDirection(Direction direction) { int xPos = x; int yPos = y; // Search in the direction until a wall or Link is encountered. while (!objects.isWallAtPosition(xPos, yPos)) { // Increment the direction specified. switch (direction) { case UP: yPos -= 32; break; case DOWN: yPos += 32; break; case RIGHT: xPos += 32; break; case LEFT: xPos -= 32; break; } // Check for a collision at the current position with Link. GameObject position = new GameObject(objects, xPos, yPos); if (position.isCollidingWith(objects.link)) { return true; } } return false; }
4095523c-98dc-4da1-8dfa-d3d50fa71a60
8
public void onUpdate() { this.prevPosX = this.posX; this.prevPosY = this.posY; this.prevPosZ = this.posZ; if (this.materialType == Material.water) { this.particleRed = 0.2F; this.particleGreen = 0.3F; this.particleBlue = 1.0F; } else { this.particleRed = 1.0F; this.particleGreen = 16.0F / (float)(40 - this.bobTimer + 16); this.particleBlue = 4.0F / (float)(40 - this.bobTimer + 8); } this.motionY -= (double)this.particleGravity; if (this.bobTimer-- > 0) { this.motionX *= 0.02D; this.motionY *= 0.02D; this.motionZ *= 0.02D; this.setParticleTextureIndex(113); } else { this.setParticleTextureIndex(112); } this.moveEntity(this.motionX, this.motionY, this.motionZ); this.motionX *= 0.9800000190734863D; this.motionY *= 0.9800000190734863D; this.motionZ *= 0.9800000190734863D; if (this.particleMaxAge-- <= 0) { this.setDead(); } if (this.onGround) { if (this.materialType == Material.water) { this.setDead(); this.worldObj.spawnParticle("splash", this.posX, this.posY, this.posZ, 0.0D, 0.0D, 0.0D); } else { this.setParticleTextureIndex(114); } this.motionX *= 0.699999988079071D; this.motionZ *= 0.699999988079071D; } Material var1 = this.worldObj.getBlockMaterial(MathHelper.floor_double(this.posX), MathHelper.floor_double(this.posY), MathHelper.floor_double(this.posZ)); if (var1.isLiquid() || var1.isSolid()) { double var2 = (double)((float)(MathHelper.floor_double(this.posY) + 1) - BlockFluid.getFluidHeightPercent(this.worldObj.getBlockMetadata(MathHelper.floor_double(this.posX), MathHelper.floor_double(this.posY), MathHelper.floor_double(this.posZ)))); if (this.posY < var2) { this.setDead(); } } }
7ae0af91-8361-4b06-be1a-80b77e4caddc
3
public Relation(State stateFrom, State stateTo, String symbol) { this.stateFrom = stateFrom; this.stateTo = stateTo; this.symbol = symbol; if (stateFrom == null || stateTo == null) { throw new IllegalArgumentException("Relation can't be build on null states."); } if (stateFrom == stateTo) { throw new IllegalArgumentException("States can't be equal."); } }
71997a33-4815-4293-84d5-d45145498594
4
private void performHashFunctionTests(){ String hashFunc = (String) this.hashFunction.getValue(); Path[] paths = new Path[selectedFiles.length]; for(int i=0; i<selectedFiles.length; i++) paths[i] = Paths.get(selectedFiles[i].getAbsolutePath()); if(this.jRadioButtonVitesse.isSelected()) hash.HashFunctionTests.speedTests(paths, HashFunction.getHashFunction(hashFunc)); if(this.jRadioButtonCollisions.isSelected()) hash.HashFunctionTests.collisionTests(paths, HashFunction.getHashFunction(hashFunc)); if(this.jRadioButtonLoiUniforme.isSelected()) hash.HashFunctionTests.uniformDistribTest(HashFunction.getHashFunction(hashFunc), true); }
d1ad8ae7-795c-496b-9b15-b6ed3183cc19
9
List<Range> exclude(Range another) throws RangesNotMergeableException { if (!isOverlappedWith(another)) throw new RangesNotMergeableException(this, another); final List<Range> result = new ArrayList<Range>(); if (another.contains(this)) return result; if (contains(another)) { if (from < another.from) result.add(new Range(from, another.from)); if (another.to < to) result.add(new Range(another.to, to)); } if (isOverlappedWith(another) && from > another.from) result.add(new Range(max(from, another.to), max(to, another.from))); if (isOverlappedWith(another) && to < another.to) result.add(new Range(min(from, another.to), min(to, another.from))); return result; }
07dbf571-7164-471a-bf59-9a44a8a8158a
0
public Blog saveBlog(Blog pBlog){ return this.blogModelBS.saveBlog(pBlog); }
f6770e15-114e-45a6-9bd9-d445dee221e7
9
public boolean skipPast(String to) throws JSONException { boolean b; char c; int i; int j; int offset = 0; int length = to.length(); char[] circle = new char[length]; /* * First fill the circle buffer with as many characters as are in the * to string. If we reach an early end, bail. */ for (i = 0; i < length; i += 1) { c = next(); if (c == 0) { return false; } circle[i] = c; } /* We will loop, possibly for all of the remaining characters. */ for (;;) { j = offset; b = true; /* Compare the circle buffer with the to string. */ for (i = 0; i < length; i += 1) { if (circle[j] != to.charAt(i)) { b = false; break; } j += 1; if (j >= length) { j -= length; } } /* If we exit the loop with b intact, then victory is ours. */ if (b) { return true; } /* Get the next character. If there isn't one, then defeat is ours. */ c = next(); if (c == 0) { return false; } /* * Shove the character in the circle buffer and advance the * circle offset. The offset is mod n. */ circle[offset] = c; offset += 1; if (offset >= length) { offset -= length; } } }
d1bd987f-47e5-4082-8ff5-78fa828dca04
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(EditarCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(EditarCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(EditarCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(EditarCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } java.awt.EventQueue.invokeLater(new Runnable() { public void run() { EditarCliente dialog = new EditarCliente(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); }
c1c7a197-7971-4d03-b7cb-87c262a01edc
6
@Override protected void controlUpdate(float tpf) { if(gameInfo.playerNode != null && lastFloor != gameInfo.playerNode.getFloor()) { if(gameInfo.playerNode.getFloor() < floor && !isInvisible) { //Make invisible setInvisibility(true); } else if(gameInfo.playerNode.getFloor() >= floor && isInvisible){ //Make visible setInvisibility(false); } lastFloor = gameInfo.playerNode.getFloor(); } }
cc90d549-9f86-4dbc-9b0a-90d2f7a7b6c0
6
@Override public boolean equals( Object otherObj ) { if ( this == otherObj ) { return true; } if ( otherObj == null || !(getClass().isInstance( otherObj )) ) { return false; } Pair<T1, T2> otherPair = getClass().cast( otherObj ); return (first == null? otherPair.first == null : first.equals( otherPair.first )) && (second == null? otherPair.second == null : second.equals( otherPair.second )); }
9c1c9d60-544b-401f-834b-fee9bf0ac2f1
4
@Override public void setValueAt(Object value, int rowIndex, int columnIndex) { Language language = languages.get(rowIndex); switch (columnIndex) { case COLUMN_NAME: language.setName(value.toString()); break; case COLUMN_FILE_EXTENSION: language.setFileExtension(value.toString()); break; case COLUMN_CMD_COMPILE: language.setCmdCompile(value.toString()); break; case COLUMN_CMD_EXECUTE: language.setCmdExecute(value.toString()); break; } DbAdapter.updateLanguage(language); this.fireTableDataChanged(); // update JTable }
28573dd0-ea09-46e9-adbc-b5396b7c3295
7
private String readLine(Socket client) throws IOException { InputStreamReader in = new InputStreamReader(client.getInputStream()); int offset = 0; boolean receivedNewline = false; do { int length = in.read(inputBuffer, offset, inputBuffer.length - offset); if (length == -1) { return null; } else { int newOffset = offset; for (; newOffset < offset + length && !receivedNewline; newOffset++) { if (inputBuffer[newOffset] == '\n') { receivedNewline = true; } } offset = newOffset; } if (offset == inputBuffer.length) { receivedNewline = true; } } while (!receivedNewline); if (offset < inputBuffer.length) { return String.valueOf(inputBuffer, 0, offset).trim(); } else { return null; } }
436a8ec6-490f-4156-bceb-e4c59b12ef5a
3
@Override protected void paintComponent(Graphics g) { g.setColor(Color.WHITE); g.fillOval(0, 0, R*2, R*2); g.setColor(Color.BLACK); g.drawOval(0, 0, R*2, R*2); g.drawString(id, R-5, R/2+3); if(signal.length()>0){// TODO знову якісь костилі, пов'язано з тим, що при повторниму аналізі зникають сигнали if(signal.charAt(0) == 'S' ){ g.drawString(String.valueOf(0), R-5, R*3/2); }else{ g.drawString(signal, R-5, R*3/2); } }else{ g.drawString("0", R-5, R*3/2); } if(code != null){ g.setColor(Color.RED); g.drawString(code, 0, R/2); g.setColor(Color.BLACK); } g.drawLine(0, R, R*2, R); }
b7995034-389b-44d7-b1bf-8975b8ae3355
3
public String getValue() { try { return readValue(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (RuntimeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
a9a49e75-7bce-45ea-b507-f108a7d02bf2
0
public void setQuantity(String quantity) { this.quantity = quantity; }
e85d0264-9cd0-4f60-ae62-31230bf9f945
8
public void addLockUnlockUnitsForThread2() { Iterator unitIt = this.unitChain.iterator(); while (unitIt.hasNext()) { Unit u = (Unit) unitIt.next(); Stmt s = (Stmt) u; Iterator boxIt = s.getUseBoxes().iterator(); while( boxIt.hasNext() ) { final ValueBox box = (ValueBox) boxIt.next(); Value value = box.getValue(); if (value instanceof InterfaceInvokeExpr && ((InterfaceInvokeExpr) value).getMethod().getName().equals("lock")) { if (!this.lockUnitsForThread1.contains(u)) { this.lockUnitsForThread2.add(u); } } if (value instanceof InterfaceInvokeExpr && ((InterfaceInvokeExpr) value).getMethod().getName().equals("unlock")) { if(!this.unlockUnitsForThread1.contains(u)) { this.unlockUnitsForThread2.add(u); } } } } }
5d4ce352-0ef3-421b-86e0-6f75f15937f8
5
public long[] roots() throws Exception { ArrayList<Polynomial> lf = this.factor(1); // factorize into monomials // check factors are all monomials, eliminate any constants int constants = 0; for (Polynomial f : lf) { int x = f.degree(); if (x > 1) return new long[0]; if (x < 1) constants++; } long[] r = new long[lf.size() - constants]; int i = 0; for (Polynomial f: lf) if (f.degree() == 1) r[i++] = PF.div(PF.neg(f.tail()), f.head()); return r; }
a96563a4-6ff2-41a8-8664-1a96abd441f4
9
private static String stringConverter(String in) { String out = ""; int level = 0; String[] sep1 = in.split("\\["); for (int i = 0; i < sep1.length; i++) { String[] sep2; boolean found = false; if (sep1[i].indexOf("]") != -1) { sep2 = sep1[i].split("\\]"); found = true; } else { sep2 = new String[1]; sep2[0] = sep1[i]; } for (int j = 0; j < sep2.length; j++) { if (sep2[j].indexOf(",") == 0) { sep2[j] = sep2[j].substring(1); } if (sep2[j].compareTo("") != 0) { String[] sep3 = sep2[j].split(","); for (int k = 0; k < sep3.length; k++) { if (sep3[k].indexOf(" ") == 0) { sep3[k] = sep3[k].substring(1); } out += "\n" + spaces(level) + sep3[k]; } } if (found && j + 1 != sep2.length) { level--; } } level++; } return out; }
2c11f86f-b862-4c59-9d4a-9ec2515894bd
7
public Cycle add(FigurativeNumber number) { // Printer.print("attempt : " + number + " first two " + firstTwoOfFist); if (isCycle.isPresent()) { if (isCycle.get()) { // Printer.print("Nothing added. Cycle is already a cycle"); return this; } } //TODO containsElementWith(Predicate<E>) if (firstTwoOfFist != null && number.getLastTwo().equals(firstTwoOfFist)) { cycle.add(number); isCycle = Optional.of(true); Printer.print("added last peace of the puzzle. isCycle!"); return this; } if (firstTwoOfFist == null) { // Printer.print("first entry"); cycle.add(number); firstTwoOfFist = number.getFirstTwo(); return this; } if (firstTwoOfFist != null) { FigurativeNumber lastNumber = getLast(); if (lastNumber.getLastTwo().equals(number.getFirstTwo())) { cycle.add(number); // Printer.print("just another Joe"); } return this; } return this; }
a46e2ba8-070e-4cb4-8011-f636049d63d7
2
public void run(){ while(true){ TankClient.this.repaint(); try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } }
4856d406-0d91-4460-8c93-642f6a2efc03
7
private void start() { List<File> tempMoveFile = new ArrayList<File>(); for (int i = 0; i < list_main.size(); i++) { for (int j = i + 1; j < list_main.size(); j++) { for (int iIn = 0; iIn < list_main.get(i).size(); iIn++) { for (int jIn = 0; jIn < list_main.get(j).size(); jIn++) { File iInFile = list_main.get(i).get(iIn); File jInFile = list_main.get(j).get(jIn); if (iInFile.getName().equals(jInFile.getName())) { if (iInFile.length() >= jInFile.length()) { tempMoveFile.add(iInFile); } else { tempMoveFile.add(jInFile); } break; } } } } } removeDuplicateWithOrder(tempMoveFile); jTa.setText(""); for (File file : tempMoveFile) { FileUtils.move(file, new File(savePath + "\\" + file.getName()), true, jTa); } jTa.append("操作完成"); jTa.paintImmediately(jTa.getBounds()); }
be521237-ba1f-49d2-9d98-c77cb25d9d45
4
private CFGResult funcBody(String funcName, VariableTable globalVarList, ArrayList<String> paramsList) throws SyntaxFormatException, IOException { VariableTable localVar = varDecl(); for (VariableTable newDecl = varDecl(); newDecl != null; newDecl = varDecl()) { localVar.append(newDecl); } // Take every params as a local variable. // Then we need to load these params from caller stack into params table // param table stored inside function if (localVar == null) { localVar = new VariableTable(); } VariableTable paramTable = inter.registerFormalParam(paramsList); localVar.append(paramTable); if (checkCurrentType(TokenType.BEGIN_BRACE)) { moveToNextToken(); Block codeBlock = new Block(localVar, globalVarList); CFGResult pendingBody = new CFGResult(codeBlock); Function.registerFunction(new Function(funcName, paramsList, pendingBody)); if (paramTable != null) { inter.stubLoadParams(codeBlock, paramsList); } CFGResult body = statSequence(codeBlock); assertAndMoveNext(TokenType.END_BRACE); return body; } return null; }
c82ffbe6-b7d7-489a-a097-0120b0276747
0
@Override public String toString() { return String.format( "containsMethod(%s(%s))", this.name, Arrays.toString( this.argumentsType ) ); }
a6c41822-b09f-4a97-9566-72d3d764e03d
9
public void addNote(String userId, String note) throws Exception { if(currentUser == null || currentUser.getDepartment() != Department.COMPUTER_SCIENCE || (currentUser.getRole() == Role.STUDENT && !(userId.equals(currentUser.getId())))) { Exception exception = new InvalidUserException("Invalid user"); throw exception; } if(this.recordList == null) { Exception e = new InvalidStudentListException(); throw e; } int index = -1, count = 0; for(StudentRecord sRecord : this.recordList) { if(userId.equals(sRecord.getStudent().getId())) index = count; count++; } if(index == -1){ Exception e = new InvalidStudentListException(); throw e; } else { this.recordList.get(index).addNote(note); } String representation = new GsonBuilder().setPrettyPrinting().create().toJson(this.recordList); try { FileWriter out = new FileWriter("resources/students.txt"); out.write(representation); out.close(); } catch(IOException e) { throw e; } }
bf1e9977-6597-418b-9f2f-9a8eb0de8a58
9
public byte[] getPacket() throws IOException { int lengthHi = 0; int typ = 0; int lengthLo = 0; int length = 0; int pos = 0; typ = _in.read(); // System.out.println(typ); switch (typ) { case 0xc1: case 0xc3: { length = _in.read(); pos = 2; // System.out.println("c1c3:S"+length); } break; case 0xc2: case 0xc4: { lengthLo = _in.read(); lengthHi = _in.read(); pos = 3; length = lengthHi * 256 + lengthLo; // System.out.println("c2c4:S"+length); } break; default: { System.out.println("Unknown Header type"); } } if (length < 0) { System.out.println("client terminated connection"); throw new IOException("EOF"); } final byte[] incoming = new byte[length - pos]; int receivedBytes = pos; int newBytes = 0; while (newBytes != -1 && receivedBytes < length) { newBytes = _in.read(incoming, 0, length - pos); receivedBytes = receivedBytes + newBytes; } if (incoming.length <= 0) { return null; } byte[] decr = new byte[incoming.length]; decr = dec(incoming, pos); if (f) { _packArea.append("\n" + printData(decr, decr.length, "[C->S]")); // System.out.println("\n" + printData(decr, decr.length // ,"[C->S]")); } return decr; }
7aca8af5-edf0-4a49-9d46-d55b468589fc
1
public void visit_if_acmpne(final Instruction inst) { if (longBranch) { final Label tmp = method.newLabel(); addOpcode(Opcode.opc_if_acmpeq); addBranch(tmp); addOpcode(Opcode.opc_goto_w); addLongBranch((Label) inst.operand()); addLabel(tmp); } else { addOpcode(Opcode.opc_if_acmpne); addBranch((Label) inst.operand()); } stackHeight -= 2; }
a0d5b6be-ab14-4702-bf60-62e676c11e85
9
public Sprite createSprite(String oldName, String newName, int pos, int z) throws IOException { oldName = oldName.toLowerCase(); int x = 0; int y = 0; BufferedImage image = null; for (Tuple2<String, BufferedImage> entry : imageCache) { if (entry.x.equals(oldName)) { image = entry.y; break; } } if (image == null) { image = ImageIO.read(new File(krkr.getOutputFolder()+"/../foreground/"+oldName)); while (imageCache.size() >= maxImageCacheSize) { imageCache.remove(0); } imageCache.add(Tuple2.newTuple(oldName, image)); } int iw = Math.round(scale * image.getWidth()); int ih = (int)Math.floor(scale * image.getHeight()); //System.out.println(scale + " " + image.getWidth() + "x" + image.getHeight() + " -> " + iw + "x" + ih); y = 192 - ih; if (pos == 0) { x = (256 - iw) / 2; } else if (pos == 1) { x = 256*3/10 - iw/2; } else if (pos == 2) { x = 256*7/10 - iw/2; } else if (pos == 3) { x = 256/4 - iw/2; } else if (pos == 4) { x = 256*3/4 - iw/2; } return new Sprite(x, y, z, newName, iw); }
ea8ebea1-99ea-48dd-999b-16ad27949fc9
5
public static dtAllocHint swigToEnum(int swigValue) { if (swigValue < swigValues.length && swigValue >= 0 && swigValues[swigValue].swigValue == swigValue) return swigValues[swigValue]; for (int i = 0; i < swigValues.length; i++) if (swigValues[i].swigValue == swigValue) return swigValues[i]; throw new IllegalArgumentException("No enum " + dtAllocHint.class + " with value " + swigValue); }
7c1f5a11-27d6-46e6-87ea-f4b7b6550e6b
3
public static ArrayList<bRegistro> PesquisaFun(String arg_serial) throws SQLException, ClassNotFoundException { ArrayList<bRegistro> sts = new ArrayList<bRegistro>(); ResultSet rs; Connection conPol = conMgr.getConnection("PD"); if (conPol == null) { throw new SQLException("Numero Maximo de Conexoes Atingida!"); } try { call = conPol.prepareCall("SELECT " + "tb_registro.cod_cr, " + "tb_registro.cod_status, " + "tb_registro.cod_prod, " + "tb_registro.serial, " + "'GMP-' || cod_gmp || '-' || cod_posto AS posto_gmp, " + "tb_registro.datah, " + "tb_registro.complemento, " + "tb_registro.inspecao, " + "tb_operador.str_nome " + "FROM tb_registro, " + "tb_operador " + "WHERE " + "serial = ? " + "AND tb_operador.cod_cr = tb_registro.cod_cr " + "ORDER BY datah;"); call.setString(1, arg_serial); rs = call.executeQuery(); while (rs.next()) { bRegistro bObj = new bRegistro(); bObj.setCod_status(rs.getInt("cod_status")); bObj.setCod_prod(rs.getString("cod_prod")); bObj.setSerial(rs.getString("serial")); bObj.setPosto_gmp(rs.getString("posto_gmp")); bObj.setDatah(rs.getTimestamp("datah")); bObj.setComplemento(rs.getString("complemento")); bObj.setInspecao(rs.getString("inspecao")); bObj.setStr_nome(rs.getString("str_nome")); sts.add(bObj); } return sts; } finally { if (conPol != null) { conMgr.freeConnection("PD", conPol); } } }
ac8c287f-a6b3-4e9d-bbf8-324fc151a16a
4
private void resolveLine(Node lineNode) throws RrdException { if(hasChildNode(lineNode, "datasource")) { // ordinary line definition validateTagsOnlyOnce(lineNode, new String[] { "datasource", "color", "legend", "width" }); String datasource = getChildValue(lineNode, "datasource"); String colorStr = getChildValue(lineNode, "color"); Color color = Color.decode(colorStr); String legend = getChildValue(lineNode, "legend", false); // line width is not mandatory int width = 1; try { width = getChildValueAsInt(lineNode, "width"); } catch(RrdException e) { } rrdGraphDef.line(datasource, color, legend, width); } else if(hasChildNode(lineNode, "time1")) { // two point definition validateTagsOnlyOnce(lineNode, new String[] { "time1", "time2", "value1", "value2", "color", "legend", "width" }); String t1str = getChildValue(lineNode, "time1"); GregorianCalendar gc1 = Util.getGregorianCalendar(t1str); String t2str = getChildValue(lineNode, "time2"); GregorianCalendar gc2 = Util.getGregorianCalendar(t2str); double v1 = getChildValueAsDouble(lineNode, "value1"); double v2 = getChildValueAsDouble(lineNode, "value2"); String colorStr = getChildValue(lineNode, "color"); Color color = Color.decode(colorStr); String legend = getChildValue(lineNode, "legend", false); int width = 1; try { width = getChildValueAsInt(lineNode, "width"); } catch(RrdException e) { } rrdGraphDef.line(gc1, v1, gc2, v2, color, legend, width); } else { throw new RrdException("Unrecognized <line> format"); } }
0e5530a3-166c-4031-9dde-4570a8f5c09c
5
public void contextInitialized(ServletContextEvent arg0) { CometContext cc = CometContext.getInstance(); Map<String, String> rtnMap = new HashMap<String, String>(); // 注册应用的channel cc.registChannel(CHANNEL); Map<String, MeasureSite> siteMap = new HashMap<String, MeasureSite>(); // 获取当前机器所有的COM端口 portList = CommPortIdentifier.getPortIdentifiers(); List<MeasureSite> measureSiteList = findAllMeasureSite(); for (Iterator<MeasureSite> iterator = measureSiteList.iterator(); iterator.hasNext();) { MeasureSite measureSite = iterator.next(); siteMap.put(measureSite.getComPort(), measureSite); } if (null != measureSiteList) { System.out.println("measureSite.size: " + measureSiteList.size()); } // 遍历所有的COM端口 while (portList.hasMoreElements()) { // 取得第一个COM端口 portId = (CommPortIdentifier) portList.nextElement(); String portName = portId.getName(); System.out.println("Port Name:" + portName); // 如果COM端口是串口,则执行下面的操作 if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL && siteMap.containsKey(portName)) { // System.out.println("portId.getName(): " + portId.getName()); // 如果端口名是对应计量秤的端口,则继续执行下面的操作 // if (portName.equals("COM4")) { // 启动计量线程 Thread measureAppModule = new Thread(new MeasureAppModule(portName, rtnMap), "Sender App Module " + portName); measureAppModule.setDaemon(true); measureAppModule.start(); //break; // } // if (portName.equals("COM5")) { // // 启动计量线程 // Thread measureAppModule = new Thread(new MeasureAppModule(portName, rtnMap), "Sender App Module " + portName); // measureAppModule.setDaemon(true); // measureAppModule.start(); // break; // } } } }
270e8698-9ea3-49f9-85da-e6762d514442
1
private void saveToFile() { try { FileOutputStream fileOut = new FileOutputStream(CONFIG_FILE); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(this); out.close(); fileOut.close(); } catch (IOException e) { e.printStackTrace(); } }
2305ba44-7c38-4082-83d1-4d0152f0a229
8
public ResultatComparaison comparerAvec(Combinaison autreCombinaison) { int nombreDePionsBienPlaces = 0; int nombreDePionsMalPlaces = 0; boolean[] pionANegligerDansLaCombinaison = new boolean[this.pions.length]; boolean[] pionANegligerDansLAutreCombinaison = new boolean[this.pions.length]; for (int numeroDuPion = 0; numeroDuPion < this.pions.length; numeroDuPion++) { pionANegligerDansLaCombinaison[numeroDuPion] = false; pionANegligerDansLAutreCombinaison[numeroDuPion] = false; } for (int numeroDuPion = 0; numeroDuPion < this.pions.length; numeroDuPion++) { if ((this.pions[numeroDuPion].equals(autreCombinaison.pions[numeroDuPion]))) { nombreDePionsBienPlaces++; pionANegligerDansLaCombinaison[numeroDuPion] = true; pionANegligerDansLAutreCombinaison[numeroDuPion] = true; } } for (int numeroDuPionDansLaCombinaison = 0; numeroDuPionDansLaCombinaison < this.pions.length; numeroDuPionDansLaCombinaison++) { if (pionANegligerDansLaCombinaison[numeroDuPionDansLaCombinaison]) continue; for (int numeroDuPionDansLAutreCombinaison = 0; numeroDuPionDansLAutreCombinaison < this.pions.length; numeroDuPionDansLAutreCombinaison++) { if (pionANegligerDansLAutreCombinaison[numeroDuPionDansLAutreCombinaison]) continue; if (this.pions[numeroDuPionDansLaCombinaison].equals(autreCombinaison.pions[numeroDuPionDansLAutreCombinaison])) { nombreDePionsMalPlaces++; pionANegligerDansLaCombinaison[numeroDuPionDansLaCombinaison] = true; pionANegligerDansLAutreCombinaison[numeroDuPionDansLAutreCombinaison] = true; break; } } } return new ResultatComparaison(nombreDePionsBienPlaces, nombreDePionsMalPlaces); }
abf940e9-4878-4379-a4bb-97fa29fc98d1
0
public void setIsRunning(boolean running) { this.running = running; }
cea4d18b-e86f-46b9-9e0c-84de65752950
1
public void append(char c) { // array full? if (top == capacity) { // double the space resize(capacity * 2); } // insert data[top++] = c; }
2bc6c969-f1ca-4216-b864-bc03c4c33de3
8
@Override public boolean equals(Object rhs) { if (this == rhs) { return true; } if (rhs == null) { return false; } if (!(rhs instanceof BaseAccount)) { return false; } BaseAccount other = (BaseAccount) rhs; if (acctNumber != other.acctNumber) { return false; } if (Double.compare(this.balance, other.balance) != 0) { return false; } if (owner == null) { if (other.owner != null) { return false; } } else if (!owner.equals(other.owner)) { return false; } return true; }
2b74ee48-a8a6-43ec-88ed-ce8231751027
1
public final JSONObject optJSONObject(String key) { Object o = opt(key); return o instanceof JSONObject ? (JSONObject)o : null; }
7f7e23fd-d52b-41f9-907a-62fc794d2652
2
public void actionPerformed(ActionEvent evt) { if (actionListeners != null) { Object[] listenerList = actionListeners.getListenerList(); // Recreate the ActionEvent and stuff the value of the // ACTION_COMMAND_KEY ActionEvent e = new ActionEvent(evt.getSource(), evt.getID(), (String) getValue(Action.ACTION_COMMAND_KEY)); for (int i = 0; i <= listenerList.length - 2; i += 2) { ((ActionListener) listenerList[i + 1]).actionPerformed(e); } } }
71339bda-32ac-4a53-9a30-762a6fa11747
2
static double[][] transpose(double[][] A){ double[][] B = new double[A[0].length][A.length]; for(int i = 0; i < A.length; i++){ for(int j = 0; j < A[i].length; j++){ B[j][i] = A[i][j]; } } return B; }
3a013c61-d159-4b66-bb73-7d1862fae28a
2
private void doViewAllUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pageNum = StringUtil.toString(request.getParameter("pageNum")); if("".equals(pageNum)) { pageNum = "1"; } try { Pager<User> pager = manager.getCurrentPageUsers(pageNum); request.setAttribute("pager",pager); request.getRequestDispatcher("/admin/user/adminManager.jsp").forward(request,response); return; } catch (SQLException e) { logger.error("查找所有用户失败",e); request.setAttribute("errorMsg","查找所有用户失败"); request.getRequestDispatcher("/admin/error.jsp").forward(request, response); return; } }
8f1246ca-9d0b-4846-9caf-f66a2d8720a2
5
public int getLeft(int yBottom, int range, TBlock movingBlk) { int maxX = 0; int yTop = yBottom + range; for (TBlock blk: blks) { if (!blk.equals(movingBlk)) { TSquare[] sqs = blk.getSquares(); for (int i = 0; i < sqs.length; i++) { Point2D pInContainer = blk.getSqCoordinate(i); int x = (int)pInContainer.getX(); int y = (int)pInContainer.getY(); //if the x of the sq is in the [yBottom, yRight), choose the maximum of sq.x and maxX if ((y >= yBottom) && (y < yTop)) { maxX = Math.max(maxX, x); } } } } return maxX; }
dea305a0-772a-4f2d-a271-dc41517cb041
9
public void run(IAction action) { try { if ("unknown".equals(this.selected)) { MessageDialog.openInformation(new Shell(), "Easy Explore", "Unable to explore " + this.selectedClass.getName()); EasyExplorePlugin .log("Unable to explore " + this.selectedClass); return; } File directory = null; if (this.selected instanceof IResource) directory = new File(((IResource) this.selected).getLocation() .toOSString()); else if (this.selected instanceof File) { directory = (File) this.selected; } if (this.selected instanceof IFile) { directory = directory.getParentFile(); } if (this.selected instanceof File) { directory = directory.getParentFile(); } String target = EasyExplorePlugin.getDefault().getTarget(); if (!(EasyExplorePlugin.getDefault().isSupported())) { MessageDialog .openInformation( new Shell(), "Easy Explore", "This platform (" + System.getProperty("os.name") + ") is currently unsupported.\n" + "You can try to provide the correct command to execute in the Preference dialog.\n" + "If you succeed, please be kind to post your discovery on EasyExplore website http://sourceforge.net/projects/easystruts,\n" + "or by email farialima@users.sourceforge.net. Thanks !"); return; } if (target.indexOf("{0}") == -1) { target = target.trim() + " {0}"; } target = MessageFormat.format(target, new String[] { directory.toString() }); try { EasyExplorePlugin.log("running: " + target); Runtime.getRuntime().exec(target); } catch (Throwable t) { MessageDialog.openInformation(new Shell(), "Easy Explore", "Unable to execute " + target); EasyExplorePlugin.log(t); } } catch (Throwable e) { EasyExplorePlugin.log(e); } }
ee99fc76-54d8-4712-8961-54a2bc73d0dd
9
private void btn_scanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_scanActionPerformed try { CommPortIdentifier cpid = CommPortIdentifier.getPortIdentifier(port); sp = (SerialPort) cpid.open("Virtual 3D Designer", 3000); os = sp.getOutputStream(); os.write(65); os.close(); is = sp.getInputStream(); isr = new InputStreamReader(is); read = new Thread(new Runnable() { byte[] buffer = new byte[5]; float dis; int i; boolean limit = true; @Override public void run() { while (limit) { try { if (is.read() == 65) { for (int a = 0; a < 5; a++) { byte b = (byte) is.read(); if ((b > 47 && b < 58) || b == 46) { buffer[a] = b; } else { buffer[a] = 48; } } dis = Float.parseFloat(new String(buffer)); dataSet[i] = dis; System.out.println(dataSet[i]); i++; overallPB.setValue(((i+1)*100)/numPoint); //System.out.println(((i+1)*100)/numPoint); currentPB.setValue((((i+1)%roundStep)*100)/roundStep); if (i == numPoint - 1) { limit = false; } } } catch (IOException ex) { System.out.println(ex); } } } }); read.start(); } catch (Exception e) { System.out.println(e); } }//GEN-LAST:event_btn_scanActionPerformed
c684a216-19f0-4a66-b101-5d3af1f1ef41
4
private void sink(int k) { while (2 * k <= N) { int j = 2 * k; if (j < N && greater(j, j + 1)) j++; if (!greater(k, j)) break; exch(k, j); k = j; } }
ec2f7126-1186-4e10-a16a-c748f2e32901
3
public void askAttendant(ArrayList<Attendant> aList){ if (!free){ for (int i=0;i<aList.size();i++){ if (aList.get(i).free()){ aList.get(i).busy(); } } } }
d98741f1-e0a5-4673-afb0-c7051993a197
5
public int canJump(String side, Hexpos pos){ State state = this; if(side != "red" && side != "blue") return -1; if(state.owner(pos) != null) return 0; MyList jumpArea = pos.jumpNeighbours(); for(Object tmp : jumpArea){ if(state.owner((Hexpos)tmp) == side) return 2; } return 1; }
8426437b-7c76-48c7-a507-bfaa7778b108
4
public void saveStatus(){ // EDebug.print("I have been called upon"); if (wait){ wait = false; return; } // EDebug.print("\nFirst place"); // for (int i = 0; i < myDeck.size(); i++) // EDebug.print(((LinkedList)myDeck).get(i).hashCode()); // if (myDeck.size() > 0) // EDebug.print("The top of deck hash is " + myDeck.peek().hashCode()); myDeck.push((Automaton)myMaster.clone()); //push on head // EDebug.print("The master that is getting pushed on has hascode = " + myMaster.hashCode()); System.out.println(); // EDebug.print("Second place"); // for (int i = 0; i < myDeck.size(); i++) // EDebug.print(((LinkedList)myDeck).get(i).hashCode()); // // EDebug.print("\n"); if (myDeck.size() >= 2) { Automaton first = myDeck.pop(); Automaton second = myDeck.pop(); // EDebug.print("The first is " + first.hashCode() + "While the second is " + second.hashCode()); if (first.hashCode() == second.hashCode()){ myDeck.push(first); } else{ myDeck.push(second); myDeck.push(first); myBackDeck.clear(); } } // EDebug.print("Third place"); // for (int i = 0; i < myDeck.size(); i++) // EDebug.print(((LinkedList)myDeck).get(i).hashCode()); // EDebug.print(myDeck.size()); while (myDeck.size() > numUndo) myDeck.removeLast(); }
ba01d6ca-bcfe-40ed-b6ce-9788031ad51a
0
public final String getAuthor() { return author; }
87e078c8-c6ba-4340-a324-ef90b2d1395a
4
@Override public void execute(String[] args) { String dbId = args[1]; String[] userNames = args[2].split(";"); String path = args[3]; Db db = DbFactory.getDb(dbId); String triggersPath = path + "triggers\\"; String functionsPath = path + "functions\\"; String proceduresPath = path + "procedures\\"; String packagesPath = path + "packages\\"; String typesPath = path + "types\\"; String viewsPath = path + "views\\"; try { Map<String, User> users = db.getCustomUsers(); for (String userName : userNames) { if (!users.containsKey(userName)) { System.out.println("Не найден пользователь " + userName); continue; } User user = users.get(userName); for (Trigger trigger : user.getTriggers()) { saveToFile(triggersPath + trigger + ".TRG", trigger.getDdlScript()); } } } catch (Exception e) { e.printStackTrace(); } }
6995b4c1-4c06-4b31-94dc-70e084407dbc
8
public static void main(String[] args) { //initialize game BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String input = null; initializeGame(); drawBoard(); //game loop while (true){ //read the player's move input = null; try { if (whiteTurn){ System.out.println("White player's turn:"); }else{ System.out.println("Black player's turn:"); } boolean check = gameboard.detectCheck(whiteTurn); if (check == true) { if (whiteTurn) { System.out.println("white king in check"); }else { System.out.println("black king in check"); } } input = br.readLine(); parseInput(input); drawBoard(); check = gameboard.detectCheck(!whiteTurn); if (check == true) { if (!whiteTurn) { System.out.println("Checkmate"); System.out.println("Black wins"); }else { System.out.println("Checkmate"); System.out.println("White wins"); } System.exit(1); } if ( gameboard.checkStalemate( whiteTurn)){ System.out.println("Stalemate"); System.exit(1); } } catch (IOException e) { System.out.println("Invalid input. Try again."); } } //exit }
58c068b6-2e59-4aad-b5b5-e32b4374e3fb
5
public List<Flight> searchUserFlight(FlightDTO dto) { List<Flight> flights = null; String DepArrKey = (dto.getDepLoc() + dto.getArrLoc()).toUpperCase(); try{ flights = FlightData.getDepArrivalFlights(DepArrKey); } catch(NewCustomException exception){ exception.printMessage(); } if(flights!=null){ Iterator<Flight> iterator = flights.iterator(); while (iterator.hasNext()) { Flight flight = iterator.next(); if (!((dto.getFlightDate().before(flight.getValidTill())) && (flight .getFlightClass().contains((CharSequence) dto .getFlightClass().toUpperCase())))) { iterator.remove(); } } } return flights; }
4c85544b-2a64-4d8b-b81b-1307205ef12a
7
public static double getApproximateHeight( java.awt.Font f, String s, double w ) { double len = StringTool.getApproximateStringWidth( f, s ); while( len > w ) { int lastSpace = -1; int j = s.lastIndexOf( "\n" ) + 1; len = 0; while( (len < w) && (j < s.length()) ) { len += StringTool.getApproximateCharWidth( f, s.charAt( j ) ); if( s.charAt( j ) == ' ' ) { lastSpace = j; } j++; } if( len < w ) { break; // got it } if( lastSpace == -1 ) { // no spaces to break apart if( s.indexOf( ' ' ) == -1 ) { break; } lastSpace = s.lastIndexOf( ' ' ); // break at } s = s.substring( 0, lastSpace ) + "\n" + s.substring( lastSpace + 1 ); } int nl = s.split( "\n" ).length; java.awt.FontMetrics fm = java.awt.Toolkit.getDefaultToolkit().getFontMetrics( f ); java.awt.font.LineMetrics lm = f.getLineMetrics( s, fm.getFontRenderContext() ); // this calc appears to match Excel's ... float l = lm.getLeading(); //float h= lm.getHeight(); //System.out.println("Font: " + f.toString()); //System.out.println("l-i:" + fm.getLeading() + " l:" + l + " h-i:" + fm.getHeight() + " h:" + h + " a-i:" + fm.getAscent() + " a:" + lm.getAscent() + " d-i:" + fm.getDescent() + " d:" + lm.getDescent()); float h = fm.getHeight(); // KSC: revert for now ... - l/3; // i don't know why but this seems to match Excel's the closest return Math.ceil( h * (nl) );//+1)); // KSC: added + 1 for testing }
01ba20bb-e0d4-4bd0-bf20-8df70bf13ad2
3
public synchronized void update(long elapsedTime) { if (frames.size() > 1) { animTime += elapsedTime; if (animTime >= totalDuration) { animTime = animTime % totalDuration; currentFrame = 0; } while (animTime > getFrame(currentFrame).endTime) { currentFrame++; } } }
217c29e3-d1cb-4fd5-9974-7d3271d48255
6
private void sotilaanKorottaminen(int korMista, int levMista, int korMinne, int levMinne, List<int[]> mahdollisetSiirrot) { if (nappula[korMista][levMista].nimi() == 's') { for (int[] s : mahdollisetSiirrot) { if (s[0] == korMinne && s[1] == levMinne && (korMinne == 0 || korMinne == 7)) { PELILAUTA[korMista][levMista] = new Kuningatar(nappula[korMista][levMista].vari(), korMista, levMista); paivita = true; } } } }
9cb04e4d-e5dd-4212-909c-62be9b8904d7
9
public void write (Kryo kryo, Output output, Map map) { int length = map.size(); output.writeInt(length, true); Serializer keySerializer = this.keySerializer; if (keyGenericType != null) { if (keySerializer == null) keySerializer = kryo.getSerializer(keyGenericType); keyGenericType = null; } Serializer valueSerializer = this.valueSerializer; if (valueGenericType != null) { if (valueSerializer == null) valueSerializer = kryo.getSerializer(valueGenericType); valueGenericType = null; } for (Iterator iter = map.entrySet().iterator(); iter.hasNext();) { Entry entry = (Entry)iter.next(); if (keySerializer != null) { if (keysCanBeNull) kryo.writeObjectOrNull(output, entry.getKey(), keySerializer); else kryo.writeObject(output, entry.getKey(), keySerializer); } else kryo.writeClassAndObject(output, entry.getKey()); if (valueSerializer != null) { if (valuesCanBeNull) kryo.writeObjectOrNull(output, entry.getValue(), valueSerializer); else kryo.writeObject(output, entry.getValue(), valueSerializer); } else kryo.writeClassAndObject(output, entry.getValue()); } }
13fbfa27-1da8-4e81-b1ee-83e58f58e981
8
* @param carrier The carrier to board. * @return True if the unit boards the carrier. */ public boolean boardShip(Unit unit, Unit carrier) { if (!requireOurTurn()) return false; // Sanity checks. if (unit == null) { logger.warning("unit == null"); return false; } if (carrier == null) { logger.warning("Trying to load onto a non-existent carrier."); return false; } if (unit.isNaval()) { logger.warning("Trying to load a ship onto another carrier."); return false; } if (unit.isInEurope() != carrier.isInEurope() || unit.getTile() != carrier.getTile()) { logger.warning("Unit and carrier are not co-located."); return false; } // Proceed to board UnitWas unitWas = new UnitWas(unit); if (askServer().embark(unit, carrier, null) && unit.getLocation() == carrier) { gui.playSound("sound.event.loadCargo"); unitWas.fireChanges(); nextActiveUnit(); return true; } return false; }
7d883f4a-ab13-48cc-8426-276ad0f506ac
5
public boolean isBlocked(boolean front) { if (front) { for (Creature c : game.getCreatures()) { if (c.getLocation() == current.getNeighbors()[faceTo]) { return true; } } return false; } else { for (Creature c : game.getCreatures()) { if (c.getLocation() == current.getNeighbors()[backTo]) { return true; } } return false; } }