text
stringlengths
14
410k
label
int32
0
9
@Test (timeout = 1000) public void testLeave() { //start server processor ServerProcess processor = new ServerProcess(); processor.start(); try { //writer and reader for file PrintWriter writer = new PrintWriter(new FileWriter("src/server/test.txt", false)); BufferedReader in = new BufferedReader(new FileReader("src/server/test.txt")); //command through server processor processor.addLine("username gabo", writer); String response; while((response =in.readLine()) == null){ //flush writer -> write message writer.flush(); } //Checking correct message assertEquals(response, "start gabo ? "); //erasing file FileOutputStream eraser = new FileOutputStream("src/server/test.txt"); eraser.write((new String()).getBytes()); eraser.close(); processor.addLine("new gabo", writer); while ((response = in.readLine())== null) { //flush writer -> write message writer.flush(); } //checking for correct response assertEquals(response, "new gabo 0"); //erasing file FileOutputStream eraser2 = new FileOutputStream("src/server/test.txt"); eraser2.write((new String()).getBytes()); eraser2.close(); while((response =in.readLine()) == null){ //flush writer -> write message writer.flush(); } //Checking correct message assertEquals(response, "create 0"); //erasing file FileOutputStream eraser3 = new FileOutputStream("src/server/test.txt"); eraser3.write((new String()).getBytes()); eraser3.close(); PrintWriter chauWriter = new PrintWriter(new FileWriter("src/server/test1.txt", false)); BufferedReader inChau = new BufferedReader(new FileReader("src/server/test1.txt")); processor.addLine("username chau", chauWriter); while ((response = inChau.readLine())== null) { //flush writer -> write message chauWriter.flush(); } //checking if correct message was sent assertEquals(response, "start chau gabo ? 0"); //erasing file FileOutputStream eraserchau = new FileOutputStream("src/server/test1.txt"); eraserchau.write((new String()).getBytes()); eraserchau.close(); processor.addLine("invite chau 0", writer); while ((response = in.readLine())==null) { //flush writer -> write message writer.flush(); } //checking if correct message was sent assertEquals(response, "connect chau"); while ((response = inChau.readLine())==null) { //flush writer -> write message chauWriter.flush(); } assertEquals(response, "new gabo chau ? 0"); while ((response = in.readLine())==null) { //flush writer -> write message writer.flush(); } //checking if correct message was sent assertEquals(response, "add chau 0"); //leave message to server processor.addLine("leave gabo 0", writer); while((response =inChau.readLine()) == null){ //flush writer -> write message chauWriter.flush(); } //checking for correct response assertEquals(response, "leave gabo 0"); //erasing file FileOutputStream eraser4 = new FileOutputStream("src/server/test.txt"); eraser4.write((new String()).getBytes()); eraser4.close(); //Closing writer and reader in.close(); inChau.close(); writer.close(); } catch (IOException e){ System.out.println(e.getMessage()); throw new RuntimeException(); } }
9
protected void loadRegulation() { String name = "Regulation"; String fileName = dirName + name + ".txt"; if (verbose) Timer.showStdErr("Loading " + name + " from '" + fileName + "'"); int i = 1; for (String line : Gpr.readFile(fileName).split("\n")) { // Parse line String rec[] = line.split("\t"); String id = rec[0]; String regulatedEntityId = rec[1]; String regulatorId = rec[2]; if (id.equals("DB_ID")) continue; // Skip title // Add event to pathway // Gpr.debug("Adding:\tregulatedEntityId: " + regulatedEntityId + "\t" + objectType.get(regulatedEntityId)); Reaction reaction = (Reaction) entityById.get(regulatedEntityId); if (reaction == null) continue; // Reaction not found? Skip Entity e = getOrCreateEntity(regulatorId); reaction.addRegulator(e, objectType.get(id)); if (verbose) Gpr.showMark(i++, SHOW_EVERY); } if (verbose) System.err.println(""); if (verbose) Timer.showStdErr("Total regulations assigned: " + (i - 1)); }
7
public byte[] processProxyMessage( int messageReference, boolean messageIsRequest, String remoteHost, int remotePort, boolean serviceIsHttps, String httpMethod, String url, String resourceType, String statusCode, String responseContentType, byte[] message, int[] action) { if (messageIsRequest == false) { if (debug) System.out.println("DEBUG: Response for URL: " + url); String strMessage = new String(message); String[] strHeadersAndContent = strMessage.split("\\r\\n\\r\\n"); byte[] byteOrigMessageContent = strHeadersAndContent[1].getBytes(); // RFC1950 Compression? byte[] byteInflatedMessageContent = com.gdssecurity.utils.Compression.inflate(byteOrigMessageContent,false); if (debug) { if (!byteInflatedMessageContent.equals(byteOrigMessageContent)) { System.out.println("DEBUG: Using RFC1950 compression"); } } // RFC1951 Compression? if (byteInflatedMessageContent.equals(byteOrigMessageContent)) { byteInflatedMessageContent = com.gdssecurity.utils.Compression.inflate(byteOrigMessageContent,true); if (debug) { if (!byteInflatedMessageContent.equals(byteOrigMessageContent)) { System.out.println("DEBUG: Using RFC1951 compression"); } } } /* If message contents have been changed, * 1) Update Content-Length header * 2) Remove Content-Encoding: deflate header */ if (!byteInflatedMessageContent.equals(byteOrigMessageContent)) { strHeadersAndContent[0] = com.gdssecurity.utils.HttpHelper.updateContentLength(strHeadersAndContent[0],byteInflatedMessageContent.length); strHeadersAndContent[0] = com.gdssecurity.utils.HttpHelper.removeHttpHeader(strHeadersAndContent[0],"Content-Encoding: deflate\\r\\n"); strHeadersAndContent[1] = new String(byteInflatedMessageContent); return (strHeadersAndContent[0] + "\r\n\r\n" + strHeadersAndContent[1]).getBytes(); } else { return message; } } return message; }
8
private String getPagina(URL url) { StringWriter writer = new StringWriter(); try {IOUtils.copy(url.openStream(), writer);} catch (IOException ex) {Logger.getLogger(WebCrawler.class.getName()).log(Level.SEVERE, null, ex);} String contenidoString = writer.toString(); return contenidoString; }
1
public boolean equals(Object object) { try { PDATransition t = (PDATransition) object; return super.equals(object) && myInputToRead.equals(t.myInputToRead) && myStringToPop.equals(t.myStringToPop) && myStringToPush.equals(t.myStringToPush); } catch (ClassCastException e) { return false; } }
4
@Override protected void onStarted() { GlobalUtil.threadExecutor().execute(new Runnable() { @Override public void run() { FileReceivingController receiver; int percent; int speed; while (isRunning()) { for (CoreFileInfo file : receivingFiles.keySet()) { if (file != null) { receiver = receivingFiles.get(file); if (receiver != null) { if (receiver.getReceivedLength() < file.length) { percent = (int) (receiver.getReceivedLength() * 100 / file.length); speed = (int) (receiver.getReceivedLength() / (System.currentTimeMillis() - receiver.getStartReceivingTime())); if(GlobalUtil.SHOW_SYSTEM_OUT) System.out.println("Receiving file " + file.pathName + " with " + speed + " KB/s."); onReceivingFile(file, percent, speed); } else { receivingFiles.put(file, null); } } } } try { Thread.sleep(1000); } catch (Exception e) { e.printStackTrace(System.err); } } receivingFiles.clear(); } }); }
7
public synchronized void attack(Attack attack){ /* Funcion de ataqueProvisional*/ attackPool.add(attack); Actor attacker = (attack.caster); for(Map.Entry actor : actores.entrySet()) { Actor a = (Actor)actor.getValue(); // Con este if evitamos el fuego amigo // if (attack.caster.type != attacker.type){ if ( a.uid != attacker.uid &&(Math.abs(attack.center[0]-a.getPos()[0])< attack.range && Math.abs(attack.center[1]-a.getPos()[1])< attack.range)){ if(a.health > 0 && a.isAttacked(attack)==0){ //0 es ataque basico /* Aqui se trata la muerte del personaje*/ //attacker.killed_creatures++; attack.caster.killed_creatures++; onDie(a); } // } } } }
6
public String getIP(){ if(HOSTIP != null){ return HOSTIP; } else { try { for ( final Enumeration< NetworkInterface > interfaces = NetworkInterface.getNetworkInterfaces( ); interfaces.hasMoreElements( ); ) { final NetworkInterface cur = interfaces.nextElement( ); if ( cur.isLoopback( ) ) { continue; } for ( final InterfaceAddress addr : cur.getInterfaceAddresses( ) ) { final InetAddress inet_addr = addr.getAddress( ); if ( !( inet_addr instanceof Inet4Address ) ) { continue; } HOSTIP = inet_addr.getHostAddress(); System.out.println("address: " + HOSTIP); jTextField3.setText("Your IP: " + HOSTIP); return HOSTIP; } } } catch (SocketException ex) { ex.printStackTrace(); } } //default case return ""; }
6
void createHMlut(int [] kernel, int [] lut){ int i, j, match, toMatch; for(i=0;i<512;i++) lut[i]=1; toMatch=0; for(j=0;j<9;j++){ if (kernel[j]!=2) toMatch++; } //System.out.println("Debug: to match: "+toMatch); //make lut for(i=0;i<512;i++){ match=0; for(j=0;j<9;j++){ if (kernel[j]!=2){ if ((((i & (int)Math.pow(2,j))!=0)?1:0) == kernel[j]) match++; } } if (match!=toMatch){ lut[i]=0; } } }
9
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); Connection con=(Connection)Konekcija.konekcija(); int zahtev=0; String []g = request.getParameterValues("check"); String dugme=request.getParameter("dugme"); if(dugme.equalsIgnoreCase("dodaj")){ if (g != null) { for (int i = 0; i < g.length; i++) { String ime=g[i]; Statement st1=null; Statement st=null; ResultSet rs=null; Statement st2=null; try{ st=con.createStatement(); rs=st.executeQuery("select * from zahtev where ime='"+ime+"'"); if(rs.next()){ String upit1 = "INSERT INTO korisnik (korisnickoIme,ime,prezime,lozinka,adresa,telefon,email,vrstaKorisnika,zahtev) " + "VALUES ('"+rs.getString(1)+"','"+rs.getString(2)+"','"+rs.getString(3)+"','"+rs.getString(4)+"','"+rs.getString(5)+"','"+rs.getString(6)+"','"+rs.getString(7)+"','"+rs.getString(8)+"','"+zahtev+"')"; st1=con.createStatement(); st1.executeUpdate(upit1); st2=con.createStatement(); int zahtev1=1; st2.executeUpdate("UPDATE zahtev set zahtev='"+zahtev1+"' where ime='"+ime+"'"); out.println("<a href='logovanjeAdministratora.jsp'>Uspesno ste odobrili zahteve</a>"); } }catch(SQLException e){} } } }else if(dugme.equalsIgnoreCase("odbij")){ if (g != null) { for (int i = 0; i < g.length; i++) { String ime=g[i]; Statement st2=null; try{ int zahtev1=1; st2=con.createStatement(); st2.executeUpdate("UPDATE zahtev set zahtev='"+zahtev1+"' where ime='"+ime+"'"); out.println("Odbili ste zahtev za registraciju"); RequestDispatcher dis=request.getRequestDispatcher("logovanjeAdministratora.jsp"); dis.forward(request, response); }catch(SQLException e){} } } } }
9
private void clearNearCache(Block block) { String selfMeta = null; String neighborMeta = null; if (block.getType() == Material.WALL_SIGN) { selfMeta = FILTER_INVENTORY; neighborMeta = HopperFilter.MATCHERS; } else if (block.getType() == Material.HOPPER) { selfMeta = HopperFilter.MATCHERS; neighborMeta = FILTER_INVENTORY; } if (selfMeta != null && neighborMeta != null) { if (block.hasMetadata(selfMeta)) { block.removeMetadata(selfMeta, plugin); } for (BlockFace direction: HopperFilter.signDirections) { Block neighbor = block.getRelative(direction); if (neighbor.hasMetadata(neighborMeta)) { neighbor.removeMetadata(neighborMeta, plugin); } } } }
7
@Override public void paintComponent(Graphics g) { super.paintComponent(g); // Draws the background paintBackground(g); // Creates or destroys the triple buffer as needed if (tripleBuffered) { checkTripleBuffer(); } else if (tripleBuffer != null) { destroyTripleBuffer(); } // Paints the buffer in the canvas onto the dirty region if (tripleBuffer != null) { mxUtils.drawImageClip(g, tripleBuffer, this); } // Paints the graph directly onto the graphics else { Graphics2D g2 = (Graphics2D) g; RenderingHints tmp = g2.getRenderingHints(); // Sets the graphics in the canvas try { mxUtils.setAntiAlias(g2, antiAlias, textAntiAlias); drawGraph(g2, true); } finally { // Restores the graphics state g2.setRenderingHints(tmp); } } eventSource.fireEvent(new mxEventObject(mxEvent.PAINT, "g", g)); }
3
public PDFObject dereference() throws IOException { if (type == INDIRECT) { PDFObject obj = null; if (cache != null) { obj = (PDFObject) cache.get(); } if (obj == null || obj.value == null) { if (owner == null) { System.out.println("Bad seed (owner==null)! Object=" + this); } obj = owner.dereference((PDFXref)value, getDecrypter()); cache = new SoftReference<PDFObject>(obj); } return obj; } else { // not indirect, no need to dereference return this; } }
5
public String bestQuestion() { if(questionStats.size() > 0) { QuestionStatistic max = Collections.max(questionStats); return max.questionText + ", " + max.correctAnswers + " times."; } return "no statistics found!"; }
1
public void setRightBranch(ClusterNode rightBranch) { this.rightBranch = rightBranch; }
0
public ListNode getIntersectionNode(ListNode headA, ListNode headB) { // find length of A int alen = findLength(headA); if (alen == 0) return null; // find length of B int blen = findLength(headB); if (blen == 0) return null; // move the difference ListNode p1, p2; if( alen > blen) { p1 = premove(headA, alen - blen); p2 = headB; } else { p1 = headA; p2 = premove(headB, blen - alen); } // move A and B together until hit the intersection while (p1 != p2) { p1 = p1.next; p2 = p2.next; } // check if the final nodes are the same if (p1 != null && p1 == p2) return p1; return null; }
6
public static double deltaAngle(double angle1, double angle2) { while (angle2 <= -180) angle2 += 360; while (angle2 > 180) angle2 -= 360; while (angle1 <= -180) angle1 += 360; while (angle1 > 180) angle1 -= 360; double r = angle2 - angle1; return r + ((r > 180) ? -360 : (r < -180) ? 360 : 0); }
6
@Test public void testGetSingleTransactionRecordById() { CardPaymentRequest paymentRequest = getCreditCardPaymentRequest( getRandomOrderId("TEST"), "90.00"); try { PaymentResponse payment = beanstream.payments().makePayment(paymentRequest); Assert.assertNotNull("Payment was null, cannot proceed with test", payment); Assert.assertNotNull("Payment had no ID, cannot proceed with test", payment.id); Transaction transaction = beanstream.reports().getTransaction(payment.id); Assert.assertNotNull(transaction); Assert.assertEquals("Amounts did not match", "90.0", transaction.getAmount()); } catch (BeanstreamApiException ex) { Logger.getLogger(ReportsAPITest.class.getName()).log(Level.SEVERE, "Error accessing Beanstream API "+ex.getCode()+", "+ex.getCategory()+", "+ex.getMessage(), ex); Assert.assertTrue("Unexpected Exception", false); } }
1
public List<QuadTree> getBottomNeighbors() { QuadTree sibling = this.getBottomSibling(); if ( sibling == null ) return new ArrayList<QuadTree>(); return sibling.getTopChildren(); }
1
public Quiz buildQuiz(Quiz q, TreeMap<SubjectType, Integer> subjects) { Random random = new Random(); for(SubjectType s : subjects.keySet()) { int[] selections = new int[subjects.get(s)]; for(int i = 0; i < selections.length; i++) selections[i] = -1; Query query = em.createQuery("SELECT q FROM Question q where q.subject like '"+s.getLabel()+"'"); List<Question> results = query.getResultList(); if(results.size() >= selections.length) { for(int i = 0; i < selections.length; i++) { int n = 0; boolean contains = false; do { contains = false; n = random.nextInt(results.size()); for(int j = 0; j < selections.length; j++) if(selections[j] == n) { contains = true; break; } }while(contains); selections[i] = n; } for(int i : selections) { q.addQuestion(results.get(i)); } } else { for(int i = 0; i < results.size(); i++) { q.addQuestion(results.get(i)); } } } q.setIsTemporary(true); // em.persist(q); return q; }
9
@Override public void cleanUp() { stopSound(); if (source != null) { source.projectileReturned(); } }
1
public void addOneToBasket(int productId) { boolean isAdded; if (basket.containsKey(productId)) { isAdded = basket.get(productId).addOneProduct(); } else { ProductInBasket prod = new ProductInBasket(); ProductDAO dao = DAOFactory.getInstance().getProductDAO(); isAdded = prod.setProduct(dao.findProduct(productId)); if (isAdded) basket.put(productId, prod); } if (isAdded) { numProductsInBasket++; } }
3
private void light(int x, int y) { int key = genKey(x, y); if (actorHashMap.containsKey(key)) { currentSenses.putActor(key, actorHashMap.get(key)); } if (tileHashMap.containsKey(key)) { currentSenses.putTile(key, tileHashMap.get(key)); } if (playerloc.equals(new Point(x, y))) { currentSenses.playerLoc(playerloc); } if (entities.containsKey(key)) { currentSenses.putEntities(key, entities.get(key)); } }
4
protected MOB getCharmer() { if(charmer!=null) return charmer; if((invoker!=null)&&(invoker!=affected)) charmer=invoker; else if((text().length()>0)&&(affected instanceof MOB)) { final Room R=((MOB)affected).location(); if(R!=null) charmer=R.fetchInhabitant(text()); } if(charmer==null) return invoker; return charmer; }
7
public static Digraph rootedInDAG(int V, int E) { if (E > (long) V * (V - 1) / 2) throw new IllegalArgumentException("Too many edges"); if (E < V - 1) throw new IllegalArgumentException("Too few edges"); Digraph G = new Digraph(V); SET<Edge> set = new SET<Edge>(); // fix a topological order int[] vertices = new int[V]; for (int i = 0; i < V; i++) vertices[i] = i; StdRandom.shuffle(vertices); // one edge pointing from each vertex, other than the root = // vertices[V-1] for (int v = 0; v < V - 1; v++) { int w = StdRandom.uniform(v + 1, V); Edge e = new Edge(v, w); set.add(e); G.addEdge(vertices[v], vertices[w]); } while (G.E() < E) { int v = StdRandom.uniform(V); int w = StdRandom.uniform(V); Edge e = new Edge(v, w); if ((v < w) && !set.contains(e)) { set.add(e); G.addEdge(vertices[v], vertices[w]); } } return G; }
7
public boolean showAddDialog() { this.setTitle("ҪӵѧϢ"); canceled = false; this.getRootPane().setDefaultButton(button); this.setVisible(true); return !canceled; }
0
public ViewerMain(final Book book) { this.book = book; pageId = 7; loadPage(pageId); setLayout(new BorderLayout()); add(new JLabel() { private static final long serialVersionUID = 1L; @Override public Dimension getPreferredSize() { return new Dimension(1500, 600); } @Override public void paint(Graphics gg) { Graphics2D g = (Graphics2D) gg; super.paint(g); double f = .2; g.scale(f, f); AffineTransform baseTrans = g.getTransform(); for (BookElement el : page.pics) { g.setTransform(baseTrans); g.translate(el.left, el.top); int offX = el.width / 2, offY; // switch (el.dock) { // case top: // offY = el.height; // break; // case middle: offY = el.height / 2; // break; // case bottom: // offY = 0; // break; // default: // throw new RuntimeException( // "This command should never be called"); // } g.translate(offX, offY); double ang = el.angleDegrees / 180f * Math.PI; g.rotate(ang); g.translate(-offX, -offY); Image img; if (el instanceof BookPicture) { BookPicture pic = (BookPicture) el; img = pic.getImage(book); if (img != null) { int w = img.getWidth(null); int h = img.getHeight(null); System.out.println(">" + w + " " + h + " " + pic.cropX + " " + pic.cropY + " " + pic.cropW + " " + pic.cropH); if (w > 0) { g.drawImage(img, 0, 0, el.width, el.height, r(pic.cropX * w), r(pic.cropY * h), r((pic.cropX + pic.cropW) * w), r((pic.cropY + pic.cropH) * h), null); } else img = null; g.setFont(g.getFont().deriveFont(0).deriveFont(70f)); g.drawString(pic.getOrigName(), 0, 0); } } else if (el instanceof BookText) { BookText text = (BookText) el; String txt = text.getText(book); if (txt != null) { g.setFont(g.getFont().deriveFont(60f)); FontMetrics fm = g.getFontMetrics(); g.drawString(txt, 0, fm.getHeight()); } // int w = img.getWidth(null); // int h = img.getHeight(null); // System.out.println(">" + w + " " + h + " " + // text.cropX // + " " + text.cropY + " " + text.cropW + " " // + text.cropH); // if (w > 0) { // g.drawImage(img, 0, 0, el.width, el.height, // r(text.cropX * w), r(text.cropY * h), // r((text.cropX + text.cropW) * w), // r((text.cropY + text.cropH) * h), null); // } else img = null; } else { img = null; } if (img == null) { g.setColor(Color.LIGHT_GRAY); g.drawRect(0, 0, el.width, el.height); g.drawLine(0, 0, el.width, el.height); g.drawLine(0, el.height, el.width, 0); } // g.drawImage(img, 0, 0, pic.width, pic.height, null); } g.setTransform(baseTrans); pageBorders(g); } private void pageBorders(Graphics2D g) { g.setColor(Color.BLUE); // final int ox = 102; // final int oy = 102; // // <Width>7712</Width> // // <Height>2953</Height> // g.drawRect(ox + 0, oy + 0, ox + 7712, oy + 2953); // // <GuideLine x1="3778" y1="0" x2="3778" y2="2953" /> // g.drawLine(ox + 3778, oy + 0, ox + 3778, oy + 2953); // // <GuideLine x1="3934" y1="0" x2="3934" y2="2953" /> // g.drawLine(ox + 3934, oy + 0, ox + 3934, oy + 2953); // // <GuideBox left="220" top="220" width="7272" height="2513" // /> // g.drawRect(ox + 220, oy + 220, ox + 7272, oy + 2513); final int ox = 0; final int oy = 0; // <LeftSideOffset>0</LeftSideOffset> // <RightSideOffset>3531</RightSideOffset> // <LeftPageOffset>-102</LeftPageOffset> // <RightPageOffset>102</RightPageOffset> // <Width>7062</Width> // <Height>2504</Height> // /* dpi */300, // /* width */7062, /* height */2504, // /* margin */9.33d, /* bleed */9.33d); PaperSize p = new PaperSize.A4_Portrait(); g.drawRect(ox + 0, oy + 0, ox + p.ifolorDoubleWidth, oy + p.ifolorHeight); // <GuideLine x1="3531" y1="0" x2="3531" y2="2504" /> g.drawLine(ox + p.ifolorDoubleWidth / 2, oy + 0, ox + p.ifolorDoubleWidth / 2, oy + p.ifolorHeight); // <GuideBox left="40" top="40" width="6982" height="2424" /> g.drawRect(ox + 40, oy + 40, ox + p.ifolorDoubleWidth - 80, oy + p.ifolorHeight - 80); } private int r(double d) { return (int) d; } }, BorderLayout.CENTER); JPanel control = new JPanel(); final JLabel label = new JLabel(); control.add(label); JButton b = new JButton("<"); b.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (--pageId < 0) pageId = 0; label.setText(String.valueOf(pageId)); loadPage(pageId); } }); control.add(b); b = new JButton(">"); b.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (++pageId >= book.pages.size()) pageId = book.pages.size() - 1; label.setText(String.valueOf(pageId)); loadPage(pageId); } }); control.add(b); add(control, BorderLayout.SOUTH); }
9
public SourceFixe(String arg) { informationGeneree = new Information<Boolean>(); informationEmise = informationGeneree; //Parcourir l'argument saisi par l'utilisateur for (int i = 0; i < arg.length(); i++) { //Si le caractere en cours est un 0 if (arg.charAt(i) == '0') //Ajouter false a la liste informationGeneree informationGeneree.add(false); //Si le caractere en cours est un 1 else if (arg.charAt(i) == '1') //Ajouter true a la liste informationGeneree informationGeneree.add(true); } }
3
public void saveShieldsToFile() { if (plugin.getListener() == null || plugin.getListener().getShields() == null) { return; } if (!shieldsFile.exists()) { try { shieldsFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } try { shieldsDB.save(shieldsFile); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } HashMap<ShieldOwner, Shield> map = plugin.getListener().getShields(); final Iterator<Entry<ShieldOwner, Shield>> iter = map.entrySet().iterator(); while (iter.hasNext()) { final Entry<ShieldOwner, Shield> entry = iter.next(); final Object value = entry.getValue().owner.getId(); final String key = entry.getKey().toString(); write2(key, value, shieldsFile); } }
6
public static void main(String args[]) throws InterruptedException { int i = 1; ThreadExecutor executor = new ThreadExecutor(); long startTime = System.currentTimeMillis(); while ((System.currentTimeMillis() - startTime) < 1 * 60 * 1000) { HttpAsyncClientImpl httpImpl = new HttpAsyncClientImpl(i); try { executor.executeTask(httpImpl); } catch (Exception e) { logger.error("Exception occured I " + i, e); } i++; } executor.shutDownExecutor(); if (Main.futureList.size() > 0) { for (Future<Response> futureList : Main.futureList) { try { logger.debug("Response Code " + futureList.get()); } catch (ExecutionException e) { logger.error( "Exception occured while processing the responses " + i, e); e.printStackTrace(); } } } }
5
public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; for (int i = characters.size() - 1; i > -1; i--) { characters.get(i).paintCharacter(g2); } for (int i = projectiles.size() - 1; i > -1; i--) { projectiles.get(i).paintProjectile(g2); } for (int i = 0; i < blocks.size(); i++) { g2.draw(blocks.get(i)); } for (int i = 0; i < powerUps.size(); i++) { powerUps.get(i).paintPowerUp(g2); } }
4
int insertKeyRehash(long val, int index, int hash, byte state) { // compute the double hash final int length = _set.length; int probe = 1 + (hash % (length - 2)); final int loopIndex = index; int firstRemoved = -1; /** * Look until FREE slot or we start to loop */ do { // Identify first removed slot if (state == REMOVED && firstRemoved == -1) firstRemoved = index; index -= probe; if (index < 0) { index += length; } state = _states[index]; // A FREE slot stops the search if (state == FREE) { if (firstRemoved != -1) { insertKeyAt(firstRemoved, val); return firstRemoved; } else { consumeFreeSlot = true; insertKeyAt(index, val); return index; } } if (state == FULL && _set[index] == val) { return -index - 1; } // Detect loop } while (index != loopIndex); // We inspected all reachable slots and did not find a FREE one // If we found a REMOVED slot we return the first one found if (firstRemoved != -1) { insertKeyAt(firstRemoved, val); return firstRemoved; } // Can a resizing strategy be found that resizes the set? throw new IllegalStateException("No free or removed slots available. Key set full?!!"); }
9
public LoperFrame(final Sponsorloop loop) { this.loop = loop; sf = null; setSize(200, 200); lab1 = new JLabel("Lopers", JLabel.CENTER); lab2 = new JLabel(); updateAantal(); listModel = new DefaultListModel(); list = new JList(listModel); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); deselect(); list.setVisibleRowCount(5); b1 = new JButton("Nieuwe Loper"); b2 = new JButton("Verwijder Loper"); JScrollPane listScrollPane = new JScrollPane(list); JPanel lowerPane = new JPanel(); lowerPane.setLayout(new BorderLayout()); //Wat er gebeurt bij veranderen van selectie in het menu list.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent arg0) { if (!arg0.getValueIsAdjusting()) { if (sf != null) { sf.dispose(); } if (list.getSelectedValue() != null) { sf = new SponsorFrame(loop.getLoper(getLoper())); updateAantal(); b2.setEnabled(true); geefDoor(); } if (list.getSelectedValue() == null) { b2.setEnabled(false); } } } }); add(lab1, BorderLayout.NORTH); lowerPane.add(lab2, BorderLayout.NORTH); lowerPane.add(b1, BorderLayout.CENTER); lowerPane.add(b2, BorderLayout.SOUTH); b2.setEnabled(false); add(listScrollPane, BorderLayout.CENTER); add(lowerPane, BorderLayout.SOUTH); b1.addActionListener(this); b2.addActionListener(this); for (Loper l : loop.getLopers()) { listModel.addElement(l.getNummer() + ". " + l.getNaam()); } Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); this.setLocation(450, dim.height / 2 - this.getSize().height / 2); setVisible(true); this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { mf.deselect(); if (sf != null) { sf.dispose(); } } }); }
6
public int split(int i, int j) throws Exception { if (i > j) throw new Exception("Invalid Matrix sequence"); if (i > n || j > n) throw new Exception("Non existent matrix specified"); return split[i][j]; }
3
public int getBlue(int row, int col) { if (row >=0 && row < rows && col >= 0 && col < columns && grid[row][col] != null) return grid[row][col].getBlue(); else return defaultColor.getBlue(); }
5
public ROPacketTransmitter getPacketTransmitter() { return packetTransmitter; }
0
public String isOkay(String e, boolean anyOfSuit){ int h = convert(e); if (h < 0 || h > _hand.size()-1){return "Illegal move. Please select a card in your hand.";} Card d = _hand.get(h); String retStr = ""; if ( isLeading == true && isBroken == false && d.getSuit() == 0) {retStr = "Illegal move. Hearts has not yet been broken, please lead a card of another suit.";} if (isLeading == false && _trickSuit != d.getSuit() && anyOfSuit == true){retStr = "Illegal move. You have a " + _table.get(0).getSuitName() + ", so you must play it.";} //make getSuitName return retStr; }
8
public double modulo(){ return sqrt(x*x + y*y + z*z); }
0
public void setLHS(String lhs) { myLHS = lhs; }
0
@Override public boolean executeValidation(CreditCard creditCard) { log.fine("Starting credit card validation"); boolean isValid = true; isValid = validateCardNumber(creditCard.getCardNumber()) && isValid; // Only check the type if the number was valid, since the type depends // on it if (isValid) { isValid = validateCardType(creditCard.getCardNumber(), creditCard.getCardType()) && isValid; } isValid = validateExpirationDate(creditCard.getValidUntilMonth(), creditCard.getValidUntilYear()) && isValid; return isValid; }
4
@Override public void onAnalog(String name, float isPressed, float tpf) { float pos = isPressed / tpf; if (name.equals("Accelerate Vehicle")){ if (car != null) { car.throttlePressed(pos); } } if (name.equals("Brake Vehicle")) { if (car != null) { car.brakePressed(pos); } } if (name.equals("Steer Left")){ if (car != null) { car.steer(pos, tpf); } } if (name.equals("Steer Right")){ if (car != null) { car.steer(-pos, tpf); } } }
8
public String changeKeyboardLayout() { String previous = pref.getKeyboardLayout(); String[] layouts = pref.getExistingKeyboardLayouts(); // TODO: pass current item name ChooseFromExisting dialog = new ChooseFromExisting(layouts); dialog.dispose(); String newLayout = dialog.getChosen(); // Don't do anything if nothing changed if (newLayout == null || newLayout.equals(previous)) return previous; boolean foundFlag = false; // Check if new layout is in the list of existing layouts for (int i = 0; i < layouts.length; i++) { // If found, make the new layout first in list if (layouts[i].equals(newLayout)) { String tmp = layouts[i]; layouts[i] = layouts[0]; layouts[0] = tmp; foundFlag = true; break; } } // Update list of layouts String newLayoutList = ""; if (foundFlag == false) newLayoutList += newLayout + ","; for (int i = 0; i < layouts.length - 1; i++) newLayoutList += layouts[i] + ","; newLayoutList += layouts[layouts.length - 1]; pref.setExistingKeyboardLayouts(newLayoutList); pref.update(); return newLayout; }
6
public Element handle(FreeColServer server, Player player, Connection connection) { ServerPlayer serverPlayer = server.getPlayer(connection); Unit unit; try { unit = player.getFreeColGameObject(unitId, Unit.class); } catch (Exception e) { return DOMMessage.clientError(e.getMessage()); } Tile tile; try { tile = unit.getNeighbourTile(directionString); } catch (Exception e) { return DOMMessage.clientError(e.getMessage()); } IndianSettlement is = tile.getIndianSettlement(); if (is == null) { return DOMMessage.clientError("There is no native settlement at: " + tile.getId()); } Unit missionary = is.getMissionary(); if (denounce) { if (missionary == null) { return DOMMessage.clientError("Denouncing an empty mission at: " + is.getId()); } else if (missionary.getOwner() == player) { return DOMMessage.clientError("Denouncing our own missionary at: " + is.getId()); } } else { if (missionary != null) { return DOMMessage.clientError("Establishing extra mission at: " + is.getId()); } } MoveType type = unit.getMoveType(is.getTile()); if (type != MoveType.ENTER_INDIAN_SETTLEMENT_WITH_MISSIONARY) { return DOMMessage.clientError("Unable to enter " + is.getName() + ": " + type.whyIllegal()); } // Valid, proceed to denounce/establish. return (denounce) ? server.getInGameController() .denounceMission(serverPlayer, unit, is) : server.getInGameController() .establishMission(serverPlayer, unit, is); }
9
public MyGraph computeCover4() { MyGraph cover = new MyGraph(this); ArrayList<MyNode> hightDegreeNodes = new ArrayList<MyNode>(); for (MyNode n : cover.getNodes()) { if (n.getDegree() > 2) { hightDegreeNodes.add(n); } } for (MyNode node : hightDegreeNodes) { for (MyEdge edge : cover.outEdges(node)) { if (cover.isNotVine(node, edge)) { double oldW = edge.getWeight(); edge.setWeight(oldW / 2); } } } while (!cover.isPaths()) { ArrayList<MyEdge> cuts = null; while (cuts == null && !hightDegreeNodes.isEmpty()) { MyNode node = hightDegreeNodes.get(0); cuts = cover.computeWorstEdges(node); hightDegreeNodes.remove(0); } for (MyEdge e : cuts) { cover.removeEdge(e); } } return cover; }
9
@Test public void testGetSubset() { DoubleIntervalMap<double[]> map = new DoubleIntervalMap<double[]>(); StupidDoubleIntervalMap stupid = new StupidDoubleIntervalMap(); RandomIter iter = new RandomIter( getSeed(), 0, 1000 ); final int testCount = 2000; final int subtestCount = 100; for( int t = 0; t < testCount; t++ ) { int keyCount = iter.mRand.nextInt( 200 ); for( int i = 0; i < keyCount; i++ ) { double[] key = iter.next(); map.put( key, key ); stupid.put( key, key ); } } for( int i = 0; i < subtestCount; i++ ) { double[] key = iter.next(); double[] a = map.getSubset( key ); double[] b = stupid.getContained( key ); if( (a == null) != (b == null) || a != null && a[0] != b[0] && a[1] != b[1] ) { map.getSubset( key ); } assertEquals( a, b ); } }
7
@Deprecated private Mesh calculateTesselator() { ArrayList<Vector3f> vertices = new ArrayList<Vector3f>(); ArrayList<Integer> indices = new ArrayList<Integer>(); int z = -fraction / 2; int x; while ( z <= fraction / 2 ) { x = -fraction / 2; while ( x <= fraction / 2 ) { float rand1 = MathHelper.rand( -0.3f, 0.3f ); float rand2 = MathHelper.rand( -0.3f, 0.3f ); for ( int i = 0; i < 6; i++ ) vertices.add( new Vector3f( ( x + rand1 ) / fraction, noise[x + fraction / 2][z + fraction / 2] / ( fraction / smooth ), ( z + rand2 ) / fraction, this.color ) ); x++; } z++; } z = 0; int test = ( fraction + 1 ) * 6; int actual = 0; int index = 0; while ( z < fraction ) { x = 0; while ( x < fraction ) { if ( actual != fraction * 6 + index ) { indices.add( actual ); indices.add( actual + test + 2 ); indices.add( actual + 6 + 4 ); indices.add( actual + 6 + 5 ); indices.add( actual + test + 1 ); indices.add( actual + test + 6 + 3 ); } else index += fraction * 6 + 6; actual += 6; x++; } z++; } ArrayList<Triangle> triangles = new ArrayList<Triangle>(); for ( int i = 0; i < indices.size(); i += 3 ) triangles.add( new Triangle( vertices.get( indices.get( i ) ), vertices.get( indices.get( i + 1 ) ), vertices.get( indices.get( i + 2 ) ) ) ); return new Mesh( triangles ); }
7
public Writer write(Writer writer) throws JSONException { try { boolean b = false; int len = length(); writer.write('['); for (int i = 0; i < len; i += 1) { if (b) { writer.write(','); } Object v = this.myArrayList.get(i); if (v instanceof JSONObject) { ((JSONObject)v).write(writer); } else if (v instanceof JSONArray) { ((JSONArray)v).write(writer); } else { writer.write(JSONObject.valueToString(v)); } b = true; } writer.write(']'); return writer; } catch (IOException e) { throw new JSONException(e); } }
5
public void compareJvmCost() { String rMapperFile = "realMapper.txt"; String rReducerFile = "realReducer.txt"; String realJvmCostDir = bigBaseDir + bigJobName + "/RealJvmCost/"; String estiJvmCostDir = compBaseDir + compJobName + "/estimatedDM/"; String compJvmCostDir = compBaseDir + compJobName + "/compJvmCost/"; List<SplitMapperRealJvmCost> rMapperJvmCostList = readRealMapperJvmCost(realJvmCostDir + rMapperFile); List<SplitReducerRealJvmCost> rReducerJvmCostList = readRealReducerJvmCost(realJvmCostDir + rReducerFile); String eMapperFile = "eJvmMappers.txt"; String eReducerFile = "eJvmReducers.txt"; String cMapperFile = "compMappers.txt"; String cReducerFile = "compReducers.txt"; String diffMapper = "diffMappers.txt"; String diffReducer = "diffReducers.txt"; File diffMapperFile = new File(compJvmCostDir + diffMapper); File diffReducerFile = new File(compJvmCostDir + diffReducer); if(!diffMapperFile.getParentFile().exists()) diffMapperFile.getParentFile().mkdirs(); PrintWriter diffMapperWriter; PrintWriter diffReducerWriter; try { diffMapperWriter = new PrintWriter(new BufferedWriter(new FileWriter(diffMapperFile))); diffReducerWriter = new PrintWriter(new BufferedWriter(new FileWriter(diffReducerFile))); printDiffTitle(diffMapperWriter, diffReducerWriter); File eDir = new File(estiJvmCostDir); for(File jobIdFile : eDir.listFiles()) { String jobIdName = jobIdFile.getName(); List<SplitMapperPredictedJvmCost> eMapperJvmCostList = readEstimatedMapperJvmCost(estiJvmCostDir + jobIdName + File.separator + eMapperFile); List<SplitReducerPredictedJvmCost> eReducerJvmCostList = readEstimatedReducerJvmCost(estiJvmCostDir + jobIdName + File.separator + eReducerFile); List<SplitMapperCompJvmCost> cMapperJvmCostList = compareMapperJvmCost(rMapperJvmCostList, eMapperJvmCostList); List<SplitReducerCompJvmCost> cReducerJvmCostList = compareReducerJvmCost(rReducerJvmCostList, eReducerJvmCostList); try { displayCompResults(cMapperJvmCostList, cReducerJvmCostList, compJvmCostDir + jobIdName + File.separator + cMapperFile, compJvmCostDir + jobIdName + File.separator + cReducerFile, jobIdName); evaluateJvmCostDiff(cMapperJvmCostList, cReducerJvmCostList, diffMapperWriter, diffReducerWriter, jobIdFile.getName()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } diffMapperWriter.close(); diffReducerWriter.close(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }
4
protected short parse_config_param(final String param_title, final String param_content) { short ret = MsgDumperCmnDef.MSG_DUMPER_SUCCESS; boolean found = false; for (int index = 0 ; index < title_len ; index++) { if (param_title.indexOf(title[index]) == 0) { switch(index) { case 0: server_list = param_content; break; case 1: server_port = param_content; break; default: MsgDumperCmnDef.WriteErrorFormatSyslog(__FILE__(), __LINE__(), "Incorrect parameter: %s=%s", param_title, param_content); ret = MsgDumperCmnDef.MSG_DUMPER_FAILURE_INVALID_ARGUMENT; break; } found = true; MsgDumperCmnDef.WriteDebugFormatSyslog(__FILE__(), __LINE__(), "Update parameter: %s=%s", param_title, param_content); break; } } // If the title is NOT found... if (!found) { MsgDumperCmnDef.WriteErrorFormatSyslog(__FILE__(), __LINE__(), "Incorrect parameter, fail to find the title: %s", param_title); ret = MsgDumperCmnDef.MSG_DUMPER_FAILURE_INVALID_ARGUMENT; } return ret; }
5
public static boolean CheckUserProfile(Map<String, String> ProfileData) throws SQLException { boolean success = false; boolean found = false; for (int j = 0; j < GlobalData.UserProfileRecs.size(); j++) { UserProfileRec rec = GlobalData.UserProfileRecs.get(j); if (rec.username.equalsIgnoreCase(ProfileData.get("username"))) { found = true; // String userid; // String username; String email = ProfileData.get("email"); String address = ProfileData.get("address"); String officehours = ProfileData.get("officehours"); String telecontact = ProfileData.get("telecontact"); String mobilecontacts = ProfileData.get("mobilecontacts"); String logo = ProfileData.get("logo"); if (!rec.email.equalsIgnoreCase(email) || !rec.address.equalsIgnoreCase(address) || !rec.officehours.equalsIgnoreCase(officehours) || !rec.telecontact.equalsIgnoreCase(telecontact) || !rec.mobilecontacts.equalsIgnoreCase(mobilecontacts) || !rec.logo.equalsIgnoreCase(logo)){ success = UpdateUserProfilesTable(ProfileData); rec.UpdateProfileRec(email, address, officehours, telecontact, mobilecontacts,logo); } break; } } if (!found) { success = InsertIntoUserProfilesTable(ProfileData); GlobalData.UserProfileRecs .add(new UserProfileRec(null, ProfileData)); } return success; }
9
public void update(String player, String element, String value) { Node players = doc.getFirstChild(); NodeList playerNode = null; NodeList list = players.getChildNodes(); for(int i = 0; i < list.getLength(); i++) { Node node = list.item(i); if(player.equals(node.getNodeName())) playerNode = node.getChildNodes(); } for(int i = 0; i < playerNode.getLength(); i++) { Node node = playerNode.item(i); if(element.equals(node.getNodeName())) node.setTextContent(value); } try { TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer; transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(filePath)); transformer.transform(source, result); } catch (TransformerException e) { e.printStackTrace(); } }
5
public void keyReleased(KeyEvent e) { }
0
Point3f getMax() { if (max == null) max = new Point3f(); if (list.isEmpty()) { max.set(0, 0, 0); return max; } Cuboid c = getCuboid(0); max.x = c.getMaxX(); max.y = c.getMaxY(); max.z = c.getMaxZ(); synchronized (list) { int n = count(); if (n > 1) { for (int i = 1; i < n; i++) { c = getCuboid(i); if (max.x < c.getMaxX()) { max.x = c.getMaxX(); } if (max.y < c.getMaxY()) { max.y = c.getMaxY(); } if (max.z < c.getMaxZ()) { max.z = c.getMaxZ(); } } } } return max; }
7
private void constructBoard() { for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if (chessGame.gameState[i][j].getColor() != ChessPiece.COLOR_RED && chessGame.gameState[i][j].getColor() != ChessPiece.COLOR_BLUE) { if (j % 2 == 0) { if (i % 2 == 0) { chessGame.gameState[i][j] = new ChessPiece(ChessPiece.GROUND_WHITE, ChessPiece.COLOR_WHITEBOARD); } else { chessGame.gameState[i][j] = new ChessPiece(ChessPiece.GROUND_BLACK, ChessPiece.COLOR_BLACKBOARD); } } else { if (i % 2 == 0) { chessGame.gameState[i][j] = new ChessPiece(ChessPiece.GROUND_BLACK, ChessPiece.COLOR_BLACKBOARD); } else { chessGame.gameState[i][j] = new ChessPiece(ChessPiece.GROUND_WHITE, ChessPiece.COLOR_WHITEBOARD); } // chessGame.gameState[i][j] = new // ChessPiece(ChessPiece.GROUND_BLACK, // ChessPiece.COLOR_BLACKBOARD); } } } } }
7
protected boolean isAttribute(ResTable_Map map) { return map.name == ATTR_TYPE || map.name == ATTR_MIN || map.name == ATTR_MAX || map.name == ATTR_L10N || map.name == ATTR_OTHER || map.name == ATTR_ZERO || map.name == ATTR_ONE || map.name == ATTR_TWO || map.name == ATTR_FEW || map.name == ATTR_MANY; }
9
private String saveTmpFile(ByteBuffer b, int offset, int len) { String path = ""; if (len > 0) { FileOutputStream fileOutputStream = null; try { TempFile tempFile = tempFileManager.createTempFile(); ByteBuffer src = b.duplicate(); fileOutputStream = new FileOutputStream(tempFile.getName()); FileChannel dest = fileOutputStream.getChannel(); src.position(offset).limit(offset + len); dest.write(src.slice()); path = tempFile.getName(); } catch (Exception e) { // Catch exception if any System.err.println("Error: " + e.getMessage()); } finally { safeClose(fileOutputStream); } } return path; }
2
public Tffst toSingleInputLabelTransitions() { Tffst simpleTffst = new Tffst(); HashMap<State, State> m = new HashMap<State, State>(); State last; Set<State> states = getStates(); for (State s : states) { System.out.println(s.toString()); if (m.get(s) == null) { last = new State(); m.put(s, last); last.accept = s.accept; if (s == initial) simpleTffst.initial = last; } else { last = m.get(s); } for (Transition t : s.getTransitions()) { if (m.get(t.getTo()) == null) { State newTo = new State(); m.put(t.getTo(), newTo); newTo.accept = t.getTo().accept; if (t.getTo() == initial) simpleTffst.initial = t.getTo(); } Transition lastTran = new Transition(last, new TfString(t.labelIn), new TfString(t.labelOut), m.get(t.getTo())); while (lastTran.getLabelIn().size() > 1 ) { last = lastTran.getFrom(); State ns = new State(); lastTran.setFrom(ns); if (lastTran.getLabelIn().size() > 1 ) { new Transition(last, new TfString(lastTran.getLabelIn().remove(0)), new TfString(SimpleTf.Epsilon()), ns); } } } } return simpleTffst; }
8
public static Map<String, Object> formatResponseAsMap(InputStream stream) throws Exception { Map<String, Object> mapResponse = new LinkedHashMap<String, Object>(); try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = docFactory.newDocumentBuilder(); Document document = builder.parse(stream); document.getDocumentElement().normalize(); NodeList response = document.getElementsByTagName("response"); for(int i=0; i< response.getLength(); i++){ //response Node responseItem = response.item(i); //responseID, result NodeList allResponseChild = responseItem.getChildNodes(); for(int j=0; j< allResponseChild.getLength(); j++){ //responseID, result Node eachResponseChild = allResponseChild.item(j); if(eachResponseChild.getNodeName().equals("responseID")){ mapResponse.put("responseID", eachResponseChild.getTextContent()); continue; } NodeList resultItem = eachResponseChild.getChildNodes(); Map<String,Object> mapResult = new LinkedHashMap<String,Object>(); for(int k=0; k < resultItem.getLength(); k++){ //resultID, item Node eachResultItem = resultItem.item(k); if(eachResultItem.getNodeName().equals("resultID")){ mapResult.put("resultID", eachResultItem.getTextContent()); continue; } //item, key/value NodeList nodeItemAtResult = eachResultItem.getChildNodes(); String key = null; String value = null; for(int c = 0; c < nodeItemAtResult.getLength(); c++){ //key, value Node eachItemAtResult = nodeItemAtResult.item(c); if(eachItemAtResult.getNodeName().equals("key")){ key = eachItemAtResult.getTextContent(); }else{ value = eachItemAtResult.getTextContent(); } } mapResult.put(key, value); } mapResponse.put(String.valueOf(mapResult.get("resultID")), mapResult); } } return mapResponse; } catch (Exception e) { throw new Exception("Error formatting response", e); } }
8
public void setUpcomingEventsCount(int upcomingEventsCount) { this.upcomingEventsCount = upcomingEventsCount; }
0
private static String[] getSubjectAlts( final X509Certificate cert, final String hostname) { int subjectType; if (isIPAddress(hostname)) { subjectType = 7; } else { subjectType = 2; } LinkedList<String> subjectAltList = new LinkedList<String>(); Collection<List<?>> c = null; try { c = cert.getSubjectAlternativeNames(); } catch(CertificateParsingException cpe) { } if(c != null) { for (List<?> aC : c) { List<?> list = aC; int type = ((Integer) list.get(0)).intValue(); if (type == subjectType) { String s = (String) list.get(1); subjectAltList.add(s); } } } if(!subjectAltList.isEmpty()) { String[] subjectAlts = new String[subjectAltList.size()]; subjectAltList.toArray(subjectAlts); return subjectAlts; } else { return null; } }
9
public DreamerNini() { super(); courseTitles= new ArrayList<String>(); works= new ArrayList<String>(); }
0
@Override public void logOut(String username) { ResultSet rs; try { PreparedStatement statement = connection.prepareStatement( "SELECT * FROM Users " + "WHERE username = ?", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); statement.setString(1, username); rs = statement.executeQuery(); while (rs.next()) { rs.updateString(WebServerInfo.status, WebServerInfo.inactive); rs.updateRow(); break; } rs.close(); } catch (SQLException e) { e.printStackTrace(); } }
2
public float getX(float y) { if (isVertical) { return value; } else if (isHorizontal) { return Float.NaN; } else { return (y - this.b) / this.k; } }
2
public Boolean actualizar_estado(String estado, String estadoNuevo) { Boolean est = false; List DNList = new cDN().leer_por_estado(estado); Transaction trns = null; sesion = HibernateUtil.getSessionFactory().openSession(); try { trns = sesion.beginTransaction(); for (Iterator it = DNList.iterator(); it.hasNext();) { DocumentoNotificacion objDN = (DocumentoNotificacion) it.next(); DocumentoNotificacion objDNActualizar = new cDN().leer_cod(objDN.getCodDocumentoNotificacion()); objDNActualizar.setEstado(estadoNuevo); sesion.update(objDNActualizar); } sesion.getTransaction().commit(); } catch (Exception e) { if (trns != null) { trns.rollback(); } e.printStackTrace(); setError("Tabla_actualizar_registro: " + e.getMessage()); } finally { sesion.flush(); sesion.close(); } return est; }
3
public static JSONObject listMessages(int id, int nb, int off,String last) throws emptyResultException { try { JSONObject json = new JSONObject(); Mongo m = new Mongo(BDStatic.mongoDb_host,BDStatic.mongoDb_port); DB db = m.getDB(BDStatic.mysql_db); DBCollection collection = db.getCollection("messages"); BasicDBObject query = new BasicDBObject(); if(id != -1) query.put("id",id); DBCursor cursor = collection.find(query).sort(new BasicDBObject("date",-1)).limit(nb).skip(off); while(cursor.hasNext()){ DBObject next = cursor.next(); if(last != null && last != "" && next.get("_id").toString().equals(last)) { cursor.close(); m.close(); return json; } json.accumulate("messages", next); } cursor.close(); m.close(); return json; }catch (UnknownHostException e) { return ErrorMsg.bdError(); }catch (JSONException e) { return ErrorMsg.bdError(); } }
7
private final String getChunk(String s, int slength, int marker) { StringBuilder chunk = new StringBuilder(); char c = s.charAt(marker); chunk.append(c); marker++; if (isDigit(c)) { while (marker < slength) { c = s.charAt(marker); if (!isDigit(c)) break; chunk.append(c); marker++; } } else { while (marker < slength) { c = s.charAt(marker); if (isDigit(c)) break; chunk.append(c); marker++; } } return chunk.toString(); }
5
public double getSpeedBalance() { return 0.5 * ((GUI.controls != null && GUI.controls.get("p_auto-speed") != null && GUI.controls .get("p_auto-speed").isActive()) ? stableSpeedBalance : 1); }
3
public void setX(double _x) { x = _x; }
0
private void init() { VerticalLayout layout = (VerticalLayout) this.getContent(); layout.setMargin(true); layout.setSpacing(true); Label message = new Label("<b>Please type your website URL to begin making your E-book! (e.g. www.example.com)</b>"); message.setContentMode(Label.CONTENT_XHTML); message.setSizeUndefined(); this.addComponent(message); final TextField urlField = new TextField(); urlField.setInputPrompt("Enter your website URL here"); urlField.setSizeFull(); layout.addComponent(urlField); HorizontalLayout bottombar = new HorizontalLayout(); progressBar.setIndeterminate(true); progressBar.setPollingInterval(5000); progressBar.setEnabled(false); bottombar.addComponent(progressBar); final Button okay = new Button("Okay!"); okay.addListener(new Button.ClickListener() { public void buttonClick(ClickEvent event) { if (!(((String)urlField.getValue()).startsWith("www.") || ((String)urlField.getValue()).startsWith("http://"))) { getWindow().showNotification( "I couldn't recognize the website name!", "Did you make sure to type www. or http:// in front of your website url? " + "Click this box to try again.", Notification.TYPE_ERROR_MESSAGE); } else { url = (String) urlField.getValue(); StartModalWindow.this.getApplication().setUser(new Account()); //wait until website is scraped Worker worker = new Worker(); worker.start(); progressBar.setEnabled(true); progressBar.setVisible(true); urlField.setEnabled(false); okay.setCaption("Please wait while we grab your site..."); okay.setEnabled(false); } } }); // The components added to the window are actually added to the window's // layout; you can use either. Alignments are set using the layout bottombar.addComponent(okay); layout.addComponent(bottombar); layout.setComponentAlignment(bottombar, Alignment.BOTTOM_CENTER); layout.setSizeUndefined(); }
2
private void doTunnelHandshake(final Socket tunnel, final String host, final int port) throws IOException { final OutputStream out = tunnel.getOutputStream(); final String msg = "CONNECT " + host + ":" + port + " HTTP/1.0\n" + "User-Agent: BoardPad Server" + "\r\n\r\n"; byte b[]; try { //We really do want ASCII7 -- the http protocol doesn't change with locale. b = msg.getBytes("ASCII7"); } catch (final UnsupportedEncodingException ignored) { //If ASCII7 isn't there, something serious is wrong, but Paranoia Is Good (tm) b = msg.getBytes(); } out.write(b); out.flush(); // We need to store the reply so we can create a detailed error message to the user. final byte[] reply = new byte[200]; int replyLen = 0; int newlinesSeen = 0; boolean headerDone = false; //Done on first newline final InputStream in = tunnel.getInputStream(); while (newlinesSeen < 2) { final int i = in.read(); if (i < 0) { throw new IOException("Unexpected EOF from proxy"); } if (i == '\n') { headerDone = true; ++newlinesSeen; } else if (i != '\r') { newlinesSeen = 0; if (!headerDone && replyLen < reply.length) { reply[replyLen++] = (byte) i; } } } /* * Converting the byte array to a string is slightly wasteful * in the case where the connection was successful, but it's * insignificant compared to the network overhead. */ String replyStr; try { replyStr = new String(reply, 0, replyLen, "ASCII7"); } catch (final UnsupportedEncodingException ignored) { replyStr = new String(reply, 0, replyLen); } /* We check for Connection Established because our proxy returns HTTP/1.1 instead of 1.0 */ if (!replyStr.toLowerCase().contains("200 connection established")) { throw new IOException("Unable to tunnel through. Proxy returns \"" + replyStr + "\""); } /* tunneling Handshake was successful! */ }
9
public static void loadInput(String inFile, int linesToRead) throws IOException { int lines = readLines(inFile); if (linesToRead != -1 && linesToRead < lines) { lines = linesToRead; } word1 = new String[lines]; word2 = new String[lines]; BufferedReader br = null; try { br = new BufferedReader(new FileReader(new File(inFile))); String line = null; int i = 0; while ((line = br.readLine()) != null && i < linesToRead) { line = line.trim(); String[] tokens = line.split("\\s+"); word1[i] = tokens[0]; word2[i] = tokens[1]; i++; } } finally { if (br != null) br.close(); } }
5
void init(int n) { bitrev = new int[n / 4]; trig = new float[n + n / 4]; log2n = (int) Math.rint(Math.log(n) / Math.log(2)); this.n = n; int AE = 0; int AO = 1; int BE = AE + n / 2; int BO = BE + 1; int CE = BE + n / 2; int CO = CE + 1; // trig lookups... for (int i = 0; i < n / 4; i++) { trig[AE + i * 2] = (float) Math.cos((Math.PI / n) * (4 * i)); trig[AO + i * 2] = (float) -Math.sin((Math.PI / n) * (4 * i)); trig[BE + i * 2] = (float) Math.cos((Math.PI / (2 * n)) * (2 * i + 1)); trig[BO + i * 2] = (float) Math.sin((Math.PI / (2 * n)) * (2 * i + 1)); } for (int i = 0; i < n / 8; i++) { trig[CE + i * 2] = (float) Math.cos((Math.PI / n) * (4 * i + 2)); trig[CO + i * 2] = (float) -Math.sin((Math.PI / n) * (4 * i + 2)); } { int mask = (1 << (log2n - 1)) - 1; int msb = 1 << (log2n - 2); for (int i = 0; i < n / 8; i++) { int acc = 0; for (int j = 0; msb >>> j != 0; j++) { if (((msb >>> j) & i) != 0) { acc |= 1 << j; } } bitrev[i * 2] = ((~acc) & mask); // bitrev[i*2]=((~acc)&mask)-1; bitrev[i * 2 + 1] = acc; } } scale = 4.f / n; }
5
@Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { int progress = 0; if (value instanceof Float) { progress = Math.round(((Float) value)); } else if (value instanceof Integer) { progress = (Integer) value; } setValue(progress); return this; }
2
private boolean isOnMap(int x, int y) { if(x < 0 || x >= getXSize() || y < 0 || y >= getYSize()) { return false; } else { return true; } }
4
@Override public String getDetails() { StringBuffer sb = new StringBuffer(); Rectangle2D b = gp.getBounds2D(); sb.append("ShapeCommand at: " + b.getX() + ", " + b.getY() + "\n"); sb.append("Size: " + b.getWidth() + " x " + b.getHeight() + "\n"); sb.append("Mode: "); if ((style & FILL) != 0) { sb.append("FILL "); } if ((style & STROKE) != 0) { sb.append("STROKE "); } if ((style & CLIP) != 0) { sb.append("CLIP"); } return sb.toString(); }
3
public static void adminstrate(StanzaAndType s, FilterChain chain, Attachment aAtt) throws JAXBException { StanzaProperties stanzaProperties = StanzaProperties.getInstance(); if(s.getStringType().equals(stanzaProperties.getMessageName())) { XmppParserMessage parser = new XmppParserMessage(s.getStanza(), jabber.server.Message.class.getPackage().getName()); jabber.server.Message message = parser.unmarshal(NioProperties.getInstance().getClientType()); BodyMessageServer bodyMessage = new BodyMessageServer(message); if(bodyMessage.existsBody()){ String to = message.getTo(); int index = message.getTo().indexOf("/"); if (index > 0) { to = to.substring(0, index); } String from = aAtt.getUser() + "@" + aAtt.getHost(); if (from.equals(to)) { String newFrom = aAtt.getUser() + "@" + aAtt.getHost(); String resources = aAtt.getResources(); if (resources != null) { newFrom += "/" + aAtt.getResources(); } message.setFrom(newFrom); if (parseInstruction(bodyMessage.getBody().getValue(), chain)) { bodyMessage.changeBody("Command success"); s.setStanza(parser.marshal(bodyMessage.getMessage())); } else if (!bodyMessage.getBody().getValue().equals("MONITOR")) { bodyMessage.changeBody("Invalid command"); s.setStanza(parser.marshal(bodyMessage.getMessage())); } } } } }
7
private static double det(double[][] arr) { int N = arr.length; double[][] M = new double[N][N]; for (int i = 0; i < arr.length; i++) System.arraycopy(arr[i], 0, M[i], 0, N); double mult = 1; for (int r = 0; r < N; r++) { int k = r; while (M[k][r] == 0) { k++; if (k == N) return 0; } double[] temp = M[r]; M[r] = M[k]; M[k] = temp; if (r != k) { mult *= -1; } double lv = M[r][r]; for (int j = 0; j < N; j++) M[r][j] /= lv; mult *= lv; for (int i = r; i < N; i++) { if (i != r) { lv = M[i][r]; for (int j = r; j < N; j++) M[i][j] -= lv * M[r][j]; } } } return mult; }
9
private void drawControlPanel(Graphics2D g, int x, int y) { if (startIcon != null) { g.setStroke(thinStroke); startIcon.setColor(getContrastColor(x, y)); startIcon.paintIcon(this, g, x - startIcon.getIconWidth() * 3 - 12, y); } if (resetIcon != null) { g.setStroke(thinStroke); resetIcon.setColor(getContrastColor(x, y)); resetIcon.paintIcon(this, g, x - resetIcon.getIconWidth() * 2 - 8, y); } if (graphIcon != null) { g.setStroke(thinStroke); graphIcon.setColor(getContrastColor(x, y)); graphIcon.paintIcon(this, g, x - graphIcon.getIconWidth() - 4, y); } if (modeIcon != null) { g.setStroke(thinStroke); modeIcon.setColor(getContrastColor(x, y)); modeIcon.paintIcon(this, g, x, y); } if (prevIcon != null) { g.setStroke(thinStroke); prevIcon.setColor(getContrastColor(x, y)); prevIcon.paintIcon(this, g, x + nextIcon.getIconWidth() + 4, y); } if (nextIcon != null) { g.setStroke(thinStroke); nextIcon.setColor(getContrastColor(x, y)); nextIcon.paintIcon(this, g, x + nextIcon.getIconWidth() * 2 + 8, y); } if (isFullScreen() && switchIcon != null) { g.setStroke(thinStroke); switchIcon.setColor(getContrastColor(x, y)); switchIcon.paintIcon(this, g, x + switchIcon.getIconWidth() * 3 + 12, y); } }
8
@Override public void mouseDragged(MouseEvent e) { if (tempCard == null) { return; } int newx = tempCard.getXpos() - tempX + e.getX(); int newy = tempCard.getYpos() - tempY + e.getY(); int margin = TCard.H() / 2; if (newx < margin) { newx = margin; } else if (newx > Table.SIZE.width - margin) { newx = Table.SIZE.width - margin; } if (newy < margin) { newy = margin; } else if (newy > Table.SIZE.height - margin) { newy = Table.SIZE.height - margin; } tempCard.setCardPosition(newx, newy); }
5
private static boolean isDifferent(Tile t1, Tile t2, boolean biome) { if (biome) { if (t1 == null || t2 == null) { return false; } else { if ((t1.tile == t2.tile && !(Tiles.getPrecedence(t1.tile) > Tiles.getPrecedence(t2.tile)) || t1.floor != t2.floor)) return false; else return true; } } else { if (t1 == null || t2 == null) { return false; } else { if (t1.floor >= t2.floor) return false; else return true; } } }
9
public String getUnit(URL url) { String detail = ""; Document doc; try { doc = tidy.parseDOM(url.openStream(), null); System.out.println(getUnitOutline(doc)); getUnitStats(doc); getProductionStats(doc); getCombatStats(doc); getFieldManual(doc); getStrongAgainst(doc); getWeakAgainst(doc); getCounterMeasures(doc); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (XPathExpressionException e) { e.printStackTrace(); } return detail; }
3
public void i2c_write(short address, byte[] data) throws IOException { if (data.length==0) { throw new IOException("no data"); } if (data.length==1) { this.write_single(address, data[0]); } else { this.write_multiple(address, data); } }
2
*/ public boolean canRecruitFoundingFather() { Specification spec = getGame().getSpecification(); switch (getPlayerType()) { case COLONIAL: break; case REBEL: case INDEPENDENT: if (!spec.getBoolean("model.option.continueFoundingFatherRecruitment")) return false; break; default: return false; } return canHaveFoundingFathers() && currentFather == null && !getSettlements().isEmpty() && getFatherCount() < spec.getFoundingFathers().size(); }
7
public void randDnaSeqGetBasesTest(int numTests, int numTestsPerSeq, int lenMask, long seed) { Random rand = new Random(seed); for( int t = 0; t < numTests; t++ ) { String seq = ""; int len = (rand.nextInt() & lenMask) + 10; // Randomly select sequence length seq = randSeq(len, rand); // Create a random sequence DnaNSequence bseq = new DnaNSequence(seq); // Retrieve numTestsPerSeq random bases from the sequence for( int i = 0; i < numTestsPerSeq; i++ ) { int randPos = rand.nextInt(len); int randLen = rand.nextInt(len - randPos); String basesOri = seq.substring(randPos, randPos + randLen); String basesBin = bseq.getBases(randPos, randLen); Assert.assertEquals(basesOri, basesBin); if( verbose ) System.out.println("randDnaSeqGetBasesTest:\tPos: " + randPos + "\t" + "Len: " + randLen + "\t'" + basesOri + "'\t=\t'" + basesBin + "'"); } } }
3
public Copy getCopy(int copyId){ try { if(conn == null || conn.isClosed()){ conn = DatabaseConnection.getConnection(); } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { Statement stmnt = conn.createStatement(); String sql = "SELECT * Copies where id = " + copyId; ResultSet res = stmnt.executeQuery(sql); while(res.next()) { copy = new Copy(res.getInt("copy_id"), res.getInt("book_id"), res.getInt("edition"), res.getBoolean("lendable")); } } catch(SQLException e) { System.out.println("PROBLEM"); e.printStackTrace(); return copy; } return copy; }
5
public void addType(Scanner sc) { System.out.println("Add a type"); System.out.print("Enter type name: "); String nameType = sc.nextLine(); System.out.println(); System.out.print("Enter type price: "); double price = Double.parseDouble(sc.nextLine()); System.out.println(); System.out.print("Enter Maximum number of guest: "); int numOfGuest = Integer.parseInt(sc.nextLine()); System.out.println(); shsmb.createRoomType(nameType, numOfGuest, price); shsmb.persistRoomType(); System.out.println("Successfully added a new room type"); }
0
public void pedirNumero(){ try{ FileReader fr = new FileReader("Datos.txt"); BufferedReader br = new BufferedReader(fr); String cadena; // char valor; //String uno = Integer.toString(numero); while ((cadena=br.readLine())!=null){ for(int j=0;j<=cadena.length()-1;j++){ valor=cadena.charAt(j); signo=valor+""; if(valor!=' '){ if(miVector.size()==2){ if(signo.equals("+")){ parcial=(Integer.parseInt(miVector.pop()))+(Integer.parseInt(miVector.pop())); } if(signo.equals("-")){ op1=(Integer.parseInt(miVector.pop())); op2=(Integer.parseInt(miVector.pop())); parcial=op1-op2; } if(signo.equals("*")){ parcial=(Integer.parseInt(miVector.pop()))*(Integer.parseInt(miVector.pop())); } if(signo.equals("/")){ op1=(Integer.parseInt(miVector.pop())); op2=(Integer.parseInt(miVector.pop())); parcial=op1/op2; } miVector.push(Integer.toString(parcial)); }else{ miVector.push(signo); } } } System.out.println("\nEl total es: "+parcial); cadena=br.readLine(); } }catch(Exception ex){ } }
9
private void createActiveCluster(double[] timeVector, String user) { double[] post_count = timeVector; double totalPost = 0.0; for (double i : post_count) { totalPost += i; } double threshHold = (20 * totalPost) / 100; double firstClusterSize = post_count[0] + post_count[1] + post_count[2] + post_count[3]; double secondClusterSize = post_count[4] + post_count[5] + post_count[6] + post_count[7]; double thirdClusterSize = post_count[8] + post_count[9] + post_count[10] + post_count[11]; double fourthClusterSize = post_count[12] + post_count[13] + post_count[14] + post_count[15]; double fifthClusterSize = post_count[16] + post_count[17] + post_count[18] + post_count[19]; double sixthClusterSize = post_count[20] + post_count[21] + post_count[22] + post_count[23]; if (firstClusterSize > threshHold) { firstActivitycluster0004.add(user); } if (secondClusterSize > threshHold) { firstActivitycluster0408.add(user); } if (thirdClusterSize > threshHold) { firstActivitycluster0812.add(user); } if (fourthClusterSize > threshHold) { firstActivitycluster1216.add(user); } if (fifthClusterSize > threshHold) { firstActivitycluster1620.add(user); } if (sixthClusterSize > threshHold) { firstActivitycluster2000.add(user); } } //
7
public void setSelected(TreeNode node, boolean select) { if (select) selectedNodes.put(node, null); else selectedNodes.remove(node); }
1
public void Move(Direction direction) { switch(direction) { case Down: super.translatePosition(0, +1, 0); break; case Left: super.translatePosition(0, -1, 0); break; case Right: super.translatePosition(+1, 0, 0); break; case Up: super.translatePosition(-1, 0, 0); break; default: break; } }
4
public int cdlDarkCloudCoverLookback( double optInPenetration ) { if( optInPenetration == (-4e+37) ) optInPenetration = 5.000000e-1; else if( (optInPenetration < 0.000000e+0) || (optInPenetration > 3.000000e+37) ) return -1; return (this.candleSettings[CandleSettingType.BodyLong.ordinal()].avgPeriod) + 1; }
3
public void assureIntegrity(){ MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); messageDigest=digest.digest((username+message).getBytes("UTF-8")); }catch (NoSuchAlgorithmException e1){ e1.printStackTrace(); } catch(UnsupportedEncodingException e2){ e2.printStackTrace(); } }
2
public void CreateAANakedTorsoAlternativeTexturesFemales() throws Exception { SPProgressBarPlug.setStatus("Create AA naked torso alternative textures for females"); NumberFormat formatter = new DecimalFormat("000"); List<ARMA> ListRBSAANakedTorso = new ArrayList<>(); for (ARMA sourceAA : SkyProcStarter.patch.getArmatures()) { if (sourceAA.getEDID().contains("NakedTorsoRBS_F")) { ListRBSAANakedTorso.add(sourceAA); } } for (int bodies = 1; bodies < RBS_Main.amountBodyTypes; bodies++) { String s_bodies = formatter.format(bodies); for (int list = 0; list < ListRBSAANakedTorso.size(); list++) { if (ListRBSAANakedTorso.get(list).getEDID().equals("NakedTorsoRBS_F" + "standard" + s_bodies)) { for (TXST t : SkyProcStarter.patch.getTextureSets()) { if (t.getEDID().contains("RBS_F_TEXT")) { String[] splitResult = t.getEDID().split("RBS_F_TEXT"); String bodyID = splitResult[1]; ARMA targetAA = (ARMA) SkyProcStarter.patch.makeCopy(ListRBSAANakedTorso.get(list), ListRBSAANakedTorso.get(list).getEDID() + "RBS_F_TEXT" + bodyID); targetAA.setSkinTexture(t.getForm(), Gender.FEMALE); // patch.addRecord(targetAA); } } } } } }
7
@Override public void actionPerformed(ActionEvent e) { if (e.getSource() == cancelButton) { dispose(); } else if (e.getSource() == nextButton) { switchToPage(currentPage.getNextPage()); } else if (e.getSource() == previousButton) { switchToPage(currentPage.getPreviousPage()); } else if (e.getSource() == finishButton) { finishPressed = true; dispose(); } }
4
@Test public void testReadField_public() { Assert.assertEquals( "public", ReflectUtils.readField(new Bean(), "_field4") ); }
0
private static String getString(ByteBuf packetPDU) { String value = ""; byte nextChar = -1; while ((nextChar = packetPDU.readByte()) != 0x2F) { // read until a '/' is encountered value += ((char) nextChar); } return value; }
1
private int getSyndromeIndex(String recievedi) { int[] recieved = new int[7]; for(int i = 0; i < 7; ++i) { recieved[i] = recievedi.charAt(i) == '0' ? 0 : 1; } int[] syndrome = new int[3]; Arrays.fill(syndrome, 0); // calc syndrome by z=Hr for(int i = 0; i < 3; ++i) for(int k = 0; k < 7; ++k) { syndrome[i] += H[i][k] * recieved[k]; } // convert to index int indexSyndrome = 0; for (int i = 0 ; i < 3; ++i) { syndrome[i] %= 2; indexSyndrome += syndrome[i] * (int)Math.pow((double)2, (double)(2 - i)); } return indexSyndrome; }
5
public static void main(String[] args) { System.out.println("Введіть розмірність ->"); Scanner ku = new Scanner(System.in); int size = ku.nextInt(); int vector[] = null; vector = new int[size]; System.out.println("Введіть мінімум -->"); int min = ku.nextInt(); System.out.println("Введіть максимум -->"); int max = ku.nextInt(); ku.close(); for (int i=0; i<size; i++) { vector[i]=(int) (Math.random()*(max+1-min)+min-1); System.out.print(vector[i]+" "); } int max_=vector[0]; int index=0; for (int i=0; i<size; i++) { if (vector[i]>max_){max_=vector[i];index=i;} } System.out.println("\nНайбільше="+max_); System.out.println("Індекс найбільшого="+(index+1)); int min_=vector[0]; int index2=0; for (int i=0; i<size; i++) { if (vector[i]<min_){min_=vector[i];index2=i;} } System.out.println("Найменьше="+min_); System.out.println("Індекс найменшого="+(index2+1)); }
5
public String getStyle(String lineEnding) { return FileTools.readFileToString(this.styleName, lineEnding); }
0
@Override public void handleEvent(Event event) { if (event.getType() == EventType.PLAYER_STATUS_CHANGE && event.getOriginator() instanceof Player) { Player player = (Player) event.getOriginator(); if (player.getPlayerStatus() == PlayerStatus.WON) { getGrid().getEventManager().sendEvent(new Event(EventType.END_GAME, player)); } else if (player.getPlayerStatus() == PlayerStatus.LOST) { // next players turn has to be incremented if (player.equals(getActivePlayer())) setNextActivePlayer(); players.remove(player); playersLost.add(player); getGrid().permanentlyRemoveElement(player); if (players.size() == 1) getGrid().getEventManager().sendEvent(new Event(EventType.END_GAME, getActivePlayer())); } } }
6