method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
dd6ee098-f62b-4781-b5ea-00700b0df021
5
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MarkPk other = (MarkPk) obj; if (idCours != other.idCours) return false; if (idUser != other.idUser) return false; return true; }
2ff1cc96-564d-45ca-97af-413ee90dc0bb
3
public UIMenu toUIMenu(String heading) { if (null == heading) throw new IllegalArgumentException(); if (_menu.size() <= 1) throw new IllegalStateException(); UIMenu.Pair[] array = new UIMenu.Pair[_menu.size()]; for (int i = 0; i < _menu.size(); i++) array[i] = _menu.get(i); return new UIMenu(heading, array); }
dc0612aa-3d2e-448f-b1e1-2d054d326a14
5
public static void main(String[] args) throws Exception { String urlString; if (args.length == 0) { urlString = "http://www.w3.org/"; System.out.println("Using " + urlString); } else urlString = args[0]; URL url = new URL(urlString); InputStream in = url.openStream(); XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader parser = factory.createXMLStreamReader(in); while (parser.hasNext()) { int event = parser.next(); if (event == XMLStreamConstants.START_ELEMENT) { if (parser.getLocalName().equals("a")) { String href = parser.getAttributeValue(null, "href"); if (href != null) System.out.println(href); } } } }
3a610b7a-923d-4083-a37f-20a9e875533c
7
private NodeVariable getFixableLoad(NodeFunction f) throws NoMoreValuesException { LinkedList<NodeVariable> xes = new LinkedList<NodeVariable>(f.getNeighbour()); Collections.shuffle(xes); //for (NodeVariable x : f.getNeighbour()) { // xes let the load to be chosen in random order (not always the first one available) for (NodeVariable x : xes) { try { if (x.getStateArgument().getValue() == (Integer) f.id()) { for (NodeArgument na : x.getArguments()) { Integer id_f = (Integer) na.getValue(); if (id_f != f.id() && NodeFunction.getNodeFunction(id_f).actualValue() < Double.POSITIVE_INFINITY) { return x; } } } } catch (VariableNotSetException ex) { ex.printStackTrace(); } catch (FunctionNotPresentException ex) { ex.printStackTrace(); } } throw new NoMoreValuesException(); }
ec1ccb43-fdfa-4719-b66b-894f2e3b69f0
5
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AffectationPK other = (AffectationPK) obj; if (idEmp != other.idEmp) return false; if (idProj != other.idProj) return false; return true; }
cdfbdbe2-1edd-4038-888b-137dd8064355
9
public Expr Mul_Expr() throws ParseException { Expr e, et; Token tok; e = Un_Expr(); label_25: while (true) { switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) { case MUL: case DIV: case MOD: break; default: jj_la1[57] = jj_gen; break label_25; } switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) { case MUL: tok = jj_consume_token(MUL); break; case DIV: tok = jj_consume_token(DIV); break; case MOD: tok = jj_consume_token(MOD); break; default: jj_la1[58] = jj_gen; jj_consume_token(-1); throw new ParseException(); } et = Un_Expr(); e = new BinOpExpr(e, tok, et); } return e; }
06d43bac-26da-4b11-9693-72f7ebbba081
5
public void parse(String fileName) { parserFactory = new ObjLineParserFactory(this); InputStream fileInput = ResourceLoader.getResourceAsStream(fileName); if (fileInput == null) { // Could not find the file in the jar. try { File file = new File(fileName); if (file.exists()) fileInput = new FileInputStream(file); } catch (Exception e2) { e2.printStackTrace(); } } BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(fileInput)); String currentLine = null; while ((currentLine = in.readLine()) != null) parseLine(currentLine); in.close(); } catch (Exception e) { Log.e("Error reading file " + fileName, e); throw new RuntimeException(e); } // // Log.finest("Loaded OBJ from file " + fileName); // Log.finest(getVertices().size() + " vertices."); // Log.finest(getNormals().size() + " normals."); // Log.finest(getTextures().size() + " textures coordinates."); // Log.finest(getFaces().size() + " faces."); }
cf363864-c7eb-4a73-a1a3-e7e222abda5c
4
public static int lastIndexOfNonWhiteSpace( String string ) { if ( isEmpty( string ) ) { return 0; } int right = string.length(); char[] chars = string.toCharArray(); for ( int idx = right - 1; idx > 0; idx-- ) { char eachChar = chars[idx]; if ( eachChar != ' ' && eachChar != '\t' ) { break; } right--; } return right; }
58b6a42c-386a-4f99-9434-5be56b43ec64
9
public List<WorldNode> getNeighbours(WorldNode node) { if(log.isLoggable(Logger.INFO)) log.log(Logger.INFO, "getNeighbours() for node: " + node.getxCoord() + ", " + node.getyCoord()); List<WorldNode> result = new ArrayList<WorldNode>(); int[] offset = {1, -1}; WorldNode child = null; for (int i : offset) { if (0<=(node.getxCoord()+i) && (node.getxCoord()+i) <4) { child = worldMap[node.getxCoord()+i][node.getyCoord()]; if (child != null) result.add(child); } if (0<=(node.getyCoord()+i) && (node.getyCoord()+i) <4) { child = worldMap[node.getxCoord()][node.getyCoord()+i]; if (child != null) result.add(child); } } if(log.isLoggable(Logger.INFO)) log.log(Logger.INFO, "Anzahl Neighbours: " + result.size()); return result; }
c0cfec0d-18a6-4899-89fc-fc71cd64fa93
6
public boolean run( char option, char jogador ) { switch( option ) { case 'P': // TODO break; case 'N': // TODO break; case 'U': // TODO break; case 'F': // TODO break; case 'T': return runTabela(); case 'H': return runHelp(); } Util.println( "Opção não implementada." ); return false; }
66555365-9e5e-41f4-a896-48f64b1d6e8d
9
public String getColumnText(Object element, int columnIndex) { if (element != null) { switch (columnIndex) { case 0: return ((StockDTO) element).getTickerSymbol(); case 1: return ((StockDTO) element).getLastTrade().toString(); case 2: return numberFormat.format(((StockDTO) element).getVolume()); case 3: return ((StockDTO) element).getDaysRange(); case 4: return numberFormat.format(((StockDTO) element).getAvgVol()); case 5: return ((StockDTO) element).getDaysRange(); case 6: return ((StockDTO) element).getFiftyTwoWeekRange(); case 7: return ((StockDTO) element).getMarketCap(); } } return ""; }
68d174b1-855a-4f2d-b568-086c2b6a2402
3
protected List[] verticalSlices(List childBoundables, int sliceCount) { int sliceCapacity = (int) Math.ceil(childBoundables.size() / (double) sliceCount); List[] slices = new List[sliceCount]; Iterator i = childBoundables.iterator(); for (int j = 0; j < sliceCount; j++) { slices[j] = new ArrayList(); int boundablesAddedToSlice = 0; while (i.hasNext() && boundablesAddedToSlice < sliceCapacity) { Boundable childBoundable = (Boundable) i.next(); slices[j].add(childBoundable); boundablesAddedToSlice++; } } return slices; }
cc34c912-71ff-44b4-9f06-06ff119cf058
4
static void bindMouseEvents(Drawer drawer, Component component) { MouseAdapter mouseAdapter = new MouseAdapter() { public void mouseClicked(MouseEvent evt) { if ((evt.getModifiers() & InputEvent.BUTTON1_MASK) != 0) { // source.setText(source.getText() + "nLeft mouse button clicked on point [" + evt.getPoint().x + "," + evt.getPoint().y + "]"); } if ((evt.getModifiers() & InputEvent.BUTTON2_MASK) != 0) { } if ((evt.getModifiers() & InputEvent.BUTTON3_MASK) != 0) { } } }; MouseWheelListener listener = e -> { if (e.getWheelRotation() > 0) { drawer.setScale(drawer.scale * 0.9); } else { drawer.setScale(drawer.scale * 1.1); } }; component.addMouseWheelListener(listener); component.addMouseListener(mouseAdapter); }
3224372a-9949-4575-a325-dabc8902d9c3
7
@Override public void handleFile(File file) { if (getProcessMode() == MODE_BIG_CHUNK) { String contents = FileTools.readFileToString(file, getOpenEncoding(), lineEnding); contents = processContents(file, contents); // If contents are null then don't write anything out. if (contents == null) { return; } // Clean last line ending if neccessary. int lineEndingLength = lineEnding.length(); int contentsLength = contents.length(); if (!lineEndingAtEnd && (contentsLength >= lineEndingLength)) { contents = contents.substring(0, contentsLength - lineEndingLength); } try { FileTools.dumpStringToFile(file, contents, getSaveEncoding()); } catch (IOException ioe) { ioe.printStackTrace(); } } else if (getProcessMode() == MODE_ARRAYS) { ArrayList lines = new ArrayList(); ArrayList lineEndings = new ArrayList(); FileTools.readFileToArrayOfLines(file, getOpenEncoding(), lines, lineEndings); boolean modified = processContents(file, lines, lineEndings); if (modified) { FileTools.dumpArrayOfLinesToFile(file, getSaveEncoding(), lines, lineEndings); } } else { System.out.println("Error: Unknown process mode."); } }
ca4f1e74-1d3f-46b3-91b2-29a2e9b482c2
6
public void loadEquipment(Element docEle){ NodeList equipmentsList = docEle.getElementsByTagName("Equipment"); Node equipmentsNode = equipmentsList.item(0); Element equipmentElement = (Element)equipmentsNode; String equipmentsPath = equipmentElement.getAttribute("FolderPath"); String equipmentPrefix = equipmentElement.getAttribute("Prefix"); NodeList nList = equipmentsNode.getChildNodes(); for(int i = 0; i < nList.getLength(); i++){ Node node = nList.item(i); if(node.getNodeType() == Node.ELEMENT_NODE){ Element ele = (Element) node; String name = node.getNodeName(); String id = ele.getAttribute("ID"); String path = equipmentsPath+ele.getAttribute("Path"); String description = ele.getAttribute("Description"); if(!graphics.containsKey(path)) graphics.put(path, Utilities.loadImage(path)); BufferedImage image = graphics.get(path); NodeList animationsList = ele.getElementsByTagName("Animations"); node = animationsList.item(0); NodeList nAnimationList = node.getChildNodes(); List <Rect2i> animationBoxes = new ArrayList<Rect2i>(); for(int a = 0; a<nAnimationList.getLength();a++){ Node animationNode = nAnimationList.item(a); if(animationNode.getNodeType() == Node.ELEMENT_NODE){ Element animation = (Element)animationNode; animationBoxes.add(new Rect2i(Integer.parseInt(animation.getAttribute("x")),Integer.parseInt(animation.getAttribute("y")), Integer.parseInt(animation.getAttribute("w")),Integer.parseInt(animation.getAttribute("h")))); } } Rect2i[] boxes = new Rect2i[animationBoxes.size()]; for(int b = 0; b < animationBoxes.size(); b++){ boxes[b] = animationBoxes.get(b); } new Armor(equipmentPrefix+id, null, null, name, description, image, boxes); } } }
1f25e561-a6a3-440b-b440-dca04a2ec3f0
0
public Marker getMarker (Position position){ return (Marker)board[position.getY()][position.getX()]; }
7cf9d3da-bded-46e7-b8fa-257dcc346889
7
public static byte[] getFileBytes(File file) { try { InputStream is = new FileInputStream(file); long length = file.length(); if (length > Integer.MAX_VALUE) { System.out.println("File " + file.getName() + " was too big to attain file bytes."); is.close(); return null; } byte[] bytes = new byte[(int)length]; for(int i = 0; i < length; i++) { bytes[i] = 0x0; } int offset = 0; int numRead = 0; while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length - offset)) >= 0) { offset += numRead; } if (offset < bytes.length) { is.close(); throw new IOException("Could not completely read file "+file.getName()); } is.close(); return bytes; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
49710d88-5327-4ae7-94bc-c9b31b1383cb
1
public void addOuterValueListener(OuterValueListener l) { if (ovListeners == null) ovListeners = new Vector(); ovListeners.addElement(l); }
51687b25-8ac1-4de5-ac7a-f76d54e486e0
8
private int fillOcean(Map map, Position p, ServerRegion region, Rectangle bounds) { Queue<Position> q = new LinkedList<Position>(); int n = 0; boolean[][] visited = new boolean[map.getWidth()][map.getHeight()]; visited[p.getX()][p.getY()] = true; q.add(p); while ((p = q.poll()) != null) { Tile tile = map.getTile(p); region.addTile(tile); n++; for (Direction direction : Direction.values()) { Position next = p.getAdjacent(direction); if (map.isValid(next) && !visited[next.getX()][next.getY()] && bounds.contains(next.getX(), next.getY())) { visited[next.getX()][next.getY()] = true; Tile t = map.getTile(next); if ((t.getRegion() == null || t.getRegion() == region) && !t.isLand()) { q.add(next); } } } } return n; }
63ca76a0-aea1-4118-9f7a-ba2192f64b16
3
@Override protected void setRolloverTab(int index) { int oldIndex = getRolloverTab(); super.setRolloverTab(index); if (oldIndex != index) { if (oldIndex != -1) { tabPane.repaint(getTabBounds(tabPane, oldIndex)); } if (index != -1) { tabPane.repaint(getTabBounds(tabPane, index)); } } }
b3c0c114-61c9-45bc-907f-f229a8544e8d
7
public static TestThread createRequestGenerator(Scanner canal, int src){ if(src == 1) System.out.print("Origin: "); int origin = Integer.parseInt(canal.nextLine()); if(src == 1) System.out.print("Target: "); int target = Integer.parseInt(canal.nextLine()); if(src == 1) System.out.print("Operations: "); int operations = Integer.parseInt(canal.nextLine()); if(src == 1) System.out.print("Rate: "); int rate = Integer.parseInt(canal.nextLine()); if(src == 1) System.out.print("Duration: "); int duration = Integer.parseInt(canal.nextLine()); if(src == 1) System.out.print("Results File:"); String results = canal.nextLine(); TestThread t = null; try { t = new TestThread(1, new FileWriter(results)); t.setParam(origin, target, operations, rate, duration); } catch (IOException e) { return null; } return t; }
2be03dbd-9d06-46e9-bb0e-b8937a640410
4
public void saveData(Result result) { // Erstelle ein TemplateObject für die Ausgabedatei Template tpl = new Template(); // Lade vorlage tpl.load("templates/truth.kml.tpl"); // Füge Name im Template ein tpl.replace("name", result.getName()); if(result.getOSMWays().size() > 1) throw new UnsupportedOperationException("Kann derzeit nur einen Weg als Ergebnis speichern"); if(result.getOSMWays().isEmpty()) throw new UnsupportedOperationException("Kann keine leeren Ergebnisse behandeln"); // Lade ersten Weg aus Result (muss später durch einen Loop o.ä. ersetzt werden) List<OSMNode> currentWay = result.getOSMWays().get(0).getWayComponents(); // Iteriere durch alle Nodes for (Iterator<OSMNode> it = currentWay.iterator(); it.hasNext();) { OSMNode node = it.next(); // Baue Node-String String coordinateString = node.getNodeCoordinate().getLongitude() + "," + node.getNodeCoordinate().getLatitude(); // Falls es noch einen nächsten gibt füge einen Zeilenumbruch an if(it.hasNext()) coordinateString += "\n"; // Ersetze Coordinates-Loop mit der aktuellen Zeile tpl.replace("coordinates", coordinateString); } // Speicher Template ab tpl.save(path + "/" + result.getName() + "." + result.getId() + ".truth.kml"); }
93f17291-cfbe-489d-bbcf-f55c67092eb0
1
private byte[] encrypt(byte[] data) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException { if (data.length > MAX_ENC_SIZE) { System.err .println("Data to long to encrypt. Reason: Possible cheating! Fix: Exit"); System.exit(1); } RSAKeyParameters kp = new RSAKeyParameters(false, n, e); RSAEngine engine = new RSAEngine(); engine.init(true, kp); byte[] cText = engine.processBlock(data, 0, data.length); return cText; }
0b385f08-18e6-4c28-a2bc-82500fbc0209
6
public void doMain(String[] args) { CmdLineParser parser = new CmdLineParser(this); try { parser.parseArgument(args); } catch (CmdLineException e) { // TODO Auto-generated catch block e.printStackTrace(); parser.printUsage(System.out); return; } if (help) parser.printUsage(System.out); else { Timer time = new Timer(); // Instantiate Timer Object MonitorTask monit = new MonitorTask(); // Instantiate SheduledTask class time.schedule(monit, 0, 10000); // Create Repetitively task for every 10 secs if (flush) CreateSampleDocuments.flushDB(); if (datas) CreateSampleDocuments.storeFakeDocs(); try { BufferedReader br = new BufferedReader(new InputStreamReader( System.in)); String input; while ((input = br.readLine()) != null) { System.out.println(input); } } catch (IOException io) { io.printStackTrace(); } } }
001ec829-5860-4b95-b293-d7c553162452
4
public static boolean checkEnfrentamiento(Cancha cancha, int x, int y){ int[][] dimension=cancha.getDimension(); for (int i=(x-4);i<x+4;i++){ for(int j=(y-4);j<(y+4);j++){ if(dimension[i][j]==1 || dimension[i][j]==2){ return true; //true igual conflicto posiciones } } } return false; }
69167de2-cdaf-47c4-8fd7-6aa75a2de429
4
*/ public void selectAll () { checkWidget (); if ((getStyle () & SWT.SINGLE) != 0) return; selectedItems = new CTableItem [itemsCount]; System.arraycopy (items, 0, selectedItems, 0, itemsCount); if (isFocusControl () || (getStyle () & SWT.HIDE_SELECTION) == 0) { redraw (); } for (int i = 0; i < selectedItems.length; i++) { selectedItems[i].getAccessible(getAccessible(), 0).selectionChanged(); } getAccessible().selectionChanged(); }
76b6d764-642f-406e-973e-9c993f1778f6
1
public static void setPropertyAsString(PropertyContainer container, String key, String value) { if (container != null) { container.setProperty(key, value); } else { throw new IllegalArgumentException("Provided PropertyContainer was null."); } }
d622f5ca-89a0-4c4b-91e6-7ad996f91b67
7
public static ArrayList<PenPoint> readPointsFromFile(File f) { BufferedReader br = null; ArrayList<PenPoint> points; points = new ArrayList<PenPoint>(); try { String sCurrentLine; br = new BufferedReader(new FileReader(f)); boolean flagForPenState = false; while((sCurrentLine = br.readLine()) != null){ if(flagForPenState){ if(sCurrentLine.equals(".PEN_UP")){ flagForPenState = false; } PenPoint p = new PenPoint(); String splitted[] = sCurrentLine.split(" "); p.setX(Integer.parseInt(splitted[0])); p.setY(Integer.parseInt(splitted[1])); points.add(p); } else if(sCurrentLine.equals(".PEN_DOWN")){ flagForPenState = true; } } } catch(IOException e){ e.printStackTrace(); } finally { try { if (br != null)br.close(); } catch (IOException ex) { ex.printStackTrace(); } } return points; }
6144c343-50a4-42fe-855e-ec5a8bab4248
3
@Override public void run(){ try{ System.out.println("HireDataNodeServer is waiting for new workers on the port: "+this.portNum); while(running){ Socket dataNodeSocket = serverSocket.accept(); DataNodeManagerServer managerServer = new DataNodeManagerServer(nn,dataNodeSocket); new Thread(managerServer).start(); } }catch(IOException e){ e.printStackTrace(); System.out.println("socket server accept failed"); } try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); System.out.println("socket Server failed to close"); } }
d231fbe2-99ce-4806-8a79-7993c0c00d1f
5
public Norm containsNorm(Action ac, NormType nt) { for ( Norm norm: getAllRestrictNorms().values() ) { Action a = norm.getNormResource().getAction(); if ( a!=null && a.getName().equalsIgnoreCase(ac.getName()) && norm.getNormType() == nt && norm.isActive() ) { return norm; } } return null; }
63b49582-02ea-4888-b6b6-05963e1914c8
6
public static void main(String[] args) { String movie = ""; Sub sub = null; while(true) { movie = CLib.input("SubID"); try { /*context = JAXBContext.newInstance(Root.class); File file = new File("./omdbapi_text.xml"); System.out.println("Unmarshaling..."); Root r = (Root) context.createUnmarshaller().unmarshal(file);*/ JAXBContext jc = JAXBContext.newInstance(Subtitle.class); Unmarshaller u = jc.createUnmarshaller(); URL url = new URL( "http://10.0.1.92/getSubs.php?movieID=" + movie ); Subtitle subtitle = (Subtitle) u.unmarshal(url); if(subtitle != null) { //item = as.getItems().item.get(i); for(int j = 0; j < subtitle.getSub().size()-800; j++) { sub = subtitle.getSub().get(j); System.out.println("\nid: " + sub.getId() + " FromTime: " + sub.getFromTime() + " ToTime: " + sub.getToTime()); for(int i = 0; i < sub.getLines().getLine().size(); i++) { System.out.print("Line " + i+": " + sub.getLines().getLine().get(i)); } } } } catch (JAXBException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } } }
a50565b4-2d91-4e43-9257-df575e4687b0
2
@Override public void keyReleased(KeyEvent e) { if (e.getKeyChar() == 's') { plateau.resetVitesse(); } if (e.getKeyChar() == '2') { plateau2.resetVitesse(); } }
adb3ca60-f966-4d58-858f-cf0135b2c6f7
0
@Override public void windowClosing(WindowEvent arg0) { }
2a1e7e1a-3e89-4523-b08d-fe9b08a2c71b
2
@Test public void getFinishedQuestions() throws Exception { for (int i = 0; i < 10; i++) { assertEquals(i, st.getFinishedQuestions()); if (i % 2 == 0) { st.incRightQuestions(); } else { st.incMistakeQuestions(); } } }
b477f25c-3cb8-45a3-824b-066e5a694fb0
7
public static void main(String[] args) { int BITS_PER_LINE = 16; if (args.length == 1) { BITS_PER_LINE = Integer.parseInt(args[0]); } int count; for (count = 0; !BinaryStdIn.isEmpty(); count++) { if (BITS_PER_LINE == 0) { BinaryStdIn.readBoolean(); continue; } else if (count != 0 && count % BITS_PER_LINE == 0) StdOut.println(); if (BinaryStdIn.readBoolean()) StdOut.print(1); else StdOut.print(0); } if (BITS_PER_LINE != 0) StdOut.println(); StdOut.println(count + " bits"); }
e0fed38a-457a-43e2-9842-6b38bc2e0bc1
6
public LLNode getSummedLinkedList(LLNode head1, LLNode head2, int carry) { if(head1==null && head2==null) return null; else { LLNode node=null; int num1 = (head1==null)?0:head1.data; int num2 = (head2==null)?0:head2.data; int sum = num1+num2+carry; node = new LLNode(sum%10); node.next = getSummedLinkedList((head1==null)?head1:head1.next, (head2==null)?head2:head2.next, sum/10); return node; } }
8c074915-57df-4946-aafc-cc6fce6cc993
0
public Integer getExtraPoints() { return extraPoints; }
6d99117c-5d56-4b86-afb8-f20a4b257465
2
boolean isSkip(String skipName) { return (skipName.equals(name)&&skip==true)? true : false; }
18787f8a-d4b2-439b-b1dd-58c2f979b18c
3
private static void doDescriptionTest() { System.out.print("Testing description command "); try { File testFolder = new File( TEST_FOLDER ); String mvdName = TEST_FOLDER+File.separator+"test.mvd"; if ( !testFolder.exists() ) testFolder.mkdir(); String[] args0 = { "-c","create","-m",mvdName,"-d","test" }; MvdTool.run( args0, out ); String[] args2 = {"-c","description","-m",mvdName,"-d","new value"}; MvdTool.run( args2, out ); ByteArrayOutputStream bos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream( bos, true, "UTF-8" ); String[] args3 = {"-c","description","-m",mvdName}; MvdTool.run( args3, ps ); ps.close(); String description = bos.toString().trim(); if ( !description.equals("new value") ) throw new MVDTestException("Description string not equal to set value"); System.out.print("."); testsPassed++; System.out.println(" test passed."); } catch ( Exception e ) { doTestFailed( e ); } }
e5fda61e-0e7d-4250-959a-fb9f16e69072
2
public void startLogger() { Calendar cal = Calendar.getInstance(); cal.clear(Calendar.HOUR); cal.clear(Calendar.MINUTE); cal.clear(Calendar.SECOND); cal.clear(Calendar.MILLISECOND); logger = new Logger("logs/" + cal.getTime() + ".txt", this); String filename = cal.getTime().toString().replace(" ", "-"); String finalname = filename.split("-")[0] + "-" + filename.split("-")[1] + "-" + filename.split("-")[2]; try { logger.ChangeFilePath("logs/" , finalname + ".txt"); } catch (IOException e2) { System.out.println("logs/" + finalname + ".txt"); e2.printStackTrace(); } try { logger.Start(false); } catch (FileNotFoundException e) { e.printStackTrace(); } }
6974c53f-eb66-49fb-abf3-7f868ca1f638
1
public void atualizar(Local local) throws Exception { String sql = "UPDATE local SET cidade = ?, estado = ?, descricao = ? WHERE id = ?"; try { PreparedStatement stmt = ConnectionFactory.getConnection().prepareStatement(sql); stmt.setString(1, local.getCidade()); stmt.setString(2, local.getEstado()); stmt.setString(3, local.getDescricao()); stmt.setLong(4, local.getId()); stmt.executeUpdate(); } catch (SQLException e) { throw e; } }
cee0b885-02f5-45f9-b03e-cba4ae8ff663
7
*/ public void centerHorizontal(FastVector nodes) { // update undo stack if (m_bNeedsUndoAction) { addUndoAction(new centerHorizontalAction(nodes)); } int nMinY = -1; int nMaxY = -1; for (int iNode = 0; iNode < nodes.size(); iNode++) { int nY = getPositionY((Integer) nodes.elementAt(iNode)); if (nY < nMinY || iNode == 0) { nMinY = nY; } if (nY > nMaxY || iNode == 0) { nMaxY = nY; } } for (int iNode = 0; iNode < nodes.size(); iNode++) { int nNode = (Integer) nodes.elementAt(iNode); m_nPositionY.setElementAt((nMinY + nMaxY) / 2, nNode); } }
5917af32-6cd8-4f56-9a0c-1fc3d7efc35e
9
public static void writeHttpRequest(OutputStream stream, Keyword method, String host, String urlPath, KeyValueList headers, Stella_Object content) { { long contentlength = 0l; stream.nativeStream.print(method.symbolName + " " + urlPath + " HTTP/1.0\r\n"); if (host != null) { if (headers == null) { headers = KeyValueList.newKeyValueList(); } headers.insertAt(StringWrapper.wrapString("Host"), StringWrapper.wrapString(host)); } if (content != null) { { Object [] caller_MV_returnarray = new Object[1]; content = Http.getContentAndLength(content, caller_MV_returnarray); contentlength = ((long)(((LongIntegerWrapper)(caller_MV_returnarray[0])).wrapperValue)); } if (headers == null) { headers = KeyValueList.newKeyValueList(); } headers.insertAt(StringWrapper.wrapString("Content-Length"), StringWrapper.wrapString(Native.integerToString(contentlength))); } if (headers != null) { { StringWrapper key = null; StringWrapper value = null; KvCons iter000 = headers.theKvList; for (;iter000 != null; iter000 = iter000.rest) { key = ((StringWrapper)(iter000.key)); value = ((StringWrapper)(iter000.value)); stream.nativeStream.print(StringWrapper.unwrapString(key) + ": " + StringWrapper.unwrapString(value) + "\r\n"); } } } stream.nativeStream.print("Connection: close\r\n"); stream.nativeStream.print("\r\n"); if (content != null) { { Surrogate testValue000 = Stella_Object.safePrimaryType(content); if (Surrogate.subtypeOfStringP(testValue000)) { { StringWrapper content000 = ((StringWrapper)(content)); stream.nativeStream.print(StringWrapper.unwrapString(content000)); } } else if (Surrogate.subtypeOfP(testValue000, Http.SGT_STELLA_INPUT_STREAM)) { { InputStream content000 = ((InputStream)(content)); InputStream.copyStreamToStream(content000, stream); } } else { { OutputStringStream stream000 = OutputStringStream.newOutputStringStream(); stream000.nativeStream.print("`" + testValue000 + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace())); } } } } OutputStream.flushOutput(stream); } }
f3ed45f8-8a79-4348-9118-ece435820cdb
4
public static void sobreescribirFichero(ArrayList<Cliente> array){ try{ FileWriter fichero=new FileWriter("src/Ficheros/Clientes.txt"); PrintWriter pw=new PrintWriter(fichero); float aux_cuenta_corriente=0, aux_cuenta_ahorro=0, aux_penalizacion=0; for(int i=0; i<array.size(); i++){ if(array.get(i).getCunetacorriente()==null){ aux_cuenta_corriente=-1; }else{ aux_cuenta_corriente=array.get(i).getCunetacorriente().consultar(); } if(array.get(i).getCunetaahorro()==null){ aux_cuenta_ahorro=-1; aux_penalizacion=-1; }else{ aux_cuenta_ahorro=array.get(i).getCunetaahorro().consultar(); aux_penalizacion=array.get(i).getCunetaahorro().get_penalizacion(); } pw.println(array.get(i).getDni()+";"+aux_cuenta_corriente+";"+aux_cuenta_ahorro+";"+aux_penalizacion+";"); } pw.close(); fichero.close(); }catch(Exception e){ System.out.println("Error al escribir en la BBDD de los clientes"); } }
1efa4467-ed89-473c-b797-e5d08ae2bf7c
7
public double FindPeak(long[][] arr) { long max = 0; for (int i = 0; i < ximlen; i++) { for (int j = 0; j < yimlen; j++) { if (arr[i][j] > max) { max = arr[i][j]; } } } // this fractal has extreme values at certain points, cut down the max // value if (gradient <= 0.3) return Math.pow(max, 0.9); else if (gradient <= 0.2) return Math.pow(max, 0.7); else if (gradient <= 0.1) return Math.pow(max, 0.4); else if (gradient <= 0.05) return Math.pow(max, 0.3); else return max; }
200201a3-1018-48e9-a306-6bb9962f9266
1
@Override public int getRoll(){ if(Historical.getInstance().isEmpty()){ return getRandomInt(); } return getMediumHistoricResult(); }
290dbca4-586b-4d30-8468-01e374074132
9
public static void handleItemOption7(Player player, int slotId, int itemId, Item item) { long time = Utils.currentTimeMillis(); if (player.getLockDelay() >= time || player.getEmotesManager().getNextEmoteEnd() >= time) return; if (!player.getControlerManager().canDropItem(item)) return; player.stopAll(false); if (item.getDefinitions().isOverSized()) { player.getPackets().sendGameMessage("The item appears to be oversized."); player.getInventory().deleteItem(item); return; } if (item.getDefinitions().isDestroyItem()) { player.getDialogueManager().startDialogue("DestroyItemOption", slotId, item); return; } if (player.getPetManager().spawnPet(itemId, true)) { return; } player.getInventory().deleteItem(slotId, item); if (player.getCharges().degradeCompletly(item)) return; World.addGroundItem(item, new WorldTile(player), player, false, 180, true); player.getPackets().sendSound(2739, 0, 1); if (player.isBurying() && Bone.forId(itemId) != null) { return; } }
46f98a7a-e3e5-4e3d-ac64-34ad8acf4b2f
6
public List<DisplayTable> getTables(String world) { Connection conn = null; PreparedStatement st = null; ResultSet rs = null; List<DisplayTable> tables = new ArrayList<DisplayTable>(); try { conn = getConnection(); st = conn.prepareStatement(SELECT_WORLD); st.setString(1, world); rs = st.executeQuery(); while(rs.next()) { DisplayTable table = new DisplayTable(rs.getInt(1), rs.getString(2), rs.getInt(3), rs.getInt(4), rs.getInt(5), rs.getString(6), rs.getInt(7), rs.getShort(8)); tables.add(table); } } catch(Exception e) { Brabotools.logger.warning(plugin.getName() + " Error loading tables of world " + world); e.printStackTrace(); } finally { try { if(conn != null) conn.close(); if(st != null) st.close(); if(rs != null) rs.close(); } catch(Exception e) {} } return tables; }
7e765231-7943-4a63-a55b-df5abbb42ea4
1
public void visitNegExpr(final NegExpr expr) { if (isLeaf(expr.expr())) { firstOrder = true; } }
65e085df-c6ab-4ea5-b22e-d4e91e1ff4f3
5
private void writeSelectorsAndHuffmanTables() throws IOException { final BZip2BitOutputStream bitOutputStream = this.bitOutputStream; final byte[] selectors = this.selectors; final int totalSelectors = selectors.length; final int[][] huffmanCodeLengths = this.huffmanCodeLengths; final int mtfAlphabetSize = this.mtfAlphabetSize; final int totalTables = huffmanCodeLengths.length; bitOutputStream.writeBits (3, totalTables); bitOutputStream.writeBits (15, totalSelectors); // Write the selectors MoveToFront selectorMTF = new MoveToFront(); for (int i = 0; i < totalSelectors; i++) { bitOutputStream.writeUnary (selectorMTF.valueToFront (selectors[i])); } // Write the Huffman tables for (int i = 0; i < totalTables; i++) { final int[] tableLengths = huffmanCodeLengths[i]; int currentLength = tableLengths[0]; bitOutputStream.writeBits (5, currentLength); for (int j = 0; j < mtfAlphabetSize; j++) { final int codeLength = tableLengths[j]; final int value = (currentLength < codeLength) ? 2 : 3; int delta = Math.abs (codeLength - currentLength); while (delta-- > 0) { bitOutputStream.writeBits (2, value); } bitOutputStream.writeBoolean (false); currentLength = codeLength; } } }
6cf2b52b-d630-4c03-a91e-6a5fde55bb55
5
@EventHandler public void onInteract(PlayerInteractEvent event) { final Player p = event.getPlayer(); if (Core.getState() != State.INGAME) { if (event.getAction() != Action.RIGHT_CLICK_AIR && event.getAction() != Action.RIGHT_CLICK_BLOCK) return; if (event.getItem() == null) return; if (event.getItem().getItemMeta().getDisplayName() == null) return; p.performCommand("hub"); } }
d1acfd42-c587-4b12-9901-a74fa3687d82
4
@Override public String execute() throws Exception { try { Map session = ActionContext.getContext().getSession(); setUser((User) session.get("User")); setUserdetails((UserDetails) getMyDao().getDbsession().get(UserDetails.class, getUser().getEmailId())); if (getUserdetails() != null) { Criteria ucri = getMyDao().getDbsession().createCriteria(UserDetails.class); ucri.add(Restrictions.like("user", getUser().getEmailId())); ucri.setMaxResults(1); setUserdetails((UserDetails) (ucri.list().get(0))); return "update"; } else { return "save"; } } catch (HibernateException e) { addActionError("Server Error Please Try Again Later "); e.printStackTrace(); return "error"; } catch (NullPointerException ne) { addActionError("Server Error Please Try Again Later "); ne.printStackTrace(); return "error"; } catch (Exception e) { addActionError("Server Error Please Try Again Later "); e.printStackTrace(); return "error"; } }
63f80e57-52e2-4a2d-a09b-551154df2c43
4
public Manacher(String s) { this.s = s.toCharArray(); t = preprocess(); p = new int[t.length]; int center = 0, right = 0; for (int i = 1; i < t.length - 1; i++) { int mirror = 2 * center - i; if (right > i) p[i] = Math.min(right - i, p[mirror]); // attempt to expand palindrome centered at i while (t[i + (1 + p[i])] == t[i - (1 + p[i])]) p[i]++; // if palindrome centered at i expands past right, // adjust center based on expanded palindrome. if (i + p[i] > right) { center = i; right = i + p[i]; } } }
65837eff-d979-42f0-922b-922ea570e746
3
public static void compress() { int run = 0; boolean old = false; while (!BinaryStdIn.isEmpty()) { boolean current = BinaryStdIn.readBoolean(); // alternate bit if (current != old) { BinaryStdOut.write(run, lgR); run = 1; old = !old; } // same bit else { // max count if (run == R - 1) { BinaryStdOut.write(run, lgR); // print dummy alternate bit whose length is 0 run = 0; BinaryStdOut.write(run, lgR); } run++; } } BinaryStdOut.write(run, lgR); BinaryStdOut.close(); }
8a84ef25-07ad-4a4b-b117-a41c243be6a5
7
private void setUpField() throws Exception { m_fieldIndex = -1; m_fieldValueIndex = -1; m_field = null; if (m_fieldDefs != null) { m_fieldIndex = getFieldDefIndex(m_fieldName); if (m_fieldIndex < 0) { throw new Exception("[NormDiscrete] Can't find field " + m_fieldName + " in the supplied field definitions."); } m_field = m_fieldDefs.get(m_fieldIndex); if (!(m_field.isString() || m_field.isNominal())) { throw new Exception("[NormDiscrete] reference field " + m_fieldName +" must be categorical"); } if (m_field.isNominal()) { // set up the value index m_fieldValueIndex = m_field.indexOfValue(m_fieldValue); if (m_fieldValueIndex < 0) { throw new Exception("[NormDiscrete] Unable to find value " + m_fieldValue + " in nominal attribute " + m_field.name()); } } else if (m_field.isString()) { // add our value to this attribute (if it is already there // then this will have no effect). m_fieldValueIndex = m_field.addStringValue(m_fieldValue); } } }
1ad76875-46b0-45ad-858c-892c739d3057
2
static double[][] add(double[][] matrix1, double[][] matrix2){ double[][] sum = new double[matrix1.length][matrix1[0].length]; for(int i = 0; i < sum.length; i++) for(int j = 0; j < sum[0].length; j++) sum[i][j] = matrix1[i][j] + matrix2[i][j]; return sum; }
fb76f268-1987-4aa2-808e-e103522fa2a6
5
public byte[] renderImage(final ACamera camera) { // measure render time LOG.info("rendering image..."); this.information = new RenderInformation(); this.information.start(); // calculate the size of the image data this.data = new byte[this.settings.getBytes()]; // initialize the render pool int threadCount = Runtime.getRuntime().availableProcessors(); ExecutorService pool = Executors.newFixedThreadPool(threadCount); Chunk base = new Chunk(32, 32); // v for (int v = 0; v < this.settings.getHeight() / base.height; v++) { // u for (int u = 0; u < this.settings.getWidth() / base.width; u++) { Chunk chunk = new Chunk(u * base.width, v * base.height, base.width, base.height); pool.execute(new RenderChunk(chunk, camera, this.scene, this.listener, this.settings, this.information, this.data)); } // u rest int ur = this.settings.getWidth() - (int) (this.settings.getWidth() / base.width) * base.width; if (ur > 0) { Chunk chunk = new Chunk((this.settings.getWidth() / base.width) * base.width, v * base.height, ur, base.height); pool.execute(new RenderChunk(chunk, camera, this.scene, this.listener, this.settings, this.information, this.data)); } } // v rest int vr = this.settings.getHeight() - (int) (this.settings.getHeight() / base.height) * base.height; if (vr > 0) { // TODO: Qbit - this is a hack, handle last line properly Chunk chunk = new Chunk(0, (this.settings.getHeight() / base.height) * base.height, this.settings.getWidth(), vr); pool.execute(new RenderChunk(chunk, camera, this.scene, this.listener, this.settings, this.information, this.data)); } // wait for all threads to finish try { pool.shutdown(); pool.awaitTermination(20, TimeUnit.MINUTES); } catch (InterruptedException e) { LOG.log(Level.SEVERE, "an error occured while executing render threads", e); } // log render results this.information.stop(); LOG.info("rendering done"); LOG.info(this.information.printInfos(this.settings)); return this.data; }
b9863003-184e-437b-ae98-26a5472ca3e7
7
@Override protected boolean processSourceMessage(CMMsg msg, String str, int numToMess) { if(msg.sourceMessage()==null) return true; int wordStart=msg.sourceMessage().indexOf('\''); if(wordStart<0) return true; String wordsSaid=CMStrings.getSayFromMessage(msg.sourceMessage()); if(wordsSaid == null) return true; if(numToMess>0) wordsSaid=messChars(ID(),wordsSaid,numToMess); final String fullMsgStr = CMStrings.substituteSayInMessage(msg.sourceMessage(),wordsSaid); wordStart=fullMsgStr.indexOf('\''); String startFullMsg=fullMsgStr.substring(0,wordStart); if(startFullMsg.indexOf("YELL(S)")>0) { msg.source().tell(L("You can't yell in sign language.")); return false; } final String oldStartFullMsg = startFullMsg; startFullMsg = CMStrings.replaceFirstWord(startFullMsg, "say(s)", "sign(s)"); startFullMsg = CMStrings.replaceFirstWord(startFullMsg, "ask(s)", "sign(s) askingly"); startFullMsg = CMStrings.replaceFirstWord(startFullMsg, "exclaim(s)", "sign(s) excitedly"); if(oldStartFullMsg.equals(startFullMsg)) { int x=startFullMsg.toLowerCase().lastIndexOf("(s)"); if(x<0) x=startFullMsg.trim().length(); else x+=3; startFullMsg = startFullMsg.substring(0,x)+" in sign" +startFullMsg.substring(x); } msg.modify(msg.source(), msg.target(), this, CMath.unsetb(msg.sourceCode(), CMMsg.MASK_SOUND|CMMsg.MASK_MOUTH) | CMMsg.MASK_MOVE, startFullMsg + fullMsgStr.substring(wordStart), msg.targetCode(), msg.targetMessage(), msg.othersCode(), msg.othersMessage()); return true; }
5e84bf33-28a3-424f-b9a9-5bde025f6b1b
5
private void pop(char c) throws JSONException { if (this.top <= 0) { throw new JSONException("Nesting error."); } char m = this.stack[this.top - 1] == null ? 'a' : 'k'; if (m != c) { throw new JSONException("Nesting error."); } this.top -= 1; this.mode = this.top == 0 ? 'd' : this.stack[this.top - 1] == null ? 'a' : 'k'; }
20bd7b0f-465e-48d6-961d-0f6ebfc35143
2
public Coord mod(Coord d) { int v, w; v = x % d.x; w = y % d.y; if (v < 0) v += d.x; if (w < 0) w += d.y; return (new Coord(v, w)); }
ca978f0a-7949-477b-a61f-9bf2bf386784
0
public long getLength() { return length; }
3761b856-a351-4b51-bc10-e735c4a9d1c1
7
private Boolean waitForJobToComplete(String jobId, String sqsQueueURL) throws InterruptedException, JsonParseException, IOException { Boolean messageFound = false; Boolean jobSuccessful = false; while (!messageFound) { out.println("Checking for messages on queue '" + sqsQueueURL + "'..."); ReceiveMessageRequest request = new ReceiveMessageRequest(sqsQueueURL) .withMaxNumberOfMessages(10); List<Message> msgs = sqsClient.receiveMessage(request).getMessages(); int numMsgs = msgs.size(); if (numMsgs > 0) { out.println("Found " + numMsgs + " message" + (numMsgs == 1 ? "" : "s") + "; looking for job '" + jobId + "'..."); for (Message msg : msgs) { JsonNode bodyNode = parseJSON(msg.getBody()); String body = bodyNode.get("Message").getTextValue(); JsonNode descriptionNode = parseJSON(body); String retrievedJobId = descriptionNode.get("JobId").getTextValue(); String statusCode = descriptionNode.get("StatusCode").getTextValue(); if (retrievedJobId.equals(jobId)) { out.println("Found job '" + retrievedJobId + "' and status '" + statusCode + "'!"); messageFound = true; if (statusCode.equals("Succeeded")) { jobSuccessful = true; } } } } else { out.println("No messages found; sleeping '" + SLEEP_TIME + "' seconds..."); Thread.sleep(SLEEP_TIME * 1000); } } return (messageFound && jobSuccessful); }
c8edeca5-1639-4bf0-8bd9-2dc6766b82c7
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; } } }
c7e6de1a-84f7-4427-8e84-8da59104269b
9
static int blendfactor(int c, int factor, int src, int dst) { switch (factor) { case 1: return c; case 2: return colorMul(c, src); case 3: return colorMul(c, colorSub(0xFFFFFFFF, src)); case 4: return colorMul(c, dst); case 5: return colorMul(c, colorSub(0xFFFFFFFF, dst)); case 6: return colorScale(c, src >>> 24); case 7: return colorScale(c, 255 - (src >>> 24)); case 8: return colorScale(c, dst >>> 24); case 9: return colorScale(c, 255 - (dst >>> 24)); default: return 0; } }
65f41f5f-26c7-4889-8f6e-d61657805f1e
1
public char getChar(){ if( value.length() != 1 ) throw new XException( "not a character: " + value ); return value.charAt( 0 ); }
c9532fc4-2efb-428d-82fb-e7b7555bdb50
3
private void rellenarTabla() { TableColumnModel tcm; if(tarea.getSubtareas()!=null && !tarea.getSubtareas().isEmpty()){ tableModel = new JDEditar.TableModel(tarea.getSubtareas()); jTabla.setModel(tableModel); } tcm = jTabla.getColumnModel(); for (int col = 0; col < headers.length; col++) { tcm.getColumn(col).setHeaderValue(headers[col]); } jTabla.updateUI(); }
9534edd1-d6c8-47f5-9692-155ae92978b2
6
public static void collectVariableBinding(String name, Stella_Object type, Stella_Object binding, KeyValueList bindings) { if (binding != null) { if (type != null) { type = Logic.getDescription(type); } if (RDBMS.collectionValuedConstraintP(binding)) { { Cons args = Stella.NIL; { Stella_Object elt = null; Cons iter000 = RDBMS.collectionValuedConstraintElements(binding); Cons collect000 = null; for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) { elt = iter000.value; if (collect000 == null) { { collect000 = Cons.cons(StringWrapper.wrapString(RDBMS.coercePowerloomObjectToString(elt, ((NamedDescription)(type)))), Stella.NIL); if (args == Stella.NIL) { args = collect000; } else { Cons.addConsToEndOfConsList(args, collect000); } } } else { { collect000.rest = Cons.cons(StringWrapper.wrapString(RDBMS.coercePowerloomObjectToString(elt, ((NamedDescription)(type)))), Stella.NIL); collect000 = collect000.rest; } } } } binding = args; } } else { binding = StringWrapper.wrapString(RDBMS.coercePowerloomObjectToString(binding, ((NamedDescription)(type)))); } } bindings.insertAt(StringWrapper.wrapString(name), binding); }
fc23c233-bea9-464f-ae56-50fd7f94b1c9
0
public void setMedicoCollection(Collection<Medico> medicoCollection) { this.medicoCollection = medicoCollection; }
eebdd440-bbb3-463b-af34-4715efa1f27c
9
public Powerup(){ int i = rand.nextInt(225); if (i >= 25) this.type = PowerupType.NUKE; if (i < 25) this.type = PowerupType.SLOWTIME; if(i >= 100) this.type = PowerupType.LIVES; if(i >= 150) this.type = PowerupType.SHRINK; if(i >= 200) this.type = PowerupType.RANDOM; this.xPos = this.rand.nextInt(Snow.game.currentWidth - this.size); this.size = 10; if(this.type == PowerupType.NUKE){ this.red = 0.8f; this.green = 0.3f; this.blue = 0.2f; } if(this.type == PowerupType.SLOWTIME){ this.red = 0.3f; this.green = 0.8f; this.blue = 0.2f; } if(this.type == PowerupType.LIVES){ this.red = 0.2f; this.green = 0.3f; this.blue = 0.8f; } if(this.type == PowerupType.SHRINK){ this.red = 0.8f; this.green = 0.8f; this.blue = 0.2f; } }
35ebd8e5-7dd1-4ea8-81f8-9791389b1207
3
@Override public void mark(int boardPosition, Cell[] cellBoard, int rows, int columns) throws IllegalMark { //Find the row. int boardPositionRow = boardPosition / columns; //Find the column. int boardPositionColumn = boardPosition % columns; //Position to mark. int positionToMark = boardPosition; if (boardPositionRow +2 < rows){ //Left side. if(boardPositionColumn -1 >= 0){ positionToMark = (boardPositionRow +2) * columns + boardPositionColumn -1; mark(boardPosition,positionToMark, cellBoard); } //Right side. if(boardPositionColumn +1 < columns){ positionToMark = (boardPositionRow +2) * columns + boardPositionColumn +1; mark(boardPosition,positionToMark, cellBoard); } } }
89f1c626-c2d3-4607-b8d1-8d2ba9a6644b
7
public boolean collision(HashMap<Body, Personnage> personnages) { if (world == null) return false; Personnage persCourant; // collision avec l'environnement est apparu? CollisionEvent[] evenement = world.getContacts(body); float Normal_x; for (int i = 0; i < evenement.length; i++) { Normal_x = evenement[i].getNormal().getX(); // regarde qu'elle corps est rentre en collision avec quelque chose if (Normal_x < -0.5 || Normal_x > 0.5) { // corps B est rentre en collision, est ce la balle ? si oui, // collision, si touche un ennemi, appelle la fonction toucher // de cet ennemi pour lui enlever 1 pt de vie if (evenement[i].getBodyB() == body) { persCourant = personnages.get(evenement[i].getBodyA()); // Current vaut null si le body mise en cause n'est pas un body de personnage if (persCourant != null && cible(persCourant)) persCourant.toucher(valeurDmg); return true; } } } return false; }
a7403599-8dab-466e-a997-72283acc7143
3
public static void main(String[] args){ Socket socket = null; DataOutputStream os = null; DataInputStream is = null; Scanner sc = new Scanner(System.in); try{ socket = new Socket("192.168.22.1",5000); os = new DataOutputStream(socket.getOutputStream()); is = new DataInputStream(socket.getInputStream()); while(true){ System.out.print("Send message to server: "); String sendMessage = sc.nextLine(); os.writeUTF(sendMessage); if(sendMessage.equals("end")){ socket.close(); is.close(); os.close(); break; } String receiveMessage = is.readUTF(); System.out.println("Receive from server: " + receiveMessage); } } catch(Exception e){ System.out.println(e.getMessage()); } }
87a6550a-f8e4-4969-9412-a5a95bda0846
7
public final String methodR(int j) { if(j >= 0 && j < 10000) return String.valueOf(j); if(j >= 10000 && j < 10000000) return j / 1000 + "K"; if(j >= 10000000 && j < 999999999) return j / 1000000 + "M"; if(j >= 999999999) return "*"; else return "?"; }
edfd3dd1-1917-430a-9054-079a7b2c8e6d
8
@Override public void stateChanged(ChangeEvent evt) { if (evt.getSource().equals(targetDayPicker.getModel())) { targetDay.set( targetDayPicker.getModel().getYear(), targetDayPicker.getModel().getMonth(), targetDayPicker.getModel().getDay()); updateRosterList(); updateTripList(); } if (evt.getSource().equals(detailsStartTimeSpinner)) { TripComponent t = tripList.getSelectedValue(); if (t == null) return; Date d = (Date)detailsStartTimeSpinner.getValue(); Calendar c = Calendar.getInstance(); c.setTime(d); int m = c.get(Calendar.MINUTE); if (m % 15 != 0) { if (m%15 > 8) { m -= m%15; } else { m += 15 - m%15; } c.set(Calendar.MINUTE, m); } t.getTrip().setTripStartTime(c.getTime()); detailsStartTimeSpinner.setValue (c.getTime()); return; } if (evt.getSource().equals(tabpanePlanningSteps)) { showAllRivers.setVisible(tabpanePlanningSteps.getSelectedIndex() == 0); if (tabpanePlanningSteps.getSelectedIndex() == 3) updateTimePanel(); if (tabpanePlanningSteps.getSelectedIndex() == 4) panelPreview.checkTrips(); } }
42233c55-7363-4d7d-8efe-a26249048429
5
public Notebook() { getContentPane().add(content); scrollPane = new JScrollPane(content); getContentPane().add(scrollPane, "Center"); for (menu_count = 0; menu_count < menu.length; menu_count++) { nbMenuBar.add(menu[menu_count]); menu[menu_count].addActionListener(this); while ((menu_count == 0) && (menuitem_count < File_Item.length)) { menu[0].add(File_Item[menuitem_count]); File_Item[menuitem_count].addActionListener(this); menuitem_count++; } menuitem_count = 0; while ((menu_count == 1) && (menuitem_count < Edit_Item.length)) { menu[1].add(Edit_Item[menuitem_count]); Edit_Item[menuitem_count].addActionListener(this); menuitem_count++; } } // Font_Dialog.add menu[3].add(Abt_Item); menu[2].add(Font_Item); Abt_Item.addActionListener(this); Font_Item.addActionListener(this); setJMenuBar(nbMenuBar); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); }
1b250b14-ef3c-4ca3-81c3-c5a679449973
7
public void monitorarSoro(float qtdSoro, Paciente paciente) throws ControllerException { try { if (qtdSoro < 0 || qtdSoro > 500) { throw new ControllerException( "valor de quantidade de soro inválido"); } if (ValidarPaciente(paciente) && qtdSoro < 20) { Publish publish = new Publish(paciente.getIdTopico(), uriHub); Evento evento = new Evento(QTD_SORO + "=" + qtdSoro, Calendar.getInstance(), paciente); eventoDAO.save(evento); publish.publish(evento.getDescricao()); } } catch (ObjetoNuloException | ValorInvalidoException e) { throw new ControllerException(e.getMessage()); } catch (ComunicationException e) { throw new ControllerException(e.getMessage()); } catch (DAOException e) { throw new ControllerException(e.getMessage()); } }
d41f21e2-7203-4cae-bb0b-821a4811c780
8
public int largestRectangleArea(int[] height) { // Start typing your Java solution below // DO NOT write main() function Stack<Pair> sta = new Stack<Pair>(); if (height.length == 0) return 0; int res = 0; int i = 0; for (; i < height.length; i++) { int preH = sta.isEmpty() ? -1 : height[sta.peek().index]; if (height[i] > preH) // situation 1 sta.push(new Pair(i, i)); else if (height[i] < preH) { // situation 3 int last = 0; do { last = sta.pop().preIndex; res = Math.max((i - last) * preH, res); } while (!sta.isEmpty() && (preH = height[sta.peek().index]) >= height[i]); sta.push(new Pair(i, last)); } } while (!sta.isEmpty()) { Pair cur = sta.pop(); res = Math.max((i - cur.preIndex) * height[cur.index], res); } return res; }
15491180-2c82-49c4-a320-3a603b89ea4b
1
public Boolean equals(Eisenstein that) { return this.a == that.a && this.b == that.b; }
1f49529d-6ac0-4adb-ab3e-c66778dcb898
5
@Override public String toString() { String result = ""; int counter = 0; if (!isEmpty()) { for (Object obj : queue) { if (obj != null) { result += counter + "[" + obj + "] "; if (counter == (head) % queue.length) { result += "(head) "; } if (counter == (tail) % queue.length) { result += "(tail) "; } } counter++; } } else { result = "Queue is empty."; } return result; }
da621315-ce01-491b-81d8-7de044716b8c
5
public Card handleSuggestion(Solution suggestion){ ArrayList<Card> clues = new ArrayList<Card>(); Random roller = new Random(); for(Player player : players) { if(player.getName().equals(suggestion.getPerson())) player.setLocation(currentPlayer.getLocation()); if(players.get(currentPlayerIndex) == player) { } else { if(player.disproveSuggestion(suggestion) != null) { clues.add(player.disproveSuggestion(suggestion)); } } } if(clues.size() == 0) return null; else { int cardIndex = roller.nextInt(clues.size()); ComputerPlayer.updateSeen(clues.get(cardIndex)); return clues.get(cardIndex); } }
4b1a13eb-4926-4a84-8981-6da08f6938ce
9
static String findCommonString(String string1, String string2) { int length1 = string1.length(); int length2 = string2.length(); int[][] traceMap = new int[length1][length2]; int maxNum = 0; int lastSubBegin = 0; String commonSub = ""; if(length1==0 || length2==0) return ""; for(int i=0;i<length1;i++) { for(int j=0;j<length2;j++) { if(string1.charAt(i)==string2.charAt(j)) { if(i==0 || j==0) { traceMap[i][j] = 1; } else { traceMap[i][j] = traceMap[i-1][j-1] + 1; } if(maxNum<traceMap[i][j]) { maxNum++; int thisSubBegin = i+1-traceMap[i][j]; if(lastSubBegin==thisSubBegin) { commonSub += string1.charAt(i); } else { lastSubBegin = thisSubBegin; commonSub = string1.substring(thisSubBegin, i+1); } } } } } return commonSub; }
ed1d9ba7-11d2-43c6-94fd-abce176bf458
3
public VariableStack mapStackToLocal(VariableStack stack) { VariableStack newStack; int params = cond.getFreeOperandCount(); if (params > 0) { condStack = stack.peek(params); newStack = stack.pop(params); } else newStack = stack; VariableStack after = VariableStack.merge(thenBlock .mapStackToLocal(newStack), elseBlock == null ? newStack : elseBlock.mapStackToLocal(newStack)); if (jump != null) { jump.stackMap = after; return null; } return after; }
680c9feb-927d-4578-bdd8-195c8ac01f57
9
private int square(Piece[][] pieces, int from_x, int from_y, int to_x, int to_y) { if((to_x == from_x && Math.abs(to_y - from_y) == 1 || to_y == from_y && Math.abs(to_x - from_x) == 1 || Math.abs(to_x - from_x) == 1 && Math.abs(to_y - from_y) == 1) && (isOccupiedByAnOpponent(pieces[to_x][to_y]) || isEmpty(pieces[to_x][to_y]))) { if(isOccupiedByAnOpponent(pieces[to_x][to_y])) { last_move_info = "Kx" + (char)(((int)'a') + to_y) + "" + (8 - to_x) + " "; } else { last_move_info = "K" + (char)(((int)'a') + to_y) + "" + (8 - to_x) + " "; } pieces[to_x][to_y] = pieces[from_x][from_y]; pieces[from_x][from_y] = null; return MOVED; } return NOT_MOVED; }
1398f55d-1783-429c-aafd-65e2b0e7b323
6
void FillDistancesPrices() { for (int i = Base.kStartPosModelIndex; i < Base.kNumFullDistances; i++) { final int posSlot = GetPosSlot(i); final int footerBits = ((posSlot >> 1) - 1); final int baseVal = (2 | posSlot & 1) << footerBits; tempPrices[i] = BitTreeEncoder.ReverseGetPrice(_posEncoders, baseVal - posSlot - 1, footerBits, i - baseVal); } for (int lenToPosState = 0; lenToPosState < Base.kNumLenToPosStates; lenToPosState++) { int posSlot; final BitTreeEncoder encoder = _posSlotEncoder[lenToPosState]; final int st = lenToPosState << Base.kNumPosSlotBits; for (posSlot = 0; posSlot < _distTableSize; posSlot++) { _posSlotPrices[st + posSlot] = encoder.GetPrice(posSlot); } for (posSlot = Base.kEndPosModelIndex; posSlot < _distTableSize; posSlot++) { _posSlotPrices[st + posSlot] += (posSlot >> 1) - 1 - Base.kNumAlignBits << SevenZip.Compression.RangeCoder.Encoder.kNumBitPriceShiftBits; } final int st2 = lenToPosState * Base.kNumFullDistances; int i; for (i = 0; i < Base.kStartPosModelIndex; i++) { _distancesPrices[st2 + i] = _posSlotPrices[st + i]; } for (; i < Base.kNumFullDistances; i++) { _distancesPrices[st2 + i] = _posSlotPrices[st + GetPosSlot(i)] + tempPrices[i]; } } _matchPriceCount = 0; }
6cba0dfb-c82a-434a-bf9a-2e11b946c416
4
@Override public void run(ListIterator<Instruction> iter){ Instruction i = iter.next(); // if this function does any function calls, the return // address will need to be saved if(i instanceof Call) { registersUsed.add(retAddrReg); } Integer color = i.getColor(); // negative values are used as special placeholders if(color != null && color >= 0) { // color is a 0 based number, check if this value will be // spilled if(color >= registersAvailable) { memNeeded = Math.max(memNeeded, color - registersAvailable + 1); } else { registersUsed.add(color); } } }
06dd37a1-00bc-430a-bbf0-686db0734554
5
public boolean isFull(int i, int j) // is site (row i, column j) full? { if (i<1 || i>N || j<1 || j>N) { throw new java.lang.IndexOutOfBoundsException(); } return isOpen(i, j) && uf_real.connected(N * (i - 1) + j - 1, N * N); }
d34f1d1b-a2e4-4141-929c-730a223fbe9b
9
static void lsp_to_curve(float[] curve, int[] map, int n, int ln, float[] lsp, int m, float amp, float ampoffset) { int i; float wdel = M_PI / ln; for (i = 0; i < m; i++) { lsp[i] = Lookup.coslook(lsp[i]); } int m2 = (m / 2) * 2; i = 0; while (i < n) { int k = map[i]; float p = .7071067812f; float q = .7071067812f; float w = Lookup.coslook(wdel * k); for (int j = 0; j < m2; j += 2) { q *= lsp[j] - w; p *= lsp[j + 1] - w; } if ((m & 1) != 0) { /* odd order filter; slightly assymetric */ /* the last coefficient */ q *= lsp[m - 1] - w; q *= q; p *= p * (1.f - w * w); } else { /* even order filter; still symmetric */ q *= q * (1.f + w); p *= p * (1.f - w); } // q=frexp(p+q,&qexp); q = p + q; int hx = Float.floatToIntBits(q); int ix = 0x7fffffff & hx; int qexp = 0; if (ix >= 0x7f800000 || (ix == 0)) { // 0,inf,nan } else { if (ix < 0x00800000) { // subnormal q *= 3.3554432000e+07; // 0x4c000000 hx = Float.floatToIntBits(q); ix = 0x7fffffff & hx; qexp = -25; } qexp += ((ix >>> 23) - 126); hx = (hx & 0x807fffff) | 0x3f000000; q = Float.intBitsToFloat(hx); } q = Lookup.fromdBlook(amp * Lookup.invsqlook(q) * Lookup.invsq2explook(qexp + m) - ampoffset); do { curve[i++] *= q; } while (i < n && map[i] == k); } }
71f189a8-65a7-4758-8db7-bf18f5772bf7
6
public String nextCDATA() throws JSONException { char c; int i; StringBuffer sb = new StringBuffer(); for (;;) { c = next(); if (end()) { throw syntaxError("Unclosed CDATA"); } sb.append(c); i = sb.length() - 3; if (i >= 0 && sb.charAt(i) == ']' && sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') { sb.setLength(i); return sb.toString(); } } }
62338984-cc0f-4df1-b0dc-ac11a7ef08e6
1
@Override public int decidePlay(int turn, int drawn, boolean fromDiscard) { DataInstance d = getHistory(drawn, false); playNet.compute(d.inputs); int actual = playNet.getOutput()-1; //Train if (model_mimic != null){ int target = model_mimic.decidePlay(turn, drawn, fromDiscard); playNet.trainBackprop(0.01, target+1); } return actual; }
c6b28227-0427-4816-995d-e74528ddb9c2
8
private String queryServer() throws IOException { ih_str = ""; byte[] info_hash = this.torrentInfo.info_hash.array(); for (int i = 0; i < info_hash.length; i++) { ih_str += "%" + this.HEXCHARS[(info_hash[i] & 0xF0) >>> 4] + this.HEXCHARS[info_hash[i] & 0x0F]; } //System.out.println("info hash: " + ih_str); /*Save the info hash for later usage as an array of bytes*/ this.info_hash = this.torrentInfo.info_hash.array(); // String query = "announce?info_hash=" + ih_str + "&peer_id=" + host.getPeerID() + "&port=" + host.getPort() + "&left=" + torinfo.file_length + "&uploaded=0&downloaded=0"; String query=null; //this makes sure that event is either started, completed, or stopped if(this.torrentHandler.getBytesDownloaded()==0){ this.event="started"; }else if(this.torrentInfo.file_length==0){ this.event="completed"; }else{ this.event="not done yet"; //this is checked in the next method and eliminated } if((this.event.equalsIgnoreCase("started")) || (this.event.equalsIgnoreCase("completed")) || (this.event.equalsIgnoreCase("stopped")) ){ //does nothing if its one of the strings stated above }else{ this.event=null; } if(this.event==null){ query = "announce?info_hash=" + ih_str + "&peer_id=" + this.peer_id + "&port="+this.serverPort+"&left=" + this.torrentInfo.file_length + "&uploaded="+this.torrentHandler.getBytesUploaded()+ "&downloaded="+this.torrentHandler.getBytesDownloaded(); }else{ query = "announce?info_hash=" + ih_str + "&peer_id=" + this.peer_id + "&port="+this.serverPort+"&left=" + this.torrentInfo.file_length + "&uploaded="+this.torrentHandler.getBytesUploaded()+ "&downloaded="+this.torrentHandler.getBytesDownloaded()+ "&event="+this.event; } URL urlobj; urlobj = new URL(this.torrentInfo.announce_url, query); //System.out.println(urlobj); HttpURLConnection uconnect = (HttpURLConnection) urlobj .openConnection(); uconnect.setRequestMethod("GET"); BufferedReader in = new BufferedReader(new InputStreamReader( uconnect.getInputStream())); StringBuffer response = new StringBuffer(); String inline = ""; while ((inline = in.readLine()) != null) { response.append(inline); } //System.out.println(peer_id +"\n" +response.toString()); return response.toString(); //html response }
aa4a2698-f21a-4d0a-b793-339a10302cec
7
@Override public boolean onResponse(Message message) { String msg = message.content.toLowerCase(); Pattern pattern = Pattern.compile("^@((qinbot)|(亲妹子)) +help(.*)"); Matcher matcher = pattern.matcher(msg); if (matcher.find()) { //总帮助提示 if (matcher.group(4)==null||matcher.group(4).trim().equals("")) { StringBuilder sb = new StringBuilder(); sb.append("\\\\n输入@QinBot help 插件名称 获取具体帮助\\\\n当前插件如下:\\\\n"); for (int i = 1; i < plugins.size(); i++) { sb.append(plugins.get(i).name).append(" ver:").append(plugins.get(i).version).append("\\\\n"); } message.reply(sb.toString()); }else { String help = null; for (int i = 1; i < plugins.size(); i++) { if (plugins.get(i).name.equals(matcher.group(4).trim())) { PluginBase pluginBase = plugins.get(i); help =String.format("\\\\n简介:%s\\\\n帮助:%s\\\\n",pluginBase.descrition,pluginBase.help); break; } } if (help!=null) { message.reply(help); }else { message.reply("未找到"+matcher.group(4)); } } return true; } return false; }
ca76db57-be02-4b9d-87bc-791880e13ebd
1
public long getElapsedTimeSecs() { long elapsed; if (running) { elapsed = ((System.currentTimeMillis() - startTime) / 1000); } else { elapsed = ((stopTime - startTime) / 1000); } return elapsed; }
b9f9f2da-ed54-4679-b3bf-5ba18bf66110
9
public ArrayList<Disciplina> Disciplinas() throws FileNotFoundException { try { Scanner fi = new Scanner(new File("src/Ficheiros/disciplinas.txt")); Scanner ji = new Scanner(new File("src/Ficheiros/disciplinas.txt")); String bb = fi.nextLine(); String bbb = ji.nextLine(); // leitura de ficheiro linha-a-linha String[] c; int t = -1; do { ArrayList<Professor> y = new ArrayList<Professor>(); String b = fi.nextLine(); c = b.split(";"); int i = 5; do { int j = 0; do { String o = getProfessor().get(j).getSigla(); if (c[i].equalsIgnoreCase(o)) { y.add(getProfessor().get(j)); // x2.get(j).getListaDisciplinas().add(x4.get(t)); } j++; } while (getProfessor().size() > j); i++; } while (i < c.length); // System.out.println(c[1]); Disciplina a = new Disciplina(c[0], c[1], Integer.parseInt(c[2]), Integer.parseInt(c[3]), c[4], y); getDisciplina().add(a); } while (fi.hasNextLine()); do { String b = ji.nextLine(); t++; c = b.split(";"); int i = 5; do { int j = 0; do { String o = getProfessor().get(j).getSigla(); if (c[i].equalsIgnoreCase(o)) { getProfessor().get(j).getListaDisciplinas().add(getDisciplina().get(t)); } j++; } while (getProfessor().size() > j); i++; } while (i < c.length); } while (ji.hasNextLine()); //System.out.println(professor.get(2).toStringProfessor()); } catch (FileNotFoundException e) { // System.out.println("Ficheiro basico de disciplinas não encontrado."); // JOptionPane.showMessageDialog(null, "Ficheiro basico das disciplinas não encontrado."); fiDisciplina = false; ghjk = false; } return getDisciplina(); }
269d609c-fe8f-40eb-a7f2-73d31a9d97d1
1
public void addMarker(double latitude,double longtitude) { if(markers<20) { marker[markers] = new MarkerRect(latitude,longtitude); markers++; } }
68ab5afc-ff4f-4714-a66c-65c411c622df
7
@Override // Over writes the table cell renderer to perform custom cell rendering public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { // Create a rendered label for easy manipulation JLabel renderedLabel = (JLabel) super.getTableCellRendererComponent( table, value, isSelected, hasFocus, row, column); // Set the horizontal alignment based on the column if(column == CustomModel.TEAM_NAME_COL) { renderedLabel.setHorizontalAlignment(SwingConstants.LEFT); } else { renderedLabel.setHorizontalAlignment(SwingConstants.CENTER); } // Determine the color for this cell Color cellColor; // Set the color to grey wherever the user currently is highlighting if(isSelected && hasFocus) { cellColor = Color.gray; } // Set the draft column to a special color else if (column == CustomModel.DRAFT_ORDER_COL){ cellColor = lavender; } // Set picked columns to yellow else if( (value != null) && value.toString().equals(CustomModel.PICKED)) { cellColor = Color.yellow; } // If this is an even row, set the color one way else if( (row%2) == 0) { cellColor = honeyDew; } // Otherwise set the color to the default else { cellColor = mintCream; } renderedLabel.setOpaque(true); renderedLabel.setBackground(cellColor); renderedLabel.setForeground(midnightBlue); renderedLabel.setFont(new Font("Dialog", Font.PLAIN, 14)); return renderedLabel; }
ef911ba3-5af4-47e2-b664-a381ddc8dd62
1
private static void addAll(Set<String> target, Set<String> toAdd, String prefix){ for(String i : toAdd){ // System.out.println((prefix+i)); target.add((prefix+i)); } }
ab8df6e9-fa22-4d03-96bd-1f81f8ec6106
4
@Override protected void paintScreen(Graphics2D g) { paintInstructions(g); int maxNbChoicesOnScreen = (getScreenHeight() - INSTRUCTIONS_AREA_HEIGHT) / CHOICE_HEIGHT - 1; int start = 0; if (selectedIndex >= maxNbChoicesOnScreen) { start = selectedIndex - maxNbChoicesOnScreen + 1; } int lastChoiceToDisplay = Math.min(start + maxNbChoicesOnScreen, choices.length); for (int index = start; index < lastChoiceToDisplay; index++) { Choice choice = choices[index]; String str = getDisplayName(choice); if (index == selectedIndex) { g.setColor(SELECTED_CHOICE_COLOR); g.setFont(SELECTED_CHOICE_FONT); str = "\u00bb " + str + " \u00ab"; } else { g.setColor(DEFAULT_CHOICE_COLOR); g.setFont(DEFAULT_CHOICE_FONT); } GUIUtils.drawCenteredString(g, str, getScreenWidth(), INSTRUCTIONS_AREA_HEIGHT + CHOICE_HEIGHT * (index - start)); } if (lastChoiceToDisplay < choices.length) { g.setFont(DEFAULT_CHOICE_FONT); g.setColor(DEFAULT_CHOICE_COLOR); GUIUtils.drawCenteredString(g, "...", getScreenWidth(), INSTRUCTIONS_AREA_HEIGHT + CHOICE_HEIGHT * maxNbChoicesOnScreen); } }
944f26c4-3231-4ac0-b5f8-a1d032867754
8
public boolean isBlockSolidOnSide(World world, int x, int y, int z, int side) { int meta = world.getBlockMetadata(x, y, z); if (this instanceof BlockStep) { return (((meta & 8) == 8 && (side == 1)) || isOpaqueCube()); } else if (this instanceof BlockFarmland) { return (side != 1 && side != 0); } else if (this instanceof BlockStairs) { boolean flipped = ((meta & 4) != 0); return ((meta & 3) + side == 5) || (side == 1 && flipped); } return isBlockNormalCube(world, x, y, z); }
539d56e6-9b33-440c-afd3-ee69a46eb0d3
7
protected void updateOrigin() { mxRectangle bounds = getGraphBounds(); if (bounds != null) { double scale = getView().getScale(); double x = bounds.getX() / scale - getBorder(); double y = bounds.getY() / scale - getBorder(); if (x < 0 || y < 0) { double x0 = Math.min(0, x); double y0 = Math.min(0, y); origin.setX(origin.getX() + x0); origin.setY(origin.getY() + y0); mxPoint t = getView().getTranslate(); getView().setTranslate( new mxPoint(t.getX() - x0, t.getY() - y0)); } else if ((x > 0 || y > 0) && (origin.getX() < 0 || origin.getY() < 0)) { double dx = Math.min(-origin.getX(), x); double dy = Math.min(-origin.getY(), y); origin.setX(origin.getX() + dx); origin.setY(origin.getY() + dy); mxPoint t = getView().getTranslate(); getView().setTranslate( new mxPoint(t.getX() - dx, t.getY() - dy)); } } }
813ec839-c512-4066-a8f9-cb3a7cc6cdfb
7
public static void main(String[] args) throws Exception { IfolorLoader loader = new IfolorLoader(); ProjectPath path = TestData.getTestProject(); Book book = loader.load(path); HashSet<String> duplicateFind = new HashSet<String>(); int doubles = 0; for (BookPage pg : book.pages) for (BookElement el : pg.pics) if (el instanceof BookPicture) { BookPicture pic = (BookPicture) el; String name = pic.getSourceName(book); if (name == null || name.isEmpty() || name.startsWith("Images::")) continue; if (duplicateFind.contains(name)) { System.out.println("Double use of file: " + name); doubles++; } System.out.println(name); duplicateFind.add(name); } System.out.println(); System.out.printf("%s duplicate warnings\n", doubles); System.out.printf("%s unique files\n", duplicateFind.size()); }