text
stringlengths
14
410k
label
int32
0
9
@Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (label.equalsIgnoreCase("tenki")) { if (sender instanceof Player) { Player player = (Player) sender; if (args.length == 0) { player.sendMessage(ChatColor.RED + "値が正しくありません。"); return false; } else if (args[0].equalsIgnoreCase("hare")) { player.sendMessage(ChatColor.AQUA + "晴れになりました。"); player.getWorld().setStorm(false); return true; } else if (args[0].equalsIgnoreCase("ame")) { player.sendMessage(ChatColor.AQUA + "雨になりました。"); player.getWorld().setThundering(true); return true; } else if (args[0].equalsIgnoreCase("kaminari")) { player.sendMessage(ChatColor.AQUA + "雷雨になりました。"); player.getWorld().setStorm(true); return true; } else { player.sendMessage(ChatColor.RED + "値が正しくありません。"); return false; } } else { sender.sendMessage("このコマンドはプレイヤーのみ使用できます"); } } return true; }
6
public double getOut4Organism() { double out = 0.0; for (int i = 0; i < outNodes.size(); i++) { out += outNodes.get(i).getPotential(); } return out; }
1
public static Object newProxyInstance(Class<?> superclass, Class<?>[] interfaces, InvocationHandler h) throws ExportException { HandlerAdapter ha = new HandlerAdapter(h, superclass, interfaces); if (interfaces != null) { Class<?>[] source = interfaces; interfaces = new Class<?>[source.length + 1]; System.arraycopy(source, 0, interfaces, 1, source.length); } else { interfaces = new Class<?>[1]; } //Pop in the CGILibSerializableProxy interface to support serialization of the proxy: interfaces[0] = CGILibSerializableProxy.class; //Check that we have a no arg constructor: try { superclass.getDeclaredConstructor(new Class<?> [] {}); } catch (NoSuchMethodException nsme) { throw new ExportException("Can't export " + superclass.getName() + " because it doesn't define a no arg constructor. Try exporting with specified service interfaces", nsme); } // System.out.println("CGLIB CREATING PROXY for " + superclass.getName() + " with interfaces: " + Arrays.asList(interfaces)); Enhancer e = new Enhancer(); e.setClassLoader(JMSRemoteSystem.INSTANCE.getUserClassLoader(ha)); e.setSuperclass(superclass); e.setInterfaces(interfaces); e.setCallback(ha); Object obj = e.create(); generatedClasses.put(obj.getClass(), null); return obj; }
8
public boolean isOfType(Type type) { return (type.typecode == TC_INTEGER && (((IntegerType) type).possTypes & possTypes) != 0); }
1
@Override public void keyPressed(KeyEvent e) { //Uso del teclado para la traslacion //tecla z y x para la traslacion en 'Z' int keyCode = e.getKeyCode(); switch( keyCode ) { case KeyEvent.VK_UP: transformaciones.Traslacion(0, -15, 0); break; case KeyEvent.VK_DOWN: transformaciones.Traslacion(0, 15, 0); break; case KeyEvent.VK_LEFT: transformaciones.Traslacion(-15, 0, 0); break; case KeyEvent.VK_RIGHT : transformaciones.Traslacion(15, 0, 0); break; case KeyEvent.VK_Z : transformaciones.Traslacion(0, 0, 15); break; case KeyEvent.VK_X : transformaciones.Traslacion(0, 0, -15); break; } }
6
@Override public T pull() throws InterruptedException { updateLength(-1); return taskSupplier.pull(); }
0
private boolean isMoving(){ if(state == StateActor.UP || state == StateActor.DOWN || state == StateActor.LEFT || state == StateActor.RIGHT){ return true; } else return false; }
4
public String displayGW_ShoreMMSI (List<Integer> mm,int totalDigits) { StringBuilder sb=new StringBuilder(); int a,digitCounter=0; for (a=0;a<6;a++) { // High nibble int hn=(mm.get(a)&240)>>4; // Low nibble int ln=mm.get(a)&15; // The following nibble int followingNibble; // Look at the next byte for this unless this is the last byte if (a<5) followingNibble=(mm.get(a+1)&240)>>4; else followingNibble=0; boolean alternate; // Low nibble // If the following nibble (which is in the high nibble of the next byte) is less than 0x8 then we use the alternate numbering method if (followingNibble<0x8) alternate=true; else alternate=false; sb.append(convertShoreNum(ln,alternate)); digitCounter++; // Once digit counter is totalDigits then we are done if (digitCounter==totalDigits) return sb.toString(); // High nibble // If the following nibble (which is in the low nibble) is less than 0x8 then we use the alternate numbering method if (ln<0x8) alternate=true; else alternate=false; sb.append(convertShoreNum(hn,alternate)); digitCounter++; // Once the digit counter is totalDigits then we are done if (digitCounter==totalDigits) return sb.toString(); } return sb.toString(); }
6
public String getHost() { return host; }
0
public void mousePressed(int button,int x,int y){ if(xpos >= Button.GAME_WIDTH/2-replayWidth/2 && xpos <= Button.GAME_WIDTH/2+replayWidth/2 ){ if(ypos >= Button.GAME_HEIGHT/2+100 && ypos <= Button.GAME_HEIGHT/2+100+replayHeight){ mousePress = true; } } }
4
private String removeDuplicateCharacters(String s) { Set characters = new HashSet(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < s.length(); i++) { Character c = new Character(s.charAt(i)); if (characters.add(c)) sb.append(c.charValue()); } return sb.toString(); }
2
public void set_field( String section, String field, String data ) throws NullPointerException { Hashtable s; if( section== null || field == null ) throw new NullPointerException(); s = (Hashtable) sections.get(section); if(s==null) { s = new Hashtable(); sections.put(section, s); } s.put(field, data); }
3
public static int prevenirHostChanged(String id) { // previens une machine que cette machine remplace m pour le paquet d'id // Id SocketChannel clientSocket; Paquet p = Donnees.getHostedPaquet(id); int placeToModify = p.power; LinkedList<String> table = new LinkedList<String>(); for (int i = 0; i < Global.NOMBRESOUSPAQUETS; i++) { if (i != placeToModify) { Machine m = p.otherHosts.get(i); if (!table.contains(m.toString())) { table.add(m.toString()); } } else { if (!table.contains(p.owner.toString())) { table.add(p.owner.toString()); } } } while (!table.isEmpty()) { String s2 = table.poll(); Scanner scan = new Scanner(s2); scan.useDelimiter("-"); Machine m = new Machine(scan.next(), scan.nextInt()); /* * HashSet<Machine> listeM = new HashSet<Machine>(); for (int i = 0; * i < 5; i++) { * * if (i != placeToModify) { * * listeM.add(p.otherHosts.get(i)); // Utilitaires.out("Place : " + * placeToModify + " "+ // m.toString()); } else { * listeM.add(p.owner); } } for (Machine m : listeM) { * Utilitaires.out("C'est pour m : " +m.toString()); } */ try { clientSocket = SocketChannel.open(); // init connection InetSocketAddress local = new InetSocketAddress(0); clientSocket.bind(local); InetSocketAddress remote = new InetSocketAddress(m.ipAdresse, m.port); //Utilitaires.out("jessaye de me connect a : " + m.ipAdresse + "-" + m.port); if (!clientSocket.connect(remote)) Utilitaires.out("Ca a foiré !"); // message ByteBuffer buffer = Utilitaires.stringToBuffer(Message.HOST_CHANGED); //ByteBuffer buffer2 = Utilitaires.stringToBuffer(Message.HOST_CHANGED); //Utilitaires.out(Utilitaires.buffToString(buffer2)); clientSocket.write(buffer); buffer.clear(); clientSocket.read(buffer); buffer.flip(); String response = Utilitaires.buffToString(buffer); if (response.equals(Message.OK)) { String s = Global.MYSELF.toString() + " " + id + " " + placeToModify + " " + Message.END_ENVOI + " "; // buffer.flip(); buffer = Utilitaires.stringToBuffer(s); clientSocket.write(buffer); } clientSocket.close(); } catch (IOException e) { e.printStackTrace(); } finally { scan.close(); } } return p.power ; }
8
public Builder electricCharge(int receivedElectricCharge) { if (receivedElectricCharge < 0) { this.population = -receivedElectricCharge; return this; } this.electricCharge = receivedElectricCharge; return this; }
1
public void testGetPartialConverterRemovedNull() { try { ConverterManager.getInstance().removePartialConverter(NullConverter.INSTANCE); try { ConverterManager.getInstance().getPartialConverter(null); fail(); } catch (IllegalArgumentException ex) {} } finally { ConverterManager.getInstance().addPartialConverter(NullConverter.INSTANCE); } assertEquals(PARTIAL_SIZE, ConverterManager.getInstance().getPartialConverters().length); }
1
public void addUnsearchList(String url){ if(url.length() > DB_URL_CHAR_SIZE){ log.warn("URL size is too long: "+url); return; } // List<SqlParameter> sqlParamList = new LinkedList<SqlParameter>(); // sqlParamList.add(new SqlParameter(Types.VARCHAR, url)); // sqlParamList.add(new SqlParameter(Types.VARCHAR, "1")); // sqlParamList.add(new SqlParameter(Types.TIMESTAMP, new java.sql.Timestamp(new Date().getTime()))); // final StringBuilder sql = new StringBuilder(); // sql.append("INSERT INTO WAIT_SEARCH_URL_WIKI (URL, WEIGHT, UPDATE_TIME) VALUES (?, ?, ?)"); // this.sqlUpdater.executeSql(sql.toString(), sqlParamList); this.sqlUpdater.executeSql("INSERT INTO WAIT_SEARCH_URL_WIKI (URL) VALUES ('"+ url +"')"); }
1
public void start() { if ( isRunning ) return; run(); }
1
@Override public void validate() { if (platform == null) { addActionError("Please Select Platorm"); } if (location == null) { addActionError("Please Select Location"); } if (iphone.equals("Please select")) { addActionError("Please Select Os"); } if (gender == null) { addActionError("Please Select Gender"); } if (age == null) { addActionError("Please Select Age"); } }
5
public EventService(EntityManager manager, EntityTransaction tx){ this.manager = manager; this.tx = tx; }
0
public void installAndMakeSelecatable(AID packageAID, AID appletAID, AID instanceAID, byte privileges, byte[] installParams, byte[] installToken) throws GPException, CardException { if (installParams == null) { installParams = new byte[] { (byte) 0xC9, 0x00 }; } if (instanceAID == null) { instanceAID = appletAID; } if (installToken == null) { installToken = new byte[0]; } ByteArrayOutputStream bo = new ByteArrayOutputStream(); try { bo.write(packageAID.getLength()); bo.write(packageAID.getBytes()); bo.write(appletAID.getLength()); bo.write(appletAID.getBytes()); bo.write(instanceAID.getLength()); bo.write(instanceAID.getBytes()); bo.write(1); bo.write(privileges); bo.write(installParams.length); bo.write(installParams); bo.write(installToken.length); bo.write(installToken); } catch (IOException ioe) { } CommandAPDU install = new CommandAPDU(CLA_GP, INSTALL, 0x0C, 0x00, bo.toByteArray()); ResponseAPDU response = transmit(install); short sw = (short) response.getSW(); if (sw != ISO7816.SW_NO_ERROR) { throw new GPException(sw, "Install for Install and make selectable failed"); } }
5
static public void testStorage(Storage storage, String fileName) throws IOException { int entryCount, uniqueWordsCount; long start, end; BufferedReader br = new BufferedReader(new FileReader(fileName)); String line = br.readLine(); String[] words; Matcher matcher; start = System.currentTimeMillis(); while (line != null) { words = line.split(" "); for(String word : words) { matcher = pattern.matcher(word); if(matcher.matches()) { word = matcher.group(1); storage.add(word.toLowerCase()); } } line = br.readLine(); } end = System.currentTimeMillis(); System.out.println("Initialization time: " + (end - start)); start = System.currentTimeMillis(); entryCount = storage.entryCount("love"); uniqueWordsCount = storage.uniqueWordsCount(); end = System.currentTimeMillis(); System.out.println("Methods time: " + (end - start)); System.out.println("Entry count: " + entryCount + ", unique words: " + uniqueWordsCount); System.out.println(); }
3
@Test public void onlyBishopOnFilledBoard() { Map<String, Integer> figureQuantityMap = new HashMap<>(); figureQuantityMap.put(BISHOP.toString(), 2); Chessboard chessboard = Chessboard.newBuilder(figureQuantityMap).withDimension(DIMENSION_6).withBishop().build(); assertThat("all elements are not present on each board", chessboard.placeFiguresOnBoard("bbbbbb\n" + "b....b\n" + "b....b\n" + "b....b\n" + "b....b\n" + "bbbbbb\n") .parallel() .filter(board -> !board.contains(KING.getFigureAsString()) && !board.contains(QUEEN.getFigureAsString()) && board.contains(BISHOP.getFigureAsString()) && !board.contains(ROOK.getFigureAsString()) && !board.contains(KNIGHT.getFigureAsString()) && board.contains(FIELD_UNDER_ATTACK_STRING) && !board.contains(EMPTY_FIELD_STRING) && leftOnlyFigures(board).length() == 20) .map(e -> 1) .reduce(0, (x, y) -> x + y), is(1)); }
7
public static boolean removeContactAcct(String contactID,int index){ boolean status = false; AddressBook addressBook = Helpers.getAddressBook(); if (addressBook == null) { System.out.println("removeContactAcct - addressBook returns null"); return false; } for(int i=0;i<addressBook.GetContactCount();i++){ Contact contact = addressBook.GetContact(i); if(contact==null) continue; if(contactID.equals(contact.getContact_id())){ status = contact.RemoveContactAcct(index); System.out.println("removeContactAcct status contact.RemoveContactAcct:" + status); if(status) status = otapi.StoreObject(addressBook, "moneychanger", "gui_contacts.dat"); System.out.println("removeContactAcct status addressBook otapi.StoreObject:" + status); break; } } return status; }
5
public void actionPerformed(ActionEvent event) { Date now = new Date(); System.out.println("At the tone, the time is " + now); if (beep) Toolkit.getDefaultToolkit().beep(); }
1
public void updateDirection() throws BadMoveException { if(start.row == end.row && start.column == end.column) { throw new Board.BadMoveException("Bad move initialized"); } if(start.column == end.column) { if(start.row > end.row) { direction = Direction.UP; } else { direction = Direction.DOWN; } } else if(start.row == end.row) { if(start.column > end.column) { direction = Direction.LEFT; } else { direction = Direction.RIGHT; } } else { if(start.row < end.row) { if(start.column < end.column) { direction = Direction.DOWNRIGHT; } else { direction = Direction.DOWNLEFT; } } else { if(start.column < end.column) { direction = Direction.UPRIGHT; } else { direction = Direction.UPLEFT; } } } }
9
public String getName() { if (isFree) { return ("FREE"); } if (isInvalid) { return ("INVALID-CONSTANT"); } return name; }
2
protected void loadReactionlikeEvent2CatalystActivity() { String name = "ReactionlikeEvent_2_catalystActivity"; String fileName = dirName + name + ".txt"; if (verbose) Timer.showStdErr("Loading " + name + " from '" + fileName + "'"); int i = 1; for (String line : Gpr.readFile(fileName).split("\n")) { // Parse line String rec[] = line.split("\t"); String id = rec[0]; String catalystId = rec[1]; if (id.equals("DB_ID")) continue; // Skip title // Add event to pathway Reaction reaction = (Reaction) entityById.get(id); if (reaction == null) continue; // Reaction not found? Skip Entity e = getOrCreateEntity(catalystId); reaction.addCatalyst(e); if (verbose) Gpr.showMark(i++, SHOW_EVERY); } if (verbose) System.err.println(""); if (verbose) Timer.showStdErr("Total outputs assigned: " + (i - 1)); }
7
private String prepareConfigString(String configString) { int lastLine = 0; int headerLine = 0; String[] lines = configString.split("\n"); StringBuilder config = new StringBuilder(""); for(String line : lines) { if(line.startsWith(this.getPluginName() + "_COMMENT")) { String comment = "#" + line.trim().substring(line.indexOf(":") + 1); if(comment.startsWith("# +-")) { if(headerLine == 0) { config.append(comment + "\n"); lastLine = 0; headerLine = 1; } else if(headerLine == 1) { config.append(comment + "\n\n"); lastLine = 0; headerLine = 0; } } else { String normalComment; if(comment.startsWith("# ' ")) normalComment = comment.substring(0, comment.length() - 1).replaceFirst("# ' ", "# "); else normalComment = comment; if(lastLine == 0) config.append(normalComment + "\n"); else if(lastLine == 1) config.append("\n" + normalComment + "\n"); lastLine = 0; } } else { config.append(line + "\n"); lastLine = 1; } } return config.toString(); }
8
@Override public void startSetup(Attributes atts) { super.startSetup(atts); addActionListener(this); Outliner.documents.addOutlinerDocumentListener(this); Outliner.documents.addDocumentRepositoryListener(this); setEnabled(false); }
0
public void setTaintWrapper(ITaintPropagationWrapper taintWrapper) { this.taintWrapper = taintWrapper; }
0
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(AddStaffUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(AddStaffUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(AddStaffUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(AddStaffUI.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 AddStaffUI().setVisible(true); } }); }
6
@Test public void canGetProductsByCost() { ProductModel addedProduct = ProductModel.builder("Night Visions", 1) .description("Imagine Dragons").cost(149).rrp(400).build(); List<ProductModel> products = null; boolean isInResult = false; try { addedProduct = new ProductModel(insertProduct(addedProduct), addedProduct); products = pd.getProductsByCost(addedProduct.getCost()); for (ProductModel product : products) { if (addedProduct.equals(product)) { isInResult = true; break; } } deleteProduct(addedProduct.getId()); } catch (WebshopAppException e) { e.printStackTrace(); } assertTrue(isInResult); }
3
public static final Method getMethod(final Class clazz, final String methodName, Class... parameters) { parameters = parameters == null ? new Class[0] : parameters; Method method = null; try { method = clazz.getMethod(methodName, parameters); } catch (NoSuchMethodException e) { } if (method != null) { return method; } Class[] parameterTypes = null; final Method[] methods = clazz.getMethods(); for (int i = methods.length - 1; i >= 0; i--) { if (!methodName.equals(methods[i].getName())) { continue; } parameterTypes = methods[i].getParameterTypes(); if (parameterTypes.length != parameters.length) { continue; } boolean classMatch = true; for (int j = parameterTypes.length - 1; j >= 0; j--) { if (!classMatch(parameterTypes[j], parameters[j])) { classMatch = false; break; } } if (classMatch) { method = methods[i]; break; } } return method; }
9
@Override public void paintComponent(Graphics g) { super.paintComponent(g); // redraw paint method. so it doesnt draw on // top of each other mainMenuObj.menuMessage(mx, g); if (currentMode.equals(mode1)) { // MainMenu mainMenuObj.paint(g, hoverLeft); } else if (currentMode.equals(mode2)) { // tictactoe sub menu ticTacToeSubMenuObj.paint(g); } else if (currentMode.equals(mode3) || currentMode.equals(mode4)) { // tictactoe // player // 1 ticTacToeboardObj.paint(g, ticTacToePlayerObj); if (squareStore != null) { ticTacToeFunctionsObj.paintCharacters(g, squareStore); } } else if (currentMode.equals(mode5)) { goSettingObj.paint(g); } else if (currentMode.equals(mode6)) { // go board goBoardObj.paint(g); if (goSquareStore != null) { goFunctionsObj.paintCharacters(g, goSquareStore); } } repaint(); }
8
@Override public void doAction (String o) { setVisible(false); dispose(); }
9
public ExtraLife(int courtWidth, int courtHeight, int INIT_X) { super(INIT_VEL_X, INIT_VEL_Y, INIT_X, INIT_Y, SIZE, SIZE, courtWidth, courtHeight); try { if (img == null) { img = ImageIO.read(new File(img_file)); } } catch (IOException e) { System.out.println("Internal Error:" + e.getMessage()); } }
2
public void filter(List<String> guessHistory, List<String> feedbackHistory) { Iterator<String> it = possibleAnswer.iterator(); int i = feedbackHistory.size() - 1; if (i >= guessHistory.size()){ return; } String gs = guessHistory.get(i); String fb = feedbackHistory.get(i); for (int count = 0; count < level && it.hasNext(); count++) { String code = it.next(); String temp = CodeFeedback.getValidFeedback(code, gs); if (!temp.equals(fb)){ it.remove(); continue; } } }
4
public boolean stem() { int v_1; int v_2; int v_3; int v_4; // (, line 157 // do, line 159 v_1 = cursor; lab0: do { // call prelude, line 159 if (!r_prelude()) { break lab0; } } while (false); cursor = v_1; // do, line 160 v_2 = cursor; lab1: do { // call mark_regions, line 160 if (!r_mark_regions()) { break lab1; } } while (false); cursor = v_2; // backwards, line 161 limit_backward = cursor; cursor = limit; // do, line 162 v_3 = limit - cursor; lab2: do { // call standard_suffix, line 162 if (!r_standard_suffix()) { break lab2; } } while (false); cursor = limit - v_3; cursor = limit_backward; // do, line 163 v_4 = cursor; lab3: do { // call postlude, line 163 if (!r_postlude()) { break lab3; } } while (false); cursor = v_4; return true; }
8
public ArrayList<Meld> getInitialMeld() throws Exception{ ArrayList<Meld> melds; int score; melds = getGroups(); melds.addAll(getRuns()); melds = findLargestSubset(new ArrayList<Tile>(this.getTiles()), new ArrayList<Tile>(), melds); if(melds == null) return null; score = 0; for(int i=0; i<melds.size(); i++) score = score + melds.get(i).getScore(); if(score < 30) return null; // FIXME move this for(Set set : melds) for(Tile usedTile : set.getTiles()) this.removeTile(usedTile); return melds; }
5
public void updateCraftingResults() { for(int var1 = 0; var1 < this.inventorySlots.size(); ++var1) { ItemStack var2 = ((Slot)this.inventorySlots.get(var1)).getStack(); ItemStack var3 = (ItemStack)this.inventoryItemStacks.get(var1); if(!ItemStack.areItemStacksEqual(var3, var2)) { var3 = var2 == null?null:var2.copy(); this.inventoryItemStacks.set(var1, var3); for(int var4 = 0; var4 < this.crafters.size(); ++var4) { ((ICrafting)this.crafters.get(var4)).updateCraftingInventorySlot(this, var1, var3); } } } }
4
public Object[][] updateAccountManagerTableView() { Collection<User> users = instance.getUsers(); //calculate number of rows int rows = 0; for (User user : users) { if (!user.isActiveCustomer()) { rows++; } for (Account acc : user.getAccounts()) { if (!acc.isClosed()) { rows++; } } } Object[][] accountManagerTable = new Object[rows][4]; //display users int i = 0; for (User user : users) { accountManagerTable[i][0] = user; StringBuilder formattedSsn = new StringBuilder(String.format("%09d", user.getSsn())); formattedSsn.insert(3, "-").insert(6, "-"); accountManagerTable[i][1] = formattedSsn; for (Account account : user.getAccounts()) { if (!account.isClosed()) { accountManagerTable[i][2] = account; BigDecimal balance = account.getBalance(); if (account.getType().isLoan()) { balance = balance.negate(); } accountManagerTable[i][3] = new DollarAmountFormatter().valueToString(balance); i++; } } if (!user.isActiveCustomer()) { i++; } } return accountManagerTable; }
9
public String getFullHouse() { String stt = "0"; //search for a set (three of a kind) and a pair. if found, we probably have a winner :D if (cards[0].getRank() == cards[1].getRank() && cards[1].getRank() == cards[2].getRank()) { if (cards[3].getRank() == cards[4].getRank()) { stt = Character.toString(cards[0].getCharCard()) + cards[3].getCharCard(); return stt; } } if (cards[2].getRank() == cards[3].getRank() && cards[3].getRank() == cards[4].getRank()) { if (cards[0].getRank() == cards[1].getRank()) { stt = Character.toString(cards[2].getCharCard()) + cards[0].getCharCard(); } } return stt; }
6
public static DeckArrayManager getDeckArrayManager() { if (instance == null) { instance = new DeckArrayManager(1); log.debug("[DeckArrayManager] inside getter() method"); } return instance; }
1
public Product(Character productCode) { prices = new TreeMap<Integer, BigDecimal>(); this.productCode = productCode; }
0
@Test public void testQueueUsage() { Thread testThread = new Thread(pipelinedFDstage); //A thread running through pipelined FDstage. testThread.start(); //Start the thread, which runs until interrupted (execute stage is responsible for terminating int opcodeValue = 0; for (int i = 0; i < 10; i ++) { //There are 10 instruction declarations in simpleEquation.txt program used in assembler try { opcodeValue = testFetchToExecuteQueue.take().getOpcode().getValue(); //Have THIS thread Take from the queue } catch (InterruptedException e) { e.printStackTrace(); } Instruction actualInstruction = (Instruction) assembler.getProgramCode()[i]; assertEquals(actualInstruction.getOpcode().getValue(), opcodeValue); //Compare the opcode of the instruction from the assembly //file to the one put into the queue by the fetch/decode stage. } testThread.interrupt(); //Stops the thread while(testThread.isAlive()); //Ensures the thread dies as it should after an interrupt System.out.println("Done!"); //This statement will not be reached if the interrupt does not terminate the thread //Note that the thread is not strictly terminated but is forced to run to completion without fetching or decoding any more //instructions. }
3
public static String longToName(long longName) { try { if (longName <= 0L || longName >= 0x5b5b57f8a98a5dd1L) return "invalid_name"; if (longName % 37L == 0L) return "invalid_name"; int i = 0; char name[] = new char[12]; while (longName != 0L) { long n = longName; longName /= 37L; name[11 - i++] = VALID_CHARACTERS[(int) (n - longName * 37L)]; } return new String(name, 12 - i, i); } catch (RuntimeException runtimeexception) { signlink.reporterror("81570, " + longName + ", " + (byte) -99 + ", " + runtimeexception.toString()); } throw new RuntimeException(); }
5
@Override public boolean colides(SchlangenKopf head) { if (!super.colides(head)) { head.die(); return true; } return false; }
1
@Override public void dispose () { super.dispose(); if (this.conn != null) { try { if (this.conn.isClosed() == false) { this.conn.close(); } } catch (SQLException ex) { LOGGER.warning("Unable to close connection"); } } }
3
public static void processAction(Object container,SwingWorkerInterface swingworker){ ActionProcessor processor=new ActionProcessor(); try{ try { if(!swingworker.proceed()){ return; } processor.initCompsAndValidate(container,swingworker); if(!processor.confirmMessages.isEmpty() && !processor.isUserSayingOkToContinue()){ return; } if(!processor.isError) { DataMapper.mapData(container); processor.isError=!swingworker.validateAndPopulate(processor.scopeObj); if(!processor.isError) { processor.scopeObj.setContainer(container); processor.scopeObj.setFieldsOfTheContainer(processor.fieldsOfContainer); swingworker.execute(); }else{ processor.showErrorDialog(); } }else { processor.showErrorDialog(); } }finally { CommonUI.restoreComponentsToInitialState(processor.fieldsOfContainer); if(processor.isError) { RequestScope.endOfRequest(processor.scopeObj); } } } catch(Exception e){ CommonUI.restoreComponentsToInitialState(processor.fieldsOfContainer); if(e instanceof SwingObjectsExceptions) { CommonUI.showErrorDialogForComponent((SwingObjectsExceptions)e); }else { CommonUI.showErrorDialogForComponent(new SwingObjectRunException(e,ErrorSeverity.SEVERE, FrameFactory.class)); } } }
8
public double teaTypeInfo() { double result = 0.0; double blackTeaSize = 0.0; double blackGood = 0.0; double blackBad = 0.0; double whiteTeaSize = 0.0; double whitekGood = 0.0; double whiteBad = 0.0; double greenTeaSize = 0.0; double greenGood = 0.0; double greenBad = 0.0; for (Tea t : trainingSet) { if (t.getTeaType().equals(Tea.BLACK_TEA)) { blackTeaSize++; if (t.isDrinkable()) { blackGood++; } else { blackBad++; } } if (t.getTeaType().equals(Tea.GREEN_TEA)) { whiteTeaSize++; if (t.isDrinkable()) { whitekGood++; } else { whiteBad++; } } if (t.getTeaType().equals(Tea.WHITE_TEA)) { greenTeaSize++; if (t.isDrinkable()) { greenGood++; } else { greenBad++; } } } result = blackTeaSize / trainingSet.size() * entropy(blackGood / blackTeaSize, blackBad / blackTeaSize); result += whiteTeaSize / trainingSet.size() * entropy(whitekGood / whiteTeaSize, whiteBad / whiteTeaSize); result += greenTeaSize / trainingSet.size() * entropy(greenGood / greenTeaSize, greenBad / greenTeaSize); return result; }
7
public final void setProgress(int var1) { if(!this.minecraft.running) { throw new StopGameException(); } else { long var2; if((var2 = System.currentTimeMillis()) - this.start < 0L || var2 - this.start >= 20L) { this.start = var2; int var4 = this.minecraft.width * 240 / this.minecraft.height; int var5 = this.minecraft.height * 240 / this.minecraft.height; GL11.glClear(16640); ShapeRenderer var6 = ShapeRenderer.instance; int var7 = this.minecraft.textureManager.load("/dirt.png"); GL11.glBindTexture(3553, var7); float var10 = 32.0F; var6.begin(); var6.color(4210752); var6.vertexUV(0.0F, (float)var5, 0.0F, 0.0F, (float)var5 / var10); var6.vertexUV((float)var4, (float)var5, 0.0F, (float)var4 / var10, (float)var5 / var10); var6.vertexUV((float)var4, 0.0F, 0.0F, (float)var4 / var10, 0.0F); var6.vertexUV(0.0F, 0.0F, 0.0F, 0.0F, 0.0F); var6.end(); if(var1 >= 0) { var7 = var4 / 2 - 50; int var8 = var5 / 2 + 16; GL11.glDisable(3553); var6.begin(); var6.color(8421504); var6.vertex((float)var7, (float)var8, 0.0F); var6.vertex((float)var7, (float)(var8 + 2), 0.0F); var6.vertex((float)(var7 + 100), (float)(var8 + 2), 0.0F); var6.vertex((float)(var7 + 100), (float)var8, 0.0F); var6.color(8454016); var6.vertex((float)var7, (float)var8, 0.0F); var6.vertex((float)var7, (float)(var8 + 2), 0.0F); var6.vertex((float)(var7 + var1), (float)(var8 + 2), 0.0F); var6.vertex((float)(var7 + var1), (float)var8, 0.0F); var6.end(); GL11.glEnable(3553); } this.minecraft.fontRenderer.render(this.title, (var4 - this.minecraft.fontRenderer.getWidth(this.title)) / 2, var5 / 2 - 4 - 16, 16777215); this.minecraft.fontRenderer.render(this.text, (var4 - this.minecraft.fontRenderer.getWidth(this.text)) / 2, var5 / 2 - 4 + 8, 16777215); Display.update(); try { Thread.yield(); } catch (Exception var9) { ; } } } }
5
public String longestPalindrome(String s) { // Start typing your Java solution below // DO NOT write main() function if (s == null || "".equals(s.trim())) return s; for (int i = s.length() ; i >= 1 ; i-- ) { for (int j = 0; j < s.length() - i + 1 ; j ++ ) { if (checkPalindromic(s.substring(j,j+i))) { return s.substring(j, j+i); } } } return null; }
5
public static void main(String[] args) { int input=1000000; ArrayList<Integer> prime=new ArrayList<Integer>(); prime.add(3); prime.add(5); int primes= 3; //long start=System.currentTimeMillis(); long startTime = new Date().getTime(); boolean temp=false; for(int i=7; i<=input; i+=2){ temp=false; int index=0; int j=prime.get(index); int sqrt=(int)(Math.floor(Math.sqrt(i))); for(; j<=sqrt; ){ int k=i%j; if( k == 0){ temp=true; break; } j=prime.get(++index); } if(!temp){ if(i <(input/2)){ prime.add(i); } primes++; } } long endTime = new Date().getTime(); long duration = endTime - startTime; System.out.println("Time taken is : " + duration+" milliseconds"); System.out.println("Number of prime count for input : "+input+" is : "+primes); }
5
public Diff getDifForDirection() { Diff diff = null; switch (this) { case UP: diff = createDiff(0, -1); break; case DOWN: diff = createDiff(0, 1); break; case RIGHT: diff = createDiff(1, 0); break; case LEFT: diff = createDiff(-1, 0); break; } return diff; }
4
private BasicComboBoxRenderer dayRenderer() { BasicComboBoxRenderer renderer = new BasicComboBoxRenderer(){ public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value != null) { String item = (String)value; setText( item ); } if (index == -1) { //ComboBoxInterface item = (ComboBoxInterface)value; //setText( "None" ); } return this; } }; return renderer; }
2
@SuppressWarnings({ "rawtypes", "unchecked" }) public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException{ resp.setContentType("text/html"); resp.setCharacterEncoding("utf-8"); Cache cache = null; try { CacheFactory cacheFactory = CacheManager.getInstance() .getCacheFactory(); Map props = new HashMap(); // 完全キャッシュ有効期間15分 props.put(GCacheFactory.EXPIRATION_DELTA, 60 * 15); cache = cacheFactory.createCache(props); } catch (CacheException e) { } String column = (String) cache.get("namecolumn"); if (column == null) { WakeBackends wb = new WakeBackends(); wb.newColumn(); } StringBuilder sb = new StringBuilder(); sb.append( "<html><head><title>共演検索マシーン - 共同開発者募集</title><meta name=\"viewport\" content=\"user-scalable=no\" /><meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\" />") .append("<meta name=\"description\" content=\"共演検索マシーンは共同開発者を募集しています。\">") .append("<meta name=\"keywords\" content=\"声優,共演,検索,アニメ,開発\">") .append("<script type=\"text/javascript\">") .append("function ChangeSelection1(form, selection) {\n") .append("form.n.value = selection.options[selection.selectedIndex].value;\n") .append("change_flag1(false);\n") .append("}\n") .append("function ChangeSelection2(form, selection) {\n") .append("form.m.value = selection.options[selection.selectedIndex].value;\n") .append("change_flag2(false);\n") .append("}\n") .append("function change_flag1(boolean) {\n") .append("if(boolean)\n") .append("document.getElementById(\"col_style1\").style.display = \"inline\";\n") .append("else\n") .append("document.getElementById(\"col_style1\").style.display = \"none\";\n") .append("}\n") .append("function change_flag2(boolean) {\n") .append("if(boolean)\n") .append("document.getElementById(\"col_style2\").style.display = \"inline\";\n") .append("else\n") .append("document.getElementById(\"col_style2\").style.display = \"none\";\n") .append("}\n") .append(" var _gaq = _gaq || [];") .append(" _gaq.push(['_setAccount', 'UA-28405404-2']);") .append(" _gaq.push(['_trackPageview']);") .append(" (function() { var ga = document.createElement('script');") .append(" ga.type = 'text/javascript'; ga.async = true;") .append(" ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';") .append(" var s = document.getElementsByTagName('script')[0];") .append(" s.parentNode.insertBefore(ga, s); })();") .append("</script>") .append("<link href=\"table.css\" rel=\"stylesheet\" type=\"text/css\" />") .append("</head><body onload=\"change_flag1(false),change_flag2(false)\">") .append("<div id=\"head\"><a href=\"/\" class=\"top\">サイトTOP</a><a href=\"guide\" class=\"guide\">ガイド</a><a href=\"past\" class=\"past\">検索履歴</a>") .append("<a href=\"ranking\" class=\"ranking\">総合ランキング</a><a href=\"pair\" class=\"pair\">男女ランキング</a><form action=\"co\" method=\"GET\"><input class=\"text\" type=\"text\" name=\"n\" value=\"") .append("") .append("\" onmouseover=\"change_flag1(true),change_flag2(false)\" onclick=\"change_flag1(false)\" />") .append(" & <input class=\"text\" type=\"text\" name=\"m\" onmouseover=\"change_flag2(true),change_flag1(false)\" onclick=\"change_flag2(false)\"/>") .append(" の共演を <input type=\"submit\" value=\"調べる\" />") .append("<div id=\"col_style1\"><select id=\"column1\" onchange=\"ChangeSelection1(this.form, this)\">") .append(column) .append("</select></div>") .append("<div id=\"col_style2\"><select id=\"column2\" onchange=\"ChangeSelection2(this.form, this)\">") .append(column).append("</select></div></form></div><div id=\"wrap\">") .append("<br /><div id=\"space\"></div>") .append("<div id=\"guide\"><h2>共同開発者募集</h2>") .append("共演検索マシーンでは、共同開発者を募集しています。") .append("<br />ご興味のある方は、<a href=\"mailto:[email protected]>[email protected]</a>までコンタクトください。<ol><li>作品のタイトル</li><li>作品のカテゴリ</li><li>公開された年</li></ol>") .append("<dl><dt>作品のタイトルについて</dt><dd>Wikipediaの記事の中で、出演作品リストと判断されたブロックの各行から、</dd>") .append("<dd>キャラクター名と判断される部分を除いた文字列を作品タイトルと判断しており、これが両者で一致する必要があります。</dd>") .append("<dd>この時、記号文字の差異・アルファベットの大小はある程度許容されます。スペースの有無、-と〜など。</dd>") .append("<dd>許容されない記号文字としては!や?があります。</dd>") .append("<dt>作品のカテゴリについて</dt>") .append("<dd>「テレビアニメ」「劇場アニメ」「ドラマCD」「ゲーム」等を指します。</dd>") .append("<dd>Wikipediaの見出しからこれらを取得し、各出演作品に付加しています。このカテゴリが両者で一致する必要があります。</dd>") .append("<dd>Wikipediaでは、同一の作品でも記事によってカテゴリの表記がゆれます。</dd>") .append("<dd>イベントの様子を収めたDVDソフトを「実写」とするか「その他」とするかは記事によります。</dd>") .append("<dd>また海外制作のテレビアニメを吹き替えた際に「吹き替え(アニメ)」とするか単に「テレビアニメ」とするか等でも違いがあります。</dd>") .append("<dd>これらの差異を、現状では一部のケースを除き許容(修正)できていません。(後述の“部分一致”でフォローしています。)</dd>") .append("<dd>基本的には両者のカテゴリ名が同一である必要があります。</dd>") .append("<dt>公開された年について</dt>") .append("<dd>Wikipediaでは、テレビアニメであれば放映年(正確には、対象の声優が出演した回の放映年)、</dd><dd>ゲームであれば発売年、映画であれば公開年が各出演作品には付加されています。</dd>") .append("<dd>これも参照しており、そのルールはやや複雑です。以下のいずれかを満たせばよいものとします。</dd>") .append("<dd><ul>" + "<li>公開された年が完全に同一である。たとえば2005年・2005年など。</li>" + "<li>公開された年が空欄である。片方、あるいは両方。たとえば2007年・(空欄)。</li>" + "<li>片方、あるいは両方の役名が“太字”、主要なキャラクターであり、なおかつ、太字でない方のキャラクターは、太字のキャラクターよりも後の年に登場している。</li></ul></dd>") .append("<dd>条件を満たさないのは、違う年が明記されており、なおかつお互いが主要キャラクターでない場合。</dd>") .append("<dd>あるいは、違う年が明記されており、なおかつ非主要キャラクターが主要キャラクターよりも前の年に登場している場合です。</dd></dl>") .append("<br />タイトル・カテゴリ・放映年と、全ての条件を満たしたものが「完全一致」となり、この件数が簡易履歴に表示されます。また、ランキングにも登録されます。") .append("<h2>部分一致</h2>") .append("表記のゆれなどの理由で、本来は共演しているのに漏れてしまったタイトルがあります。それらをすくい上げる意味で、部分一致カテゴリを用意しています。<br />") .append("部分一致が参照しているのは<i>“Wikipediaで各出演タイトルに関連づけられているリンク先”</i>です。<br />") .append("桑谷夏子さんの出演タイトルに「魔法先生ネギま! 〜白き翼 ALA ALBA〜」がありますが、Wikipediaでタイトル名をクリックすると<br />") .append("Wikipediaの記事「魔法先生ネギま!_(OVA)」にジャンプします。共演検索マシーンでは、このジャンプ先の記事が同一であれば、") .append("<br />いかにタイトル・カテゴリ・公開された年が違っていても“部分一致”としてリストの下段に表示します。") .append("<h2>当サイトの「共演」の定義</h2>") .append("以上のことから、当サイトでいう「共演」とはかなり範囲の広い言葉になっています。<br />") .append("厳密には共演とは、「同じスタジオで一緒にアフレコした」ということを指すのだと思いますが、<br />") .append("当サイトでは共演とは、<b>「同一カテゴリの同一タイトルに、同じ年に関わっていた(あるいは違う年に関わっていた)」</b>ということを指します。<br />") .append("これはWikipediaをソースとしていることからくる仕様です。<br />ご利用の際や、話題にされる際はどうかこの点にご留意ください。") .append("</div></div></body></html>"); resp.getWriter().println(new String(sb)); }
2
public static List<Appointment> findByDay(long uid, long day) throws SQLException { List<Appointment> aAppt = new ArrayList<Appointment>(); // once aAppt.addAll(Appointment.findOnceByDaySpan(uid, day, day)); // daily aAppt.addAll(Appointment.findDailyByDaySpan(uid, day, day)); // weekly aAppt.addAll(Appointment.findWeeklyByDay(uid, day)); // monthly aAppt.addAll(Appointment.findMonthlyByDaySpan(uid, day, day)); return aAppt; }
0
public void commit() { // if you haven't committed anything in 10,000 cycles, simulator is probably deadlocked --> kill SimAssert.check(((currCycle - lastCommitCycle) < 10000), "Deadlock! no commits in 10K cycles", currCycle); for (int i = 0; i < machineWidth; i++) { if (ROB.isEmpty()) // nothing to commit. bye! break; ROB_entry head = ROB.head(); Uop headUop = head.theUop; if (head.doneCycle <= currCycle && (head.doneCycle != -1)) { head.commitCycle = currCycle; if (debug_f) { head.printCycles(); head.printInputRegisters(); head.printOutputRegisters(); headUop.print_macro_micro_names(); } // at commit, free the overwritten register for (int out = 0; out < Uop.MAX_OUTPUTS; out++) { if (headUop.outputRegs[out] != -1) { FreeList.addLast(head.overwrittenRegs[out]); } } ROB.dequeue(); totalUops++; lastCommitCycle = currCycle; } } }
7
public static void main(String[] args){ for(int i= 20*19; i<Integer.MAX_VALUE; i++){ //will go through all integers until it reaches an answer boolean goodnum = true; //if it is the right number for(int j = 20; (goodnum == true) && (j>0); j--){ //goes through from 20 to 1 and tests if it is divisible, if not, it is not a goodnum, move on if(i%j != 0){ goodnum = false; } } if(goodnum == true){ System.out.println("number is: " + i); //answer return; } // else{ // goodnum = ; // } } System.out.println("unable to find, exiting"); return; }
5
public Set<Map.Entry<Byte,V>> entrySet() { return new AbstractSet<Map.Entry<Byte,V>>() { public int size() { return _map.size(); } public boolean isEmpty() { return TByteObjectMapDecorator.this.isEmpty(); } public boolean contains( Object o ) { if ( o instanceof Map.Entry ) { Object k = ( ( Map.Entry ) o ).getKey(); Object v = ( ( Map.Entry ) o ).getValue(); return TByteObjectMapDecorator.this.containsKey( k ) && TByteObjectMapDecorator.this.get( k ).equals( v ); } else { return false; } } public Iterator<Map.Entry<Byte,V>> iterator() { return new Iterator<Map.Entry<Byte,V>>() { private final TByteObjectIterator<V> it = _map.iterator(); public Map.Entry<Byte,V> next() { it.advance(); byte k = it.key(); final Byte key = (k == _map.getNoEntryKey()) ? null : wrapKey( k ); final V v = it.value(); return new Map.Entry<Byte,V>() { private V val = v; public boolean equals( Object o ) { return o instanceof Map.Entry && ( ( Map.Entry ) o ).getKey().equals( key ) && ( ( Map.Entry ) o ).getValue().equals( val ); } public Byte getKey() { return key; } public V getValue() { return val; } public int hashCode() { return key.hashCode() + val.hashCode(); } public V setValue( V value ) { val = value; return put( key, value ); } }; } public boolean hasNext() { return it.hasNext(); } public void remove() { it.remove(); } }; } public boolean add( Map.Entry<Byte,V> o ) { throw new UnsupportedOperationException(); } public boolean remove( Object o ) { boolean modified = false; if ( contains( o ) ) { //noinspection unchecked Byte key = ( ( Map.Entry<Byte,V> ) o ).getKey(); _map.remove( unwrapKey( key ) ); modified = true; } return modified; } public boolean addAll( Collection<? extends Map.Entry<Byte,V>> c ) { throw new UnsupportedOperationException(); } public void clear() { TByteObjectMapDecorator.this.clear(); } }; }
7
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub JSONObject jb = new JSONObject(); String userId = request.getParameter("userId"); String dateTimeInMillis = request.getParameter("dateTimeInMillis"); dateToQuery.setTime(Long.parseLong(dateTimeInMillis)); //String username = new String(request.getParameter("username").getBytes("ISO-8859-1"),"UTF-8"); try{ connection = new Mongo(); scheduleDB = connection.getDB("schedule"); eventCollection = scheduleDB.getCollection("event_" + userId); BasicDBObject eventCheckQuery = new BasicDBObject(); BasicDBObject conditionOne = new BasicDBObject(); BasicDBObject conditionTwo = new BasicDBObject(); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(dateToQuery.getTime()); Date dateBegin = new Date(); Date dateEnd = new Date(); dateBegin.setTime(cal.getTimeInMillis()); conditionTwo.put("$gte", dateBegin); cal.roll(Calendar.DAY_OF_YEAR, true); dateEnd.setTime(cal.getTimeInMillis()); conditionOne.put("$lte", dateEnd); eventCheckQuery.put("calFrom",conditionOne); eventCheckQuery.put("calTo",conditionTwo); DBCursor cur = eventCollection.find(eventCheckQuery); JSONArray ja = new JSONArray(); while(cur.hasNext()){ //ja.add(cur.next()); JSONObject eventJSONObject= new JSONObject(); DBObject dbo = cur.next(); String id = dbo.get("_id").toString(); String eventName = (String)dbo.get("eventName"); Date calFrom = (Date)dbo.get("calFrom"); Date calTo = (Date)dbo.get("calTo"); String locationName = (String)dbo.get("locationName"); String locationCoordinate = (String)dbo.get("locationCoordinate"); String decription = (String)dbo.get("decription"); String photo = (String)dbo.get("photo"); String record = (String)dbo.get("record"); int commentCount = (Integer)dbo.get("commentCount"); String commentsString; try{ commentsString = dbo.get("comments").toString(); eventJSONObject.put("commentsString", commentsString); }catch(NullPointerException npe){ JSONArray nullArray = new JSONArray(); eventJSONObject.put("commentsString", nullArray.toString()); } String updateTime = (String)dbo.get("updateTime"); eventJSONObject.put("_id", id); eventJSONObject.put("eventName", eventName); eventJSONObject.put("calFrom", calFrom.getTime()); eventJSONObject.put("calTo", calTo.getTime()); eventJSONObject.put("locationName", locationName); eventJSONObject.put("locationCoordinate", locationCoordinate); eventJSONObject.put("decription", decription); eventJSONObject.put("photo", photo); eventJSONObject.put("record", record); eventJSONObject.put("commentCount", commentCount); eventJSONObject.put("updateTime", updateTime); eventJSONObject.put("publisherId",userId); DBCollection userCollection = scheduleDB.getCollection("user"); DBObject imageQuery = new BasicDBObject(); imageQuery.put("_id", new ObjectId(userId)); DBCursor cur3 = userCollection.find(imageQuery); DBObject dbo3 = cur3.next(); String image = (String)dbo3.get("image"); String publisherName = (String)dbo3.get("username"); eventJSONObject.put("publisherImage",image); eventJSONObject.put("publisherName",publisherName); ja.add(eventJSONObject); } jb.put("result", Primitive.ACCEPT); jb.put("eventArray", ja); }catch(MongoException e){ jb.put("result", Primitive.DBCONNECTIONERROR); e.printStackTrace(); } response.setCharacterEncoding("UTF-8"); PrintWriter writer = response.getWriter(); String jbString = new String(jb.toString().getBytes(),"UTF-8"); writer.write(jbString); writer.flush(); writer.close(); }
3
public JSONObject toJSONObject(JSONArray names) throws JSONException { if (names == null || names.length() == 0 || this.length() == 0) { return null; } JSONObject jo = new JSONObject(); for (int i = 0; i < names.length(); i += 1) { jo.put(names.getString(i), this.opt(i)); } return jo; }
4
public void dijkstra(int s) { PriorityQueue<Edge> q = new PriorityQueue<Edge>(); q.add(new Edge(s, 0)); dis[s] = 0; while (!q.isEmpty()) { Edge cur = q.poll(); if (vis[cur.id]) continue; vis[s] = true; for (int i = 0; i < adj[cur.id].size(); i++) { Edge neigh = adj[cur.id].get(i); if (!vis[neigh.id]) { if (dis[cur.id] + neigh.w < dis[neigh.id]) { dis[neigh.id] = dis[cur.id] + neigh.w; parent[neigh.id] = cur.id; q.add(new Edge(neigh.id, dis[neigh.id])); } } } } }
5
@Override public void init(List<String> argumentList) { lineNumber = Integer.parseInt(argumentList.get(0)); }
0
private void give(String name, int amount, String playerName, CommandSender sender){ Player player = Bukkit.getPlayer(playerName); if(!player.getName().equals(sender.getName())){ if(!sender.hasPermission(pluginMain.pluginManager.getPermission("thf.give.others"))){ sender.sendMessage(ChatColor.DARK_RED + "You can't give items to other people!"); return; } } String[] itemName = name.split(":"); name = itemName[0]; if(!items.containsKey(name.toLowerCase())){ sender.sendMessage(ChatColor.DARK_RED + "Cannot find item " + name); return; } int id = items.get(name.toLowerCase()); ItemStack give = new ItemStack(id, amount); if(itemName.length == 2){ try{ short durability = Short.parseShort(itemName[1]); give.setDurability(durability); }catch(NumberFormatException e){ } } player.getInventory().addItem(give); player.sendMessage("[THF] You were given " + amount + " " + name + "(s)"); sender.sendMessage("[THF] Spawned item(s) for " + player.getName()); }
5
private int jjMoveStringLiteralDfa14_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(12, old0); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(13, active0); return 14; } switch(curChar) { case 103: return jjMoveStringLiteralDfa15_0(active0, 0x100L); case 104: return jjMoveStringLiteralDfa15_0(active0, 0x400L); case 112: return jjMoveStringLiteralDfa15_0(active0, 0x80L); case 116: return jjMoveStringLiteralDfa15_0(active0, 0x40L); default : break; } return jjStartNfa_0(13, active0); }
6
public static int parseString(StringBuilder sb, String[] args, int offset) { // string is empty? return an empty string if (offset >= args.length || args[offset].isEmpty()) { sb.append(""); return 1; } // first char is not a quote char? return the string final char quoteChar = args[offset].charAt(0); if (quoteChar != '"' && quoteChar != '\'') { sb.append(args[offset]); return 1; } String string = args[offset].substring(1); // string has at least 2 chars and ends with the same quote char? return the string without quotes if (string.length() > 0 && string.charAt(string.length() - 1) == quoteChar) { sb.append(string.substring(0, string.length() - 1)); return 1; } sb.append(string); offset++; int consumed = 1; while (offset < args.length) { sb.append(' '); consumed++; string = args[offset++]; if (string.length() > 0 && string.charAt(string.length() - 1) == quoteChar) { sb.append(string.substring(0, string.length() - 1)); break; } sb.append(string); } return consumed; }
9
public int getScore(final List<Vraag> vragen) { int vragenGoed = 0; for (Vraag vraag : vragen) { int aantalGoed = 0; int aantalFout = 0; int jokers = vraag.getHoeveelJokersGebruikt(); for (GekozenAntwoord gk : vraag.getGekozenAntwoorden()) if (gk.isGoed()) aantalGoed++; else aantalFout++; vragenGoed += aantalGoed + Math.min(aantalFout, jokers); } double bedrag = 0; for (Vraag vraag : vragen) { bedrag += vragenGoed * vraag.getHoeveelWaard(); if (vraag.isDoubling()) bedrag *= 2; } if (bedrag > MAX_BELASTINGVRIJ) bedrag /= KANSSPELBELASTING / 100 + 1; return (int) Math.round(bedrag); }
6
public void perteTerritoire(Territoire t) { int unite = t.getNbUnite(); /* Recherche dans les bonus s'il faut défausser une unité ou non */ //if (unite > 1) { << TODO: Utilité du if ? if( !( this.bonusDefausseUnite() || (hasPower() && pouvoir.bonusDefausseUnite()) ) ){ unite--; this.nbUnite--; } //} this.nbUniteEnMain += unite; quitterTerritoire(t); }
3
public void mouseReleased(MouseEvent me) { Node mouseNode = getMouseNode(); if(me.getButton() == MouseEvent.BUTTON1) { target = mouseNode; System.out.println("Target pos set to: x= "+mouseNode.getX()+", y= "+mouseNode.getY()); if(start != null) { clearPath(); AStar.findPath(start.getX(), start.getY(), target.getX(), target.getY(), lab.getWalkways()); render(); } } else if (me.getButton() == MouseEvent.BUTTON3) { start = mouseNode; System.out.println("Start pos set to: x= "+mouseNode.getX()+", y= "+mouseNode.getY()); } }
3
public static void add(short magic, Class clazz) { if(magic < MIN_CUSTOM_MAGIC_NUMBER) throw new IllegalArgumentException("magic ID (" + magic + ") must be >= " + MIN_CUSTOM_MAGIC_NUMBER); if(magicMapUser.containsKey(magic) || classMap.containsKey(clazz)) alreadyInMagicMap(magic, clazz.getName()); Object inst=null; try { inst=clazz.newInstance(); } catch(Exception e) { throw new IllegalStateException("failed creating instance " + clazz, e); } Object val=clazz; if(Header.class.isAssignableFrom(clazz)) { // class is a header checkSameId((Header)inst, magic); val=((Header)inst).create(); } if(Constructable.class.isAssignableFrom(clazz)) { val=((Constructable)inst).create(); inst=((Supplier<?>)val).get(); if(!inst.getClass().equals(clazz)) throw new IllegalStateException(String.format("%s.create() returned the wrong class: %s\n", clazz.getSimpleName(), inst.getClass().getSimpleName())); } magicMapUser.put(magic, val); classMap.put(clazz, magic); }
8
private int checkChar(char c) { switch (c) { case '{': return 1; case '[': return 2; case '\"': return 3; case '-': return 4; case '}': case ']': return 6; default: { if (Character.isDigit(c)) return 4; if (Character.isLetter(c)) return 5; return 0; } } }
8
public void handleCommand(Message message) { if(!conn.isConnected()) return; String body = message.getBody(); if(body.startsWith(prefix)){ body = body.substring(prefix.length()); }else{ //(message.getBody().startsWith(connection.getNick()){ body = body.substring(conn.getNick().length()); if(body.matches("[:>]? .*")){ body = body.substring(1).trim(); }else{ return; } } String[] command = body.split(" +"); if(logger.isTraceEnabled()){logger.trace("Handling command: " + Arrays.toString(command));} String from = message.getFrom(); int priv = getPrivLevel(from); switch (command[0]) { case "commands": printCommands(); break; case "help": printHelp(command[1]); break; default: CommandWrapper cw = plugins.getCommand(command[0]); if(cw == null) return; Command c = (Command) cw.getPlugin(); if(c.getPrivLevel() <= priv){ c.handleCommand(new CommandMessageImpl(message, this, body.substring(command[0].length()))); }else if(logger.isInfoEnabled()){ logger.info("User " + from + " (priv " + priv + ") tried to do '" + message.getBody() + "' (priv " + c.getPrivLevel() + ")"); } break; } }
9
public static List<List<Integer>> subsets(int[] S) { Arrays.sort(S, 0, S.length); List<List<Integer>> res = new ArrayList<List<Integer>>(); List<Integer> n = new ArrayList<Integer>(); res.add(n); for (int i : S) { int len = res.size(); for (int j = 0; j < len; j++) { ArrayList<Integer> t = (ArrayList<Integer>) res.get(j); ArrayList<Integer> c = (ArrayList<Integer>) t.clone(); c.add(i); if (!res.contains(c)) { res.add(c); } } } return res; }
3
private LinkedList generatecontent() { int maxitems=0; LinkedList loot = new LinkedList(); //Maximale Anzahl von Items in einer Kiste int randmax = UtilFunctions.randomizer(1, 100); if (randmax <80) { maxitems=1; } else if (randmax >=80 && randmax < 98) { maxitems=2; } else if (randmax >=98 && randmax <=100) { maxitems=3; } //Würfeln vom seltensten bis zum häufigsten Item bis maximale Anzahl erreicht ist while (loot.size() < maxitems) { for (int i = 0; i < allitems.size(); i++) { Item item = allitems.get(i); if (item.getItemlvl()<=main.getCurrentDungeonLevel()) { double d = item.getDroprate(); int rand = UtilFunctions.randomizer(1, 100000); if (rand < d) { loot.add(item); break; } } } } return loot; }
9
public void checkActive() { if (building.requires.length > 0 && !castle.getBuildings().containsAll(Arrays.asList(building.requires))) { buy.setEnabled(false); String requirestr = "<i>Wymaga: "; Set<core.CastleBuilding> diff = new HashSet<core.CastleBuilding>(Arrays.asList(building.requires)); diff.removeAll(castle.getBuildings()); System.out.println(diff); int i = 0; for (core.CastleBuilding b: diff) { if (i != 0) requirestr += ", "; requirestr += b.name; ++i; } requirestr += "</i>"; require.setText(requirestr); return; } else { require.setText(""); } if (castle.isBuyed()) { buy.setEnabled(false); return; } if (player.getResource(core.ResourceType.GOLD) < building.cost.gold) { buy.setEnabled(false); return; } if (player.getResource(core.ResourceType.WOOD) < building.cost.wood) { buy.setEnabled(false); return; } if (player.getResource(core.ResourceType.ORE) < building.cost.ore) { buy.setEnabled(false); return; } System.out.println(castle.getBuildings()); System.out.println(Arrays.asList(building.requires)); if (castle.getBuildings().contains(building)) { buy.setEnabled(false); return; } }
9
protected void createCalendarDoc() { try { /** * Clear the document. Required for date roll overs. */ document.remove(0, document.getLength()); /** * Insert the calendar header of month and year. */ document.insertString(0, MONTHS[displayMonth] + HEADER_TAB_SPACE[displayMonth] + HEADER_WHITE_SPACE + displayYear + "\n", title); SimpleAttributeSet attrs = weekday; /** * Get the starting day of week for the month. */ int startDay = dayOfWeek(displayMonth, 1, displayYear); /** * Insert any blank days into the first line of the calendar pane. */ for(int i = 0; i < startDay; i++) { document.insertString(document.getLength(), "\t", attrs); } /** * Iterate through the days in the month. */ for(int i = 1; i <= daysInMonth; i++) { /** * Set the text style attributes of the day numbers base on: * weekday, Sunday, Saturday, and today. */ if(isSaturday(i)) { attrs = saturday; } else if(isSunday(i)) { attrs = sunday; } else { attrs = weekday; } if(isToday(i)) { attrs = today; } /** * Provide a single space of left padding for the single digit * dates. */ if(i<10) { document.insertString(document.getLength(), " ", attrs); } /** * Insert the appropriate date number. */ document.insertString(document.getLength(), String.format("%2d", i), attrs); /** * Insert a line break at the end of week and end of month. Else, * insert a tab between the numbers. */ if(((i + startDay) % 7 == 0) || (i == daysInMonth)) { document.insertString(document.getLength(), "\n", attrs); } else { document.insertString(document.getLength(), "\t", attrs); } } } catch(Exception e) { /** * Log any exceptions that are thrown during the document creation process. */ LOGGER.severe(e.getMessage()); } }
9
public static Cons idlTranslateUnit(TranslationUnit unit) { { Symbol testValue000 = unit.category; if (testValue000 == Stella.SYM_STELLA_GLOBAL_VARIABLE) { return (null); } else if (testValue000 == Stella.SYM_STELLA_TYPE) { return (TranslationUnit.idlTranslateDeftypeUnit(unit)); } else if (testValue000 == Stella.SYM_STELLA_CLASS) { return (TranslationUnit.idlTranslateDefineNativeClassUnit(unit)); } else if ((testValue000 == Stella.SYM_STELLA_METHOD) || (testValue000 == Stella.SYM_STELLA_MACRO)) { return (null); } else if (testValue000 == Stella.SYM_STELLA_PRINT_METHOD) { return (null); } else if ((testValue000 == Stella.SYM_STELLA_STARTUP_TIME_PROGN) || (testValue000 == Stella.SYM_STELLA_VERBATIM)) { return (null); } else { { OutputStringStream stream000 = OutputStringStream.newOutputStringStream(); stream000.nativeStream.print("`" + testValue000 + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace())); } } } }
8
public FileParser getParserInstance() { if (system.indexOf(UNIX_IDENTIFICATION) >= 0) { log.debug("Found UNIX identification, try to use UNIX file parser"); return new UnixFileParser(locale); } else if (system.indexOf(WINDOWS_IDENTIFICATION) >= 0) { log.debug("Found WINDOWS identification, try to use WINDOWS file parser"); return new WindowsFileParser(locale); } else if (system.indexOf(VMS_IDENTIFICATION) >= 0) { log.debug("Found VMS identification, try to use VMS file parser"); return new VMSFileParser(locale); } else if (system.indexOf(NETWARE_IDENTIFICATION) >= 0) { log.debug("Found NETWARE identification, try to use NETWARE file parser"); return new NetwareFileParser(locale); } else { log.warn("Unknown SYST '" + system + "', trying UnixFileParsers"); return null; } }
4
protected Variable getImportedVar(String name) throws UtilEvalError { // Try object imports if (importedObjects != null) for (int i = 0; i < importedObjects.size(); i++) { Object object = importedObjects.get(i); Class clas = object.getClass(); Field field = Reflect.resolveJavaField(clas, name, false/* onlyStatic */); if (field != null) return new Variable(name, field.getType(), new LHS(object, field)); } // Try static imports if (importedStatic != null) for (int i = 0; i < importedStatic.size(); i++) { Class clas = importedStatic.get(i); Field field = Reflect.resolveJavaField(clas, name, true/* onlyStatic */); if (field != null) return new Variable(name, field.getType(), new LHS(field)); } return null; }
6
public String nextLine() { if(console) advance(); String ret = line; st = new StringTokenizer(""); //force advance to readLine if(!console) advance(); return ret; }
2
@Override public void display( GLAutoDrawable glautodrawable ) { long now_time = System.currentTimeMillis(); float dt = (now_time - last_time)*0.001f; last_time = now_time; //System.out.println(dt); // Clear The Screen And The Depth Buffer GL2 gl2 = glautodrawable.getGL().getGL2(); gl2.glClearColor(0,0,0,0); // Special handling for the case where the GLJPanel is translucent // and wants to be composited with other Java 2D content if (GLProfile.isAWTAvailable() && (glautodrawable instanceof javax.media.opengl.awt.GLJPanel) && !((javax.media.opengl.awt.GLJPanel) glautodrawable).isOpaque() && ((javax.media.opengl.awt.GLJPanel) glautodrawable).shouldPreserveColorBufferIfTranslucent()) { gl2.glClear(GL2.GL_DEPTH_BUFFER_BIT); } else { gl2.glClear(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT); } // move everything world.update(dt); // draw the world world.render(gl2); // update input states Input.GetSingleton().update(); }
4
private Collection getMimeTypes2(Collection mimeTypes, InputStream in) { try { if (mimeTypes.isEmpty() || mimeTypes.size() > 1) { Collection mimeTypes2 = getMimeTypesInputStream(in = new BufferedInputStream( in)); if (!mimeTypes2.isEmpty()) { if (!mimeTypes.isEmpty()) { // more than one glob matched // Check for same mime type for (Iterator it = mimeTypes.iterator(); it.hasNext();) { String mimeType = (String) it.next(); if (mimeTypes2.contains(mimeType)) { // mimeTypes = new ArrayList(); mimeTypes.add(mimeType); // return mimeTypes; } // Check for mime type subtype for (Iterator it2 = mimeTypes2.iterator(); it2 .hasNext();) { String mimeType2 = (String) it2.next(); if (isMimeTypeSubclass(mimeType, mimeType2)) { // mimeTypes = new ArrayList(); mimeTypes.add(mimeType); // return mimeTypes; } } } } else { // No globs matched but we have magic matches return mimeTypes2; } } } } catch (Exception e) { throw new MimeException(e); } finally { closeStream(in); } return mimeTypes; }
9
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(ModalProducto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ModalProducto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ModalProducto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ModalProducto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { ModalProducto dialog = new ModalProducto(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); }
6
@Override public void paint(Graphics g) { g.setColor(super.getBackground()); g.fillRect(0, 0, this.getWidth(), this.getHeight()); if(autosize) { if(mouseOver) { if(!selected) { Image tmp = this.icon_hover.getImage().getScaledInstance(this.getWidth(), this.getHeight(), java.awt.Image.SCALE_SMOOTH); g.drawImage(new ImageIcon(tmp).getImage(), 0, 0, null); } else { Image tmp = this.alt_icon_hover.getImage().getScaledInstance(this.getWidth(), this.getHeight(), java.awt.Image.SCALE_SMOOTH); g.drawImage(new ImageIcon(tmp).getImage(), 0, 0, null); } } else { if(!selected) { Image tmp = this.icon.getImage().getScaledInstance(this.getWidth(), this.getHeight(), java.awt.Image.SCALE_SMOOTH); g.drawImage(new ImageIcon(tmp).getImage(), 0, 0, null); } else { Image tmp = this.alt_icon.getImage().getScaledInstance(this.getWidth(), this.getHeight(), java.awt.Image.SCALE_SMOOTH); g.drawImage(new ImageIcon(tmp).getImage(), 0, 0, null); } } } else { if(mouseOver) { g.drawImage(this.icon_hover.getImage(), 0, 0, null); } else { g.drawImage(this.icon.getImage(), 0, 0, null); } } }
5
public List getBundles() { clearResultMetaInformation(); List bundles = new ArrayList(); StringBuffer result = new StringBuffer(); GetMethod get = new GetMethod(apiEndpoint + DeliciousConstants.BUNDLES_ALL); get.setDoAuthentication(true); try { httpResult = httpClient.executeMethod(get); checkNotAuthorized(httpResult); logger.debug("Result: " + httpResult); if (get.getResponseBodyAsStream() != null) { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream(), DeliciousUtils.UTF_8)); String input; while ((input = bufferedReader.readLine()) != null) { result.append(input).append(DeliciousUtils.LINE_SEPARATOR); } get.releaseConnection(); Document document = documentBuilder.parse(new InputSource(new StringReader(result.toString()))); NodeList bundleItems = document.getElementsByTagName(DeliciousConstants.BUNDLE_TAG); if (bundleItems != null && bundleItems.getLength() > 0) { for (int i = 0; i < bundleItems.getLength(); i++) { Node bundleItem = bundleItems.item(i); Bundle bundle; String name = bundleItem.getAttributes().getNamedItem(DeliciousConstants.BUNDLE_NAME_ATTRIBUTE).getNodeValue(); String tags = bundleItem.getAttributes().getNamedItem(DeliciousConstants.BUNDLE_TAGS_ATTRIBUTE).getNodeValue(); bundle = new Bundle(name, tags); bundles.add(bundle); } } } } catch (IOException e) { logger.error(e); } catch (SAXException e) { logger.error(e); throw new DeliciousException("Response parse error", e); } return bundles; }
7
@Test public void testBubbleSort(){ sortSelection.load(array,null,null); sortSelection.run(); assertArrayEquals(array, arrayActuals); }
0
public boolean updateEmptySpace () { int i = 0, j = 0; /* Checks the size */ if (size.equals("9x9")){ /* Uses nested for loops to check if a space is empty */ for (i = 0; i < 9; i++) { for (j = 0; j < 9; j++) { if (entries[i][j].getText().equals("")) { entries[i][j].setText(solution[i][j]); } } } } else { /* Same as above for 16x16 board */ for (i = 0; i < 16; i++) { for (j = 0; j < 16; j++){ if (entries[i][j].getText().equals("")) { entries[i][j].setText(solution[i][j]); } } } } return false; }
7
public PersonAssignation() { setModal(true); setIconImage(Toolkit.getDefaultToolkit().getImage(PersonAssignation.class.getResource("/InterfazGrafica/Images/Search48.png"))); setTitle("BUSQUEDA"); setBounds(100, 100, 450, 235); getContentPane().setLayout(new BorderLayout()); contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); getContentPane().add(contentPanel, BorderLayout.CENTER); contentPanel.setLayout(null); setLocationRelativeTo(null); JLabel lblNombre = new JLabel("Nombre:"); lblNombre.setHorizontalAlignment(SwingConstants.RIGHT); lblNombre.setBounds(10, 29, 52, 23); contentPanel.add(lblNombre); { JLabel lblRNC = new JLabel("RNC:"); lblRNC.setHorizontalAlignment(SwingConstants.RIGHT); lblRNC.setBounds(35, 57, 27, 23); contentPanel.add(lblRNC); } textField_name = new JTextField(); textField_name.setBounds(72, 30, 297, 20); contentPanel.add(textField_name); textField_name.setColumns(10); textField_RNC = new JTextField(); textField_RNC.setColumns(10); textField_RNC.setBounds(72, 58, 297, 20); contentPanel.add(textField_RNC); { } { JPanel buttonPane = new JPanel(); buttonPane.setLayout(new FlowLayout(FlowLayout.CENTER)); getContentPane().add(buttonPane, BorderLayout.SOUTH); { final JLabel lbl_dontFound = new JLabel(""); lbl_dontFound.setForeground(Color.RED); lbl_dontFound.setFont(new Font("Tahoma", Font.PLAIN, 11)); lbl_dontFound.setHorizontalAlignment(SwingConstants.CENTER); lbl_dontFound.setBounds(10, 85, 414, 23); contentPanel.add(lbl_dontFound); JProgressBar progressBar = new JProgressBar(); progressBar.setVisible(false); progressBar.setBounds(95, 119, 233, 14); contentPanel.add(progressBar); JButton okButton = new JButton("Asignar"); okButton.setIcon(new ImageIcon(PersonAssignation.class.getResource("/InterfazGrafica/Images/si.png"))); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { EmploymentMarket.getInstanceEmploymentMarket().compare(CollectionCompanyApplication.getInstanceCollectionCompanyApplication().getCompanyApplication(0)); }}); okButton.setActionCommand("Buscar"); buttonPane.add(okButton); getRootPane().setDefaultButton(okButton); } { JButton cancelButton = new JButton("Cancel"); cancelButton.setIcon(new ImageIcon(SearchCompany.class.getResource("/InterfazGrafica/Images/Delete32.png"))); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { dispose(); } }); cancelButton.setActionCommand("Cancel"); buttonPane.add(cancelButton); } } }
0
public static LoLRTMPSClient returnClient(String region) throws NullClientForRegionException { if(PvPNetClients.get(region) == null) { throw new NullClientForRegionException("No client for region " + region + " available.", region); } int numClients = PvPNetClients.get(region).values().size(); LoLRTMPSClient client = (LoLRTMPSClient) PvPNetClients.get(region).values().toArray()[(int)(Math.random()*numClients)]; LolDataServer.log.fine("Loadbalancer returned " + region + "::" + client.getUserName()); return client; }
1
public ListNode deleteDuplicates(ListNode head) { if(head == null){ return null; } ListNode superHead = new ListNode(0); superHead.next = head; ListNode previous = superHead; ListNode check = head; boolean dup = false; while(check.next !=null){ if(check.val == check.next.val){ dup = true; check = check.next; } else { if (dup){ previous.next = check.next; check = previous.next; dup = false; } else { previous = check; check = check.next; } } } if(dup){ previous.next = null; } return superHead.next; }
5
private boolean okToCreate() { boolean res = false; boolean beteckningOk = !Validate.tfEmpty(tfBeteckning) && Validate.notOverSize(tfBeteckning); boolean checkDates = Validate.startdateBeforeReleasedate(calStartDate.getDate(), calReleaseDate.getDate()); if (beteckningOk) { if (checkDates) { res = true; } else { if (calStartDate.getDate() != null && calReleaseDate.getDate() != null) { lblError.setText("Sätt ett releasedatum som är senare i tid än startdatumet."); lblError.setVisible(true); } else { //if user removed the date lblError.setText("Var god välj ett datum för både start och releasedatum"); lblError.setVisible(true); } } } else { lblError.setText("Beteckningen får inte vara tom eller över 255 tecken, var vänligen skriv in en beteckning"); lblError.setVisible(true); } return res; }
5
public void pass() throws IllegalStateException{ if(passedBefore) throw new IllegalStateException(); board.pass(); this.passedBefore = true; }
1
public static double compute(double a, double x) throws ArithmeticException { if (x <= 0 || a <= 0) return 1.0; if (x < 1.0 || x < a) return 1.0 - Igam.compute(a, x); final double MACHEP = 1.11022302462515654042E-16; final double MAXLOG = 7.09782712893383996732E2; double big = 4.503599627370496e15; double biginv = 2.22044604925031308085e-16; double ans, ax, c, yc, r, t, y, z; double pk, pkm1, pkm2, qk, qkm1, qkm2; ax = a * Math.log(x) - x - LnGamma.compute(a); if (ax < -MAXLOG) return 0.0; ax = Math.exp(ax); /* continued fraction */ y = 1.0 - a; z = x + y + 1.0; c = 0.0; pkm2 = 1.0; qkm2 = x; pkm1 = x + 1.0; qkm1 = z * x; ans = pkm1 / qkm1; do { c += 1.0; y += 1.0; z += 2.0; yc = y * c; pk = pkm1 * z - pkm2 * yc; qk = qkm1 * z - qkm2 * yc; if (qk != 0) { r = pk / qk; t = Math.abs((ans - r) / r); ans = r; } else t = 1.0; pkm2 = pkm1; pkm1 = pk; qkm2 = qkm1; qkm1 = qk; if (Math.abs(pk) > big) { pkm2 *= biginv; pkm1 *= biginv; qkm2 *= biginv; qkm1 *= biginv; } } while (t > MACHEP); return ans * ax; }
8
public MainFrame(boolean silent){ super(AlienFXProperties.ALIEN_FX_APPLICATION_NAME); try{ lockApplication(); }catch(Exception e){ JOptionPane.showMessageDialog(null, AlienFXTexts.ALREADY_RUNNING_ERROR_TEXT, AlienFXTexts.ALIEN_FX_ERROR_TITLE_TEXT, JOptionPane.ERROR_MESSAGE); return; } ProfileModel model = new ProfileModel(); model.addObserver(new ProfileListener()); try { engine = new AlienFXEngine(); profiles = new AlienFXProfiles(model); profiles.loadProfiles(); setupTray(); } catch (AlienFXControllerNotFoundException e) { JOptionPane.showMessageDialog(null, AlienFXTexts.DEVICE_NOT_PRESENT_ERROR_TEXT, AlienFXTexts.ALIEN_FX_ERROR_TITLE_TEXT, JOptionPane.ERROR_MESSAGE); return; } catch (AlienFXControllerUnknownDeviceException e) { JOptionPane.showMessageDialog(null, AlienFXTexts.UNKNOWN_DEVICE_ERROR_TEXT, AlienFXTexts.ALIEN_FX_ERROR_TITLE_TEXT, JOptionPane.ERROR_MESSAGE); return; } catch (AlienFXCommunicationException e) { JOptionPane.showMessageDialog(null, AlienFXTexts.DEVICE_PERMISSION_ERROR_TEXT, AlienFXTexts.ALIEN_FX_ERROR_TITLE_TEXT, JOptionPane.ERROR_MESSAGE); return; } Container container = this.getContentPane(); container.setLayout(new BorderLayout()); JColorChooser chooser = new JColorChooser(); chooser.setPreviewPanel(new JPanel()); ColorModel colorModel = new ColorModel(); // Top row: device name, profile selection panel JPanel toprow = new JPanel(new BorderLayout()); toprow.add(new DeviceInfoPanel(engine.getController().description), BorderLayout.LINE_START); toprow.add(new ProfileSelectionPanel(model, engine, profiles), BorderLayout.CENTER); add(toprow, BorderLayout.PAGE_START); JPanel profile = new ProfilePanel(model,colorModel); profile.setBorder(BorderFactory.createTitledBorder(AlienFXTexts.PROFILE_TEXT)); add(profile, BorderLayout.CENTER); JPanel leftcolumn = new JPanel(new BorderLayout()); JPanel colorchooserpanel = new ColorChooserPanel(colorModel); colorchooserpanel.setBorder(BorderFactory.createTitledBorder(AlienFXTexts.COLORS_TEXT)); leftcolumn.add(colorchooserpanel, BorderLayout.PAGE_START); leftcolumn.add(new ColorUsedPanel(model, colorModel), BorderLayout.CENTER); add(leftcolumn, BorderLayout.LINE_START); setSize(1100,550); setLocationRelativeTo(null); setResizable(true); addWindowListener(new CloseListener()); setDefaultCloseOperation(useTrays ? JFrame.DO_NOTHING_ON_CLOSE : JFrame.EXIT_ON_CLOSE); setupMenu(); setVisible((useTrays && !silent) || !useTrays); updateTray(); }
7
public static TopQueue search(String target, String dictFile) throws IOException { BufferedReader reader; reader = new BufferedReader(new FileReader(dictFile)); TopQueue topQueue = new TopQueue(); String word; int distance; while((word = reader.readLine()) != null) { // get the number of distance in Editex distance = Editex.editex(target,word); if(!topQueue.isEmpty()){ if(distance < topQueue.getEntryDistance()){ topQueue.add(word,distance); } } else { topQueue.add(word,distance); } } return topQueue; }
3
public static void main(String[] args) throws Throwable{ int[][] res = new int[101][5]; for(int i = 1; i < res.length; i++){ res[i]=res[i-1].clone(); if(i%10<=3)res[i][0]+=(i%10); else if(i%10==4){res[i][0]++;res[i][1]++;} else if(i%10<=8){res[i][1]++;res[i][0]+=(i%10)-5;} else {res[i][0]++;res[i][2]++;} if(i/10<=3)res[i][2]+=(i/10); else if(i/10==4){res[i][2]++;res[i][3]++;} else if(i/10<=8){res[i][3]++;res[i][2]+=(i/10)-5;} else {res[i][2]++;res[i][4]++;} } BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); for(int N; (N = parseInt(in.readLine().trim()))!=0;){ System.out.println(N + ": " + res[N][0] + " i, " + res[N][1] + " v, " + res[N][2] + " x, " + res[N][3] + " l, " + res[N][4] + " c"); } }
8
public static Point invertDirection(Point direction) { Point newDirection = (Point) direction.clone(); newDirection.x *= -1; newDirection.y *= -1; return newDirection; }
0
private boolean testHypothesis() { if (hypothesis == Hypothesis.LESS_THAN && testStatistic < criticalRegion) { return true; } else if (hypothesis == Hypothesis.GREATER_THAN && testStatistic > criticalRegion) { return true; } else if (hypothesis == Hypothesis.NOT_EQUAL && (testStatistic < lowerRegion || testStatistic > upperRegion)) { return true; } else conclusion = "Test statistic is NOT within the critical region \n" + "Do NOT reject the null hypothesis"; return false; }
7
@Override public boolean equals(Object other) { if(other == this) return true; if(!(other instanceof Quantity)) return false; //return value == ((Quantity) other).convert(this.unit).value; //return value - ((Quantity) other).convert(this.unit).value < 0.00001; double otherValue = ((Quantity) other).convertTo(this.unit); return this.value == otherValue; }
2