method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
5fd5ede9-890b-40fa-8fb1-9860cf8a718f
4
public void run() { if(seconds == 0){ ArenaSetupEvent event = new ArenaSetupEvent(a); Bukkit.getServer().getPluginManager().callEvent(event); new ArenaSetupRunnable(plugin, 40, a); for(String s : a.getPlayers()){ Bukkit.getPlayerExact(s).teleport(a.getSpawn()); } Bukkit.getScheduler().cancelTask(id); } else if(seconds == 5 || seconds == 1){ Util.broadcastToArena("Time left : " + seconds, a); seconds--; } else{ seconds--; } }
535a2ad6-bb9b-405e-9643-bd61f3465364
4
public void visitTypeInsn(final int opcode, final String type) { Type t = Type.getObjectType(type); switch (opcode) { case Opcodes.NEW: anew(t); break; case Opcodes.ANEWARRAY: newarray(t); break; case Opcodes.CHECKCAST: checkcast(t); break; case Opcodes.INSTANCEOF: instanceOf(t); break; default: throw new IllegalArgumentException(); } }
3e8e7c2b-170d-4290-974f-8771fc01f21b
5
@Override public void receive(Object message) { if (!(message instanceof String)) { log.severe("Unknown message format. Can't receive information"); return; } MACKInformation info = MACKProtocolFactory .parseMessage((String) message); if (info == null) { log.severe("Message was invalid"); return; } CASi.SIM_LOG.finest(this + ": Receiving update!"); String activity = info.getAccessibleEntities().get("activity"); if (activity != null) { for (State s : State.values()) { if (s.toString().equalsIgnoreCase(activity)) { setCurrentState(s); break; } } } else { setCurrentState(State.unknown); } }
fd44000d-9a56-4348-9871-f0429d9fe3cf
2
public void sendMessage(String message, String playerName) { for (Player p : server.players) if(p.username == playerName) p.sendMessage(message); }
9825ce86-e5ce-44c2-a30e-942f18383740
1
public void addAccount(BankAccount account) throws IllegalArgumentException { if (! canHaveAsAccount(account)) throw new IllegalArgumentException(); accounts.add(account); }
7185e364-6b7f-4f66-8bce-b04b6043e306
9
@Override public void keyPressed(KeyEvent e) { dir = e.getKeyCode(); if (previousKey == dir && doubleCount == 1 && (dir == KeyEvent.VK_LEFT || dir == KeyEvent.VK_RIGHT)) { incr = STDINCR * 2; endTime = System.currentTimeMillis(); if (endTime - startTime < 200) { doubleSpeed = 2; System.out.println("Double!"); } else { doubleSpeed = 1; } } if (dir == KeyEvent.VK_LEFT || dir == KeyEvent.VK_RIGHT) { cont = true; tempKey = dir; } if (dir == KeyEvent.VK_ENTER) { if (!hasWon()) { togglePaused(); } else { reset(); } } }
45321d70-0610-4f15-9a6c-7377b6f08337
8
public void writeProperties() { List<Display> displays = defaultDisplayPane.getOpenDisplays(); //First see if we the location of the user properties file is in //the props file itself String propsPath = props.getProperty("this.path"); String fileSep = System.getProperty("file.separator"); props.setProperty("iconPath", iconPath); String filename = SunFishApp.userPropsFilename; //Remember window size props.setProperty("frame.width", String.valueOf(this.getWidth())); props.setProperty("frame.height", String.valueOf(this.getHeight())); props.setProperty("displayPane.height", String.valueOf(rightSplitPane.getDividerLocation())); logger.info("Writing properties to file: " + propsPath + filename); int fileTreePanelWidth = outerSplitPane.getDividerLocation(); props.setProperty("fileTreePanel.width", new Integer(fileTreePanelWidth).toString()); for(int i=0; i<50; i++) { props.remove("display." + Integer.valueOf(i)); props.remove("fileTree.block." + Integer.valueOf(i)); } //Write properties from file tree, mostly just which top level directories we //should remember int count = 0; List<String> fileTreeRoots = fileTreePanel.getTopLevelPaths(); for(String path : fileTreeRoots) { props.setProperty("fileTree.block." + String.valueOf(count), path); count++; } props.setProperty("fileTree.blocknum", String.valueOf(count)); count = 0; List<File> recentFiles = fileTreePanel.getRecentFiles(); for(File file : recentFiles) { props.setProperty("fileTree.recentItem." + String.valueOf(count), file.getAbsolutePath()); count++; } //Write properties for currently open displays if (displays.size()>0) { count = 0; for(Display d : displays) { File file = d.getSourceFile(); if (file!=null) { String filepath = file.getAbsolutePath(); props.setProperty("display." + count, filepath); count++; } } props.setProperty("display.number", new Integer(count).toString()); } if (propsPath==null) { propsPath = System.getProperty("user.dir"); props.setProperty("this.path", propsPath); } String fullPath = propsPath + fileSep + filename; try { FileOutputStream propsStream = new FileOutputStream(fullPath); props.store(propsStream, "--- nothing to report ----" ); propsStream.close(); } catch (IOException ioe) { logger.warning("Error writing to user properties file, tried path : " + fullPath + "\n" + ioe); } }
522f6700-f6d4-45c7-85a8-c9a0e7231d8f
9
public void reverseNotes() { final ArrayDeque<String> headReversed = new ArrayDeque<>(); final ArrayDeque<AbcEvent> notesReversed = new ArrayDeque<>(); int lineIdx = 0; boolean head = true; while (lineIdx < lines.size()) { final String line = lines.get(lineIdx++); if (notesRaw.get(0) == line) { break; } else if (head) { // keep only documentary lines at the start headReversed.addLast(line); } } final String title = this.title.toString(); this.title.setLength(0); this.title.append(title); lines.clear(); if (notes.isEmpty()) parse(); notesRaw.clear(); lines.addAll(headReversed); final Map<Class<? extends AbcEvent>, AbcEvent> lastEventMap = new HashMap<>(); lastEventMap.put(AbcVolumeChange.class, new AbcVolumeChange("mf")); final Map<String, List<AbcNote>> continuations = new HashMap<>(); for (final AbcEvent e : notes) { if (e.isMeta()) { final AbcEvent lastEvent = lastEventMap.get(e.getClass()); if (lastEvent != null) { notesReversed.addFirst(lastEvent); } lastEventMap.put(e.getClass(), e); } else { // a- <--last // a/ <-- e // reversed: // a/- <-- e // a <-- last ContiunableAbcEvent ce = (ContiunableAbcEvent) e; ce.reverseContinuation(continuations); notesReversed.addFirst(e); } } if (!continuations.isEmpty()) { // TODO possible and needs extra care? } notesReversed.addFirst(lastEventMap.get(AbcVolumeChange.class)); notes.clear(); notes.addAll(notesReversed); }
d86c4ee1-5a67-477f-a9df-23e1aa926e3d
9
private void init(AppAction a, final String iconKey, boolean showText) { enablePlasticWorkaround = UIManager.getLookAndFeel().getClass().getName().startsWith("com.jgoodies.looks.plastic."); setAction(a); addMouseListener(new MouseAdapter() { public void mouseEntered(MouseEvent e) { if (isEnabled()) { if(hoverForeground != null) { oldForeground = getForeground(); setForeground(hoverForeground); } setBorderPainted(true); if (!enablePlasticWorkaround) { setContentAreaFilled(true); } } } public void mouseExited(MouseEvent e) { setBorderPainted(false); setContentAreaFilled(enablePlasticWorkaround); if(oldForeground != null) { setForeground(oldForeground); oldForeground = null; } } }); a.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals(iconKey)) { Icon icon = (Icon) evt.getNewValue(); ActionButton.this.setIcon(icon); ActionButton.this.invalidate(); ActionButton.this.repaint(); } } }); setBorderPainted(false); setContentAreaFilled(enablePlasticWorkaround); if (a != null && a.getValue(Action.ACCELERATOR_KEY) != null) { setMnemonic(0); registerKeyboardAction(a, (KeyStroke) a.getValue(Action.ACCELERATOR_KEY), JButton.WHEN_IN_FOCUSED_WINDOW); } setIcon((Icon) a.getValue(iconKey)); if (Boolean.FALSE.equals(a.getValue(AppAction.TEXT_ON_TOOLBAR)) || !showText) { setHideText(true); } else { setHideText(false); } setVerticalTextPosition(JButton.BOTTOM); setHorizontalTextPosition(JButton.CENTER); }
89a3bf86-42ee-4511-b45a-5ba46285e69c
9
@Override public void initializeClass() { super.initializeClass(); for(final Enumeration<Ability> a=CMClass.abilities();a.hasMoreElements();) { final Ability A=a.nextElement(); if(A!=null) { final int level=CMLib.ableMapper().getQualifyingLevel(ID(),true,A.ID()); if((!CMLib.ableMapper().getDefaultGain(ID(),true,A.ID())) &&(level>0) &&((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_SPELL)) { final boolean secret=CMLib.ableMapper().getSecretSkill(ID(),true,A.ID()); if((A.classificationCode()&Ability.ALL_DOMAINS)==opposed()) { if(CMLib.ableMapper().getDefaultGain(ID(),true,A.ID())) CMLib.ableMapper().addCharAbilityMapping(ID(),level,A.ID(),0,"",false,secret); else CMLib.ableMapper().delCharAbilityMapping(ID(),A.ID()); } else if((A.classificationCode()&Ability.ALL_DOMAINS)==domain()&&(!secret)) CMLib.ableMapper().addCharAbilityMapping(ID(),level,A.ID(),25,true); else CMLib.ableMapper().addCharAbilityMapping(ID(),level,A.ID(),0,"",false,secret); } } } }
f01fe88d-1871-421d-a0a9-9ced53c5802a
0
public LocalDate getDate() { return this._date; }
3324f498-e4be-47e9-91c0-8c6f36647e16
5
public static boolean isPrime(int x) { if (x == 2) { return true; } if (x % 2 == 0 || x == 1) { return false; } for (int i = 3; i * i <= x; i += 2) { if (x % i == 0) { return false; } } return true; }
dcf2e875-bc1f-4ef4-935e-bdcceac943c8
6
private double calculateTheta(Ball b1, Ball b2) { // TODO Auto-generated method stub double theta = 0; double xComp = b1.x - b2.x; double yComp = b1.y - b2.y; if(xComp > 0) { theta = Math.atan(yComp/xComp); return theta; }else if(xComp < 0){ theta = Math.atan(yComp/xComp) + Math.PI; return theta; } else if(xComp == 0) { if(yComp == 0) { return 00; }else if (yComp > 0){ return Math.PI/2; }else if(yComp < 0) { return 3*Math.PI/2; } } return theta; }
594862ba-0825-4853-87db-ac3834f1701f
3
private static int getNumberOfColumns(Alignment layoutMap) { List<Integer> keys = new ArrayList<Integer>(layoutMap.keySet()); Collections.sort(keys); int columnsNum = 0; for(int key : keys) { Read current = layoutMap.get(key); int minusOffset = columnsNum; if (current.getOffset() <= columnsNum) { minusOffset = current.getOffset(); } else { minusOffset += (current.getOffset() - columnsNum); } int newLength = minusOffset + current.getLength(); if (newLength > columnsNum) { columnsNum = newLength; } } return columnsNum; }
ebe70ef3-e14e-486d-a65b-dee6461fc135
7
private LocationProfile parseToLatestReview(Document document, String contextPath) throws CitysearchException { LocationProfile response = null; if (document != null && document.hasRootElement()) { Element locationElm = document.getRootElement().getChild(LOCATION); if (locationElm != null) { response = parseToProfile(document, contextPath); response.setListingId(locationElm.getChildText(ID)); Element reviewsElm = locationElm.getChild("reviews"); List<Element> reviews = reviewsElm.getChildren("review"); SortedMap<Date, Element> reviewMap = new TreeMap<Date, Element>(); if (reviews != null && !reviews.isEmpty()) { SimpleDateFormat formatter = new SimpleDateFormat( PropertiesLoader.getAPIProperties().getProperty( DATE_FORMAT)); for (Element reviewElm : reviews) { String dateStr = reviewElm.getChildText("review_date"); Date date = Utils.parseDate(dateStr, formatter); if (date != null) { reviewMap.put(date, reviewElm); } } Element reviewElem = reviewMap.get(reviewMap.lastKey()); ReviewResponse reviewResponse = ReviewProxy .toReviewResponse(reviewElem); response.setReview(reviewResponse); } } } return response; }
53b5e6ea-7a80-4f04-b543-ac7c559a3b85
1
public void testSetPeriod_RP2() { MutablePeriod test = new MutablePeriod(100L, PeriodType.millis()); try { test.setPeriod(new MutablePeriod(11, 12, 13, 14, 15, 16, 17, 18)); fail(); } catch (IllegalArgumentException ex) {} assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(100, test.getMillis()); }
0267b330-d8fa-475f-b703-309007e6d8c6
8
@Override public int compareTo(Edge<V, E> e2) { if(e2 == null) return -1; int labelComparision = getLabel().compareTo(e2.getLabel()); if(labelComparision!=0) return labelComparision; Vertex<V,E> destination1 = getDestination(); Vertex<V,E> destination2 = e2.getDestination(); if(destination1 == null && destination2 == null){ return 0; }else if((destination1 == null && destination2 != null) || (destination1 != null && destination2 == null)){ return -1; }else{ return getDestination().compareTo(e2.getDestination()); } }
d6434140-448c-4dc6-91be-5127eab55e14
5
protected static boolean implementsAllIfaces(ClassInfo clazz, ClassInfo[] ifaces, ClassInfo[] otherIfaces) { big: for (int i = 0; i < otherIfaces.length; i++) { ClassInfo iface = otherIfaces[i]; if (clazz != null && iface.implementedBy(clazz)) continue big; for (int j = 0; j < ifaces.length; j++) { if (iface.implementedBy(ifaces[j])) continue big; } return false; } return true; }
ed6c0990-0d62-45f2-acc3-93e547e6f12f
5
public String syncRequest(String url, String httpMethod, OauthKey key, List<QParameter> listParam, List<QParameter> listFile) throws Exception { if (url == null || url.equals("")) { return null; } OAuth oauth = new OAuth(); StringBuffer sbQueryString = new StringBuffer(); String oauthUrl = oauth.getOauthUrl(url, httpMethod, key.customKey, key.customSecrect, key.tokenKey, key.tokenSecrect, key.verify, key.callbackUrl, listParam, sbQueryString); String queryString = sbQueryString.toString(); QHttpClient http = new QHttpClient(); if ("GET".equals(httpMethod)) { return http.httpGet(oauthUrl, queryString); } else if ((listFile == null) || (listFile.size() == 0)) { return http.httpPost(oauthUrl, queryString); } else { return http.httpPostWithFile(oauthUrl, queryString, listFile); } }
0f5a39c0-c78e-4d7c-946c-861c0be76f22
9
public String nextToken() throws JSONException { char c; char q; StringBuffer sb = new StringBuffer(); do { c = next(); } while (Character.isWhitespace(c)); if (c == '"' || c == '\'') { q = c; for (;;) { c = next(); if (c < ' ') { throw syntaxError("Unterminated string."); } if (c == q) { return sb.toString(); } sb.append(c); } } for (;;) { if (c == 0 || Character.isWhitespace(c)) { return sb.toString(); } sb.append(c); c = next(); } }
b6d7b6de-4e3a-4eb0-baf7-9c18daefe838
1
public void addFrameElementWithIDRef(String frameElementName, String idref) { //TODO: check FrameElement frameElement = frameElements.get(frameElementName); if(frameElement==null){ frameElement = new FrameElement(frameElementName); } frameElement.addIdRef(idref); frameElements.put(frameElementName, frameElement); //List<String> list = getFrameElements().get(frameElementName); //if (list == null) { // list = new ArrayList<String>(); //} //list.add(idref); //frameElements.put(frameElementName, list); }
86759418-67eb-4dbd-90a7-29f3884f94da
8
private int getEquipment(int fish) { if (fish == 317) //shrimp return 303; if (fish == 335) //trout + salmon return 309; if (fish == 337) //lobs return 301; if (fish == 361)//tuna return 311; if (fish == 7944)//monks return 303; if (fish == 383)//sharks return 311; if (fish == 389)//mantas return 303; if (fish == 15272)//Rocktails return 303; return -1; }
74cac65e-8412-45a1-8e1d-e42aa2938cdb
8
public Server() { //Creating window addWindowListener(this); JTextArea serverLog = new JTextArea(); JScrollPane scrollPane = new JScrollPane(serverLog); add(scrollPane, BorderLayout.CENTER); setSize(300,300); setTitle("Battleships Server"); setVisible(true); try { //Server Socket on port 3319 server = new ServerSocket(3319); serverLog.append("Server started at port 3319.\n"); serverLog.append("SERVER IP ADDRESS : "+InetAddress.getLocalHost()+"\n"); int noOfPlayers = 0; while (true) { //Wait for player 1 to connect if (noOfPlayers == 0) { player1 = server.accept(); toPlayer1 = new ObjectOutputStream(player1.getOutputStream()); fromPlayer1 = new ObjectInputStream(player1.getInputStream()); sendMessage("connect", toPlayer1); serverLog.append("Player 1 has joined. Waiting for Player 2...\n"); noOfPlayers++; } //Wait for player 2 to connect else if (noOfPlayers == 1) { player2 = server.accept(); toPlayer2 = new ObjectOutputStream(player2.getOutputStream()); fromPlayer2 = new ObjectInputStream(player2.getInputStream()); sendMessage("player2", toPlayer1); sendMessage("connect", toPlayer2); sendMessage("player2", toPlayer2); serverLog.append("Player 2 has joined. Starting the game session...\n"); noOfPlayers++; } //When 2 players are connected, start the game else if (noOfPlayers == 2) { String input1 = (String)fromPlayer1.readObject(); String input2 = (String)fromPlayer2.readObject(); if (input1.equals("play") && input2.equals("play")) { (new GameSession(toPlayer1,toPlayer2,fromPlayer1,fromPlayer2)).start(); serverLog.append("Game session has been launched!\n"); noOfPlayers = 0; } //If players disconnect, abort game launch else { serverLog.append("Game sesssion launch aborted.\n"); sendMessage("disconnect", toPlayer1); sendMessage("disconnect", toPlayer2); noOfPlayers = 0; } } } } catch (IOException e) { serverLog.append("Server has ran into an exception! Stopping server...\n"); System.exit(0); } catch (ClassNotFoundException e) { e.printStackTrace(); } }
b45e6750-21da-4623-9bcd-bb03b9e0bd26
8
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } GenericTreeNode<?> other = (GenericTreeNode<?>) obj; if (data == null) { if (other.data != null) { return false; } } else if (!data.equals(other.data)) { return false; } return true; }
41f15bc2-2455-4f19-9036-ec40ed53587f
8
public void rotate_all(Draw panel, int angulo, Color bg_color){ Ponto ref = new Ponto(panel.getWidth()/2,panel.getHeight()/2); circulos_desenhados_aux = new LinkedList<Circulo>(); circulos_desenhados_aux.addAll(ctrCirculo.circulos_desenhados); for (Circulo c : circulos_desenhados_aux) { figura_selecionada = c; ctrCirculo.circulos_desenhados.remove(c); this.rotacionar_figura(panel, angulo, ref, bg_color); } arco_circulos_desenhados_aux = new LinkedList<Circulo>(); arco_circulos_desenhados_aux.addAll(ctrCirculo.arcos_desenhados); for (Circulo c : arco_circulos_desenhados_aux){ figura_selecionada = c; ctrCirculo.arcos_desenhados.remove(c); this.rotacionar_figura(panel, angulo, ref, bg_color); } elipses_desenhados_aux = new LinkedList<Elipse>(); elipses_desenhados_aux.addAll(ctrElipse.elipses_desenhadas); for (Elipse c : elipses_desenhados_aux) { figura_selecionada = c; ctrElipse.elipses_desenhadas.remove(c); this.rotacionar_figura(panel, angulo, ref, bg_color); } arco_elipses_desenhados_aux = new LinkedList<Elipse>(); arco_elipses_desenhados_aux.addAll(ctrElipse.arcos_desenhados); for (Elipse c : arco_elipses_desenhados_aux){ figura_selecionada = c; ctrElipse.arcos_desenhados.remove(c); this.rotacionar_figura(panel, angulo, ref, bg_color); } poligonos_desenhados_aux = new LinkedList<PoligonoRegular>(); poligonos_desenhados_aux.addAll(ctrPoligono.poligonos_regulares_desenhados); for (PoligonoRegular c: poligonos_desenhados_aux) { figura_selecionada = c; ctrPoligono.poligonos_regulares_desenhados.remove(c); this.rotacionar_figura(panel, angulo, ref, bg_color); } retangulos_desenhados_aux = new LinkedList<Retangulo>(); retangulos_desenhados_aux.addAll(ctrRetangulo.retangulos_desenhados); for (Retangulo c : retangulos_desenhados_aux) { figura_selecionada = c; ctrRetangulo.retangulos_desenhados.remove(c); this.rotacionar_figura(panel, angulo, ref, bg_color); } retas_desenhados_aux = new LinkedList<Reta>(); retas_desenhados_aux.addAll(ctrReta.retas_desenhadas); for (Reta c : retas_desenhados_aux){ figura_selecionada = c; ctrReta.retas_desenhadas.remove(c); this.rotacionar_figura(panel, angulo, ref, bg_color); } letras_desenhados_aux = new LinkedList<>(); letras_desenhados_aux.addAll(ctrLetra.letras_text); for (Letra l : letras_desenhados_aux) { figura_selecionada = l; ctrLetra.letras_text.remove(l); this.rotacionar_figura(panel, angulo, ref, bg_color); } }
ed688f86-5551-44f5-b68a-46a91d268090
8
private void parseArray(String[] nodesList) { if (nodesList == null || nodesList.length < 1) { throw new IllegalArgumentException("nodesList is null or empty"); } if (node0 == null) { node0 = parseNodeString(nodesList[0]); } nodesMap = new LinkedHashMap<>(); int clientsCount = 0; for (String node : nodesList) { NodeInfo nodeInfo = nodesMap.get(node); if (nodeInfo == null) { nodeInfo = parseNodeString(node); if (nodeInfo.getPort() == Configuration.DEFAULT_PORT && nodeInfo.isLocalAddress()) { node = ""; } if (nodesMap.containsKey(node) == false) { nodesMap.put(node, nodeInfo); } else { nodeInfo = nodesMap.get(node); } } nodeInfo.addThreadId(clientsCount++); } }
d8810e79-836b-4e7b-bdbb-751b657068c7
7
private ByteBuffer generateStandardHeaderResponse(HTTPRequest request, HTTPStatus status, Map<HTTPHeader,String> headers, DataBuffers response) throws HTTPException { final StringBuilder str=new StringBuilder(""); final String overrideStatus = headers.get(HTTPHeader.Common.STATUS); if(overrideStatus != null) str.append("HTTP/").append(request.getHttpVer()).append(" ").append(overrideStatus); else str.append("HTTP/").append(request.getHttpVer()).append(" ").append(status.getStatusCode()).append(" ").append(status.description()); str.append(EOLN); for(final HTTPHeader header : headers.keySet()) str.append(header.makeLine(headers.get(header))); if((!headers.containsKey(HTTPHeader.Common.TRANSFER_ENCODING)) ||(!headers.get(HTTPHeader.Common.TRANSFER_ENCODING).equals("chunked"))) { if(response != null) str.append(HTTPHeader.Common.CONTENT_LENGTH.makeLine(response.getLength())); else str.append(HTTPHeader.Common.CONTENT_LENGTH.makeLine(0)); } if(response != null) str.append(HTTPHeader.Common.LAST_MODIFIED.makeLine(HTTPIOHandler.DATE_FORMAT.format(response.getLastModified()))); if(config.isDebugging()) config.getLogger().finer("Response: "+str.toString().replace('\r', ' ').replace('\n', ' ')); str.append(HTTPIOHandler.SERVER_HEADER); str.append(HTTPIOHandler.CONN_HEADER); str.append(HTTPHeader.Common.getKeepAliveHeader()); str.append(HTTPHeader.Common.DATE.makeLine(HTTPIOHandler.DATE_FORMAT.format(new Date(System.currentTimeMillis())))); str.append(HTTPIOHandler.RANGE_HEADER); str.append(EOLN); return ByteBuffer.wrap(str.toString().getBytes()); }
37bbbfbe-e693-4af5-81b6-d133c1364d02
7
private String getValidityResult(final String s) { String res = ""; boolean isValid = true; if ((s.length()<5) || (s.length()>10)) { return MSG_FAIL; } if (s.contains(" ")) { return MSG_FAIL; } if (!s.matches(".*[0-9].*")) { return MSG_FAIL; } if (!s.matches(".*[A-Z].*")) { return MSG_FAIL; } if (!s.matches(".*[@#*=].*")) { return MSG_FAIL; } if (isValid) { res = MSG_PASS; } else { res = MSG_FAIL; } return res; }
e9a522c7-46fa-4a01-ad95-6a8d7b360fd0
7
public void loadFile(String name) { try { /** create the file object */ File file = new File(name); /** if the object is a directory */ if (file != null && file.isDirectory()) { /** get the list of files in the directory */ String files[] = file.list(); /** iterate through the list */ for (int i = 0; i < files.length; i++) { /** get the path */ File leafFile = new File(file.getAbsolutePath(), files[i]); /** if it's a directory */ if (leafFile.isDirectory()) { /** recurse into the directory */ loadFile(leafFile.getAbsolutePath()); } /** if it's a file */ else { /** load the file */ addSound(leafFile); } } } /** if the object is a file and it exists */ else if (file != null && file.exists()) { /** load the file */ addSound(file); } } catch (Exception e) { } }
ce49699b-2980-468f-9ff9-0f66f58047d5
6
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onPlayerInteract(PlayerInteractEvent event) { if (event.getAction() == Action.RIGHT_CLICK_BLOCK) { Block clickedBlock = event.getClickedBlock(); if (protectableBlock(clickedBlock)) { if (event.getPlayer().getItemInHand().getType() == Material.SIGN) { Block relativeBlock = clickedBlock.getRelative(event.getBlockFace()); if (!(relativeBlock.getType() == Material.AIR)){ return; } relativeBlock.setType(Material.WALL_SIGN); //create new signdata with the right direction org.bukkit.material.Sign newSign = new org.bukkit.material.Sign(Material.WALL_SIGN); newSign.setFacingDirection(event.getBlockFace()); //cast the blockstate to a sign state Only works because we set the blocktype to Wall_sign Sign signState = (Sign) relativeBlock.getState(); //Set the data of the state to the created data and update the sign signState.setData(newSign); signState.update(); int id = plugin.storageManager.lockItem(event.getPlayer().getUniqueId()); Sign sign = (Sign) relativeBlock.getState(); sign.setLine(0, "[Ninja Proof]"); sign.setLine(1, "======="); sign.setLine(2, String.valueOf(id)); sign.setLine(3, "======="); sign.update(); event.setCancelled(true); } else { int id = searchSign(clickedBlock); if (id != 0) { if (!plugin.storageManager .playerAuthorised(id, event.getPlayer().getUniqueId())) { event.setCancelled(true); } } } } } //TODO: Check if player can interact with block }
39ef86a3-3ab0-461d-9f15-b7c00472ee0a
0
public RenderingEngine getRenderingEngine() { return renderingEngine; }
11329fb6-1236-4de5-86cc-a7a71f94df80
7
private void donneDirection (){ Coord dir = this.curent.coord.sous(this.forum.coord); this.pointCercle = this.cible; final int D = 0, B = 1, G = 2, H = 3; if(dir.y > 0){ //BAS rotation = this.cercle % 2 == 0 ? D : G; } else if(dir.y < 0){ //HAUT rotation = this.cercle % 2 == 0 ? G : D; } else if(dir.x > 0){ //DROITE rotation = this.cercle % 2 == 0 ? H : B; } else{ //GAUCHE rotation = this.cercle % 2 == 0 ? B : H; } this.direc1 = directionCercle(); changeRotation(); this.direc2 = directionCercle(); }
8c190ccd-2aaa-4faf-be91-8d8a04312d67
8
public static boolean sendFiles(ArrayList<File> alFilesToSend, String FTP_Address, int FTP_Port, PrintWriter pwOut, String FTP_SERVER_TYPE) { try { if ((alFilesToSend == null) || (alFilesToSend.size() < 1)) { return false; } File fle = null; double steps = 0.0D; try { steps = 100.0D / alFilesToSend.size(); } catch (Exception e) { steps = -1.0D; } IncrementObject fileTransferStatus = new IncrementObject(steps); for (int i = 0; i < alFilesToSend.size(); i++) { fle = (File)alFilesToSend.get(i); if ((fle == null) || (!fle.exists()) || (!fle.isFile())) { fileTransferStatus.incrementStep(); } else { FTP_Thread_Sender FTP_Sender = new FTP_Thread_Sender(true, false, FTP_Address, FTP_Port, 4096, fle, pwOut, false, FTP_SERVER_TYPE, fileTransferStatus); FTP_Sender.start(); } } Driver.sop("\nScheduling complete: " + alFilesToSend.size() + " files queued for transfer"); return true; } catch (Exception e) { Driver.eop("sendFiles", "ExfiltrateFilesUnderDirectory", e, e.getLocalizedMessage(), false); } return false; }
91dc5ad6-9f10-41ec-a1a2-e95f7f6061e0
9
public void randomlyInitializeParams() { //initializes the initial state parameters double dsum = 0; probinit = new double[numstates]; for (int ni = 0; ni < probinit.length; ni++) { probinit[ni] = theRandom.nextDouble(); dsum += probinit[ni]; } for (int ni = 0; ni < probinit.length; ni++) { probinit[ni] /= dsum; } //set to true if a transition has been eliminated elim = new boolean[numstates][numstates]; //initalize the transition matrix transitionprobs = new double[numstates][numstates]; //initialize index of the next non-zero transition transitionprobsindex = new int[numstates][numstates]; //initalize number of non-zero transitions transitionprobsnum = new int[numstates]; //initalize column-wise index of non-zero transitions transitionprobsindexCol = new int[numstates][numstates]; //number of non-zero column transitions transitionprobsnumCol = new int[numstates]; //uniformly randomly assigns transition probability values //also initializes transition indicies for (int ni = 0; ni < transitionprobs.length; ni++) { dsum = 0; double[] transitionprobs_ni = transitionprobs[ni]; for (int nj = 0; nj < transitionprobs_ni.length; nj++) { elim[ni][nj] = false; double dval = theRandom.nextDouble(); transitionprobs_ni[nj] = dval; dsum += transitionprobs_ni[nj]; transitionprobsindex[ni][nj] = nj; transitionprobsindexCol[ni][nj] = nj; } transitionprobsnum[ni] = numstates; transitionprobsnumCol[ni] = numstates; for (int nj = 0; nj < transitionprobs_ni.length; nj++) { transitionprobs_ni[nj] /= dsum; } } //uniformly randomly assigns emission probability values //also initializes emission indicies emissionprobs = new double[numstates][numdatasets][numbuckets]; for (int ni = 0; ni < emissionprobs.length; ni++) { double[][] emissionprobs_ni = emissionprobs[ni]; for (int nj = 0; nj < emissionprobs_ni.length; nj++) { double[] emissionprobs_ni_nj = emissionprobs_ni[nj]; dsum = 0; for (int nk = 0; nk < emissionprobs_ni_nj.length; nk++) { double dval = theRandom.nextDouble(); dsum += dval; emissionprobs_ni_nj[nk] = dval; } for (int nk = 0; nk < emissionprobs_ni_nj.length; nk++) { emissionprobs_ni_nj[nk] /= dsum; } } } }
fd0df646-3830-4b2b-8bd0-550d9aa96811
8
String readLineWithNewline() { // mth 2004 10 17 // for now, I am going to put in a hack here // we have some CIF files with many lines of '#' comments // I believe that for all formats we can flush if the first // char of the line is a # // if this becomes a problem then we will need to adjust while (ichCurrent < cchBuf) { int ichBeginningOfLine = ichCurrent; char ch = 0; while (ichCurrent < cchBuf && (ch = buf[ichCurrent++]) != '\r' && ch != '\n') { } if (ch == '\r' && ichCurrent < cchBuf && buf[ichCurrent] == '\n') ++ichCurrent; int cchLine = ichCurrent - ichBeginningOfLine; if (buf[ichBeginningOfLine] == '#') // flush comment lines; continue; StringBuffer sb = new StringBuffer(cchLine); sb.append(buf, ichBeginningOfLine, cchLine); return "" + sb; } // miguel 2005 01 26 // for now, just return the empty string. // it will only affect the Resolver code // it will be easier to handle because then everyone does not // need to check for the null pointer // // If it becomes a problem, then change this to null and modify // all the code above to make sure that it tests for null before // attempting to invoke methods on the strings. return ""; }
c59a6bd8-753c-4ff3-92f1-0f285f6eae8f
8
public int sqrtBetter(int x) { if (x < 0) { return -1; } if (x == 0) { return 0; } int i = 0; int j = x; while (i < j) { int m = (j - i) / 2 + i; int m1 = x / (m + 1); int m2 = x / (m + 1 + 1); if (m + 1 == m1) { return m + 1; } if (m + 1 + 1 == m2) { return m + 1 + 1; } if (m + 1 < m1 && m2 < m + 1 + 1) { return m + 1; } if (m1 < m + 1) { j = m; } else { i = m + 1; } } throw new RuntimeException(); }
3f26cc16-d321-4dc0-81d5-054071c10a9d
3
@Override public void update(SondageReponse obj) { PreparedStatement pst = null; try { pst = this.connect().prepareStatement("update SondageReponse set id_sondage=?, choix=?, nombreChoix=? where id=? ;"); pst.setInt(1, obj.getId_sondage()); pst.setInt(2, obj.getChoix()); pst.setInt(3, obj.getNombreChoix()); pst.setInt(4, obj.getId()); pst.executeUpdate(); System.out.println("modification SondageReponse effectuée"); } catch (SQLException ex) { Logger.getLogger(SondageReponseDao.class.getName()).log(Level.SEVERE, "requete modification echoué", ex); }finally{ try { if(pst != null) pst.close(); } catch (SQLException ex) { Logger.getLogger(SondageReponseDao.class.getName()).log(Level.SEVERE, "liberation prepared statement échoué", ex); } } }
c3703f58-6cd5-430f-a58d-69283e63ee27
6
public static INIFile parseFile(ArrayList<String> contents){ INIFile file = new INIFile(); INISection section = null; for(String line : contents){ //String line = data.replaceAll("\\s", ""); if(isLine(line) == false){ continue; } if(isComment(line) == true){ continue; } if(isSection(line) == true){ section = addSection(file, line); continue; } if(isParameter(line) == true){ if(section == null){ Debug.error("Parameter defined before section in INI file '" + line + "'"); } addParameter(file, line, section); continue; } } return file; }
b15f0c8c-98e6-4c1b-a862-620abc6551c8
6
public static Node circularNode(Node head) { Node slow = head; Node fast = head; while(fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; if(slow == fast) break; } if(fast == null || fast.next == null) { System.out.println("No loop exists in the Linked List!"); return null; } slow = head; while(slow != fast) { slow = slow.next; fast = fast.next; } return fast; }
00306826-693a-4a97-8b05-eb00d5c40409
3
@Override public void execute(ArrayList signature) { String variableName = (String) signature.get(1); String value = (String) signature.get(2); if (variableName.equals(COMMAND_ENCODING)) { Preferences.ENCODINGS.add(value); if (VERBOSE) { System.out.println(new StringBuffer().append(" Adding encoding type: ").append(value).toString()); } } else { Outliner.prefs.addTempValue(variableName, value); if (VERBOSE) { System.out.println(new StringBuffer().append(" Loading Pref: ").append(variableName).append(" : ").append(value).toString()); } } }
9f78c74f-e7fb-462d-a159-8122f68e755b
1
public ShaderResource() { this.program = glCreateProgram(); this.refCount = 1; if ( program == 0 ) { System.err.println( "Shader creation failed: Could not find valid memory location in constructor" ); System.exit( 1 ); } uniforms = new HashMap<String, Integer>(); uniformNames = new ArrayList<String>(); uniformTypes = new ArrayList<String>(); }
95dd23d5-4f03-4b8a-a5fd-375dfc050afa
7
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { final Set<MOB> h=properTargets(mob,givenTarget,false); if(h==null) { mob.tell(L("There doesn't appear to be anyone here worth making invisible.")); return false; } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success) { if(mob.location().show(mob,null,this,somanticCastCode(mob,null,auto),auto?"":L("^S<S-NAME> wave(s) <S-HIS-HER> arms and speak(s) softly.^?"))) for (final Object element : h) { final MOB target=(MOB)element; final CMMsg msg=CMClass.getMsg(mob,target,this,somanticCastCode(mob,target,auto),null); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); mob.location().show(target,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> fade(s) from view!")); final Spell_Invisibility spell=new Spell_Invisibility(); spell.setProficiency(proficiency()); spell.beneficialAffect(mob,target,asLevel,0); } } } else return beneficialVisualFizzle(mob,null,L("<S-NAME> wave(s) <S-HIS-HER> arms and speak(s) softly, but the spell fizzles.")); // return whether it worked return success; }
c3fdbb50-7e14-435a-9e2c-13e6b54efb9b
9
public String TypeTamGiac(){ if(IsTamGiac()==1){ if((a==b)&&(b==c)){ return"TG_DEU"; } else{ if((a==c)||(a==b)||(b==c)){ return "TG_CAN"; } if((a*a+b*b==c*c)||(a*a+c*c==b*b)||(b*b+c*c==a*a)) return "TG_VUONG"; } } return "NULL"; }
9484df9f-7640-44f7-96c1-5c862c373987
9
public void randomWalkBioData(String[] seedNames, int nArtists, int nRelated, String delimiter) throws EchoNestException, FileNotFoundException { PrintWriter pw_names = new PrintWriter("data/artistNames.txt"); for(String seedName : seedNames) { appearedArtists = new HashSet<String>(nArtists); List<Artist> artists = en.searchArtists(seedName); StringBuilder biographies; if (artists.size() > 0) { Artist seed = artists.get(0); for (int i = 0; i < nArtists; i++) { //Print artist and bio data to file if(!hasAppeared(seed)) { addArtist(seed); biographies = new StringBuilder(); String artistName = seed.getName(); String artistID = seed.getID(); System.out.println("Artist " + (i + 1) + ": " + artistName); for(Biography b : seed.getBiographies()) { biographies.append(b.getText() + " "); } PrintWriter pw = new PrintWriter("data/" + artistID + ".artist"); pw.println(biographies.toString()); pw.close(); pw_names.println(artistID + "," + artistName); } else { i--; } //Find new related artist which have not appeared yet. List<Artist> sims = seed.getSimilar(nRelated); if (sims.size() > 0) { Collections.shuffle(sims); seed = sims.get(0); int attempt = 1; while(hasAppeared(seed) && attempt < sims.size()) { seed = sims.get(attempt); attempt++; } if(attempt >= sims.size()) { seed = artists.get(0); } } else { seed = artists.get(0); } } } } pw_names.close(); }
edb83ebe-1e9f-4d2a-84ad-6be9ed229b86
7
private boolean canHaveAsWall(Wall newW) { if (newW == null) return false; if(!grid.getElementsOnPosition(newW.getPosition()).isEmpty()) return false; for(Wall wall: getAllWallsOnGrid()){ for (Position newWp : newW.getPositions()) { for (Position wp : wall.getPositions()) { if (Math.abs(newWp.xCoordinate - wp.xCoordinate) < 2 && Math.abs(newWp.yCoordinate - wp.yCoordinate) < 2) { return false; } } } } return true; }
ab47595a-1d36-4e12-b557-c309c1d9e332
4
void handleRead() throws IOException, NoSuchAlgorithmException { this.buffer.rewind(); int bytesRead = -1; try { bytesRead = this.socketChannel.read(this.buffer); } catch(Exception ex) {} if (bytesRead == -1) { close(); } else if (bytesRead > 0) { this.buffer.rewind(); if (!this.handshakeComplete) { recieveHandshake(); } else { recieveFrame(); } } }
f599e83c-8d58-4749-9ec1-5c94085c9187
7
public Estimator getEstimator() { switch (this) { case CHEN: return new Chen(); case EOM_LEE: return null; // TODO: Eom-Lee incomplete!!! case LOWER_BOUND: return new LowerBound(); case SCHOUTE: return new Schoute(); case VAHEDI: return new Vahedi(); case VOGT: return new Vogt(); case ILCM: return new ILCM(); default: return null; } }
5c4454fa-1ab3-4dbe-a0f9-b23b4d28466f
4
boolean selfTest() { int k,j,i; // loop for all the prefixes of the tree source string for ( k=1; k<length; k++ ) { // loop for each suffix of each prefix for ( j=1; j<=k; j++ ) { // search for the current suffix in the tree int len = k-j+1; char[] test = new char[len]; for ( int m=0;m<len;m++ ) test[m] = treeString[j+m]; i = findSubstring( test ); if ( i == stError ) { System.out.println("\n\nTest Results: Fail in string ("+j+","+k+").\n"); return false; } } } // if we are here no search has failed and the test passed successfully System.out.println("\n\nTest Results: Success.\n"); return true; }
144f7b77-a9c3-4936-9c57-87388d6e9d4f
1
IdentServer(PircBot bot, String login) { _bot = bot; _login = login; try { _ss = new ServerSocket(113); _ss.setSoTimeout(60000); } catch (Exception e) { _bot.log("*** Could not start the ident server on port 113."); return; } _bot.log("*** Ident server running on port 113 for the next 60 seconds..."); this.setName(this.getClass() + "-Thread"); this.start(); }
f76409f2-df16-49bb-9e94-2ce2f4643a34
1
public void addByte(final int i) { if (ClassEditor.DEBUG) { System.out.println(" " + codeLength + ": " + "byte " + i); } // The bytecode array is represented as a linked list of // ByteCells. This method creates a new ByteCell and appends it // to the linked list. final ByteCell p = new ByteCell(); p.value = (byte) (i & 0xff); p.prev = codeTail; codeTail = p; codeLength++; }
b50f8223-d7bb-4227-878b-fa9fac994d48
9
public ImageFrameEssence getDensity(ImageFrame if1) { // 2-D boolean array pixChecked = new boolean[if1.getWidth()][if1.getHeight()]; for(int i=0; i<if1.getWidth(); i++) { for(int j=0; j<if1.getHeight(); j++) { pixChecked[i][j] = false; } } //int area = pixAreaItr(5, 5, if1.getRar()); //System.out.println(area); ArrayList<DensityPix> densityPixList = new ArrayList<DensityPix>(); for (int col = 1; col < if1.getHeight()-1; col++) { for (int row = 1; row < if1.getWidth()-1; row++) { int[] color = new int[4]; if1.getRar().getPixel(row, col, color); int r = (int)(color[0]); int g = (int)(color[1]); int b = (int)(color[2]); int alpha = color[3]; if(alpha==0) { continue; } if(pixChecked[row][col]==false) { sumX = 0; sumY = 0; int area = pixAreaItr(row, col, if1.getRar()); //System.out.println("("+row+","+col+"): "+area); int avgx = sumX/area; int avgy = sumY/area; //System.out.println("("+avgx+","+avgy+"): "+area); Color c = new Color(r, g, b); if(area>3) { //System.out.println("("+avgx+","+avgy+"): "+area); densityPixList.add(new DensityPix(avgx, avgy, area, c.getRGB())); } } } } System.out.println("dens size: "+densityPixList.size()); // filter out weaker densities Collections.sort(densityPixList, new Comparator<DensityPix>() { @Override public int compare(DensityPix o1, DensityPix o2) { if(o1.area > o2.area) return -1; if(o1.area < o2.area) return 1; else return 0; } }); ImageFrameEssence ife = new ImageFrameEssence(if1.getBum()); ife.setDensityPixList(densityPixList); return ife; //return new ImageFrame(if1.getBum()); }
2e153a3d-b2fe-4263-a99a-d462ab787289
3
public void loadComponents() { // initialize all non-disabled components for(String component: registeredComponents.keySet()) { if(!registeredComponents.get(component).disabled) { try { registeredComponents.get(component).instance = registeredComponents.get(component).clazz.newInstance(); } catch(Exception e) { Logger.error("Failed to instantiate component '%s': %s", component, e.getMessage()); } } } }
01456b10-28a3-4fdf-9586-a7daa5f74854
2
public void preloadImage(String name) { BufferedImage img = null; if (window.imgs.containsKey(name)) { img = window.imgs.get(name); } else { try { img = ImageIO.read(window.getClass().getResource(name)); window.imgs.put(name, img); } catch (final IOException e) { throw new RuntimeException("Resource is not loadable!"); } } }
598a7053-26a5-48b1-88ab-140df400ae54
7
private void tableClicked(MouseEvent e) { boolean isSelected = false; JTable table = (JTable) source; if (SwingUtilities.isRightMouseButton(e) || e.isPopupTrigger()) { int row = table.rowAtPoint(e.getPoint()); int[] rows = table.getSelectedRows(); for(int i = 0; i < rows.length; i++) { if(rows[i] == row) { isSelected = true; break; } } if(!isSelected) { // The row that has been clicked on was not previously selected so select it table.changeSelection(row, 0, false, false); } view.displayPopupMenu(table, e.getX(), e.getY()); } else { int selectedRow = table.getSelectedRow(); if (selectedRow >= 0) { if (e.getClickCount() == 2) { model.stopSong(true); model.setAlbum(view.getSelectedAlbum(), view.getTrackNumber()); model.playPlaylist(); view.setDisplayedPlaylist(model.getPlaylist()); } } } }
a5e153d6-fcb5-422c-8934-8f9fec44a515
6
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MainFrame().setVisible(true); } }); }
b66ec345-9c47-44c9-82d8-e90bbc5b3199
1
public static void initLocale(ResourceBundle localebundle) { if (localebundle == null) { throw new IllegalArgumentException(); } GUIStrings.locale = localebundle; }
e184cf17-d348-4d3c-9cce-3273bde17da5
3
private int getUserId(String name) { for (int i = 0; i < users.size(); i++) { User user = users.get(i); String nameTest = " " + user.getName() + " "; if (nameTest.contains(name) && name.contains(nameTest)) { return i; } } return -1; }
b34c78b5-2d41-40d5-b9d3-850fbc3dc400
3
protected void createMoreParticles(ParticleEmitter emitterDetails, float x, float y) { int particlesToCreate = Helpers.randomBetween(emitterDetails.minimumParticles, emitterDetails.maximumParticles); for (int i = 0; i < particlesToCreate && emitterDetails.currentParticles.size() < emitterDetails.maximumTotalParticles; i++) { // Poll a particle from the current dead particles Entity deadParticle = emitterDetails.deadParticles.poll(); if (deadParticle == null) { deadParticle = createParticleEntity(emitterDetails.cachedParticleImages[0]); } /** * Reset all of the dead particle's information to randomised values */ BufferedImage particleImage = emitterDetails.cachedParticleImages[Helpers.randomBetween(0, emitterDetails.cachedParticleImages.length)]; // Get all of the details for this particle that we'll need double randomAngle = Helpers.randomBetween(emitterDetails.startAngle, emitterDetails.endAngle); int particleLife = Helpers.randomBetween(emitterDetails.minimumLife, emitterDetails.maximumLife); // Get all of the components added to the entity and reset their // details Spatial spatial = deadParticle.getComponent(Spatial.class); Draw draw = deadParticle.getComponent(Draw.class); draw.setRawImage(particleImage); deadParticle.getComponent(Particle.class).timeAlive = particleLife; spatial.x = x; spatial.y = y; spatial.width = particleImage.getWidth(); spatial.height = particleImage.getHeight(); spatial.setRotation(randomAngle); emitterDetails.currentParticles.offer(deadParticle); } }
c54342dc-d611-4e31-acd2-4921fe5a8b88
2
@Override public void run() { byte[] receiveData = new byte[1024]; while(true) { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); try { serverSocket.receive(receivePacket); } catch (IOException ex) { Logger.getLogger(ChatServer.class.getName()).log(Level.SEVERE, null, ex); } String sentence = new String( receivePacket.getData()); System.out.println("\nMessage received from chat:"); System.out.println(sentence); MainContent.chat.getjTextArea1().append("\n" + user.getId() + ": " + sentence.trim()); } }
e9dcf193-b318-4d85-b9b9-21b8d5dbf293
6
public ArrayList<Category> getAllCategory() { ArrayList<Category> ret = new ArrayList<Category>(); Connection conn = null; Statement st = null; ResultSet rs = null; try { conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/librarysystem?user=admin&password=123456"); st=conn.createStatement(); rs = st.executeQuery("SELECT * FROM Category"); while(rs.next()) { Category c = new Category(); c.setIdNumber(rs.getInt("idNumber")); c.setName(rs.getString("name")); c.setSuperCategoryId((Integer)rs.getObject("superCategoryId")); ret.add(c); } } catch (Exception e) { System.out.println(e.getMessage()); } finally { try { if(conn != null) conn.close(); if(st != null) st.close(); if(rs != null) rs.close(); } catch (Exception e) { } } return ret; }
e3289345-053f-4239-bb43-0914a2423f37
6
public static String numberToString(Number number) throws JSONException { if (number == null) { throw new JSONException("Null pointer"); } testValidity(number); // Shave off trailing zeros and decimal point, if possible. String string = number.toString(); if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) { while (string.endsWith("0")) { string = string.substring(0, string.length() - 1); } if (string.endsWith(".")) { string = string.substring(0, string.length() - 1); } } return string; }
5c922a62-09f3-4b5e-9e82-d0eaf1cca796
2
private void createActionPanel() { JPanel panel = new JPanel(); cancel = new JButton("Cancel"); cancel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { Main main = (Main) GameSettingsPanel.this.getTopLevelAncestor(); main.displayMatch(); } }); cancel.setVisible(false); panel.add(cancel); start = new JButton("Start"); start.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { Main main = (Main) GameSettingsPanel.this.getTopLevelAncestor(); Match match; if (GameSettingsPanel.this.gameTypeBox.getSelectedItem() == "Scenario") { try { match = MatchLoader.loadFromJSON(GameSettingsPanel.this.scenarioFiles[scenarioBox.getSelectedIndex()]); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } } else { match = new Match(widthSlider.getValue(), heightSlider.getValue(), playersSlider.getValue(), unitsSlider.getValue(), abilityCountSlider.getValue()); } main.setMatch(match); main.displayMatch(); } }); panel.add(start); this.settingsPanel.add(panel, BorderLayout.SOUTH); }
e651537e-8a1b-4d81-a978-85cdb0f8ee0b
0
public ReferenceType createReferenceType() { return new ReferenceType(); }
e6178019-2253-4072-8bf2-1b07520225c5
3
private ItemStack getItemStackBackwards(Item item) { int ID = item.getID(); ItemStack stack; for (int i = items.size() - 1; i >= 0; i--) { stack = items.get(i); if (stack.getItemInStackID() == ID && stack.getAmount() <= stack.getMaxStackSize()) return stack; } stack = new ItemStack(item); items.add(stack); return stack; }
852df30d-d884-4ffb-8499-5a5792dfa9da
8
private boolean r_postlude() { int among_var; int v_1; // repeat, line 70 replab0: while(true) { v_1 = cursor; lab1: do { // (, line 70 // [, line 72 bra = cursor; // substring, line 72 among_var = find_among(a_1, 3); if (among_var == 0) { break lab1; } // ], line 72 ket = cursor; switch(among_var) { case 0: break lab1; case 1: // (, line 73 // <-, line 73 slice_from("i"); break; case 2: // (, line 74 // <-, line 74 slice_from("u"); break; case 3: // (, line 75 // next, line 75 if (cursor >= limit) { break lab1; } cursor++; break; } continue replab0; } while (false); cursor = v_1; break replab0; } return true; }
ad8c8f7d-d026-4d58-b5c0-5f82353dae35
9
private boolean move(PaletteEntry entry, boolean up) { int index = getChildren().indexOf(entry); if (index < 0) { // This container does not contain the given palette entry return false; } index = up ? index - 1 : index + 1; if (index < 0 || index >= getChildren().size()) { // Performing the move operation will give the child an invalid // index return false; } if (getChildren().get(index) instanceof PaletteContainer && getUserModificationPermission() == PaletteEntry.PERMISSION_FULL_MODIFICATION) { // move it into a container if we have full permission PaletteContainer container = (PaletteContainer) getChildren().get( index); if (container.acceptsType(entry.getType()) && container.getUserModificationPermission() == PaletteEntry.PERMISSION_FULL_MODIFICATION) { remove(entry); if (up) container.add(entry); else container.add(0, entry); return true; } } List oldChildren = new ArrayList(getChildren()); getChildren().remove(entry); getChildren().add(index, entry); listeners.firePropertyChange(PROPERTY_CHILDREN, oldChildren, getChildren()); return true; }
83bf9ca7-4139-4bcb-85b0-115eb8ea0a8b
8
public static Object conversion_t( Object source, Class<?> targetClass ) throws InstantiationException, IllegalAccessException { Class<?> sourceClass = source.getClass(); Field[] sFields = sourceClass.getDeclaredFields(); Object oOut = targetClass.newInstance(); /* On parcourt chaque attribut */ for ( int i=0; i < sFields.length; i++ ) { try { // On cherche si le Field existe dans la source ET dans la distination Field f = targetClass.getDeclaredField( sFields[i].getName() ); /* Si l'attribut n'existe pas dans la Classe cible, une exception est declenchee et ca break * pour l'attribut en cours (donc on passe direct a l'attribut suivant */ System.out.println("Trying "+f.getName()); //f.set(oOut, sFields[i].get( source )); // Mettre dans l'objet de sortie le contenu du champs de meme nom venant de la classe source. /* --> Ne fonctionne pas pour les attributs privees, donc il faut utiliser les methodes setters et getters ! */ char[] stringArray = f.getName().toCharArray(); stringArray[0] = Character.toUpperCase(stringArray[0]); String fNameMaj = new String(stringArray); /* Ca c'etait juste pour transformer la premiere lettre de l'attribut en Maj xD */ Method mSet = targetClass.getDeclaredMethod("set"+fNameMaj, f.getType()); Method mGet = sourceClass.getDeclaredMethod("get"+fNameMaj); /* Comme on est super malin, on regarde si des setters/getters existent pour l'attribut en cours */ System.out.println("Found "+mSet.getName()+" and "+mGet.getName()); /* A ce point-ci, le programme doit etre content. */ mSet.invoke( oOut, mGet.invoke(source) ); /* On invoque la methode Setter du l'objet cible en passant en argument * le resultat de la methode Getter de la source. * Les getters et les setters ont des nommages clairement etablis par * des conventions, donc si les noms ne respectent pas la convention, bah tant pis ! */ } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchFieldException e) { // TODO Auto-generated catch block //e.printStackTrace(); System.out.println("Ignored : "+sFields[i].getName()); } catch (NoSuchMethodException e) { System.out.println("Getter/Setter not found for "+sFields[i].getName()); //e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { } } return oOut; }
f0b46c6f-db3a-4ab1-ba00-95c421d9c211
8
@Override protected void paintEvent(QPaintEvent e) { Set<core.Point> visible = mission.getActivePlayer().getVisible(); QPainter painter = new QPainter(this); QImage image = new QImage(tmap.length, tmap[0].length, Format.Format_RGB32); int rgb; Set<core.Point> ommit = new HashSet<core.Point>(); for (int i=0; i<tmap.length; ++i) { for (int j=0; j<tmap[0].length; ++j) { if (ommit.contains(new core.Point(j, i))) { continue; } core.WorldMapObject obj = wmap.getObjectAt(j, i); if (!visible.contains(new core.Point(j, i))) { image.setPixel(j, i, 0); continue; } else if (obj != null && obj.getColor() != null) { image.setPixel(j, i, obj.getColor().rgb); } else { image.setPixel(j, i, tmap[i][j].rgb); } core.Hero hero = wmap.getHeroAt(j, i); if (hero != null && hero.getColor() != core.Color.NONE) { //image.setPixel(j, i, hero.getColor().rgb); image.setPixel(j+1, i, hero.getColor().rgb); image.setPixel(j-1, i, hero.getColor().rgb); image.setPixel(j, i+1, hero.getColor().rgb); image.setPixel(j, i-1, hero.getColor().rgb); ommit.add(new core.Point(j, i+1)); ommit.add(new core.Point(j+1, i)); } } } //for (core.Point pos: wmap.getH) QImage scaled = image.scaled(38*5, 36*5); painter.drawImage(0, 0, scaled); image.dispose(); scaled.dispose(); //System.out.println("PAINTER"); }
01751cdd-e826-4b8c-bc3e-ca6da4e244d9
1
public void highlightTargets() { int index; for (BoardCell target : targets) { index = calcIndex(target.getRow(), target.getCol()); cells.get(index).setColor(Color.RED); } repaint(); }
4cd32938-6e7a-47db-bf93-aa517463cb33
3
public static void load() { // extract a default config if(!fileConfig.exists()) { MCNSAEssentials.getInstance().saveResource("items.yml", false); } // load items from a config file try { yamlConfig.load(fileConfig); } catch (Exception e) { e.printStackTrace(); } // get our items configuration section ConfigurationSection items = yamlConfig.getConfigurationSection("items"); // get all our keys (names) Set<String> keys = items.getKeys(false); for(String itemName: keys) { itemNames.put(itemName, items.getInt(itemName)); } }
68cd25a0-2d80-4822-8c7d-5bd7cd7703b8
0
public int getFirstID(){ return first_city.getID(); }
10ab07e3-2be1-4999-924d-1d1f001d4594
9
public void GenerateSTM(UOIGUI gui){ Random rndm = new Random(); String[] columns = {"StaticMesh","Tag","Layer","bOverrideLightMapRes","OverriddenLightMapRes","bUsePrecomputedShadows", "LightingChannels","Location","Rotation","Scale"}; Object[][] data = new Object[Integer.parseInt(gui.getStmCountField().getText())][columns.length]; ArrayList<String> lightdata; String location = "("; String rotation = "("; String scale = "("; for(int i = 0;i < data.length;i++){ location = "("; rotation = "("; scale = "("; lightdata = new ArrayList<String>(); // Meshpath if(gui.getStmMeshField().getText() != ""){ data[i][0] = gui.getStmMeshField().getText(); }else{ data[i][0] = null; } // Mesh-Tag if(gui.getStmTagField().getText() != ""){ data[i][1] = gui.getStmTagField().getText(); }else{ data[i][1] = ""; } //Mesh-Layer if(gui.getStmLayerField().getText() != ""){ data[i][2] = gui.getStmLayerField().getText(); }else{ data[i][2] = ""; } // Lightmap Override if(gui.getChckbxSTMOverride().isSelected()){ data[i][3] = true; }else{ data[i][3] = false; } // Lightmap Overriden Resolution if(gui.getStmResField().getText() != ""){ data[i][4] = gui.getStmResField().getText(); }else{ data[i][4] = 64; //TODO: Change to Template Standard } // Use Realtime Lighting data[i][5] = gui.getChckbxSTMPrec().isSelected(); // Lighting Channels Mesh is reacting to data[i][6] = gui.getCbSTMChannels(); //TODO: change to array with selected channels // Location if(gui.getChckbxSTMLRange().isSelected()){ // X location += rndm.nextFloat() * (Float.parseFloat(gui.getStmLMaxXField().getText()) - Float.parseFloat(gui.getStmLMinXField().getText())) + Float.parseFloat(gui.getStmLMinXField().getText()) + ","; // Y location += rndm.nextFloat() * (Float.parseFloat(gui.getStmLMaxYField().getText()) - Float.parseFloat(gui.getStmLMinYField().getText())) + Float.parseFloat(gui.getStmLMinYField().getText()) + ","; // Z location += rndm.nextFloat() * (Float.parseFloat(gui.getStmLMaxZField().getText()) - Float.parseFloat(gui.getStmLMinZField().getText())) + Float.parseFloat(gui.getStmLMinZField().getText()) + ")"; }else{ // X location += gui.getStmLMinXField().getText() + ","; // Y location += gui.getStmLMinYField().getText() + ","; // Z location += gui.getStmLMinZField().getText() + ")"; } data[i][7] = location; // Rotation if(gui.getChckbxSTMRRange().isSelected()){ // X rotation += rndm.nextFloat() * (Float.parseFloat(gui.getStmRMaxXField().getText()) - Float.parseFloat(gui.getStmRMinXField().getText())) + Float.parseFloat(gui.getStmRMinXField().getText()) + ","; // Y rotation += rndm.nextFloat() * (Float.parseFloat(gui.getStmRMaxYField().getText()) - Float.parseFloat(gui.getStmRMinYField().getText())) + Float.parseFloat(gui.getStmRMinYField().getText()) + ","; rotation += rndm.nextFloat() * (Float.parseFloat(gui.getStmRMaxZField().getText()) - Float.parseFloat(gui.getStmRMinZField().getText())) + Float.parseFloat(gui.getStmRMinZField().getText()) + ")"; }else{ // X rotation += gui.getStmRMinXField().getText() + ","; // Y rotation += gui.getStmRMinYField().getText() + ","; // Z rotation += gui.getStmRMinZField().getText() + ")"; } data[i][8] = rotation; // Scale if(gui.getChckbxSTMSRange().isSelected()){ // X scale += rndm.nextFloat() * (Float.parseFloat(gui.getStmSMaxXField().getText()) - Float.parseFloat(gui.getStmSMinXField().getText())) + Float.parseFloat(gui.getStmSMinXField().getText()) + ","; // Y scale += rndm.nextFloat() * (Float.parseFloat(gui.getStmSMaxYField().getText()) - Float.parseFloat(gui.getStmSMinYField().getText())) + Float.parseFloat(gui.getStmSMinYField().getText()) + ","; // Z scale += rndm.nextFloat() * (Float.parseFloat(gui.getStmSMaxZField().getText()) - Float.parseFloat(gui.getStmSMinZField().getText())) + Float.parseFloat(gui.getStmSMinZField().getText()) + ")"; }else{ // X scale += gui.getStmSMinXField().getText() + ","; // Y scale += gui.getStmSMinYField().getText() + ","; // Z scale += gui.getStmSMinZField().getText() + ")"; } data[i][9] = scale; } ((DefaultTableModel) gui.getStmTable().getModel()).setDataVector(data, columns); //TODO: Check for replace and append }
08c2cd7a-dc79-42c1-9178-e7f86d49a383
4
public static byte[] decrypt(byte[] in,byte[] key){ int i; byte[] tmp = new byte[in.length]; byte[] bloc = new byte[16]; Nb = 4; Nk = key.length/4; Nr = Nk + 6; w = generateSubkeys(key); for (i = 0; i < in.length; i++) { if (i > 0 && i % 16 == 0) { bloc = decryptBloc(bloc); System.arraycopy(bloc, 0, tmp, i - 16, bloc.length); } if (i < in.length) bloc[i % 16] = in[i]; } bloc = decryptBloc(bloc); System.arraycopy(bloc, 0, tmp, i - 16, bloc.length); tmp = deletePadding(tmp); return tmp; }
4d4be649-908c-4103-a0ad-c615343cfe75
8
public World(int w, int h, float scale) { screen = new Screen(this, w, h, scale); new Tile(); tiles = new Tile[worldSize * worldSize][layers]; for (int i = 0; i < tiles.length; i++) { tiles[i][0] = Tile.grassTile; tiles[i][1] = Tile.airTile; } for (int i = 0; i < tiles.length; i++) { if (random.nextInt(10) == 0) tiles[i][1] = Tile.treeTile; } for (int x = 0; x < worldSize; x++) tiles[x + 0 * worldSize][1] = Tile.treeTile; for (int y = 0; y < worldSize; y++) tiles[0 + y * worldSize][1] = Tile.treeTile; for (int x = 0; x < worldSize; x++) tiles[x + (worldSize - 1) * worldSize][1] = Tile.treeTile; for (int y = 0; y < worldSize; y++) tiles[(worldSize - 1) + y * worldSize][1] = Tile.treeTile; player = new Player(screen.w / 2, screen.h / 2); entities.add(player); for (int i = 0; i < 0; i++) { entities.add(new TestMob(1 + random.nextInt((worldSize - 2) * 32), 1 + random.nextInt((worldSize - 2) * 32))); } }
559c4ac8-3909-425a-ab61-dc136e742d22
0
public LocStack() { init(); }
b342f6ba-bf85-4353-8375-6ecd8a30c85b
3
public CycList<CycList<E>> combinationsOf(int n) { if (!isProperList) { throw new RuntimeException(this + " is not a proper list"); } if (this.size() == 0 || n == 0) { return new CycList<CycList<E>>(); } return combinationsOfInternal(new CycList<E>(this.subList(0, n)), new CycList<E>(this.subList(n, this.size()))); }
a6b9058d-6e46-479c-975e-1e1ba6aabf38
5
public ArrayList<String> getFileNames(){ System.out.println("Getting all files with reads per transcripts counts. Files names finish with " + fnamePattern); ArrayList<String> fileNames = new ArrayList<String>(); File dir = new File(dirName); for (File ch : dir.listFiles()) { if (ch.isDirectory()) for (File child : ch.listFiles()){ if (child.getName().equals(fnamePattern)){ fileNames.add(child.getPath()); ch.getName(); } } } int numSamples = fileNames.size(); sampleNames = new String[numSamples]; System.out.println(numSamples + " files will be processed.\n"); for (int i = 0; i < numSamples; i++){ String[] splName = fileNames.get(i).split("/"); String sampleId = splName[splName.length - 2]; sampleNames[i] = sampleId; } return fileNames; }
3f6a1298-d64e-454f-b827-f433f2e52189
8
Point3f getMin() { if (min == null) min = new Point3f(); if (list.isEmpty()) { min.set(0, 0, 0); return min; } Object3D c = list.get(0); if (c != null) { min.x = c.getMinX(); min.y = c.getMinY(); min.z = c.getMinZ(); } synchronized (list) { int n = count(); if (n > 1) { for (int i = 1; i < n; i++) { c = list.get(i); if (min.x > c.getMinX()) { min.x = c.getMinX(); } if (min.y > c.getMinY()) { min.y = c.getMinY(); } if (min.z > c.getMinZ()) { min.z = c.getMinZ(); } } } } return min; }
fb9c64db-57f1-4568-9801-c876048374c3
0
public int hashCode(){ return mKey.hashCode(); }
10c0eb1a-d526-405b-8ff2-9713e662de6d
4
public static boolean isJarURL(URL url) { String protocol = url.getProtocol(); return (URL_PROTOCOL_JAR.equals(protocol) || URL_PROTOCOL_ZIP.equals(protocol) || URL_PROTOCOL_WSJAR.equals(protocol) || (URL_PROTOCOL_CODE_SOURCE.equals(protocol) && url.getPath().contains(JAR_URL_SEPARATOR))); }
fa93f1ce-fa4f-4601-b01d-323be868daff
3
public boolean hasCard(int value, int suite) { for (Card card : hand) { if (card.value == value && card.suite == suite) { return true; } } return false; }
2fd8b26d-3b3a-4f36-a38b-f21892c23890
2
public void release(int num) { if(num >= 0 && num < seat.length) { seat[num] = false; System.out.printf("%d seat is now available.",num); } else { System.out.println("invalid seat number."); } }
1e7129c7-7bfb-4cd4-8e7e-1bc43adb9be1
3
private void startGameLoad(int delay){ SchedulerManager.registerSingle(delay, new Runnable(){ public void run(){ if(MapData.areNewMapsToLoad()){ if(MapData.loadMapsFromConfig()) BetweenMapsRuntime.start(); else{ if(MapData.loadMapsFromConfig()) BetweenMapsRuntime.start(); else SchedulerManager.registerRepeating("RealmsMain", "warning", 0, 30, new Runnable(){ public void run(){ Broadcast.error("The server's maps were not loaded properly.\nThe server needs developer attention."); } }); } }else BetweenMapsRuntime.start(); } }); }
df324d8b-c453-4fd0-ad95-440e6be50395
2
@Override protected void updateShareRates (){ for (int i = 0; i < availableShare.size(); i++){ if (availableShare.get(i) != null){ updateShareRate(availableShare.get(i)); } } flag++; }
45d3f640-2cc7-4777-b905-0a644d73d399
7
private void nextYear(Team team, PlayerPtrVector allPlayers, Positions posi) { int nofPlayers = 0; Player player = getNextSeasFirst(allPlayers, team); while (player != null) { nofPlayers++; if (player.getNation() != team.getNation()) { posi.nofForeigners++; } if (player.getPosition().getPosID() == Position.PosID.GOALIE) { posi.goalies++; } else if (player.getPosition().getPosID() == Position.PosID.DEFENDER) { posi.defenders++; } else if (player.getPosition().getPosID() == Position.PosID.RIGHTWING) { posi.rightwings++; } else if (player.getPosition().getPosID() == Position.PosID.CENTER) { posi.center++; } else { assert (player.getPosition().getPosID() == Position.PosID.LEFTWING); posi.leftwings++; } posi.age += player.getAge(); player = getNextSeasNext(allPlayers, team); } if (nofPlayers != 0) { posi.age = posi.age / nofPlayers; } }
c61fbd50-2425-4674-a250-c4e0b38e7708
3
public ServiceMethod getMethod(String name) { ServiceMethod method = this.methods.get(name); if(method == null) { for(Map.Entry<String, ServiceMethod> entry : this.methods.entrySet()) { String n = entry.getKey(); if(name.endsWith(n)) { method = entry.getValue(); break; } } } return method; }
51b30e1a-1e31-4862-a816-0a7e7cc48bf8
1
public MAdministrador(Administrador admin) { setModal(true); initComponents(); if(!(admin == null)){ edtUserName.setEnabled(false); edtUserName.setText(admin.getNombre()); jtxtPass.setText(admin.getPassword()); jlbPass.setText("Nueva Contraseña"); jtxtConfirm.setText(admin.getPassword()); edtDNI.setText(admin.getDNI()); btnSwitch.setText("Actualizar"); } this.getRootPane().setDefaultButton(btnSwitch); }
bcaac704-b068-458d-ba2d-41eb35e2158e
7
public Set<Pair<T,T>> getAllPairs(Set<T> that) { Set<Pair<T,T>> allPairs; if(that!=null) { if(this.next==null && that.next==null) { allPairs=new Set(new Pair(this.a,that.a),null); } else if(this.next!=null && that.next==null) { allPairs=new Set(new Pair(this.a,that.a),this.next.getAllPairs(that)); } else if(this.next==null && that.next!=null) { allPairs=new Set(new Pair(this.a,that.a),this.getAllPairs(that.next)); } else { allPairs=new Set(this.a,null).getAllPairs(that).concat(this.next.getAllPairs(that)); } return allPairs; } else { return null; } }
e9018233-d18a-47bf-b03a-e640c4330bdb
9
private Layer redraw(final int z) { final ArrayList<Sprite.Part> parts = new ArrayList<Sprite.Part>(); Sprite.Drawer drw = new Sprite.Drawer() { public void addpart(Sprite.Part p) { if (p.z == z) parts.add(p); } }; for (Sprite spr : sprites.values()) { if (spr != null) spr.setup(drw, Coord.z, Coord.z); } Collections.sort(parts, Sprite.partcmp); Coord ul = new Coord(0, 0); Coord lr = new Coord(0, 0); for (Sprite.Part part : parts) { if (part.ul.x < ul.x) ul.x = part.ul.x; if (part.ul.y < ul.y) ul.y = part.ul.y; if (part.lr.x > lr.x) lr.x = part.lr.x; if (part.lr.y > lr.y) lr.y = part.lr.y; } BufferedImage buf = TexI.mkbuf(lr.add(ul.inv()).add(1, 1)); Graphics g = buf.getGraphics(); /* * g.setColor(java.awt.Color.RED); g.fillRect(0, 0, buf.getWidth(), * buf.getHeight()); */ for (Sprite.Part part : parts) { part.cc = part.cc.add(ul.inv()); part.draw(buf, g); } g.dispose(); return (new Layer(buf, ul.inv())); }
63b16dc9-767a-4b80-95a6-c71b2d64b1da
2
@Override public double distance(ItemBoundable a, ItemBoundable b) { Geometry g1 = (Geometry) a.getItem(); Geometry g2 = (Geometry) b.getItem(); //and a lot of faster this way with envelope dist instead of geometry dist double distance = g1.getEnvelopeInternal().centre().distance(g2.getEnvelopeInternal().centre());//g1.distance(g2); double result = distance; //get orientation if(weight>0){ MinimumDiameter minD1 = new MinimumDiameter(g1); MinimumDiameter minD2 = new MinimumDiameter(g2); //angle 1 Coordinate a1 = minD1.getSupportingSegment().getCoordinates()[0]; //getSupportingSegment getDiameter Coordinate b1 = minD1.getSupportingSegment().getCoordinates()[1]; //getSupportingSegment getDiameter double sideA1 = b1.x- a1.x; double sideB1 = b1.y- a1.y; double m1 = sideB1 / sideA1; double alpha1 = Math.atan(m1); //angle 2 Coordinate a2 = minD2.getSupportingSegment().getCoordinates()[0]; Coordinate b2 = minD2.getSupportingSegment().getCoordinates()[1]; double sideA2 = b2.x- a2.x; double sideB2 = b2.y- a2.y; double m2 = sideB2 / sideA2; double alpha2 = Math.atan(m2); double delta = alpha1- alpha2; if (delta <0)delta=delta*-1; //weighting result = (distance * 1 + delta * weight) / (1+weight); } //System.out.println("weight="+weight+" dist="+distance +" result ="+result); return result;//distance; }
57847fd5-942f-4151-b7bf-f18d34f3f1c1
8
void draw(Graphics g) { int hs = 8; setBbox(point1, point2, hs); boolean selected = (needsHighlight() || sim.plotYElm == this); double len = (selected || sim.dragElm == this) ? 16 : dn-32; calcLeads((int) len); setVoltageColor(g, volts[0]); if (selected) g.setColor(selectColor); drawThickLine(g, point1, lead1); setVoltageColor(g, volts[1]); if (selected) g.setColor(selectColor); drawThickLine(g, lead2, point2); Font f = new Font("SansSerif", Font.BOLD, 14); g.setFont(f); if (this == sim.plotXElm) drawCenteredText(g, "X", center.x, center.y, true); if (this == sim.plotYElm) drawCenteredText(g, "Y", center.x, center.y, true); if (mustShowVoltage()) { String s = getShortUnitText(volts[0], "V"); drawValues(g, s, 4); } drawPosts(g); }
87f64d85-5271-46ce-8d83-8c15e4fe76ac
3
@Override public void updateLong() { super.updateLong(); if(generationTimerEnd == 0) { resetGenerationTimer(); } if(generationTimerEnd <= System.currentTimeMillis() && this.isActivated()) { placeableManager.playerAddItem("Iron", 1); registry.getIndicatorManager().createImageIndicator(mapX + (width / 2), mapY + height + 32, "Iron"); registry.showMessage("Success", type + " has generated Iron"); resetGenerationTimer(); } }
bdf181f3-f83f-4ac6-9c85-b1b6e002e79c
0
public static long nextMonth(long month) { return month + countDayInMonth(month) * DAY_LENGTH; }
a83053b5-ff03-41a5-8229-06ad0a8230eb
3
public void itemExpanded(TreeItem item){ super.itemExpanded(item); if(item instanceof DatabaseTreeItem){ DatabaseTreeItem dataItem = (DatabaseTreeItem) item; DataEditorTreeItem data = (DataEditorTreeItem) dataItem.editorData; data.expanded = true; } for(int i=0; i<item.getChildCount(); i++){ DatabaseTreeItem childItem = (DatabaseTreeItem) item.getChildAt(i); if(((DataEditorTreeItem)childItem.editorData).expanded){ setItemExpanded(childItem, true); } } }
d704a4fc-7240-4cfc-bde0-024fb3f3a87e
0
public void f() { System.out.println("public f()"); }
080ce235-37c1-40f1-83c6-421924d893f7
7
private String assemblePath(List list) { if (list == null) { return null; } StringBuffer buf = new StringBuffer(); if (this.is_absolute_path && (path != null && path.length() > 0)) { buf.append(PATH_DELIM); } for (int i = 0; i < list.size(); i++) { String segment = (String) list.get(i); if (segment != null) { buf.append(segment); buf.append(PATH_DELIM); } } if (this.file != null) { buf.append(this.file); } return buf.toString(); }
906163af-cdaf-40a3-b718-d132335b41a6
8
@Override public void actionPerformed(ActionEvent e) { try { if (e.getSource() == this.view.getJbErrorLift()) { Shared.getInstance().getLock().lock(); Shared.getInstance().setFlagliftAndNotify(Flag.RED); } else if (e.getSource() == this.view.getJbErrorDrag()) { Shared.getInstance().getLock().lock(); Shared.getInstance().setFlagdragAndNotify(Flag.RED); } else if (e.getSource() == this.view.getJbWarningLift()) { Shared.getInstance().getLock().lock(); Shared.getInstance().setFlagliftAndNotify(Flag.AMBER); } else if (e.getSource() == this.view.getJbWarningDrag()) { Shared.getInstance().getLock().lock(); Shared.getInstance().setFlagdragAndNotify(Flag.AMBER); } else if (e.getSource() == this.view.getJbStartSimulation()) { this.view.getJbStartSimulation().setEnabled(false); this.wf.start(); this.view.getJbErrorDrag().setEnabled(true); this.view.getJbErrorLift().setEnabled(true); this.view.getJbWarningDrag().setEnabled(true); this.view.getJbWarningLift().setEnabled(true); } else if (e.getSource() == this.view.getJbStop()) { JOptionPane.showMessageDialog(null, "Simulation abort", "End of simulation", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } else if (e.getSource() == this.view.getJbContrinue()) { // mettre dans shared les nouvo param LoadParamsFrame lpf = new LoadParamsFrame(this.view); LoadParamsFrameController lpfc = new LoadParamsFrameController(lpf); lpf.setActionListener(lpfc); this.view.getJbErrorDrag().setEnabled(true); this.view.getJbErrorLift().setEnabled(true); this.view.getJbWarningDrag().setEnabled(true); this.view.getJbWarningLift().setEnabled(true); } else { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } } catch (Exception ex) { //JOptionPane.showMessageDialog(null, "Error: "+ ex.getMessage(), "Autentification error" , JOptionPane.ERROR_MESSAGE); System.err.println(ex.getMessage()); } }
41bae4f9-a533-4e36-a57b-cb39a0b0f8ae
9
public static String makeTesnseEomi(String preword, String endword) { if(preword==null||preword.length()==0) return endword; if(endword==null||endword.length()==0) return preword; if(endword.charAt(0)=='ㅆ') { return preword.substring(0,preword.length()-1)+ MorphUtil.makeChar(preword.charAt(preword.length()-1),20)+endword.substring(1,endword.length()); } else if(endword.charAt(0)=='ㄴ') { return preword.substring(0,preword.length()-1)+ MorphUtil.makeChar(preword.charAt(preword.length()-1),4)+endword.substring(1,endword.length()); } else if(endword.charAt(0)=='ㄹ') { return preword.substring(0,preword.length()-1)+ MorphUtil.makeChar(preword.charAt(preword.length()-1),8)+endword.substring(1,endword.length()); } else if(endword.charAt(0)=='ㅁ') { return preword.substring(0,preword.length()-1)+ MorphUtil.makeChar(preword.charAt(preword.length()-1),16)+endword.substring(1,endword.length()); } else if(endword.charAt(0)=='ㅂ') { return preword.substring(0,preword.length()-1)+ MorphUtil.makeChar(preword.charAt(preword.length()-1),17)+endword.substring(1,endword.length()); } return preword+endword; }
ef4aca20-a58c-4e9b-acbc-8aef42fe0dde
1
public void create(Openchatroom entity) { EntityManager em = PersistenceManager.createEntityManager(); try { em.getTransaction().begin(); em.persist(entity); em.getTransaction().commit(); } finally { if (em.getTransaction().isActive()) em.getTransaction().rollback(); em.close(); } }
b68894aa-a24c-4ebc-8421-ec5cb484536f
9
@Override public void doGet(SimpleServletRequest request, SimpleServletResponse response) { try { response.setMimeType(MIMEType.All.html.getType()); final File pageFile=new File("web.log"); if((!pageFile.exists()) || (!pageFile.canRead()) || (pageFile.length() > Integer.MAX_VALUE)) throw HTTPException.standardException(HTTPStatus.S404_NOT_FOUND); final byte[] fileBuf = new byte[(int)pageFile.length()]; BufferedInputStream bs = null; try { bs=new BufferedInputStream(new FileInputStream(pageFile)); bs.read(fileBuf); response.getOutputStream().write("<html><body><pre>".getBytes()); response.getOutputStream().write(fileBuf); response.getOutputStream().write("</pre></body></html>".getBytes()); } catch(final FileNotFoundException e) { request.getLogger().throwing("", "", e); // not quite sure how we could get here. throw HTTPException.standardException(HTTPStatus.S404_NOT_FOUND); } catch (final IOException e) { request.getLogger().throwing("", "", e); throw HTTPException.standardException(HTTPStatus.S404_NOT_FOUND); } finally { if(bs != null) { try { bs.close(); } catch(final Exception e) {} // java really needs an " i don't care " syntax for exception handling } } } catch (final HTTPException e) { try { response.getOutputStream().write(e.generateOutput(request).flushToBuffer().array()); } catch (final Exception e1){} } }