method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
5b2f9712-c89d-461b-8196-28478b945c87
7
public static void refreshListeners() { EventManager evt = getEventManager(); if (evt == null) { System.out.println("Could not add listeners to event manager"); return; } evt.addListener(self); if (Script.paint != null) { evt.addListener(Script.paint); } if (Script.motion != null) { evt.addListener(Script.motion); } if (Script.mouse != null) { evt.addListener(Script.mouse); } if (Script.paintMotion != null) { evt.addListener(Script.paintMotion); } if (Script.paintMouse != null) { evt.addListener(Script.paintMouse); } for (EventListener e : listeners) { evt.addListener(e); } }
4a8aade9-99e6-440e-a5b4-e3a448f0e5a5
7
public InvestmentTableModel(AccountRecord account, String[] columnNames, Class<?>[] columnClasses) { if (account == null) throw new NullPointerException("No account provided"); if (columnNames == null) throw new NullPointerException("No column names provided"); if (columnClasses == null) throw new NullPointerException("No column classes provided"); if (columnNames.length != columnClasses.length) throw new IllegalArgumentException("Number of names not same as number of classes"); this.account = account; this.columnNames = columnNames; this.columnClasses = columnClasses; int listSize = TransactionRecord.transactions.size(); listData = new ArrayList<TransactionRecord>(listSize+10); // // Add transactions for the investment account // // An investment account cannot be a transfer account, so // we just need to check the source account for the transaction // for (TransactionRecord t : TransactionRecord.transactions) { if (t.getAccount() == account) listData.add(t); } }
e610d454-db8f-487b-9af9-a86c9edb9021
7
@Override public void storeImage(Image image) { ResultSet rs = null; int ID = image.getID(); if (ID > 0) { // update /////////////////////////////////////////////////////////////// // l'immagine già esiste ma non abbiamo dato la possibilità di editarla // le immagini si possono solo aggiungere e togliere ////////////////////////////////////////////////////////////// } else { // insert try { // this.iImage = connection.prepareStatement("INSERT INTO image (URL, description, name, banner)", Statement.RETURN_GENERATED_KEYS); this.iImage.setString(1, image.getURL()); this.iImage.setString(2, image.getDescription()); this.iImage.setString(3, image.getName()); this.iImage.setBoolean(4, image.isBanner()); // abbiamo finito di compilare la query if (this.iImage.executeUpdate() == 1) { rs = this.iImage.getGeneratedKeys(); if (rs.next()) { ID = rs.getInt(1); } } if (ID > 0) { image.copyFrom(getImage(ID)); // aggiorno il post } image.setDirty(false); // dico che è pulito } catch (SQLException ex) { Logger.getLogger(SitoDataLayerMysqlImpl.class.getName()).log(Level.SEVERE, null, ex); } finally { if (rs != null) { try { rs.close(); } catch (SQLException ex) { Logger.getLogger(SitoDataLayerMysqlImpl.class.getName()).log(Level.SEVERE, null, ex); } } } } }
93b4d7ff-f3c0-4776-adc3-39c33f8af8ea
9
public BoardUI(Board board, PluginInterface[] plugins) { this.board = board; this.board.addObserver(this); lists_zone = new JPanel(); lists_zone.setLayout(new BoxLayout(lists_zone, BoxLayout.X_AXIS)); lists_zone.setBorder(new EmptyBorder(new Insets(10, 10, 10, 10))); lists_zone.setBackground(new Color(100,150,200)); // HACK: Pour defocuser les textinput si on clique ailleurs, // on vole le focus si on clique sur le panel principal lists_zone.addMouseListener(new MouseAdapter() { @Override public void mouseReleased(MouseEvent e) { super.mouseReleased(e); lists_zone.grabFocus(); } }); label_menu_listener = new MouseAdapter() { @Override public void mouseReleased(MouseEvent e) { super.mouseReleased(e); //To change body of overridden methods use File | Settings | File Templates. // On vérifie que c'était un clic sensé ouvrir un menu if (e.isPopupTrigger()) { String class_src = e.getSource().getClass().getName(); if (class_src.equals("GUI.ItemUI") || class_src.equals("javax.swing.JTextArea")) { if (class_src.equals("GUI.ItemUI")) item_menu.setClickedItem((ItemUI) e.getSource()); if (class_src.equals("javax.swing.JTextArea")) item_menu.setClickedItem((ItemUI) (e.getComponent().getParent())); item_menu.show(e.getComponent(), e.getX(), e.getY()); } } } }; item_menu = new ItemMenu(); for (Core.List list : board.getLists()) { // list.addObserver(this); //setup_list(list); lists_zone.add(new ListUI(list, label_menu_listener)); lists_zone.add(Box.createRigidArea(new Dimension(10, 0))); } create_empty_list(); JScrollPane horizontal_scroll = new JScrollPane(lists_zone); horizontal_scroll.getHorizontalScrollBar().setUnitIncrement(14); frame = new JFrame(board.getName() + " - Dashlist"); frame.add(horizontal_scroll, BorderLayout.CENTER); for (PluginInterface plugin : plugins) { String[] target = plugin.getTargetContainer().split("[:]"); // On teste si le plugin veut s'attacher à un container de cette classe if (target[0].equals(this.getClass().getName())) { try { plugin.acquireContainer(((Container) (getClass().getDeclaredField(target[1]).get(this)))); } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } } buildMenuBar(); frame.setIconImage(frame.getToolkit().getImage("icon2.png")); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); Dimension current_resolution = Toolkit.getDefaultToolkit().getScreenSize(); frame.setMinimumSize(new Dimension((int)(current_resolution.width*0.5), (int)(current_resolution.height*0.5))); frame.setPreferredSize(new Dimension((int)(current_resolution.width*0.7), (int)(current_resolution.height*0.7))); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); }
4dba6ffc-5e24-43ae-8ff7-a4b6296f219f
3
@Override public void mouseClicked(MouseEvent e) { JList liste = (JList)e.getSource(); if (e.getClickCount() == 2) { synchronized(Main.lignes) { final Ligne ligne = Main.lignes.get(liste.getSelectedValue()); System.out.println("DOUBLE CLICK " +ligne.getId()); new Thread(new Runnable() { public void run() { try { Main.service.choisirLigne(ligne.getId(), new CallbackListener() { @Override public void onReturn(boolean success) { // TODO Auto-generated method stub if(success) { System.out.println("LIGNE DISPONIBLE"); ligne.setControlee(true); } else System.out.println("LIGNE INDISPONIBLE"); } }); } catch (IOException e) { e.printStackTrace(); } } }).start(); } } }
074b0076-7a4e-4f7e-8f2e-b16685777d09
5
public void fillInGenSet(Collection in, Collection gen) { if (this instanceof LocalVarOperator) { LocalVarOperator varOp = (LocalVarOperator) this; if (varOp.isRead() && in != null) in.add(varOp.getLocalInfo()); if (gen != null) gen.add(varOp.getLocalInfo()); } for (int i = 0; i < subExpressions.length; i++) subExpressions[i].fillInGenSet(in, gen); }
3473f68b-d17e-488a-98d5-70543b99416d
3
public static void showPerson(Person person, String caption) { System.out.print("\n" + caption + ": "); if (person == null) System.out.println(" not known"); else { System.out.println(person.getName().getFullName()); Date birth = person.getBirthDate(); if (birth != null) System.out.println("\tBorn: " + birth); Date death = person.getDeathDate(); if (death != null) System.out.println("\tDied: " + death); } }
e17f1d79-b6fb-44e6-a482-0e0f0ea0071c
2
public List<Fleet> EnemyFleets() { List<Fleet> r = new ArrayList<Fleet>(); for (Fleet f : fleets) { if (f.Owner() != 1) { r.add(f); } } return r; }
125f7a0c-ac46-4133-9807-9cef8c9e1d36
9
@Override @SuppressWarnings({ "nls", "boxing" }) protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder enc) { List<?> list = (List<?>) oldInstance; int size = list.size(); for (int i = 0; i < size; i++) { Expression getterExp = new Expression(oldInstance, "get", new Object[] { i }); try { // Calculate the old value of the property Object oldVal = getterExp.getValue(); // Write the getter expression to the encoder enc.writeExpression(getterExp); // Get the target value that exists in the new environment Object targetVal = enc.get(oldVal); // Get the current property value in the new environment Object newVal = null; try { newVal = new Expression(newInstance, "get", new Object[] { i }).getValue(); } catch (IndexOutOfBoundsException ex) { // The newInstance has no elements, so current property // value remains null } /* * Make the target value and current property value equivalent * in the new environment */ if (null == targetVal) { if (null != newVal) { // Set to null Statement setterStm = new Statement(oldInstance, "add", new Object[] { null }); enc.writeStatement(setterStm); } } else { PersistenceDelegate pd = enc .getPersistenceDelegate(targetVal.getClass()); if (!pd.mutatesTo(targetVal, newVal)) { Statement setterStm = new Statement(oldInstance, "add", new Object[] { oldVal }); enc.writeStatement(setterStm); } } } catch (Exception ex) { enc.getExceptionListener().exceptionThrown(ex); } } }
597608f1-14fd-4268-a0b1-e59c0d1f1b74
8
public synchronized boolean moveItem(FieldItem item, Position initial, Position finalPosition){ if ((finalPosition.getX() <= this.getXLength()) || (finalPosition.getY() <= this.getYLength())) return false; if ((initial.getX() <= this.getXLength()) || (initial.getY() <= this.getYLength())) return false; for (int i = 0; i < 10; i++) { if ((field[initial.getX()][initial.getY()] == item) && (field[finalPosition.getX()][finalPosition.getY()] == null)) { field[initial.getX()][initial.getY()] = null; field[finalPosition.getX()][finalPosition.getY()] = item; } try {Thread.currentThread().sleep(100); } catch (InterruptedException ex) {} } return false; }
5e9dfdaa-221f-4902-9eb7-04cb2748ba64
4
private void sendProcessingError(Throwable t, ServletResponse response) { String stackTrace = getStackTrace(t); if (stackTrace != null && !stackTrace.equals("")) { try { response.setContentType("text/html"); PrintStream ps = new PrintStream(response.getOutputStream()); PrintWriter pw = new PrintWriter(ps); pw.print("<html>\n<head>\n<title>Error</title>\n</head>\n<body>\n"); //NOI18N // PENDING! Localize this for next official release pw.print("<h1>The resource did not process correctly</h1>\n<pre>\n"); pw.print(stackTrace); pw.print("</pre></body>\n</html>"); //NOI18N pw.close(); ps.close(); response.getOutputStream().close(); } catch (Exception ex) { } } else { try { PrintStream ps = new PrintStream(response.getOutputStream()); t.printStackTrace(ps); ps.close(); response.getOutputStream().close(); } catch (Exception ex) { } } }
e55973aa-06a9-423f-b66a-3269972e5dd2
8
private void drawRoad(int x0, int y0, int x1, int y1) { boolean xFirst = random.nextBoolean(); if (xFirst) { while (x0 > x1) { data[x0][y0] = 0; level[x0--][y0] = TILE_ROAD; } while (x0 < x1) { data[x0][y0] = 0; level[x0++][y0] = TILE_ROAD; } } while (y0 > y1) { data[x0][y0] = 0; level[x0][y0--] = TILE_ROAD; } while (y0 < y1) { data[x0][y0] = 0; level[x0][y0++] = TILE_ROAD; } if (!xFirst) { while (x0 > x1) { data[x0][y0] = 0; level[x0--][y0] = TILE_ROAD; } while (x0 < x1) { data[x0][y0] = 0; level[x0++][y0] = TILE_ROAD; } } }
7a7b9663-f58b-4a61-b842-cbd98279fb13
5
public void insert(Node n) { Node current = head; boolean flag = false; if (n.getData() < current.getData()) { // case 1: new node becomes head n.setNext(head); head = n; }/* if */else { while (current.getNext() != null && !flag) { if (n.getData() <= current.getNext().getData()) { // case2: // insert mode // in the // middle n.setNext(current.getNext()); // Set Fat to point to hat current.setNext(n); // Test what would happen if you change // current.setNext(n) with // n.setNext(current.getNext()) flag = true; }// if(n.getData()<= else { current = current.getNext(); }// if/else (n<current.getNext()) }// while(current.getNext()!=null) if (!flag) { // case 3: new node gets appended current.setNext(n); } }// if/else }// insert(Node n)
0e93f59a-13d0-47c7-b78e-7fcc569c9588
9
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; EmployeeHistory other = (EmployeeHistory) obj; if (employee == null) { if (other.employee != null) return false; } else if (!employee.equals(other.employee)) return false; if (lastUpdate == null) { if (other.lastUpdate != null) return false; } else if (!lastUpdate.equals(other.lastUpdate)) return false; return true; }
68c283d8-bf2a-41b1-8e43-9933951469bf
2
public void testPropertyCompareToMonth() { YearMonth test1 = new YearMonth(TEST_TIME1); YearMonth test2 = new YearMonth(TEST_TIME2); assertEquals(true, test1.monthOfYear().compareTo(test2) < 0); assertEquals(true, test2.monthOfYear().compareTo(test1) > 0); assertEquals(true, test1.monthOfYear().compareTo(test1) == 0); try { test1.monthOfYear().compareTo((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.monthOfYear().compareTo(dt2) < 0); assertEquals(true, test2.monthOfYear().compareTo(dt1) > 0); assertEquals(true, test1.monthOfYear().compareTo(dt1) == 0); try { test1.monthOfYear().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} }
79502247-cbc5-46f0-9150-b98e58a57db2
4
@EventHandler public void onPlayerJoin(final PlayerJoinEvent e) { final Player player = e.getPlayer(); if (Game.started || Lobby.started) { //Teleport player to lobby player.teleport(new Location(Bukkit.getWorld(TIMV.config.getString("Worldname")), TIMV.config.getInt("Spawn.x"), TIMV.config.getInt("Spawn.y"), TIMV.config.getInt("Spawn.z"))); } else if (!Lobby.started && Game.started) { //TODO SET SPECTATOR } }
2de086ec-f777-4ccb-8cbd-2e0d4b76573b
9
private void startRootElement(final String qName, final Attributes attributes) throws SAXException, ObjectDescriptionException { if (qName.equals(ClassModelTags.INCLUDE_TAG)) { if (this.isInclude) { Log.warn("Ignored nested include tag."); return; } final String src = attributes.getValue(ClassModelTags.SOURCE_ATTR); try { final URL url = new URL(this.resource, src); startIncludeHandling(url); parseXmlDocument(url, true); endIncludeHandling(); } catch (Exception ioe) { throw new ElementDefinitionException (ioe, "Unable to include file from " + src); } } else if (qName.equals(ClassModelTags.OBJECT_TAG)) { setState(IN_OBJECT); final String className = attributes.getValue(ClassModelTags.CLASS_ATTR); String register = attributes.getValue(ClassModelTags.REGISTER_NAMES_ATTR); if (register != null && register.length() == 0) { register = null; } final boolean ignored = "true".equals(attributes.getValue(ClassModelTags.IGNORE_ATTR)); if (!startObjectDefinition(className, register, ignored)) { setState(IGNORE_OBJECT); } } else if (qName.equals(ClassModelTags.MANUAL_TAG)) { final String className = attributes.getValue(ClassModelTags.CLASS_ATTR); final String readHandler = attributes.getValue(ClassModelTags.READ_HANDLER_ATTR); final String writeHandler = attributes.getValue(ClassModelTags.WRITE_HANDLER_ATTR); handleManualMapping(className, readHandler, writeHandler); } else if (qName.equals(ClassModelTags.MAPPING_TAG)) { setState(MAPPING_STATE); final String typeAttr = attributes.getValue(ClassModelTags.TYPE_ATTR); final String baseClass = attributes.getValue(ClassModelTags.BASE_CLASS_ATTR); startMultiplexMapping(baseClass, typeAttr); } }
6424dea3-0df2-4629-b836-0a17f8225366
2
public int getNumberOfWords() { int count = 0; for (SentencePart sp : sentence) { if (sp instanceof Word) { count++; } } return count; }
a820f292-69c5-4a4e-9b2b-2072fb996c2c
0
@AfterClass public static void tearDownClass() { }
38548658-5b70-4f71-ac0d-d85c56c2a9e1
1
public float evaluate_float(Object[] dl) throws Throwable { if (Debug.enabled) Debug.println("Wrong evaluateXXXX() method called,"+ " check value of getType()."); return 0.0F; };
cc644c16-50a8-4ea5-8874-9a9b56619c00
7
public boolean isColumnUsedInTheSameQueryWithTable(String tableA, String columnA, String tableB) { for (Query q : queries) { List<String> relations = q.getRelations(); if (relations.size() > 1) { if (relations.contains(tableA) && relations.contains(tableB)) { List<QueryAttribute> projections = q.getProjections(); for (QueryAttribute qa : projections) { if (qa.getTableName().equals(tableA) && qa.getColumnName().equals(columnA)) { return true; } } } } } return false; }
618d1293-6848-4960-97cd-2090ea79efc6
9
protected void loadFields(com.sforce.ws.parser.XmlInputStream __in, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException, com.sforce.ws.ConnectionException { super.loadFields(__in, __typeMapper); __in.peekTag(); if (__typeMapper.isElement(__in, CreatedBy__typeInfo)) { setCreatedBy((com.sforce.soap.enterprise.sobject.User)__typeMapper.readObject(__in, CreatedBy__typeInfo, com.sforce.soap.enterprise.sobject.User.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, CreatedById__typeInfo)) { setCreatedById(__typeMapper.readString(__in, CreatedById__typeInfo, java.lang.String.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, CreatedDate__typeInfo)) { setCreatedDate((java.util.Calendar)__typeMapper.readObject(__in, CreatedDate__typeInfo, java.util.Calendar.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, DataCategoryGroupName__typeInfo)) { setDataCategoryGroupName(__typeMapper.readString(__in, DataCategoryGroupName__typeInfo, java.lang.String.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, DataCategoryName__typeInfo)) { setDataCategoryName(__typeMapper.readString(__in, DataCategoryName__typeInfo, java.lang.String.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, IsDeleted__typeInfo)) { setIsDeleted((java.lang.Boolean)__typeMapper.readObject(__in, IsDeleted__typeInfo, java.lang.Boolean.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, Parent__typeInfo)) { setParent((com.sforce.soap.enterprise.sobject.Question)__typeMapper.readObject(__in, Parent__typeInfo, com.sforce.soap.enterprise.sobject.Question.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, ParentId__typeInfo)) { setParentId(__typeMapper.readString(__in, ParentId__typeInfo, java.lang.String.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, SystemModstamp__typeInfo)) { setSystemModstamp((java.util.Calendar)__typeMapper.readObject(__in, SystemModstamp__typeInfo, java.util.Calendar.class)); } }
b6fbf4ca-82a3-49fd-a648-9a9f428daca4
9
public void initProvider(int port, List<Object> classesServices) { System.out.println("[Provider] : Start server on port " + port); // Create the server WebServer webServer = new WebServer(port); XmlRpcServer xmlRpcServer = webServer.getXmlRpcServer(); // Handle the services class PropertyHandlerMapping phm = new PropertyHandlerMapping(); for (Object classService : classesServices) { try { if(classService instanceof ClassInterfaceRelation) { ClassInterfaceRelation relTmp = (ClassInterfaceRelation)classService; phm.addHandler(relTmp.getCorrespondingInterface().getName(), relTmp.getCorrespondingClass()); System.out.println("[Provider] : Now handle " + relTmp.getCorrespondingInterface().getSimpleName()); } else if(classService instanceof Class) { Class classTmp = (Class)classService; if(classTmp.isInterface()) { System.err.println("[Provider] : Can't handle an interface " + classTmp.getSimpleName()); } else { phm.addHandler(classTmp.getName(), classTmp); System.out.println("[Provider] : Now handle " + classTmp.getSimpleName()); } } else { System.err.println("[Provider] : An object can't be handled"); } } catch (XmlRpcException e) { // TODO Auto-generated catch block e.printStackTrace(); System.err.println("[Provider] : Can't handle " + classService); } } xmlRpcServer.setHandlerMapping(phm); XmlRpcServerConfigImpl serverConfig = (XmlRpcServerConfigImpl) xmlRpcServer .getConfig(); serverConfig.setEnabledForExtensions(true); serverConfig.setContentLengthOptional(false); // Start the server System.out.println("[Provider] : Finish to configure services"); System.out.println("[Provider] : Available functions :"); try { for (String line : phm.getListMethods()) { System.out.println("\t" + line); } } catch (XmlRpcException e) { // TODO Auto-generated catch block e.printStackTrace(); System.err.println("[Provider] : Can't list functions."); } try { webServer.start(); System.out.println("[Provider] : Server started."); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.err .println("[Provider] : Can't start server"); } // Retrieve and save server adress InetAddress addr; try { addr = InetAddress.getLocalHost(); // Get IP Address byte[] adress = addr.getAddress(); ipAdress = convertRawToIpAddress(adress); System.out.println("[Provider] : Launch on adress " + ipAdress); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); System.err.println("[Provider] : Can't retrieve his adress."); } }
67c36552-50ce-4b78-83bd-873c0f552a12
9
public String getNumberDesc() { int n = getNumber(); if (n < 5) return "mało"; if (n < 10) return "kilka"; if (n < 20) return "watacha"; if (n < 50) return "dużo"; if (n < 100) return "horda"; if (n < 250) return "masa"; if (n < 500) return "mrowie"; if (n < 1000) return "rzesza"; if (n < 50000) return "legion"; return "wow such power much numbers"; // ;) }
0b1c6476-9d04-43c6-9b5c-5f364d4bff75
8
final public void showTable() throws ParseException { /*@bgen(jjtree) showTable */ SimpleNode jjtn000 = new SimpleNode(JJTSHOWTABLE); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); jjtn000.jjtSetFirstToken(getToken(1)); try { jj_consume_token(SHOW); jj_consume_token(TABLE); tableName(); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); jjtn000.jjtSetLastToken(getToken(0)); } } }
b8194cf2-eca6-430f-9b6e-7f96cd4541f6
5
private void displayWinner(Graphics g) { g.setColor(Color.black); if ((game.getPlayer1Color() == 4) || (game.getPlayer2Color() == 4)) g.setColor(Color.cyan); g.setFont(new Font("Times", Font.BOLD, 75)); if (game.getGameMode() == 1) { if (game.getTurn() == 1) { g.drawString(game.getP2Name() + " wins!", 100, 400); } else { g.drawString(game.getP1Name() + " wins!", 100, 400); } } else { if (game.getTurn() == 1) g.drawString("YOU LOSE!", 100, 400); else g.drawString("YOU WIN!", 100, 400); } game.setGameIsOver(true); }
be250306-d3a8-4038-8dd3-90bf6cdd18eb
4
public void Interface() { int buffersize = 1024; char stdInbuffer[] = new char[buffersize]; // makes reading from keyboard/shell ready BufferedReader stdIn = new BufferedReader(new InputStreamReader( System.in)); // 1. read from keyboard // 2. send to Server // 3. catch server answer // 4. start by 1 int stdInCounter; System.out.println("********* welcome to UserInterface **********"); try { while (true) { System.out.println("please insert a command: (e.g. HELP) "); // 1.1 read from Keyboard/shell into a buffer stdInCounter = stdIn.read(stdInbuffer); // 1.2 convert char to string String stdInString = new String(stdInbuffer, 0, stdInCounter); if (inputRFCHandling(stdInString) == true) { System.out.println("command transfered"); } else { msg.output().println(stdInString); } /* * closing userInterface */ if (inputQuit(stdInString) == true) { //FtpServerAnswerMessages.readInputStream(); break; } //FtpServerAnswerMessages.readInputStream(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
1df060bb-cde8-4355-8ebd-ee7116b5abb9
8
public void shareDirAccepted(String parentPath, String dirName, String friendName, String mod, String expo) { Map<String, Map<SafeFile, Vector<SafeFile>>> m = user.getFileMap(); Set<SafeFile> safeFiles = m.get(user.getUsername()).keySet(); String dirPath; if (!parentPath.equals("null")) { dirPath = user.getUsername() + "\\" + parentPath + "\\" + dirName; // path: username\parentPath\dirName } else { dirPath = user.getUsername() + "\\" + dirName; } for(SafeFile sf : safeFiles) { if (sf.getFilePath().equals(dirPath)) { sf.addFriend(friendName); shareSubFiles(safeFiles, sf.getFilePath(), friendName); } } BigInteger n = new BigInteger(mod); BigInteger e = new BigInteger(expo); RSAPublicKeySpec spec = new RSAPublicKeySpec(n, e); try { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); RSAPublicKey pk = (RSAPublicKey) keyFactory.generatePublic(spec); publicKeyMap.put(friendName, pk); // use pk to encrypt aesFileString, then put it on AWS String aesfilePath = user.getUsername() + "\\" + user.getUsername() + "_" + friendName + "_AESKEY"; File aesStringFile = new File(aesfilePath); if (aesStringFile.createNewFile()) { //System.out.println("Encrypted AES String file is created in local, " + aesfilePath); } else { System.out.println("Encrypted AES String file exists in local, " + aesfilePath); } Cipher cipherAES = Cipher.getInstance("RSA"); cipherAES.init(Cipher.ENCRYPT_MODE, pk); String encryptedAESInfo = parseByte2HexStr(cipherAES.doFinal(aesFileString.getBytes())); BufferedWriter outputAES = new BufferedWriter(new FileWriter(aesfilePath)); outputAES.write(encryptedAESInfo); outputAES.close(); System.out.println("Generated AES File Key string for " + friendName + ", "+ aesfilePath); //System.out.println("AES File Key string: " + aesFileString); // System.out.println("Encrypted AES File Key string: " + encryptedAESInfo); String keyAES = aesfilePath.replace("\\", "/"); fileStorage.putObject("SafeBox", keyAES, aesStringFile); //System.out.println("Encrypted AES String file uploaded successfully on AWS, " + aesfilePath); // send notification to server String os = String.format("%d;%s;%s;%s;%s", SHARE_AES_KEY, user.getUsername(), parentPath, dirName, friendName); //System.out.println(os); outToServer.println(os); outToServer.flush(); if (aesStringFile.delete()) { //System.out.println("Encrypted AES String file is deleted in local, " + aesfilePath); } } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which means your request made it " + "to Amazon S3, but was rejected with an error response for some reason."); System.out.println("Error Message: " + ase.getMessage()); System.out.println("HTTP Status Code: " + ase.getStatusCode()); System.out.println("AWS Error Code: " + ase.getErrorCode()); System.out.println("Error Type: " + ase.getErrorType()); System.out.println("Request ID: " + ase.getRequestId()); } catch (AmazonClientException ace) { System.out.println("Caught an AmazonClientException, which means the client encountered " + "a serious internal problem while trying to communicate with S3, " + "such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } catch (Exception exc) { System.out.println("Failed to generate RSA key pairs!\n" + exc.toString()); } //createShareAESKey(String friendName, String mod, String expo); }
b9483de9-fb3e-4b8b-8e00-0b0de00de96b
2
public DefaultComboBoxModel<String> buildSelectCombo() { DefaultComboBoxModel<String> model = new DefaultComboBoxModel<String>(); if(!MapPanel.actors.isEmpty()) { for(int x = 0; x<MapPanel.actors.size(); x++) { model.addElement(MapPanel.actors.get(x).getID()); } } return model; }
8c024bc2-5c4c-4614-916c-b2d736fba4c4
2
public void initRequire(String[] L) { for (int i = 0; i < L.length; i++) { if (!require.containsKey(L[i])) { require.put(L[i], 1); } else require.put(L[i], require.get(L[i]) + 1); } }
93c5ca66-7e19-4fa7-b636-58e4d7edbdf2
4
void jasmin(PrintStream out) { super.jasmin(out); out.print(lvtIndex); if (wideDesc.equals("iinc")) out.print(" " + value); }
38af9d7b-6190-4e45-8cec-3086b6d65dc5
3
private static void isort(String[] a, String[] aux, int l, int h, int d) { // insertion sort for (int i = l; i <= h; i++) for (int j = i; j > l && less(a[j], a[j - 1], d); j--) { // swap a[j - 1], a[j] String temp = a[j - 1]; a[j - 1] = a[j]; a[j] = temp; } }
651fd65c-58e1-4d1a-8f7e-14a7234cc73a
7
private void check_sig(WebauthResponse response) throws WebauthException { try { Certificate cert = keyStore.getCertificate(keyPrefix + response.get("kid")); if (cert == null) { throw new WebauthException("Failed to retrieve a key with " + "alias " + keyPrefix + response.get("kid") + " from the key store"); } WebauthDecoder decoder = new WebauthDecoder(); byte[] sigBytes = decoder.decodeBuffer(response.get("sig")); Signature signature = Signature.getInstance(SIGNATURE_SCHEME); signature.initVerify(cert); signature.update(response.getRawData().getBytes()); if (!signature.verify(sigBytes)) { throw new WebauthException( "Unable to verify response signature"); } } catch (KeyStoreException e) { throw new WebauthException("Validator keyStore object " + "not correctly initialized"); } catch (IOException e) { throw new WebauthException("Failed to decode signature string"); } catch (NoSuchAlgorithmException e) { throw new WebauthException("No security provider implementing " + "signature scheme " + SIGNATURE_SCHEME + " available in this VM"); } catch (InvalidKeyException e) { throw new WebauthException("Key with alias " + keyPrefix + response.get("kid") + " in the key store is invalid"); } catch (SignatureException e) { throw new WebauthException("Failed to verify signature - " + "signature object is not initialized"); } }
a8c3c5f0-d8c4-44d2-9a99-ed244a0bb0c6
8
@Test public void testTransductionEmission() { Source<Boolean> src = new SourceFixe("1"); TransducteurEmission te = new TransducteurEmission(); src.connecter(te); try { src.emettre(); te.emettre(); } catch (InformationNonConforme e) { e.printStackTrace(); } // Verification nb Elements (pour 1 bit en entrée, 3 en sortie) assertTrue(te.getInformationEmise().nbElements() == 3); // Verification de la bonne sequence de bits en sortie (1 0 1) int i = 0; if(te.getInformationEmise().iemeElement(i++).booleanValue() == false)fail(); if(te.getInformationEmise().iemeElement(i++).booleanValue() == true)fail(); if(te.getInformationEmise().iemeElement(i).booleanValue() == false)fail(); src = new SourceFixe("0"); te = new TransducteurEmission(); src.connecter(te); try { src.emettre(); te.emettre(); } catch (InformationNonConforme e) { e.printStackTrace(); } // Verification nb Elements (pour 1 bit en entrée, 3 en sortie) assertTrue(te.getInformationEmise().nbElements() == 3); // Verification de la bonne sequence de bits en sortie ( 0 1 0 ) i = 0; if(te.getInformationEmise().iemeElement(i++).booleanValue() == true)fail(); if(te.getInformationEmise().iemeElement(i++).booleanValue() == false)fail(); if(te.getInformationEmise().iemeElement(i).booleanValue() == true)fail(); }
0d44438a-76db-4e38-a255-0e643a77f249
4
public void standardQuery(String query) { Connection connection = null; Statement statement = null; try { connection = this.open(); statement = connection.createStatement(); statement.executeQuery(query); statement.close(); connection.close(); } catch (SQLException ex) { if (ex.getMessage().toLowerCase().contains("locking") || ex.getMessage().toLowerCase().contains("locked")) { //this.writeError("Locked",false); retryQuery(query); } else { if(!(ex.toString().contains("not return ResultSet"))) this.writeError("Error at SQL Query: " + ex.getMessage(), false); } } }
3628bf1a-7767-44e8-b622-d25ccc12d21a
4
public Point[] get3FrontVectors() { switch (this) { case UP: return new Point[] { new Point(0, -1), new Point(-1, -1), new Point(1, -1) }; case LEFT: return new Point[] { new Point(-1, 0), new Point(-1, 1), new Point(-1, -1) }; case DOWN: return new Point[] { new Point(0, 1), new Point(1, 1), new Point(-1, 1) }; case RIGHT: return new Point[] { new Point(1, 0), new Point(1, -1), new Point(1, 1) }; default: throw new IllegalStateException(); } }
2850a271-566b-4e21-850f-39bacff2d54f
8
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SSHCredentials that = (SSHCredentials) o; return !(host != null ? !host.equals(that.host) : that.host != null) && !(pass != null ? !pass.equals(that.pass) : that.pass != null) && !(userName != null ? !userName.equals(that.userName) : that.userName != null); }
10a9fbaf-81ae-41d6-9514-0bc14bf10b1d
9
public static <T> T awaitState(final long timeoutMillis, Object compareTo, final T object) { final Matcher matcher = toMatcher(compareTo); final Class<?> matcherType = Primitives.getRealClass(matcher.getType()); return (T) ProxyUtil.newProxy(object.getClass(), new InvocationHandler() { @Override public Object invoke(Object o, Method method, Object[] args) throws Throwable { if (!Primitives.getRealClass(method.getReturnType()).isAssignableFrom(matcherType)) { throw new UsageError(method + " is not comparable with " + matcherType); } long t = System.currentTimeMillis(); while (true) { Object result = null; Exception exception = null; try { result = method.invoke(object, args); if (matcher.matches(result)) { return result; } } catch (IllegalAccessException e) { throw e; } catch (IllegalArgumentException e) { throw e; } catch (InvocationTargetException e) { exception = e; } Thread.sleep(20); if (System.currentTimeMillis() - t > timeoutMillis) { if (exception != null) { throw new VerificationError("await state timed out. Got exception: " + exception.getMessage(), exception); } throw new VerificationError("await state timed out. Expected " + matcher + " but got " + result); } } } }); }
dccbb497-507d-49c8-8626-40c6cd88d787
6
public static void main(String[] args) throws Exception { HashMap<String, HashMap<Long, ContextCount>> outerMap = new HashMap<String, HashMap<Long, ContextCount>>(); List<PairedReads> pairedList = getAllBurkholderiaPairs(); for(int x=0; x < pairedList.size(); x++) { PairedReads pr = pairedList.get(x); File countFile1 = FileUtils.getCountsFile(pr.getFirstFileName()); File countFile2 = FileUtils.getCountsFile(pr.getSecondFileName()); if( countFile1.exists() && countFile2.exists()) { System.out.println("MATCH: " + countFile1.getName()); HashMap<Long, ContextCount> map1 = getFromCache(countFile1, outerMap); HashMap<Long, ContextCount> map2 = getFromCache(countFile2, outerMap); ApplyWeightedChiSquare.writePValues(B_VALUE, map1, map2, FileUtils.getSNPResultsFile(countFile1, countFile2)); for( int y=x+1; y < pairedList.size(); y++) { PairedReads pr2 = pairedList.get(y); File countFile2_1 = FileUtils.getCountsFile(pr2.getFirstFileName()); File countFile2_2 = FileUtils.getCountsFile(pr2.getSecondFileName()); if( countFile2_1.exists() && countFile2_2.exists()) { HashMap<Long, ContextCount> map2_1 = getFromCache(countFile2_1, outerMap); HashMap<Long, ContextCount> map2_2 = getFromCache(countFile2_2, outerMap); ApplyWeightedChiSquare.writePValues(B_VALUE, map1, map2_1, FileUtils.getSNPResultsFile(countFile1, countFile2_1)); ApplyWeightedChiSquare.writePValues(B_VALUE, map1, map2_2, FileUtils.getSNPResultsFile(countFile1, countFile2_2)); ApplyWeightedChiSquare.writePValues(B_VALUE, map2, map2_1, FileUtils.getSNPResultsFile(countFile2, countFile2_1)); ApplyWeightedChiSquare.writePValues(B_VALUE, map2, map2_2, FileUtils.getSNPResultsFile(countFile2, countFile2_2)); } } } } }
729144a0-51c6-4ef0-8038-ca4a2b7ab053
1
public int attackSpecial(Character opponent){ int damage; System.out.println(_name+" calls upon his CS Minions!"); damage = minions(opponent); if ( damage < 0 ) damage = 0; opponent.lowerHP( damage ); return damage;}
29f8a27b-5639-470c-bac8-42b9283018d6
5
protected void fillData() { setLayout(new BorderLayout()); model.clearList(); JPanel vest = new JPanel(); vest.setLayout(new GridBagLayout()); JPanel center = new JPanel(); center.setLayout(new BorderLayout()); GridBagConstraints c = new GridBagConstraints(); firemen = new JTable(); firemen.setRowHeight(28); JScrollPane scrl = new JScrollPane(); scrl.setViewportView(firemen); scrl.setPreferredSize(new Dimension(0, 200)); firemen.setModel(model); c.fill = GridBagConstraints.CENTER; if (timesheets.getCar() == null) { c.gridx = 0; c.gridy = 1; vest.add(new JLabel(new ImageIcon(timesheets.getStation().getIconPath())), c); JLabel stationInfo = new JLabel("" + timesheets.getStation().getName()); stationInfo.setFont(myFont); c.gridx = 0; c.gridy = 0; vest.add(stationInfo, c); } else { c.gridx = 0; c.gridy = 1; vest.add(new JLabel(new ImageIcon(timesheets.getCar().getIconPath())), c); JLabel carInfo = new JLabel("Bil Nr.: " + timesheets.getCar().getCarNr()); carInfo.setFont(myFont); c.gridx = 0; c.gridy = 0; vest.add(carInfo, c); } for (Time_Sheet a : timesheets.getTeamleaders()) { model.addTimeSheet(a); } for (Time_Sheet a : timesheets.getChauffeurs()) { model.addTimeSheet(a); } for (Time_Sheet a : timesheets.getFiremen()) { model.addTimeSheet(a); } for (Time_Sheet a : timesheets.getStationDutyFiremen()) { model.addTimeSheet(a); } center.add(scrl, BorderLayout.CENTER); add(vest, BorderLayout.WEST); add(center, BorderLayout.CENTER); center.add(getAproveCarPanel(), BorderLayout.SOUTH); addCellRenderers(); }
d467b5a3-cd6c-4393-9c00-5fccb7023cf8
5
@Override synchronized public void addOrder(final Order order) { Connection conn = null; PreparedStatement stmt = null; try { conn = dataSource.getConnection(); stmt = conn.prepareStatement("INSERT INTO \"ORDER\" (ORDER_DATE,USER_ID) VALUES(?,?)"); stmt.setTimestamp(1,new Timestamp(new Date().getTime())); stmt.setString(2, order.getUser_ID()); stmt.executeUpdate(); } catch (SQLException ex1) { throw new RuntimeException(ex1); } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException ex1) { Logger.getLogger(BookDAO.class.getName()).log(Level.SEVERE, null, ex1); } } if (conn != null) { try { conn.close(); } catch (SQLException ex1) { Logger.getLogger(BookDAO.class.getName()).log(Level.SEVERE, null, ex1); } } } }
ca6227ec-b1e7-47d0-9218-14bf4b695dbe
0
@BeforeClass public void setUp() { MeiyoVisitor.createVisitor( new AbstractVisitorConfiguration() { @Override public void configure() { handleType().annotatedWith( ClassAnnotation.class ).withHandler( new AnnotationHandler<Class, ClassAnnotation>() { public void handle( Class annnotatedElement, ClassAnnotation annotation ) { foundClassAnnotation = true; } } ); handleConstructor().annotatedWith( ConstructorAnnotation.class ).withHandler( new AnnotationHandler<Constructor, ConstructorAnnotation>() { public void handle( Constructor annnotatedElement, ConstructorAnnotation annotation ) { foundConstructorAnnotation = true; } } ); handleMethod().annotatedWith( MethodAnnotation.class ).withHandler( new AnnotationHandler<Method, MethodAnnotation>() { public void handle( Method annnotatedElement, MethodAnnotation annotation ) { foundMethodAnnotation = true; } } ); } } ).visit( AnnotatedBean.class ); }
e6004adf-adaf-4985-89c9-1e9117ad2958
2
private boolean getBoolean(CycSymbol paramName) { Object rawValue = get(paramName); if (rawValue instanceof Boolean) { return (Boolean) rawValue; } else { rawValue = getDefaultInferenceParameterDescriptions().getDefaultInferenceParameters().get(paramName); return (rawValue instanceof Boolean) ? (Boolean) rawValue : false; } }
fdee4765-5433-46f2-80fa-11ff25dfd203
5
*/ public byte[] getFinalDestination() { //return mesh address if available if(sixLoWPANpacket != null && sixLoWPANpacket.isMeshHeader()){ return sixLoWPANpacket.getFinalAddress(); //else look for an existing sixlowpan address } else if(sixLoWPANpacket != null && sixLoWPANpacket.isIphcHeader() && sixLoWPANpacket.getDestination() != null){ return sixLoWPANpacket.getDestination(); //otherwise it's really just null } else { return null; } }
2c63a402-f6d5-4fc5-a671-440edbb2cd6d
6
public static String getResultName(int result) { String value = null; switch (result) { case -2: value = "Pending"; break; case 0: value = "Accepted"; break; case 1: value = "Rejected"; break; case 2: value = "No output"; break; case 3: value = "Compilation error"; break; case 4: value = "Runtime error"; } return value; }
d9430c86-3810-46d1-b9f4-862287c79318
2
private boolean hasTag(String version) { for (final String string : Updater.NO_UPDATE_TAG) { if (version.contains(string)) { return true; } } return false; }
09e830f1-8bcc-4d21-a723-41e86cdcd6ea
0
public void setManaged(boolean managed) { this.managed = managed; }
1407cadd-f813-43d8-87b8-0468b98a1851
9
private void updateLocalTreesCorrelation(Genealogy genealogy) throws NaturalSetException { HashMap<NaturalSet, NaturalSetCollection> localTreesBiPartitions = genealogy.localTreesBiPartitions(); ArrayList<NaturalSet> frames = new ArrayList<NaturalSet>(localTreesBiPartitions.keySet()); Collections.sort(frames); for(NaturalSet x : frames){ for(NaturalSet y : frames){ if(x.compareTo(y) >= 0){ NaturalSetCollection xbp = localTreesBiPartitions.get(x); NaturalSetCollection ybp = localTreesBiPartitions.get(y); int value = xbp.intersectCount(ybp); if(env().stringProperty("DistanceMetric").equals("bs")){ value = xbp.size() + ybp.size() - haplotypeDomain().cardinality() - value; } int xmin = x.min(), xmax = x.max(), ymin = y.min(), ymax = y.max(); for(int i=xmin; i<=xmax; i++){ for(int j=ymin; j<=ymax && j<=i; j++){ if(snpDomain.contains(i) && snpDomain.contains(j)){ treeCorrelationCount[snpDomain.toRelativeCoordinate(i)][snpDomain.toRelativeCoordinate(j)] += value; } } } } } } }
8ddcb872-6d92-47e3-9887-ee2c03304424
2
private void processMoveFromBoard(MouseEvent e) { int row = findRow(e.getY()); int col = findCol(e.getX()); int index = row * 4 + col; if (index > -1 && index < 12) { activeMove = new CardMoveImpl(index, CardMoveImpl.MOVE_TYPE_FROM.FROM_BOARD); } }
86f15879-f7f3-4b15-9a15-ca0c52a4d961
7
public static boolean hasActions(Node<?> root) { Node<?> node = root; for (;;) { if (node instanceof ActionNode) return true; if (node instanceof UnaryNode) { node = ((UnaryNode) node).sibling; continue; } if (node instanceof BinaryNode) { BinaryNode n = (BinaryNode) node; if (hasActions(n)) return true; node = n.secondSibling; continue; } return false; } }
d8dd2edb-ad3b-43fd-9cf3-831183a4c941
8
@Override public void run(Player interact, Entity on, InteractionType interaction) { if(interaction == InteractionType.RIGHT){ if(type == PotionType.MANA){ if(interact.getFoodLevel() == 20) return; interact.setItemInHand(new ItemStack(ItemType.EMPTY_BOTTLE.getMaterial(), 1)); interact.setFoodLevel(20); }else if(type == PotionType.HEALTH){ ClassType playerClass = PluginData.getPlayerData(interact).getPlayerClass(); if(playerClass == null) return; if(interact.getHealth() == playerClass.getMaxHealth()) return; interact.setHealth(playerClass.getMaxHealth()); interact.setItemInHand(new ItemStack(ItemType.EMPTY_BOTTLE.getMaterial(), 1)); } } //shatter bottle, do damage else if(interaction == InteractionType.DAMAGE){ if(on instanceof LivingEntity){ LivingEntity onLe = (LivingEntity) on; onLe.damage(3); Broadcast.excelemation("You shatter your bottle on an enemy, destroying it.", interact); interact.setItemInHand(new ItemStack(Material.AIR, 1)); interact.getWorld().playEffect(onLe.getLocation(), Effect.POTION_BREAK, 1.0f); } } }
f60a687e-7b0d-4629-b0c9-14f1b110007d
3
private void assertNotPrimitiveTargetType(Class<?> sourceType, Class<?> targetType) { if (targetType.isPrimitive()) { throw new IllegalArgumentException("A null value cannot be assigned to primitive type " + targetType.getName()); } }
944352d2-2291-4c80-9628-14d408237fa3
1
@Override public void paint(Graphics g, JComponent c) { Graphics2D g2 = (Graphics2D) g.create(); if (clockwise) { g2.rotate(Math.PI / 2, c.getSize().width / 2, c.getSize().width / 2); } else { g2.rotate(-Math.PI / 2, c.getSize().height / 2, c.getSize().height / 2); } super.paint(g2, c); }
117c4531-4b3c-483b-a1af-94afd4e5e1cd
7
private void initGraph() { Node firstNode = new SimpleNode(0, Node.Types.SIMPLE, defaultResistance); nodes.add(firstNode); for(int i = 1; i < kNearestNeighbors / 2; i++) { Node nextNode = new SimpleNode(i, Node.Types.SIMPLE, defaultResistance); nextNode.addNeighbor(nodes.get(i-1), delaysDistribution.getNextValue(), false); nodes.add(nextNode); edges.add(new Edge(i-1, i)); if (i > 1) { for (int j = i-2; j >= 0; j--) { nextNode.addNeighbor(nodes.get(j), delaysDistribution.getNextValue(), false); edges.add(new Edge(i, j)); } } } for (int i = kNearestNeighbors / 2; i < initialNodesN; i++) { Node nextNode = new SimpleNode(i, Node.Types.SIMPLE, defaultResistance); nodes.add(nextNode); nextNode.addNeighbor(nodes.get(i-1), delaysDistribution.getNextValue(), false); edges.add(new Edge(i, i-1)); for (int j = i - kNearestNeighbors / 2; j < i; j++) { nextNode.addNeighbor(nodes.get(j), delaysDistribution.getNextValue(), false); edges.add(new Edge(j, i)); } } for (int i = 0; i < kNearestNeighbors / 2; i++) { for(int j = nodes.size() - 1; j > nodes.size() -1 + i - kNearestNeighbors / 2; j--) { nodes.get(i).addNeighbor(nodes.get(j), delaysDistribution.getNextValue(), false); edges.add(new Edge(i, j)); } } }
b23cb228-73df-430c-8756-5f1e3cd4853f
8
public ArrayList<PuzzleChar> getNeighbours(PuzzleChar pChar) { ArrayList<PuzzleChar> neighbours = new ArrayList<PuzzleChar>(); for(int ri = -1; ri <= 1; ri++) { for (int ci = -1; ci <= 1; ci++) { int nRow = pChar.loc.row + ri; int nCol = pChar.loc.col + ci; if ( nRow < 0 || nRow >= height()) continue; if ( nCol <0 || nCol >= width()) continue; if (nRow == pChar.loc.row && nCol == pChar.loc.col) continue; // TODO: move to factory of PuzzleChars // no need to create a new one Loc loc = new Loc(nRow, nCol); neighbours.add(new PuzzleChar(field[nRow][nCol], loc)); } } return neighbours; };
e7b8e6f2-bb11-421f-8cbe-92c426abfab5
4
public ArrayList<Object[]> getPesonnelData(String client) throws Exception{ ArrayList<String> columnName = getTableColumn("personnel"); ArrayList<Object[]> rowData = new ArrayList<>(); int num = 1; try{ String sql = "Select * FROM `personnel` where assignment = '" + client + "' order by name"; Statement st = con.createStatement(); ResultSet rs = st.executeQuery(sql); while(rs.next()){ ArrayList<String> data = new ArrayList<String>(); data.add(Integer.toString(num)); num++; for(String name:columnName){ data.add(rs.getString(name)); } rowData.add(data.toArray()); } }catch (Exception ex){ System.out.println(ex); } if(rowData.size() == 0){ throw new Exception("No Data Found!"); } return rowData; }
420bf08a-057e-45ad-a10d-a09a1d638d89
3
public void mouseEntered(MouseEvent e) { // if mouse is hovering over top right options... if (e.getSource()==InScreens.getBookHubButton()) { // animate BookHub option system.getContentPane().remove(InScreens.getOptionsUnselected()); system.getContentPane().add(InScreens.getBookHubSelected(),0); system.getContentPane().repaint(755,3,213,125); } if (e.getSource()==InScreens.getInfoCentreButton()) { // animate InfoCentre option system.getContentPane().remove(InScreens.getOptionsUnselected()); system.getContentPane().add(InScreens.getInfoCentreSelected(),0); system.getContentPane().repaint(755,3,213,125); } if (e.getSource()==InScreens.getSocialNetworkButton()) { // animate SocialNetwork option system.getContentPane().remove(InScreens.getOptionsUnselected()); system.getContentPane().add(InScreens.getNetworkSelected(),0); system.getContentPane().repaint(755,3,213,125); } }
9e4c2a89-b638-4119-96e2-dce5a69990ce
5
public static double[][] toMatrix( double[][] audioVectors ) { int m = audioVectors.length; int n = 0; for ( int i = 0; i < m; ++i ) { int tmp = audioVectors[i].length; if ( tmp > n ) n = tmp; } double[][] audioMatrix = Matrix.newMatrix(m, n); for ( int i = 0; i < m; ++i ) { for ( int j = 0; j < audioVectors[i].length; ++j ) audioMatrix[i][j] = audioVectors[i][j]; for ( int j = audioVectors[i].length; j < n; ++j ) audioMatrix[i][j] = 0.0; } return(audioMatrix); }
43739f01-8b59-4416-bfa6-9c60a68b2eb4
3
public void fire(Player player, Environment enviro){ if(canShoot){ canShoot = false; float xPos = -player.getPosition().x(); float yPos = -player.getPosition().y(); float zPos = -player.getPosition().z(); Position posToShootFrom = new Position(xPos, yPos, zPos); Position posToShootTo = Position.screenToWorld(Display.getWidth()/2, Display.getHeight()/2); //TODO Make sure the gun shoots forward shoot(new Bullet(posToShootFrom, posToShootTo, enviro), enviro); System.out.println(this.getClass().getSimpleName() + " Fired!"); } if(!canShoot){ framesSinceLastShot++; } if(framesSinceLastShot > 4){ canShoot = true; framesSinceLastShot = 0; } }
0f75064c-cdc9-41a5-bb4f-8ec046302796
1
public SettingsManager() throws IOException { prefsFile = new File("eu/beatsleigher/beattime/plugin/preferences/cfg"); preferences = new HashMap<>(); if (!prefsFile.exists()) { prefsFile.getParentFile().mkdirs(); prefsFile.createNewFile(); savePrefs(); loadPrefs(); } loadPrefs(); }
b4ae6185-1192-4373-be29-817eb0a0586e
1
public String toString() { return (parent == null) ? "base package" : getFullName(); }
9ea45727-38a2-4286-8c62-b2df0e75296c
5
public static void main(String[] args) throws Exception{ count count = new count(args[0]); ArrayList<File> files = FileFinder.GetAllFiles(count.inputFolder, ".data", true); for(File f : files){ @SuppressWarnings("resource") BufferedReader br = new BufferedReader(new FileReader(f)); String line = null; while ((line = br.readLine()) != null) { String[] split = line.split(" "); if (split.length < 2) continue; String label = split[split.length-1]; if(count.labels.containsKey(label)){ int num = count.labels.get(label); count.labels.put(label, num + 1); } else{ count.labels.put(label, 1); } } } Iterator<Entry<String, Integer>> iter = count.labels.entrySet().iterator(); while (iter.hasNext()) { Entry<String, Integer> entry = iter.next(); System.out.println(entry.getKey() + " :" + entry.getValue()); } }
68c2e4ee-4ef6-4e9e-889b-fd7ce28f98e1
1
public int getSpeed() { int result = speed + citySpeed; for (Artifact a: active.values()) { result += a.speed; } return result; }
f7f5e4bc-a81a-4154-934e-acf7a76bbac2
9
void fillSquare(PlanarSquare square, int contourIndex, int edgeMask, boolean reverseWinding) { int vPt = 0; boolean flip = reverseWinding; int nIntersect = 0; boolean newIntersect; for (int i = 0; i < 4; i++) { newIntersect = false; if ((edgeMask & (1 << i)) != 0) { triangleVertexList[vPt++] = square.vertexes[i]; } // order here needs to be considered for when Edges(A)==Edges(B) // for proper winding -- isn't up to snuff if (flip && (edgeMask & (1 << (8 + i))) != 0) { nIntersect++; newIntersect = true; triangleVertexList[vPt++] = square.intersectionPoints[contourIndex + 1][i]; } if ((edgeMask & (1 << (4 + i))) != 0) { nIntersect++; newIntersect = true; triangleVertexList[vPt++] = square.intersectionPoints[contourIndex][i]; } if (!flip && (edgeMask & (1 << (8 + i))) != 0) { nIntersect++; newIntersect = true; triangleVertexList[vPt++] = square.intersectionPoints[contourIndex + 1][i]; } if (nIntersect == 2 && newIntersect) flip = !flip; } /* * Logger.debug("\nfillSquare (" + square.x + " " + square.y + ") " + contourIndex + " " + * binaryString(edgeMask) + "\n"); Logger.debug("square vertexes:" + dumpIntArray(square.vertexes, 4)); * Logger.debug("square inters. pts:" + dumpIntArray(square.intersectionPoints[contourIndex], 4)); * Logger.debug(dumpIntArray(triangleVertexList, vPt)); */ createTriangleSet(vPt); }
f9f32f5e-b983-4a24-9160-5a7f200646d0
1
public String testStatus(String appKey, String userKey, String testId, boolean detailed) { try { appKey = URLEncoder.encode(appKey, "UTF-8"); userKey = URLEncoder.encode(userKey, "UTF-8"); testId = URLEncoder.encode(testId, "UTF-8"); } catch (UnsupportedEncodingException e) { BmLog.error(e); } return String.format("%s/api/rest/blazemeter/testGetStatus/?app_key=%s&user_key=%s&test_id=%s&detailed=%s", SERVER_URL, appKey, userKey, testId, detailed); }
de4f2c3e-05fc-44ae-96bb-cfdec0aabc89
1
private void loadCourse(Course course) { // Clear scorecard clearScorecard(); // Add par values to scorecard for (int holeNumber = 0; holeNumber < course.getNumberOfHoles(); holeNumber++) { Hole hole = course.getHole(holeNumber + 1); // +1 to match human # tblScorecard.setValueAt(hole.getPar(), holeNumber, 1); } }
23e0cdee-9a9c-43d0-836d-54a414e18098
9
public <T extends Object> T construct(NitDesc nitDesc) throws NitException { NitAgent agent = agents.get(nitDesc.spec); if (agent == null){ if (nitDesc.spec == NitDesc.NitSpec.GROOVY_CLASS_LOADER){ agent = new GroovyClasspathAgent(); } else if (nitDesc.spec == NitDesc.NitSpec.JAVASCRIPT_CLOSURE ) { agent = new JavascriptClosureAgent(); } else if (nitDesc.spec == NitDesc.NitSpec.CLOJURE_CLOSURE) { agent = new ClojureClosureAgent(); } else if (nitDesc.spec == NitDesc.NitSpec.GROOVY_CLOSURE) { agent = new GroovyClosureAgent(); } else if (nitDesc.spec == NitDesc.NitSpec.JAVA_LOCAL_CLASSPATH){ agent = new JavaLocalClasspathAgent(); } else if (nitDesc.spec == NitDesc.NitSpec.JAVA_ON_JAVA){ agent = new JavaOnJavaAgent(); } else if (nitDesc.spec == NitDesc.NitSpec.JAVA_URL_CLASSLOADER ) { agent = new UrlClassLoaderAgent(); } else if (nitDesc.spec == NitDesc.NitSpec.SCALA_CLOSURE){ agent = new ScalaClosureAgent(); } else { throw new NitException(nitDesc.spec + " not found"); } agents.put(nitDesc.spec, agent); } return (T) agent.createInstance(nitDesc); }
56b90346-7837-488b-9d95-8f8f30564270
8
private static long applyQueryDeletes(Iterable<QueryAndLimit> queriesIter, SegmentState segState) throws IOException { long delCount = 0; final LeafReaderContext readerContext = segState.reader.getContext(); for (QueryAndLimit ent : queriesIter) { Query query = ent.query; int limit = ent.limit; final IndexSearcher searcher = new IndexSearcher(readerContext.reader()); searcher.setQueryCache(null); final Weight weight = searcher.createNormalizedWeight(query, false); final Scorer scorer = weight.scorer(readerContext); if (scorer != null) { final DocIdSetIterator it = scorer.iterator(); final Bits liveDocs = readerContext.reader().getLiveDocs(); while (true) { int doc = it.nextDoc(); if (doc >= limit) { break; } if (liveDocs != null && liveDocs.get(doc) == false) { continue; } if (!segState.any) { segState.rld.initWritableLiveDocs(); segState.any = true; } if (segState.rld.delete(doc)) { delCount++; } } } } return delCount; }
ebdcb33b-6c93-48a5-9241-ab8cbb1f576f
0
public AnswerCombination(List<Token<AnswerColors>> tokens) { super(tokens); // TODO Auto-generated constructor stub }
680dbea5-d3b8-4c9a-8c04-91a5db9870b2
5
public Map<InetAddress, GatewayDevice> discover() throws SocketException, UnknownHostException, IOException, SAXException, ParserConfigurationException { Collection<InetAddress> ips = getLocalInetAddresses(true, false, false); for (int i = 0; i < searchTypes.length; i++) { String searchMessage = "M-SEARCH * HTTP/1.1\r\n" + "HOST: " + IP + ":" + PORT + "\r\n" + "ST: " + searchTypes[i] + "\r\n" + "MAN: \"ssdp:discover\"\r\n" + "MX: 2\r\n" + // seconds to delay response "\r\n"; // perform search requests for multiple network adapters concurrently Collection<SendDiscoveryThread> threads = new ArrayList<SendDiscoveryThread>(); for (InetAddress ip : ips) { SendDiscoveryThread thread = new SendDiscoveryThread(ip, searchMessage); threads.add(thread); thread.start(); } // wait for all search threads to finish for (SendDiscoveryThread thread : threads) try { thread.join(); } catch (InterruptedException e) { // continue with next thread } // If a search type found devices, don't try with different search type if (!devices.isEmpty()) break; } // loop SEARCHTYPES return devices; }
01717570-2b8d-42ba-a2e8-b5a44aee997a
8
private ScenarioGUIStep getScenarioGUIStepFromTreeStep(ScenarioTreeStep currentStep) { // Gibt das passende GUI Schritt Objekt zurück zum Szenarioschrittobjekt // und fügt das Szenarioschrittobjekt dem GUI Schritt Objekt per Konstruktor hinzu if(currentStep instanceof ScenarioTreeStepBeginning){ return new ScenarioGUIStepBeginning((ScenarioTreeStepBeginning)currentStep); } else if(currentStep instanceof ScenarioTreeStepTwoOptions) { return new ScenarioGUIStepTwoOptionsRadiobuttons((ScenarioTreeStepTwoOptions)currentStep); } else if(currentStep instanceof ScenarioTreeStepSimpleList) { return new ScenarioGUIStepDropdownList((ScenarioTreeStepSimpleList)currentStep); } else if (currentStep instanceof ScenarioTreeStepFinish){ return new ScenarioGUIStepFinish((ScenarioTreeStepFinish)currentStep); } else if (currentStep instanceof ScenarioTreeStepDBOWLTablet){ return new ScenarioGUIStepDatabaseRequestTablet((ScenarioTreeStepDBOWLTablet)currentStep); } else if (currentStep instanceof ScenarioTreeStepDBOWLNotebook){ return new ScenarioGUIStepDatabaseRequestNotebook((ScenarioTreeStepDBOWLNotebook)currentStep); } else if (currentStep instanceof ScenarioTreeStepDBOWLComputerComponents){ return new ScenarioGUIStepDatabaseRequestComputerComponents((ScenarioTreeStepDBOWLComputerComponents)currentStep); } else if (currentStep instanceof ScenarioTreeStepDBOWLSoftwareAndOS){ return new ScenarioGUIStepDatabaseRequestSoftwareAndOS((ScenarioTreeStepDBOWLSoftwareAndOS)currentStep); } // Derzeit gibt es die obigen Typen return null; }
30463981-20d0-49bc-8ee1-fede978aeeb5
0
@Override @RequestMapping(value = "/beers/{id}", method = RequestMethod.GET) @ResponseBody public BeerResponse get(@PathVariable("id") Long id) { Beer beer = persistenceService.read(Beer.class, id); return BeerResponse.createBeerResponse(beer); }
dd703364-0b7d-43c0-afec-e45ba8c97a7d
8
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line = ""; StringBuilder out = new StringBuilder(); while ((line = in.readLine()) != null && line.length() != 0) { int nSet = Integer.parseInt(line.trim()); for (int i = 0; i < nSet; i++) { if (i == 0) in.readLine(); else out.append("\n"); int[] t = readInts(in.readLine()); ArrayList<String> l = new ArrayList<String>(100); while ((line = in.readLine()) != null && line.matches(".*[10].*")) l.add(line.trim()); n = l.size(); m = l.get(0).length(); map = new char[n][m]; for (int j = 0; j < l.size(); j++) map[j] = l.get(j).toCharArray(); if (map[t[0] - 1][t[1] - 1] == '1') out.append("0\n"); else { used = new boolean[n][m]; used[t[0] - 1][t[1] - 1] = true; out.append(floodFill(t[0] - 1, t[1] - 1) + "\n"); } } } System.out.print(out); }
90fccc08-ecbb-4854-9ebf-73893e8c49ab
8
public void setOptions(String[] options) throws Exception { String args; args = Utils.getOption('C',options); if (args.length() != 0) setClassificationType(new SelectedTag(args, TAGS_CLASSIFICATIONTYPES)); else setClassificationType(new SelectedTag(CT_MEDIAN, TAGS_CLASSIFICATIONTYPES)); setBalanced(Utils.getFlag('B',options)); if (Utils.getFlag('W', options)) { m_weighted = true; // ignore any T, S, P, L and U options Utils.getOption('T', options); Utils.getOption('S', options); Utils.getOption('P', options); Utils.getOption('L', options); Utils.getOption('U', options); } else { m_tuneInterpolationParameter = Utils.getFlag('T', options); if (!m_tuneInterpolationParameter) { // ignore P, L, U Utils.getOption('P', options); Utils.getOption('L', options); Utils.getOption('U', options); // value of s args = Utils.getOption('S',options); if (args.length() != 0) setInterpolationParameter(Double.parseDouble(args)); else setInterpolationParameter(0.5); } else { // ignore S Utils.getOption('S', options); args = Utils.getOption('L',options); double l = m_sLower; if (args.length() != 0) l = Double.parseDouble(args); else l = 0.0; args = Utils.getOption('U',options); double u = m_sUpper; if (args.length() != 0) u = Double.parseDouble(args); else u = 1.0; if (m_tuneInterpolationParameter) setInterpolationParameterBounds(l, u); args = Utils.getOption('P',options); if (args.length() != 0) setNumberOfPartsForInterpolationParameter(Integer.parseInt(args)); else setNumberOfPartsForInterpolationParameter(10); } } super.setOptions(options); }
88fa2952-884a-4b0f-bc90-cd6c72ccf92a
4
@Override public void run() { options.status = "Laying tracks"; for (GameObject tunnel : ctx.objects.select().id(TUNNEL).nearest().first()) { if (ctx.camera.prepare(tunnel) && tunnel.interact("Lay-tracks", "Tunnel")) { if (Condition.wait(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return ctx.backpack.select().id(SmithTrack.TRACK_100).isEmpty(); } })) { Condition.sleep(1700); } } else { options.status = "Laying tracks [interact failed]"; } } }
2acaae44-cb8a-45f4-912f-603978308526
7
public final LatticeIF getImplementation(final LatticeType type) { switch(type) { case SHORT_RATE: { this.implementation = new ShortRateLatticeImpl(); break; } case ZERO_COUPON_BOND: { this.implementation = new ZeroCouponBondLatticeImpl(); break; } case AMER_CALL_ZERO: { this.implementation = new AmericanCallZeroLatticeImpl(); break; } case BOND_FORWARD: { this.implementation = new BondForwardImpl(); break; } case BOND_FUTURES: { this.implementation = new BondFuturesImpl(); break; } case SWAP: { this.implementation = new SwapImpl(); break; } case SWAPTION: { this.implementation = new SwaptionImpl(); break; } default: { System.err.println("No approriate implementation."); break; } } // switch ( searchType ) return this.implementation; }
2ce4db95-51ef-4855-9c08-1d4952a7e7b9
1
public int hashCode() { if (cachedHash != 0xdeadbeef) return cachedHash; return cachedHash = buffer.toString().hashCode(); }
20aba325-5afd-4958-8de3-35ad17648db0
1
public void writeToServer(String text){ try{ bw.write(text+"\n"); bw.flush(); }catch(IOException e){ System.out.println("IRC: Failure when trying to write to server: "+e.getMessage()); } }
28d0e6b3-97a4-4a40-a1d2-71fc4f6edb9d
9
public static HumanTime eval(final CharSequence s) { HumanTime out = new HumanTime(0L); int num = 0; int start = 0; int end = 0; State oldState = State.IGNORED; for (char c : new Iterable<Character>() { /** * @see java.lang.Iterable#iterator() */ public Iterator<Character> iterator() { return new Iterator<Character>() { private int p = 0; /** * @see java.util.Iterator#hasNext() */ public boolean hasNext() { return p < s.length(); } /** * @see java.util.Iterator#next() */ public Character next() { return s.charAt(p++); } /** * @see java.util.Iterator#remove() */ public void remove() { throw new UnsupportedOperationException(); } }; } }) { State newState = getState(c); if (oldState != newState) { if (oldState == State.NUMBER && (newState == State.IGNORED || newState == State.UNIT)) { num = Integer.parseInt(s.subSequence(start, end).toString()); } else if (oldState == State.UNIT && (newState == State.IGNORED || newState == State.NUMBER)) { out.nTimes(s.subSequence(start, end).toString(), num); num = 0; } start = end; } ++end; oldState = newState; } if (oldState == State.UNIT) { out.nTimes(s.subSequence(start, end).toString(), num); } return out; }
eb61a09b-f8cc-49b8-9dfe-a2e6ade3020e
8
public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { String a = sc.next(); String b = sc.next(); String c = conv(a); String d = conv(b); int kiri = -1; int kanan = -1; boolean bisa = false; for (int i = 2; i <= 36; i++) { BigInteger aa = BigInteger.ZERO; try { aa = new BigInteger(c, i); } catch (Exception e) { continue; } for (int j = 2; j <= 36; j++) { BigInteger bb = BigInteger.ZERO; try { bb = new BigInteger(d, j); } catch (Exception e) { continue; } if (aa.compareTo(bb) == 0) { kiri = i; kanan = j; bisa = true; break; } } if (bisa) { break; } } if (bisa) { System.out.println(a + " (base " + kiri + ") = " + b + " (base " + kanan + ")"); } else { System.out.println(a + " is not equal to " + b + " in any base 2..36"); } } }
24a6ded6-7f86-4398-9571-c44068a79db1
1
@Override public void destroy(Object args) { if(this.root != null) this.root.destroy(); }
d530ebaf-e477-49a0-aaef-b7d229d033f7
8
static private double anySubstitutionRatio(int taxon1, int taxon2) { double distance; double sumDistance = 0.0; double sumWeight = 0.0; boolean noGapsPairFound = false; // If both sequences are of zero length then the substitution ratio is zero because they are identical if(alignment.getPatterns().size() == 0) return 0.0; for( Pattern pattern : alignment.getPatterns() ) { State state1 = pattern.getState(taxon1); State state2 = pattern.getState(taxon2); final double weight = pattern.getWeight(); if(!state1.isGap() && !state2.isGap()) noGapsPairFound = true; if (!state1.isAmbiguous() && !state2.isAmbiguous()) { if(state1 != state2) sumDistance += weight; } sumWeight += weight; } if(!noGapsPairFound) throw new CannotBuildDistanceMatrixException("It is not possible to compute the Jukes-Cantor genetic distance " + "for these sequences because at least one pair of sequences do not overlap in the alignment."); distance = sumDistance / sumWeight; return distance; }
028b5fb1-7985-4aae-9e3c-92f2816c68c7
0
public String getURI() { return uri; }
a21bb638-1a41-4e02-8c24-875c55bc9537
3
private boolean isCanLive(Enum lifeStatus, int aliveAround) { if(lifeStatus == LifeStatus.died){ return aliveAround == 3; } return (aliveAround == 2 || aliveAround == 3) && lifeStatus == LifeStatus.alive; }
5d4353c7-3617-4a61-913b-d2e41aee2b9d
0
int getOurDocsOpen() { return ourDocsOpen; }
432c453c-418d-434b-be26-000e54cfa5e0
0
public void setId(int id) { this.id = id; }
b7e2aa1f-9583-446f-b331-e81dac8e76d8
7
private boolean isReturnExpr(List<String> tokenList) { final int St_START = 1, St_LP_START = 2; Iterator tokenIt = tokenList.iterator(); int currentState = St_START; while (tokenIt.hasNext()) { String nextToken = (String) tokenIt.next(); switch (currentState) { case St_START: if (nextToken.equals("LP")) { currentState = St_LP_START; } else if (nextToken.equals("RETURN")) { return true; } else { return false; } break; case St_LP_START: if (nextToken.equals("LP")) { // state stays the same } else if (nextToken.equals("RETURN")) { return true; } break; default: System.out.println("Error: Incorrect state in isReturnExpr"); System.exit(-1); break; } } return false; }
cac59a27-bdfb-4ea5-87a2-b8d663f79e68
9
@Override protected void writeChildren(XMLStreamWriter out) throws XMLStreamException { super.writeChildren(out); out.writeStartElement("gen"); out.writeAttribute("humidityMin", Integer.toString(humidity[0])); out.writeAttribute("humidityMax", Integer.toString(humidity[1])); out.writeAttribute("temperatureMin", Integer.toString(temperature[0])); out.writeAttribute("temperatureMax", Integer.toString(temperature[1])); out.writeAttribute("altitudeMin", Integer.toString(altitude[0])); out.writeAttribute("altitudeMax", Integer.toString(altitude[1])); out.writeEndElement(); for (Map.Entry<String, AbstractGoods> entry : primaryGoodsMap.entrySet()) { out.writeStartElement("primary-production"); out.writeAttribute("goods-type", entry.getValue().getType().getId()); out.writeAttribute(VALUE_TAG, Integer.toString(entry.getValue().getAmount())); if (entry.getKey() != null) { out.writeAttribute("tile-production", entry.getKey()); } out.writeEndElement(); } for (Map.Entry<String, AbstractGoods> entry : secondaryGoodsMap.entrySet()) { out.writeStartElement("secondary-production"); out.writeAttribute("goods-type", entry.getValue().getType().getId()); out.writeAttribute(VALUE_TAG, Integer.toString(entry.getValue().getAmount())); if (entry.getKey() != null) { out.writeAttribute("tile-production", entry.getKey()); } out.writeEndElement(); } for (Map.Entry<String, Map<GoodsType, AbstractGoods>> entry : productionMap.entrySet()) { for (AbstractGoods goods : entry.getValue().values()) { out.writeStartElement("production"); out.writeAttribute("goods-type", goods.getType().getId()); out.writeAttribute(VALUE_TAG, Integer.toString(goods.getAmount())); if (entry.getKey() != null) { out.writeAttribute("tile-production", entry.getKey()); } out.writeEndElement(); } } for (RandomChoice<ResourceType> choice : resourceType) { out.writeStartElement("resource"); out.writeAttribute("type", choice.getObject().getId()); out.writeAttribute("probability", Integer.toString(choice.getProbability())); out.writeEndElement(); } for (RandomChoice<Disaster> choice : disasters) { out.writeStartElement("disaster"); out.writeAttribute("id", choice.getObject().getId()); out.writeAttribute("probability", Integer.toString(choice.getProbability())); out.writeEndElement(); } }
1d0f2355-642e-4d11-bf6c-26e9de9cd454
9
public List<Key> getAllKeys() { try { Pattern keyIDPattern = Pattern.compile("pub\\s+\\w+/(\\w+)\\s+.*"); Pattern uidPattern = Pattern.compile("uid\\s+(\\S+[^<>]*\\S+)\\s+<([^<>]*)>.*"); List<Key> ret = new LinkedList<>(); List<String> list = new LinkedList<String>(); list.add("--list-keys"); Process p = this.runCommand(list); Scanner in = new Scanner(p.getInputStream(), "UTF-8"); String keyID = null; String uid = null; String email = null; while(in.hasNextLine()) { String data = in.nextLine(); if(data.length() == 0) { if (keyID == null) break; Key k = new Key(); k.keyID = keyID; k.uid = uid; k.email = email; ret.add(k); keyID = null; uid = null; email = null; } Matcher m = keyIDPattern.matcher(data); if(keyID == null && m.matches()) { keyID = m.group(1); } m = uidPattern.matcher(data); if(uid == null && m.matches()) { uid = m.group(1); email = m.group(2); } } in.close(); if(p.waitFor() == 0) return ret; else return null; } catch(Exception e) { return null; } }
0bcf6a08-8005-4afd-aa51-2d0b5119ba4b
7
public void warn(Event event) { switch(event.getTypeEvent()) { case GOBACKWARD_END : if(state == 0) { state++; } else if(state ==2) { fin = true; } else { ignore(); } break; case CHILDBEHAVIOR_END : if(state == 1) { state++; } else { ignore(); } break; case GOFORWARD_END : if(state == 2) { fin = true; } else { ignore(); } break; default: ignore(); break; } }
5a61db6d-bfd5-40c4-bcfa-d124a7a48b15
0
public int getHeight() { return height; }
2cdbc0e8-dd82-4fad-b7e4-ea0848bdb070
8
private void step() { for(int x = 0; x < Globals.width; x++){ for(int y = 0; y < Globals.height; y++){ float waterAmmount = 0.0f; for(int[] neighbor : HexagonUtils.neighborTiles(x, y, true)){ //waterAmmount += Globals.water.getGroundWaterLevel(neighbor[0], neighbor[1]); for(NeedsControlled nc : NeedsController.getNeed("Water")){ waterAmmount += nc.getNeed(new Needs("Water", 1.0f), neighbor[0], neighbor[1]); } } //-((x-3.5)^2)/6.125+1.0 = exponential, ranging from -1 to 1, with center i 3.5. This asumes that waterAmmount ranges from 0 to 7 float grassGrowth = (float) (-(Math.pow(waterAmmount-3.5f, 2))/6.125f+1.0f); if(grassGrowth > 0.0f){ float sunIntensity = 0.0f; for(NeedsControlled nc : NeedsController.getNeed("SunLight")){ sunIntensity += nc.getNeed(new Needs("SunLight", 1.0f), x, y); } grassGrowth *= sunIntensity; } grassLevel[x][y] += grassGrowth*Globals.getSetting("Grass growth rate", "Grass"); if(grassLevel[x][y] > 1.0f) grassLevel[x][y] = 1.0f; else if(grassLevel[x][y] < 0.0f) grassLevel[x][y] = 0.0f; } } }
db4cfda9-1861-4aca-a59a-b8eea12954d6
0
public Id3v2PictureFrame(Property prop,PropertyTree parent) { super(prop, parent); }
3169cb23-976a-42cc-ab4a-fec13862059c
1
private <T> void removeAt(T[] array, int index) { if (currentSize == 0) { shiftArrayBy(array, -1); } else { System.arraycopy(array, index + 1, array, index, array.length - index - 1); changeCapacityBy(array, -1); } }
9bb34d82-bc96-4b5a-a2c8-fc92843af83e
6
public String getComment(String path) { Preconditions.checkNotNull(path, "Path cannot be null"); Configuration root = getRoot(); if (root == null) { throw new IllegalStateException("Cannot access section without a root"); } // Return the comment associated to this element. if (path.length() == 0) { return this.getParent() == null ? null : this.getParent().getComment(this.getName()); } final char separator = root.options().pathSeparator(); // i1 is the leading (higher) index // i2 is the trailing (lower) index int i1 = -1, i2; ConfigurationSection section = this; while ((i1 = path.indexOf(separator, i2 = i1 + 1)) != -1) { section = section.getConfigurationSection(path.substring(i2, i1)); if (section == null) { return null; } } String key = path.substring(i2); if (section == this) { return comments.get(key); } return section.getComment(key); }
cd797e1f-ad20-4c9c-9a74-7d6966847282
0
@Override public void error(SAXParseException e) { System.out.println("SAXParserException Error: " + e.getMessage()); this.errorOccurred = true; }
37b9c6de-12f3-47a8-84d6-9e5d0d8d57bd
0
@Test public void testCancelButtonBeforeCalculated() throws Exception { propertyChangeSupport.firePropertyChange(DialogWindowController.PERCENTAGE, 0, 10); view.getButton().getActionListeners()[0].actionPerformed(actionEvent); assertEquals(propertyName, DialogWindowController.CANCEL); assertEquals(view.getProgressBar().getValue(), 0); }
c1a9dc5a-95da-4c1c-9814-12063268363d
9
@Override protected CommandExecutionResult executeArg(Map<String, RegexPartialMatch> arg) { final String g1 = arg.get("G1").get(0); final String g2 = arg.get("G2").get(0); // if (getSystem().isGroup(g1) && getSystem().isGroup(g2)) { // return executePackageLink(arg); // } if (getSystem().isGroup(g1) || getSystem().isGroup(g2)) { return CommandExecutionResult.error("Not implemented"); } final IEntity cl1 = getSystem().getOrCreateClass(g1); final IEntity cl2 = getSystem().getOrCreateEntity(g2, EntityType.ARC_CIRCLE); if (arg.get("G1").get(1) != null) { cl1.setStereotype(new Stereotype(arg.get("G1").get(1))); } if (arg.get("G2").get(1) != null) { cl2.setStereotype(new Stereotype(arg.get("G2").get(1))); } final LinkType linkType = new LinkType(LinkDecor.NONE, LinkDecor.NONE); String queue; if (arg.get("AR_TO_RIGHT").get(0) != null) { queue = arg.get("AR_TO_RIGHT").get(1) + arg.get("AR_TO_RIGHT").get(3); // linkType = getLinkTypeNormal(queue, arg.get("AR_TO_RIGHT").get(4)); } else { queue = arg.get("AR_TO_LEFT").get(2) + arg.get("AR_TO_LEFT").get(4); // linkType = getLinkTypeNormal(queue, arg.get("AR_TO_LEFT").get(1)).getInversed(); } final Direction dir = getDirection(arg); if (dir == Direction.LEFT || dir == Direction.RIGHT) { queue = "-"; } Link link = new Link(cl1, cl2, linkType, arg.get("END").get(0), queue.length()); if (dir == Direction.LEFT || dir == Direction.UP) { link = link.getInv(); } getSystem().addLink(link); return CommandExecutionResult.ok(); }
5f3e59e8-ae38-4ec9-a68a-0399134d0a24
4
@Override public void setBoolean(long i, boolean value ) { if (ptr != 0) { Utilities.UNSAFE.putByte(ptr + i, value == true ? (byte) 1 : (byte) 0); } else { if (isConstant()) { throw new IllegalAccessError("Constant arrays cannot be modified."); } data[(int) i] = value == true ? (byte) 1 : (byte) 0; } }