text
stringlengths
14
410k
label
int32
0
9
@Override public synchronized void clearDebri(Room room, int taskCode) { TickableGroup almostTock=null; TickClient C=null; ItemTicker I=null; Iterator<TickClient> roomSet; MOB mob=null; for(final Iterator<TickableGroup> e=tickGroups();e.hasNext();) { almostTock=e.next(); roomSet=almostTock.getLocalItems(taskCode,room); if(roomSet!=null) { for(;roomSet.hasNext();) { C=roomSet.next(); if(C.getClientObject() instanceof ItemTicker) { I=(ItemTicker)C.getClientObject(); almostTock.delTicker(C); I.setProperLocation(null); } else if(C.getClientObject() instanceof MOB) { mob=(MOB)C.getClientObject(); if((mob.isMonster())&&(!room.isInhabitant(mob))) { mob.destroy(); almostTock.delTicker(C); } } } } } }
7
public List<Byte> getByteListFromString(String xArg) { if (xArg == null || xArg.equalsIgnoreCase("")) return null; List<Byte> d = new ArrayList<Byte>(); char[] c = xArg.toCharArray(); int lastPos = 0; for (int i = 0; i < c.length; i++) { if (c[i] == ',') { d.add(Byte.valueOf(returnMergedCharacters(lastPos, i, c))); lastPos = i + 1; } } //Add the final integer. d.add(Byte.valueOf(returnMergedCharacters(lastPos, c.length, c))); return d; }
4
@Override public String getAsString(FacesContext facesContext, UIComponent component, Object object) { if (object == null || (object instanceof String && ((String) object).length() == 0)) { return null; } if (object instanceof Cotizacion) { Cotizacion o = (Cotizacion) object; return getStringKey(o.getIdCotizacion()); } else { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "object {0} is of type {1}; expected type: {2}", new Object[]{object, object.getClass().getName(), Cotizacion.class.getName()}); return null; } }
4
public String [] getOptions() { String [] options = new String [9]; int current = 0; options[current++] = "-X"; options[current++] = "" + m_CVFolds; if (m_evaluationMeasure != EVAL_DEFAULT) { options[current++] = "-E"; switch (m_evaluationMeasure) { case EVAL_ACCURACY: options[current++] = "acc"; break; case EVAL_RMSE: options[current++] = "rmse"; break; case EVAL_MAE: options[current++] = "mae"; break; case EVAL_AUC: options[current++] = "auc"; break; } } if (m_useIBk) { options[current++] = "-I"; } if (m_displayRules) { options[current++] = "-R"; } options[current++] = "-S"; options[current++] = "" + getSearchSpec(); while (current < options.length) { options[current++] = ""; } return options; }
8
public void actionPerformed(ActionEvent event) { System.out.println("TitleScreen.actionPerformed()"); Object source = event.getSource(); if (source == button_start) advanceTutorial(); else if (source == button_exit) game.quit(); // else if (source == buttonList[BUTTON_CONFIG_IDX]) toggleUserPanel(); else if (source == button_oddball) startOddballGame(); else if (source == button_bandit) startBanditGame(); // else if (source == but_configOK) // { // copyGUI_toUser(); // toggleUserPanel(); // } // else if (source == but_configCancel) toggleUserPanel(); // else if (source == dropDownController) updateJoystickAxisDropdowns(); // System.out.println("TitleScreen.actionPerformed()....selected="+dropDown_userList.getSelectedIndex()+", visible="+dropDown_userList.isPopupVisible()); // // else if (source == dropDown_userList) setUser(); // else if (source == dropDown_joystickX || source == dropDown_joystickY) // { // copyGUI_toUser(); // } }
4
public void parseRange(final BitSet bitSet, final int min, final int max, final String range, final int interval) { if(range.equals("*")) { setBits(bitSet, min, max, interval); return; } String[] split = range.split("-"); if(split.length == 1) { int val = parseInt(split[0]); if(val < min) throw new IllegalArgumentException(); if(val > max) throw new IllegalArgumentException(); setBits(bitSet, val, val, 1); } else if(split.length == 2) { int myMin = parseInt(split[0]); int myMax = parseInt(split[1]); if(myMin < min) throw new IllegalArgumentException(); if(myMax > max) throw new IllegalArgumentException(); setBits(bitSet, myMin, myMax, 1); } }
7
public Float getXMax() { return xMax; }
0
public static void hypothesizeChomsky(GrammarEnvironment env, Grammar g) { CNFConverter converter = null; try { converter = new CNFConverter(g); } catch (IllegalArgumentException e) { JOptionPane.showMessageDialog(env, e.getMessage(), "Illegal Grammar", JOptionPane.ERROR_MESSAGE); return; } Production[] p = g.getProductions(); boolean chomsky = true; for (int i = 0; i < p.length; i++) chomsky &= converter.isChomsky(p[i]); if (chomsky) { JOptionPane.showMessageDialog(env, "The grammar is already in Chomsky NF.", "Already in CNF", JOptionPane.ERROR_MESSAGE); return; } ChomskyPane cp = new ChomskyPane(env, g); env.add(cp, "Chomsky Converter", new CriticalTag() { }); env.setActive(cp); }
3
public void deploy(Territory territ, boolean all) { if (territ.owner != activePlayer) return; String placing = troopAmountCombo.getSelectedItem().toString(); int toPlace = (all || placing.equals("All")) ? deployNum : Math.min(Integer.parseInt(placing), deployNum); territ.addUnits(toPlace); deployNum -= toPlace; activePlayer.updateStats(Player.TROOPS_DEPLOYED, toPlace); log(activePlayer.name + " placed " + toPlace + " troops on " + territ.name + "."); if (deployNum == 0) enterAttackState(); else message(activePlayer.name + ", you have " + deployNum + " troops to place."); playerPnlHash.get(activePlayer).update(); }
4
private void designator() { if (have(NonTerminal.DESIGNATOR)) { tryResolveSymbol(current); nextToken(); while (accept(Token.Kind.OPEN_BRACKET)) { expression0(); expect(Token.Kind.CLOSE_BRACKET); } } }
2
public boolean isEnabled() { return comp.isEnabled() && comp.getSelectedText()!=null; }
2
public String toString() { checkInvariants(); int numBits = (wordsInUse > 128) ? cardinality() : wordsInUse * BITS_PER_WORD; StringBuilder b = new StringBuilder(6 * numBits + 2); b.append('{'); int i = nextSetBit(0); if (i != -1) { b.append(i); for (i = nextSetBit(i + 1); i >= 0; i = nextSetBit(i + 1)) { int endOfRun = nextClearBit(i); do { b.append(", ").append(i); } while (++i < endOfRun); } } b.append('}'); return b.toString(); }
4
public static int numberActionsApplicableInState(State currentState, GroundedAction action1, GroundedAction action2, boolean reverse) { GroundedAction firstAction = (reverse) ? action2 : action1; GroundedAction secondAction = (reverse) ? action1 : action2; int count = 0; State nextState = currentState.copy(); if (firstAction != null) { count += ExperimentHelper.isGroundedActionApplicableInState(currentState, firstAction) ? 1 : 0; nextState = firstAction.executeIn(currentState); } if (secondAction != null) { if (firstAction == null || (firstAction.params[1] != secondAction.params[1] && ExperimentHelper.isGroundedActionApplicableInState(nextState, secondAction))) { count++; } } return count; }
8
public boolean comparePattern (Pattern tablePattern ){ boolean levelingOK = (tablePattern.lowestRank < this.lowestRank); log.debug("tablePaTTERN lowest Rank"+ tablePattern.lowestRank+" this lowest Rank "+ this.lowestRank); boolean patternMatch = false; //__catch bombs___ if(this.isBomb() && ( tablePattern.bombIndex < this.bombIndex) ) { this.setBomb(); patternMatch = true; } //__naturally matching patterns are detected here__ this.analyzePattern(); log.debug("incoming Cards naturally is"+this.patternName+" while tablePattern is "+tablePattern.patternName+" while leveling is "+levelingOK); if(this.patternName.equals(tablePattern.patternName) && levelingOK ){ patternMatch = true; log.debug("natural matching pattern "+patternMatch); return patternMatch; } //__this adjusts the patternCheck attempting to match the table Pattern (if 2 jokers have been played) if(this.jokerCards.size() > 1 && levelingOK) { int playedSequenceDepth = this.isRunOfSequence(tablePattern.builtSequenceLength); boolean deepeningOK = (this.deepeningJokers == tablePattern.builtSequenceLength); log.debug("deep jokers "+this.deepeningJokers +" deepeningOK is "+deepeningOK +" tablePatterns Length: "+tablePattern.builtSequenceLength); log.debug("tablePattern built SequenceLength: "+tablePattern.builtSequenceLength); log.debug("tablePattern.SequenceDepth :"+ tablePattern.builtSequenceDepth+" table Card Count"+tablePattern.cardCount); log.debug("playedPattern built SequenceLength: "+this.builtSequenceLength); log.debug("playedSequenceDepth "+playedSequenceDepth); if(playedSequenceDepth == tablePattern.builtSequenceDepth) { log.debug("match is OK without deepening jokers"); patternMatch = true; log.debug("matching pattern without deepening Jokers"+patternMatch); this.setSequence(playedSequenceDepth); return patternMatch; } if(deepeningOK && ((playedSequenceDepth +1 ) == tablePattern.builtSequenceDepth) ){ log.debug("deepening Jokers used - match is ok "); this.setSequence(tablePattern.builtSequenceDepth); patternMatch = true; return patternMatch; } } log.debug("compare has not found a valid option pattern match is "+ patternMatch); return patternMatch; }
9
private boolean doReturnedReading() { if (this.ended) return false; while (!this.returned.isEmpty()) { IByteReader rest; while (true) { rest = this.returned.getFirst(); if (rest.isEnded()) this.returned.pollFirst(); else break; if (this.returned.isEmpty()) return true; } boolean readingRequested = this.listener.apply(rest); if (rest.isEnded()) this.returned.pollFirst(); if (!readingRequested) return false; } if (this.streamEnded && this.returned.isEmpty()) { this.ended = true; this.endEvent.event(this.endedStreamError); } return true; }
9
public void parserWithTokenByChar() throws Exception { Ngram ngram; int count = 0; Token pre = new Token(null, null); String preWordWithAttr = null; for (int i = 0; i < 10; i++) list = lexer.nextTokenList(); while (current != null) { if (current.getKind() == Token.Kind.TOKEN_WORD) { if (pre.getKind() == Token.Kind.TOKEN_ATTRIBUTE) { if (preWordWithAttr != null) { String attrWithWord[] = preWordWithAttr.split("_"); ngram = new Ngram(); ngram.setWordAttribute(attrWithWord[0] + "_" + pre.getContent()); ngram.setWordGroup(attrWithWord[1] + "_" + current.getContent()); count++; service.addNgram(ngram); // if (count == 200) // break; preWordWithAttr = pre.getContent() + "_" + current.getContent(); } else { preWordWithAttr = pre.getContent() + "_" + current.getContent(); } } else if (current.getKind() == Token.Kind.TOKEN_OTHERS || current.getKind() == Token.Kind.TOKEN_PUNCTION) { preWordWithAttr = null; } } pre = current; current = lexer.nextToken(); } }
7
int classCount(RoomScheme r, int code){ int count = 0; for (Subject[] room : r.rooms) { for (int j = 0; j<r.rooms[0].length; j++) { if (room[j].getCode() == code) { count ++; } } } return count; }
3
public static String getDnaSequenceFromFrame(String inSequence, int frame) throws Exception { if ( frame == 0 ) return inSequence; if ( frame == 1 ) return inSequence.substring(1); if ( frame == 2) return inSequence.substring(2); if ( frame == 3) return reverseTranscribe(inSequence); if ( frame ==4 ) return reverseTranscribe(inSequence.substring(0, inSequence.length() -1 )); if ( frame == 5 ) return reverseTranscribe(inSequence.substring(0, inSequence.length() -2)); throw new Exception("Unknown frame"); }
6
@Override public void keyPressed(KeyEvent e) { switch(e.getKeyCode()) { case KeyEvent.VK_UP: instance.level.getPlayer().move(0, -1); break; case KeyEvent.VK_RIGHT: instance.level.getPlayer().move(1, 0); break; case KeyEvent.VK_DOWN: instance.level.getPlayer().move(0, 1); break; case KeyEvent.VK_LEFT: instance.level.getPlayer().move(-1, 0); break; case KeyEvent.VK_ESCAPE: instance.endGame(); break; } }
5
public PermClass getClassUnderPoint(int x, int y) { for(PermClass p : PermData.getData().classes) { if(x >= p.x && x <= p.x + 30 && y >= p.y && y <= p.y + 30) { cox = x - p.x; coy = y - p.y; return p; } } return null; }
5
private boolean checkPackage() { if (getBarPackage().getApkFile() == null || !getBarPackage().getApkFile().canRead()) { getLog().error("APK file is not specified or cannot be read."); return false; } String apkName = getBarPackage().getApkFile().getName(); if (getBarPackage().getBarFile() == null) { getLog().error("BAR file is not specified."); return false; } File currentBarFile = new File(getBarPackage().getBarFile().getParent(), apkName.replace(".apk", ".bar")); if (!currentBarFile.exists()) { getLog().error("BAR file does not exist."); return false; } File desirableBarFile = getBarPackage().getBarFile(); if (currentBarFile.getPath().equals(desirableBarFile.getPath())) { // APK file name matches BAR file name, no need to rename. return true; } if (!currentBarFile.canWrite()) { getLog().error("BAR file does not exist or no permission to write."); return false; } // If a file with such name already exists, try to delete it. if (desirableBarFile.exists() && !desirableBarFile.delete()) { getLog().error("Failed to delete existing BAR file with desirable " + "name. Path: " + desirableBarFile.getPath()); return false; } return currentBarFile.renameTo(desirableBarFile); }
8
private void writeInt(List<Byte> ret, int val) { if (val < 0 || val >= 0x200000) { ret.add((byte)(((val >> 22) & 0x7f) | 0x80)); ret.add((byte)(((val >> 15) & 0x7f) | 0x80)); ret.add((byte)(((val >> 8) & 0x7f) | 0x80)); ret.add((byte)(val & 0xff)); } else { if (val >= 0x4000) { ret.add((byte)(((val >> 14) & 0x7f) | 0x80)); } if (val >= 0x80) { ret.add((byte)(((val >> 7) & 0x7f) | 0x80)); } ret.add((byte)(val & 0x7f)); } }
4
@SuppressWarnings("unchecked") public String open(String message,Signature signature){ //System.out.println("\n---------------Open protocol--------------\n"); long start = System.currentTimeMillis(); // Check if the signature is valid String result = ""; try{ // Check validity // Catch the fields EllipticCurve ec = new EllipticCurve(new secp256r1()); ECPoint E0 = new ECPoint(ec,signature.getE0().getx(),signature.getE0().gety()); ECPoint E1 = new ECPoint(ec,signature.getE1().getx(),signature.getE1().gety()); ECPoint E2 = new ECPoint(ec,signature.getE2().getx(),signature.getE2().gety()); // Compute S1 and S2 ECPoint MinusY1E0 = new ECPoint(ec,E0.multiply(this.osk.gety1()).getx(), E0.multiply(this.osk.gety1()).gety().negate()); ECPoint MinusY2E0 = new ECPoint(ec,E0.multiply(this.osk.gety2()).getx(), E0.multiply(this.osk.gety2()).gety().negate()); ECPoint S1 = E1.add(MinusY1E0); ECPoint S2 = E2.add(MinusY2E0); //System.out.println("S1:\n\tS1x = "+S1.getx()+"\n\tS1y = "+S1.gety()); //System.out.println("S2:\n\tS2x = "+S2.getx()+"\n\tS2y = "+S2.gety()); if(S1.getx().equals(S2.getx()) && S1.gety().equals(S2.gety())){ System.out.println("Opening succesfull!!"); } else{ System.out.println("Opening failed..."); } // Search pseudo user Boolean search = true; HashMap<String,Mpk> userList = this.issue.getMembersList(); Iterator it = userList.keySet().iterator(); while(it.hasNext() && search){ String pseudo = (String) it.next(); Mpk mpk = userList.get(pseudo); if(mpk.geth().getx().compareTo(S1.getx()) == 0 && mpk.geth().gety().compareTo(S1.gety()) == 0){ System.out.println("\nPseudo of the user who signed: "+ pseudo); result = pseudo; search = false; } } } catch(Exception e){ e.printStackTrace(); } long end = System.currentTimeMillis(); //System.out.println("\nExecution time was "+(end-start)+" ms."); //System.out.println("\n---------------DONE--------------"); return result; }
7
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + cacheSize; result = prime * result + frequency; result = prime * result + numberOfCores; result = prime * result + numberOfThreads; result = prime * result + ((socket == null) ? 0 : socket.hashCode()); return result; }
1
public static String selectQuery(String queryString) { BasicConfigurator.configure(); //create an object Sparql Query from a parameter string Query query = QueryFactory.create(queryString); try { //it connects to the server with Parliament and execute the query QueryExecution exec = QueryExecutionFactory.sparqlService( OpenstackNetProxyConstants.URL_PARLIAMENT, query); ResultSet rs = exec.execSelect(); ByteArrayOutputStream os = new ByteArrayOutputStream(); //Format the query result in RDF-XML ResultSetFormatter.outputAsRDF(os, "RDF/XML-ABBREV", rs); String w=""; try { w = new String(os.toByteArray(),"UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } //String tw = ResultSetFormatter.asText(rs); //Print the query result System.out.println(w); return w; } finally { } }
1
public void deconnexionServeur() throws IOException { connexion.envoyer("QUIT"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } connexion.fermer(); }
1
public static String validateArtist(String artist) { HashMap<String,String> artists = DataManager.getArtistMap(); for(String artistFromMap : artists.keySet()) { int levDist = StringUtils.getLevenshteinDistance(artistFromMap.toUpperCase(), artist.toUpperCase()); double ratio = (artistFromMap.length() - levDist + 0.0) / (artistFromMap.length() + 0.0); if(ratio == 1.0) { Logger.LogToStatusBar(artistFromMap + " exactly matches"); return artistFromMap; } else if(ratio >= 0.5) { ArrayList<String> matches = DataManager.getArtistMatches().get(artist); if(matches == null) { matches = new ArrayList<String>(); matches.add(artistFromMap); DataManager.getArtistMatches().put(artist, matches); } else { matches.add(artistFromMap); DataManager.getArtistMatches().remove(artist); DataManager.getArtistMatches().put(artist, matches); } } } return ""; }
4
public void putAll(Map<? extends K, ? extends V> m) { cache.putAll(m); }
2
static public String fixUrl(String inUrl) { int docLoc = inUrl.lastIndexOf('.'); int protLoc = inUrl.indexOf("://"); int slashLoc = -1; if (protLoc > 0) slashLoc = inUrl.indexOf('/', protLoc+3); else slashLoc = inUrl.indexOf('/'); if (slashLoc < 0 || (slashLoc > 0 && docLoc < slashLoc)) // none inUrl = inUrl + '/'; inUrl = removeExtraSlash(inUrl); return inUrl; }
4
@Override public List<Integer> update(Criteria beans, Criteria criteria, GenericUpdateQuery updateGeneric, Connection conn) throws DaoQueryException { List paramList1 = new ArrayList<>(); List paramList2 = new ArrayList<>(); StringBuilder sb = new StringBuilder(UPDATE_QUERY); String queryStr = new QueryMapper() { @Override public String mapQuery() { Appender.append(DAO_ORDER_SEATS, DB_ORDER_SEATS, criteria, paramList1, sb, COMMA); Appender.append(DAO_ORDER_CURR_PRICE, DB_ORDER_CURR_PRICE, criteria, paramList1, sb, COMMA); Appender.append(DAO_ORDER_CURR_DISCOUNT, DB_ORDER_CURR_DISCOUNT, criteria, paramList1, sb, COMMA); Appender.append(DAO_ORDER_USER_DISCOUNT, DB_ORDER_USER_DISCOUNT, criteria, paramList1, sb, COMMA); Appender.append(DAO_ORDER_FINAL_PRICE, DB_ORDER_FINAL_PRICE, criteria, paramList1, sb, COMMA); Appender.append(DAO_ORDER_DATE, DB_ORDER_DATE, criteria, paramList1, sb, COMMA); Appender.append(DAO_ORDER_STATUS, DB_ORDER_STATUS, criteria, paramList1, sb, COMMA); sb.append(WHERE); Appender.append(DAO_ID_ORDER, DB_ORDER_ID_ORDER, beans, paramList2, sb, AND); Appender.append(DAO_ID_USER, DB_ORDER_ID_USER, beans, paramList2, sb, AND); Appender.append(DAO_ID_TOUR, DB_ORDER_ID_TOUR, beans, paramList2, sb, AND); Appender.append(DAO_ORDER_SEATS, DB_ORDER_SEATS, beans, paramList2, sb, AND); Appender.append(DAO_ORDER_CURR_PRICE, DB_ORDER_CURR_PRICE, beans, paramList2, sb, AND); Appender.append(DAO_ORDER_CURR_DISCOUNT, DB_ORDER_CURR_DISCOUNT, beans, paramList2, sb, AND); Appender.append(DAO_ORDER_USER_DISCOUNT, DB_ORDER_USER_DISCOUNT, beans, paramList2, sb, AND); Appender.append(DAO_ORDER_FINAL_PRICE, DB_ORDER_FINAL_PRICE, beans, paramList2, sb, AND); Appender.append(DAO_ORDER_DATE, DB_ORDER_DATE, beans, paramList2, sb, AND); Appender.append(DAO_ORDER_STATUS, DB_ORDER_STATUS, beans, paramList2, sb, AND); return sb.toString(); } }.mapQuery(); paramList1.addAll(paramList2); try { return updateGeneric.sendQuery(queryStr, paramList1.toArray(), conn); } catch (DaoException ex) { throw new DaoQueryException(ERR_ORDER_UPDATE, ex); } }
1
private static Schedule getSchedule(Schedule bean, PreparedStatement stmt, ResultSet rs) throws SQLException{ stmt.setDate(1, bean.getWorkDay()); stmt.setString(2, bean.getUsername()); rs = stmt.executeQuery(); if (rs.next()) { Schedule newBean = new Schedule(); newBean.setWorkDay(rs.getDate("work_day")); newBean.setFrom(rs.getTime("work_from")); newBean.setTo(rs.getTime("work_till")); newBean.setHourRate(rs.getBigDecimal("hourly_rate")); newBean.setVacationDays(rs.getInt("vac_days")); newBean.setUsername(rs.getString("username")); return newBean; } else { System.out.println("unable to retrieve schedule info"); return null; } }
1
@Override public void init(ServletConfig config) throws ServletException{ try { // Create a JNDI Initial context to be able to lookup the DataSource InitialContext ctx = new InitialContext(); // Lookup the DataSource, which will be backed by a pool // that the application server provides. pool = (DataSource)ctx.lookup("java:comp/env/jdbc/mysql_ebookshop"); if (pool == null) throw new ServletException("Unknown DataSource 'jdbc/mysql_ebookshop'"); } catch (NamingException ex) { Logger.getLogger(EntryServlet.class.getName()).log(Level.SEVERE, null, ex); } }
2
public SimpleReplace(String args[]) { // Get input from the console String startingPath = ConsoleTools.getNonEmptyInput("Enter starting path: "); String match = ConsoleTools.getNonEmptyInput("Enter string to match: "); String replacement = ConsoleTools.getNonNullInput("Enter string to replace: "); String[] fileExtensions = ConsoleTools.getSeriesOfInputs("Enter file extension to match: "); while (fileExtensions.length <= 0) { fileExtensions = ConsoleTools.getSeriesOfInputs("Enter file extension to match: "); } System.out.println(""); // Setup the Crawler DirectoryCrawler crawler = new DirectoryCrawler(); crawler.setFileHandler(new SimRepFileConHandler(match, replacement, FileTools.LINE_ENDING_WIN)); crawler.setFileFilter(new FileExtensionFilter(fileExtensions)); // Do the Crawl System.out.println("STARTING..."); crawler.crawl(startingPath); System.out.println("DONE"); }
1
private static void parseTestNgResultCreateCsv(List<String> urlsOrFiles, String csvFileName) { List<TestResultData> testNgResultData = parseTestNgResultFromFilesOrUrls(urlsOrFiles); CsvResultFile csvResultFile = new CsvResultFile(); try { System.out.println("Creating csv file..."); csvResultFile.createCsvResultFile(csvFileName, testNgResultData); System.out.println("Successfully created csv file..."); } catch (Exception e) { System.err.print("Error while creating csvResultFile " + e); } }
1
public Archive.ArchiveData read(HistoryLinkMap linkMap, LinkDataFactory linkFactory) throws IOException { Archive.ArchiveData data = readArchiveData(linkMap, linkFactory); for (Archive.RootObject obj : data.mRootObjects) { if (obj.mDigest.isNullDigest()) { continue; } readLink(linkMap, linkFactory, obj.mDigest); } for (Block block : data.mBlocks) { for (LinkDigest digest : block.getDigests()) { if (mIgnoreMissingLinks) { try { readLink(linkMap, linkFactory, digest); } catch (IOException ioe) { // NOP } } else { readLink(linkMap, linkFactory, digest); } } } return data; }
6
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object controller) throws Exception { String uri = request.getRequestURI(); if(uri.endsWith("/login/login") || uri.endsWith("/login/logar")|| uri.endsWith("/usuario") || uri.endsWith("/usuario/cadastrarUsuario") || uri.contains("resources")){ return true; } if(request.getSession().getAttribute("usuarioLogado") != null) { return true; } response.sendRedirect(request.getContextPath()+"/login/login"); return false; }
6
public void onStart(IContext context) throws JFException { this.engine = context.getEngine(); this.indicators = context.getIndicators(); this.acount = context.getAccount(); this.rsizone = false; try { File file = new File("copyOfRsi_onBar2.csv"); printWriter = new PrintWriter(new BufferedWriter(new FileWriter(file))); // 結果出力ファイルHEADER StringBuffer print = new StringBuffer(); print.append("Type").append(SEPARATOR) .append("Label").append(SEPARATOR) .append("Amount").append(SEPARATOR) .append("Direction").append(SEPARATOR) .append("OpenPrice").append(SEPARATOR) .append("Profit/Loss in pips").append(SEPARATOR) .append("OpenDate").append(SEPARATOR) .append("CloseDate").append(SEPARATOR) .append("Comments").append(SEPARATOR) .append("A_Global (アカウントがグローバル・アカウントの場合にtrue)").append(SEPARATOR) .append("A_CreditLine (取引可能額。値は約5秒間隔で更新されている。)").append(SEPARATOR) .append("A_Currency (アカウントの通貨設定)").append(SEPARATOR) .append("A_Equity (純資産額。値は約5秒間隔で更新されている。)").append(SEPARATOR) .append("A_Leverage (レバレッジ設定)").append(SEPARATOR) .append("A_MarginCutLevel (マージンカットレベル。このレベルを超過するとマージンカット(ロスカット)。)").append(SEPARATOR) .append("A_OverWeekEndLeverage (ウィークエンド・レバレッジ・レベル。このレベルを超過するとマージンカット(ロスカット)。)").append(SEPARATOR) .append("A_UseOfLeverage (証拠金使用率。値は約5秒間隔で更新されている。)").append(SEPARATOR) .append("A_Balance"); printWriter.println(print.toString()); } catch (IOException e) { e.printStackTrace(); } }
1
public int dUpdateReservation(Reservation res) throws UnauthorizedUserException, BadConnectionException { PreparedStatement pStmnt = null; // close a reservation and leave a comment try { pStmnt = con.prepareStatement(qs.update_res_d); pStmnt.setString(1, res.getComment()); pStmnt.setInt(2, res.getReservationNumber()); pStmnt.executeQuery(); } catch(SQLException sqlE) { if(sqlE.getErrorCode() == 1142) throw(new UnauthorizedUserException("AccessDenied")); else throw(new BadConnectionException("BadConnection")); } finally { try { if(pStmnt != null) pStmnt.close(); } catch (Exception ex) { } } // update the customer reservation count and memberID (if needed) try { pStmnt = con.prepareStatement(qs.update_res_count); pStmnt.setInt(1, res.getCustomerID()); } catch(SQLException sqlE) { if(sqlE.getErrorCode() == 1142) throw(new UnauthorizedUserException("AccessDenied")); else throw(new BadConnectionException("BadConnection")); } finally { try { if(pStmnt != null) pStmnt.close(); } catch (Exception ex) { } } return 1; }
8
public void removeKey(String var) { Boolean changed = false; if(this.props.containsKey(var)) { this.props.remove(var); changed = true; } for (int i = 0; i < this.lines.size(); i++) { String line = this.lines.get(i); if (line.trim().length() == 0) { continue; } if (line.charAt(0) == '#') { continue; } if (line.contains("=")) { int delimPosition = line.indexOf('='); String key = line.substring(0, delimPosition).trim(); if (key.equals(var)) { this.lines.remove(i); changed = true; } } else { continue; } } // Save on change if(changed) save(); }
7
@Override public void onMoveFile(String arg0, String arg1, boolean replace, DokanFileInfo arg3) throws DokanOperationException { try { if (replace) { try { EntityInfo inf = fileSystem.getFileMetaData(mapWinToUnixPath(arg1)); if (DirectoryInfo.class.isInstance(inf)) fileSystem.deleteDirectoryRecursively(arg1); else fileSystem.deleteFile(arg1); } catch (PathNotFoundException e) { } } fileSystem.rename(mapWinToUnixPath(arg0), mapWinToUnixPath(arg1)); } catch (PathNotFoundException e) { throw new DokanOperationException(net.decasdev.dokan.WinError.ERROR_PATH_NOT_FOUND); } catch (DestinationAlreadyExistsException e) { throw new DokanOperationException(net.decasdev.dokan.WinError.ERROR_ALREADY_EXISTS); } catch (AccessDeniedException e) { throw new DokanOperationException(net.decasdev.dokan.WinError.ERROR_ACCESS_DENIED); } catch (Exception e) { e.printStackTrace(); } }
7
@Override public boolean canMove(int x, int y) { int diagnolY = 0, digonlX = 0,dx=1,dy=1; isValid = false; isOccupiedByOppsitPiece=true; if (Math.abs(x-(locationX/Chess.sizeOfSquare)) == Math.abs(y-(locationY/Chess.sizeOfSquare))) { isValid=true; if (x < (locationX/Chess.sizeOfSquare)) { digonlX = locationX/Chess.sizeOfSquare-1; dx=-1; }else { digonlX = (locationX/Chess.sizeOfSquare)+1; dx=1; } if (y< (locationY/Chess.sizeOfSquare)) { diagnolY = locationY/Chess.sizeOfSquare-1; dy=-1; }else { diagnolY= (locationY/Chess.sizeOfSquare)+1; dy=1; } for (int i=0;i<Math.abs(x-(locationX/Chess.sizeOfSquare))-1;i++) { if (Chess.positions[diagnolY][digonlX]!=null) { isValid=false; } digonlX+=dx; diagnolY+=dy; } } if (Chess.positions[y][x] != null) { if (Chess.positions[y][x].isWhite==isWhite) { isOccupiedByOppsitPiece=false; } } // TODO Auto-generated method stub if (isValid&&isOccupiedByOppsitPiece) { return true; }else { return false; } }
9
public SkladnikiManagerFrame(){ super("Zarz�dzaj sk�adnikami"); setSize(szerokosc, wysokosc); setAlwaysOnTop(true); Toolkit kit = Toolkit.getDefaultToolkit(); Dimension screenSize = kit.getScreenSize(); setBounds((screenSize.width-szerokosc)/2, (screenSize.height-wysokosc)/2,szerokosc,wysokosc); setResizable(false); setLayout(new BorderLayout()); setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); addWindowListener(new WindowListener(){ public void windowClosing(WindowEvent arg0) { close(); } public void windowActivated(WindowEvent e) { // TODO Auto-generated method stub } public void windowClosed(WindowEvent e) { // TODO Auto-generated method stub } public void windowDeactivated(WindowEvent e) { // TODO Auto-generated method stub } public void windowDeiconified(WindowEvent e) { // TODO Auto-generated method stub } public void windowIconified(WindowEvent e) { // TODO Auto-generated method stub } public void windowOpened(WindowEvent e) { // TODO Auto-generated method stub } }); W= new WeightTextField() {}; B= new WeightTextField() {}; T= new WeightTextField() {}; nazwa= new JTextField(13); W.setColumns(4); B.setColumns(4); T.setColumns(4); usun=new JButton("Usuń składnik"); zmien=new JButton("Aktualizuj składnik"); labelN=new JLabel("Nazwa"); labelW=new JLabel("W"); labelB=new JLabel("B"); labelT=new JLabel("T"); skladnikiCombo= new SkladnikiComboBox() { public void Action(){ skladnik= (Skladnik) this.getSelectedItem(); nazwa.setText(skladnik.name); W.setText(skladnik.W+""); B.setText(skladnik.B+""); T.setText(skladnik.T+""); } }; skladnikiCombo.SkladnikiComboInit(); zmien.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(!( B.getText().equals(skladnik.B+"") && W.getText().equals(skladnik.W+"") && T.getText().equals(skladnik.T+"") && nazwa.getText().equals(skladnik.name ) ) ) { System.out.println("Weszlo!!!!!!!!!!!!!!!!!!!!!!"); try{ skladnik.B=Integer.parseInt(B.getText()); skladnik.W=Integer.parseInt(W.getText()); skladnik.T=Integer.parseInt(T.getText()); skladnik.name=nazwa.getText(); Main.baza.InitDataBaseConnection(); Main.baza.upDateSkladnik(skladnik); Main.baza.InitSkladniki(); Main.baza.CloseConnection(); for(int i=0 ; i<5 ; i++){ MainFrame.posilkiPanel[i].skladnikiCombo.SkladnikiComboUpdate(); MainFrame.posilkiPanel[i].BudujTabele(); } skladnikiCombo.SkladnikiComboUpdate(); close(); } catch(NumberFormatException c){ JOptionPane.showMessageDialog(null, "Wpisales niedozwolone wartosci w pola! :(","Blad",JOptionPane.ERROR_MESSAGE); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }); skladnik= (Skladnik) skladnikiCombo.getSelectedItem(); nazwa.setText(skladnik.name); W.setText(skladnik.W+""); B.setText(skladnik.B+""); T.setText(skladnik.T+""); //===========rozkad========================= JPanel panelCombo = new JPanel(); // NORTH JPanel panelSkladnik1 = new JPanel();// / CENTER JPanel panelButton = new JPanel(); // SOUTH int x=15; panelSkladnik1.setLayout(null); panelSkladnik1.add(labelN);labelN.setBounds(80,2,60,19); panelSkladnik1.add(labelW);labelW.setBounds(168,2,20,19); panelSkladnik1.add(labelB);labelB.setBounds(203,2,20,19); panelSkladnik1.add(labelT);labelT.setBounds(238,2,20,19); panelSkladnik1.add(nazwa);nazwa.setBounds(x+3, 20, 140, 23); panelSkladnik1.add(W); W.setBounds(x+143, 20, 35, 23); panelSkladnik1.add(B); B.setBounds(x+178, 20, 35, 23); panelSkladnik1.add(T); T.setBounds(x+213, 20, 35, 23); panelButton.add(zmien); panelButton.add(usun); panelCombo.add(skladnikiCombo); setLayout(new BorderLayout()); add(panelCombo,BorderLayout.NORTH); add(panelSkladnik1,BorderLayout.CENTER); add(panelButton,BorderLayout.SOUTH); //rozklad======================================================== }
7
public ConfigurationSection getConfigurationSection(String path) { Object val = get(path, null); if (val != null) { return (val instanceof ConfigurationSection) ? (ConfigurationSection) val : null; } val = get(path, getDefault(path)); return (val instanceof ConfigurationSection) ? createSection(path) : null; }
3
private StringManager(String packageName) { String bundleName = packageName + ".LocalStrings"; try { bundle = ResourceBundle.getBundle(bundleName); return; } catch( MissingResourceException ex ) { // Try from the current loader ( that's the case for trusted apps ) ClassLoader cl=Thread.currentThread().getContextClassLoader(); if( cl != null ) { try { bundle=ResourceBundle.getBundle(bundleName, Locale.getDefault(), cl); return; } catch(MissingResourceException ex2) { } } if( cl==null ) cl=this.getClass().getClassLoader(); if (log.isDebugEnabled()) log.debug("Can't find resource " + bundleName + " " + cl); if( cl instanceof URLClassLoader ) { if (log.isDebugEnabled()) log.debug( ((URLClassLoader)cl).getURLs()); } } }
7
public static void convert(String kfDescPath, String textFilePath) throws IOException, ParserConfigurationException, SAXException { // Get the file descriptor from the XML file. KFileDescriptor kfd = new KFileDescriptor(kfDescPath); // Validate that keyed file and output text file are not the same. String keyedFilename = new File(kfd.getFileName()).getCanonicalPath(); String textFilename = new File(textFilePath).getCanonicalPath(); if (keyedFilename.equals(textFilename)) { throw new IllegalArgumentException("Output text file cannot be the same input keyed file"); } // Get record data and make sure is correct. int kl = kfd.getKeyLength(); int rs = kfd.getRecordSize(); if (kl <= 0 || rs <= 0 || kfd.getFieldCount() <= 0) { throw new IllegalArgumentException("Invalid input data"); } // Create appropriate file handlers. RandomAccessFile file = new RandomAccessFile(keyedFilename, "r"); BufferedWriter bw = new BufferedWriter(new FileWriter(textFilename)); // Write the header to the text file. writeHeader(kfd, bw); // Setup the null key, so valid records can be identified. byte[] nullKey = new byte[kl]; byte[] readKey = new byte[kl]; // record key byte[] record = new byte[rs]; // record contents // Start cycling through the file. long len = file.length(); long i = 516; long reg = 0; while (i < len) { while (reg < 512 && reg + rs <= len) { // Read the key of the current record. file.seek(i); file.readFully(readKey); // If a valid (non null) key is found, read the record and // write the text equivalent. if (!Arrays.equals(nullKey, readKey)) { file.seek(i); file.readFully(record); writeToText(kfd, record, bw); } // Reposition the file pointer. i += rs; reg += rs; if (reg + rs > 512) { i += 512 - reg; reg = 512; } } reg = 0; } // Close everything. bw.flush(); bw.close(); file.close(); }
9
public void removeAutoFilter() { removeFilterDatabase(); // remove the _FILTER_DATABASE name necessary for AutoFilters int zz = getIndexOf( AUTOFILTER ); // remove all AutoFitler records while( zz != -1 ) { SheetRecs.remove( zz ); zz = getIndexOf( AUTOFILTER ); } // remove the two unknown records zz = getIndexOf( (short) 155 ); if( zz > -1 ) { SheetRecs.remove( zz ); } zz = getIndexOf( (short) 157 ); if( zz > -1 ) { SheetRecs.remove( zz ); } // and hows about the Mso/Obj records, huh? huh? autoFilters.clear(); // finally, must set all rows to NOT hidden - I believe Excel does this when AutoFilters are turned off for( int i = 0; i < rows.size(); i++ ) { rows.get( i ).setHidden( false ); } }
4
public void run() { boolean done = false; while (!done) { showMenu(); int option = getOption(); doAction(option); if (option == EXIT_OPTION) { done = true; } } }
2
protected void genClosedText(MOB mob, Exit E, int showNumber, int showFlag) throws IOException { if((showFlag>0)&&(showFlag!=showNumber)) return; if(E instanceof Item) mob.tell(L("@x1. Exit Closed Text: '@x2'.",""+showNumber,E.closedText())); else mob.tell(L("@x1. Closed Text: '@x2'.",""+showNumber,E.closedText())); if((showFlag!=showNumber)&&(showFlag>-999)) return; final String newName=mob.session().prompt(L("Enter something new (null=blank)\n\r:"),""); if(newName.equals("null")) E.setExitParams(E.doorName(),E.closeWord(),E.openWord(),""); else if(newName.length()>0) E.setExitParams(E.doorName(),E.closeWord(),E.openWord(),newName); else mob.tell(L("(no change)")); }
7
public void extract(String getdata) { if (getdata.startsWith("GET")) { get = getdata; url = (getdata.substring(getdata.indexOf("/"))).split(" ")[0]; try { url = URLDecoder.decode(url, "UTF-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (url.indexOf("?") >= 0) { dataget = url.split("\\?")[1]; url = url.split("\\?")[0]; } else { dataget="ZERO"; } ext = url.split("\\.")[((url.split("\\.")).length)-1]; if (url.length() == 0) { url="index.html"; } } else if(getdata.startsWith("Accept:")) { accept = getdata.substring(getdata.indexOf(":")+1); } else if(getdata.startsWith("Accept-Language:")) { acceptLang = getdata.substring(getdata.indexOf(":")+1); } else if(getdata.startsWith("Accept-Encoding:")) { acceptEnc = getdata.substring(getdata.indexOf(":")+1); } else if(getdata.startsWith("User-Agent:")) { userAgent = getdata.substring(getdata.indexOf(":")+1); } else if(getdata.startsWith("Host:")) { host = getdata.substring(getdata.indexOf(":")+1); } }
9
public void roundInit(int round) { if(debug) print("Custom Initializing..."); firstInvocation=true; passNumber=1; timesCanPass=nplayers-1-getIndex(); if(round==1) { timesCanPass=nplayers-timesCanPass-1; } timesCanPassInitial=timesCanPass; stoppingThreshold=(int)Math.floor(timesCanPass/Math.E); }
2
public static void renderSVG(Card card, Graphics2D g) { try { SVGDiagram diagram; if (card == null) { diagram = universe.getDiagram(ImageManager.class.getResource(urlBase + "blank.svg").toURI()); } else { diagram = universe.getDiagram(ImageManager.class.getResource(urlBase + card.getSuit().name().toLowerCase() + "/" + card.getRank().ordinal() + ".svg").toURI()); } diagram.setIgnoringClipHeuristic(true); diagram.render(g); } catch (URISyntaxException e) { e.printStackTrace(); } catch (SVGException e) { e.printStackTrace(); } }
3
static final void method3514(byte i) { anInt4465++; for (Class348_Sub27 class348_sub27 = ((Class348_Sub27) Class348_Sub42_Sub20.aClass262_9711.getFirst(4)); class348_sub27 != null; class348_sub27 = (Class348_Sub27) Class348_Sub42_Sub20.aClass262_9711 .nextForward((byte) 57)) { if ((((Class348_Sub27) class348_sub27).anInt6893 ^ 0xffffffff) == 0) { ((Class348_Sub27) class348_sub27).anInt6894 = 0; if (((((Class348_Sub27) class348_sub27).anInt6905 ^ 0xffffffff) <= -1) && (((Class348_Sub27) class348_sub27).anInt6896 ^ 0xffffffff) <= -1 && ((Class367_Sub4.mapSizeX ^ 0xffffffff) < (((Class348_Sub27) class348_sub27).anInt6905 ^ 0xffffffff)) && ((Class348_Sub40_Sub3.mapSizeY ^ 0xffffffff) < (((Class348_Sub27) class348_sub27).anInt6896 ^ 0xffffffff))) Class184.method1387(i + 26, class348_sub27); } else class348_sub27.removeNode(); } if (i != -105) method3516(-128); }
7
public void run() { byte[] receiveData = new byte[20000]; while(true && !this.stop) { try { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); getServer().receive(receivePacket); ByteArrayInputStream bis = new ByteArrayInputStream(receivePacket.getData()); ObjectInput in = new ObjectInputStream(bis); Object temp = null; try { temp = in.readObject(); } catch (ClassNotFoundException e) { System.out.println("Did not find gossiped object."); e.printStackTrace(); } catch (EOFException e) { System.out.println("EOF Exception"); e.printStackTrace(); } //needs to be able to take 1 inputs //1. membership list MembershipList ml = (MembershipList) temp; //spin up a new thread to merge the two lists MergeMembershipListThread mmlt = new MergeMembershipListThread(ml, this.gs); //System.out.println(this.gs.getMembershipList().toString()); mmlt.start(); bis.close(); in.close(); } catch(SocketException e) { //System.out.println("Gossip Socket Closed.\n"); } catch(EOFException e) { System.out.println("End of File Error\n"); e.printStackTrace(); } catch(IOException e) { System.out.println("I/O issue on the server side"); e.printStackTrace(); } } }
7
public static String unescape(String string) { int length = string.length(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; ++i) { char c = string.charAt(i); if (c == '+') { c = ' '; } else if (c == '%' && i + 2 < length) { int d = JSONTokener.dehexchar(string.charAt(i + 1)); int e = JSONTokener.dehexchar(string.charAt(i + 2)); if (d >= 0 && e >= 0) { c = (char)(d * 16 + e); i += 2; } } sb.append(c); } return sb.toString(); }
6
@Override public void setDisplay() { switch (area.terrain) { case PLAINE: this.color = Color.yellow; break; case FORET: this.color = Color.green; break; case DESERT: this.color = Color.red; break; case MONTAGNE: this.color = Color.cyan; break; case VILLE: this.color = Color.pink; break; default: this.color = Color.white; break; } }
5
void init() { // Calculate pvalue cutoff scoreCutOff = scoreCutOff(); //--- // Calculate Fisher parameters //--- N = D = 0; for (String geneId : geneSets.getGenes()) if (geneSets.hasValue(geneId)) { N++; if (isTopScore(geneId)) D++; } if (verbose) Timer.showStdErr("Fisher Exact test parameters:\n\tN : " + N + "\n\tD : " + D); }
4
public static ClassInfo getClassInfo(String typeSig) { if (typeSig.charAt(0) != 'L') throw new IllegalArgumentException(); return ClassInfo.forName(typeSig.substring(1, typeSig.length() - 1) .replace('/', '.')); }
1
private int clearArea(int zombiesAboutToEncouter) { int zombiesKilled = 0; List<Survivor> team = this.raidSettings.team; for (int i = 0 ; i < zombiesAboutToEncouter ; i++) { Survivor target = team.get(Math.abs(new Random().nextInt()) % team.size()); double zombieAttack = BitingDeathGame.getRandomProbability(); boolean targetSaved = false; for (Survivor potentialSaver : team) { // Possibly the target himself if (potentialSaver.getFightingEfficiency() > zombieAttack) { targetSaved = true; } } if (! targetSaved) { // Bitten if (! this.survivorsHurtDuringRaid.contains(target)) { this.survivorsHurtDuringRaid.add(target); } } zombiesKilled++; } try { this.raidSettings.getDestination().removeZombies(zombiesKilled); } catch (IncoherentNumberException e) { System.err.println("Erreur de code dans Raid#clearArea : le nombre de zombies à supprimer est incohérent"); e.printStackTrace(); } return zombiesKilled; }
6
private final void parseChangeLog(String changelog) { String lines[] = changelog.split("\\r?\\n"); String checkVersion = lines[0]; String currentVersion = Main.getVersion(); boolean updateNeeded = false; String[] versions1 = checkVersion.split("\\."); String[] versions2 = currentVersion.split("\\."); int maxLen = (versions1.length > versions2.length ? versions1.length : versions2.length); for (int i = 0; i < maxLen; ++i) { int v1 = 0, v2 = 0; if (versions1.length > i) { try { v1 = Integer.parseInt(versions1[i]); } catch (NumberFormatException e) {} } if (versions2.length > i) { try { v2 = Integer.parseInt(versions2[i]); } catch (NumberFormatException e) {} } if (v1 > v2) { updateNeeded = true; break; } else if (v2 > v1) { break; } } if (updateNeeded) { this.showUpdateText(checkVersion); } }
9
public static String[] getFileNames(String version) throws IOException { String s = OberienURL.get(version); String[] fileNames = s.substring(s.indexOf("[files]")+7, s.indexOf("[/files]")).split("\n"); for (int i = 0; i < fileNames.length; i++) { fileNames[i] = "Game/" + fileNames[i]; } return fileNames; }
1
public static void main(String[] args) { Fast fast = new Fast(); StdDraw.setXscale(0, 32768); StdDraw.setYscale(0, 32768); StdDraw.show(0); String filename = args[0]; In in = new In(filename); int N = in.readInt(); Point[] points = new Point[N]; for (int i = 0; i < N; i++) { int x = in.readInt(); int y = in.readInt(); Point p = new Point(x, y); points[i] = p; p.draw(); } SlopePair[] slopes = new SlopePair[N]; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // http://stackoverflow.com/questions/70324/java-inner-class-and-static-nested-class slopes[j] = fast.new SlopePair(); slopes[j].index = j; slopes[j].slope = points[i].slopeTo(points[j]); } sort(slopes, N); int lo = 1; int hi = 1; while (hi < N-1) { while (slopes[lo].slope == slopes[hi].slope) { if (hi < N-1) hi++; if (hi == N-1) break; } if (hi - lo >= 3) { StdOut.print(points[i].toString()); for (int t = lo; t < hi; t++) { StdOut.print(" -> " + points[slopes[t].index]); } StdOut.println(); points[i].drawTo(points[slopes[hi - 1].index]); } lo = hi; } } StdDraw.show(0); }
9
public Expression parseExpression(String methodName, boolean allowPrefix, Object... symbols) { try { Method method = Parser.getInstance().getClass().getDeclaredMethod(methodName); method.setAccessible(true); Binary binaryExpression = null; Expression leftExpression; if (allowPrefix && SyntacticValidator.getInstance().isNextToken(ProductionRule.OPTIONAL, symbols)) { SyntacticValidator.getInstance().matchNextToken(ProductionRule.OPTIONAL, symbols); Operator operator = Operator.getOperator(TokenIterator.getInstance().getCurrent().getValue().toString()); Expression expression = (Expression) method.invoke(Parser.getInstance()); SemanticValidator.getInstance().validateExpressionIsNumeric(expression); leftExpression = binaryExpression = new Binary(operator, new Number(new Constant(0)), expression, parser.semanticAnalysis.symbolTable.declarations.types.Integer.getInstance()); if (!SyntacticValidator.getInstance().isNextToken(ProductionRule.OPTIONAL, symbols)) { SemanticValidator.getInstance().validateExpressionIsNumeric(binaryExpression); return ConstantFolder.getInstance().reduceExpression(binaryExpression); } } else { leftExpression = (Expression) method.invoke(Parser.getInstance()); if (SyntacticValidator.getInstance().isNextToken(ProductionRule.OPTIONAL, symbols)) { SemanticValidator.getInstance().validateExpressionIsNumeric(leftExpression); } else { return ConstantFolder.getInstance().reduceExpression(leftExpression); } } do { SyntacticValidator.getInstance().matchNextToken(ProductionRule.REQUIRED, symbols); Operator operator = Operator.getOperator(TokenIterator.getInstance().getCurrent().getValue().toString()); if (binaryExpression == null) { Expression rightExpression = (Expression) method.invoke(Parser.getInstance()); SemanticValidator.getInstance().validateExpressionIsNumeric(leftExpression); SemanticValidator.getInstance().validateExpressionIsNumeric(rightExpression); binaryExpression = new Binary(operator, leftExpression, rightExpression, SemanticValidator.getInstance().validateExpressionsAreOfTheSameType(leftExpression, rightExpression)); leftExpression = rightExpression; } else { Expression left = ConstantFolder.getInstance().reduceExpression(binaryExpression); Expression right = (Expression) method.invoke(Parser.getInstance()); SemanticValidator.getInstance().validateExpressionIsNumeric(left); SemanticValidator.getInstance().validateExpressionIsNumeric(right); binaryExpression = new Binary(operator, left, right, SemanticValidator.getInstance().validateExpressionsAreOfTheSameType(left, right)); } } while (SyntacticValidator.getInstance().isNextToken(ProductionRule.OPTIONAL, symbols)); return ConstantFolder.getInstance().reduceExpression(binaryExpression); } catch (Exception e) { return new InvalidExpression(); } }
7
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RepeatStatementNode other = (RepeatStatementNode) obj; if (exp1 == null) { if (other.exp1 != null) return false; } else if (!exp1.equals(other.exp1)) return false; if (stateSeq1 == null) { if (other.stateSeq1 != null) return false; } else if (!stateSeq1.equals(other.stateSeq1)) return false; return true; }
9
public static void checkAndCreateSchema(Connection conn,PrintWriter pw) { Statement stmt = null; ResultSet rs = null; try { conn.setAutoCommit(true); } catch (SQLException se) { pw.println("[NsSampleWork] Error when setting autocommit on connection; exception thrown: "); se.printStackTrace(); } // Check for existence of schema by quering the catalog systables try { stmt = conn.createStatement(); rs = stmt.executeQuery("select tablename from sys.systables " + " where tablename = 'SAMPLETBL'"); if (rs.next()) { pw.println("[NsSampleWork] Table 'SAMPLETBL' already exists; no need to create schema again."); return; } } catch (SQLException se) { pw.println("[NsSampleWork] Unable to query the metadata for existence of table SAMPLETBL; exception is "+se); pw.println("[NsSampleWork] Exiting the application."); se.printStackTrace(); System.exit(1); } // Create the necessary table and indexes try { pw.println("[NsSampleWork] Begin creating table - SAMPLETBL and necessary indexes. "); stmt.execute("create table SAMPLETBL (" + "t_int int," + "t_char char(15),"+ "t_float float," + "t_key bigint )"); stmt.execute("create index t_char_idx on SAMPLETBL ( t_char)"); stmt.execute("create index t_float_idx on SAMPLETBL ( t_float)"); stmt.execute("create index t_key_idx on SAMPLETBL ( t_key )" ); } catch (Exception e) { pw.println("[NsSampleWork] Error when creating schema; exception is " + e.toString()); pw.println("[NsSampleWork] Exiting the application."); e.printStackTrace(); System.exit(1); } finally { try { if(rs != null) rs.close(); if(stmt != null) stmt.close(); } catch (Exception e) { e.printStackTrace(); } } }//end of method checkAndCreateSchema()
7
public void setEnableExceptionTracking(boolean enableExceptions) { this.enableExceptions = enableExceptions; }
0
public List<String> locateJDK() { String JAVA_WINDOWS = "where javac"; String JAVA_LINUX = "readlink -f $(whereis javac)"; // readlink -f $(which java) //String JAVA_MAC = "ls -l `which javac`"; String JAVA_MAC = "/usr/libexec/java_home -v 1.8"; String osName = System.getProperty("os.name").toLowerCase(); //osName = "mac"; // for simulating a mac machine List<String> candidates = new ArrayList<>(); if (osName.contains("win")) { //C:\Program Files\Java\jdk1.8.0\bin\javac.exe String commandResult = executeCommand(JAVA_WINDOWS); Pattern pattern = Pattern.compile("\\s*((?<path>.:\\\\.*?\\\\javac.exe)(\\s|$))", Pattern.CASE_INSENSITIVE ); Matcher matcher = pattern.matcher(commandResult); while(matcher.find()){ String path = matcher.group("path").trim(); candidates.add(path); } } else if(osName.contains("nix") || osName.contains("nux") || osName.contains("aix")){ //String commandResult = "/javac: /usr/lib/jvm/java-7-openjdk-amd64/bin/javac /usr/lib/jvm/java-7-openjdk-amd64/bin/javac /usr/lib/jvm/java-7-openjdk-amd64/man/man1/javac.1.gz"; //just for test String commandResult = executeCommand(JAVA_LINUX); Pattern pattern = Pattern.compile("\\s*((?<path>\\/.*?\\/javac.*?)(\\s|$))", Pattern.CASE_INSENSITIVE ); Matcher matcher = pattern.matcher(commandResult); while(matcher.find()){ String path = matcher.group("path").trim(); candidates.add(path); } } else if(osName.contains("mac")){ //String commandResult = "lrwx-xr-x 1 root wheel 75 Jun 22 10:27 /usr/bin/javac -> /System/Library/Frameworks/JavaVM.framework/Versions/Current/Commands/javac" //String commandResult = "/Library/Java/JavaVirtualMachines/jdk1.8.0_66.jdk/Contents/Home /Library/Java/JavaVirtualMachines/jdk1.8.0_66.jdk/Contents/Home"; String commandResult = executeCommand(JAVA_MAC); if(commandResult.contains("Unable to finad any JVMs matching version")) return candidates; Pattern pattern = Pattern.compile("((?<path>\\/.*?\\/Home))", Pattern.CASE_INSENSITIVE ); Matcher matcher = pattern.matcher(commandResult); while(matcher.find()){ String path = matcher.group().trim(); candidates.add(path); } } return candidates; }
9
private void menor() throws Exception{ op2 = pila.pop(); if (op2.getValor().equals("null")) throw new Exception("Una de las variables esta sin inicializar!"); op1 = pila.pop(); if (op1.getValor().equals("null")) throw new Exception("Una de las variables esta sin inicializar!"); Elem resultado = new Elem("boolean"); if(op1.getTipo().equals("boolean")) { int b1 = ((Boolean)op1.getValor()).booleanValue() ? 1 : 0; int b2 = ((Boolean)op2.getValor()).booleanValue() ? 1 : 0; resultado.setValor(b1 < b2); } else if(op1.getTipo().equals("character")) resultado.setValor((((Character)op1.getValor()).charValue() < ((Character)op2.getValor()).charValue())); else //Real, Entero o Natural { double f1 = op1.getTipo().equals("float")? (Double)op1.getValor() : ((Integer)op1.getValor()).doubleValue(); double f2 = op2.getTipo().equals("float")? (Double)op2.getValor() : ((Integer)op2.getValor()).doubleValue(); resultado.setValor(f1 < f2); } pila.push(resultado); }
8
public long getBlogId() { return blogId; }
0
public void addPosition(Position position) { if(position == null) throw new NullPointerException("null cannot be added as a Position"); System.out.println("TEST1: " + otherPositions.size()); otherPositions.add(position); System.out.println("TEST2: " + otherPositions.size()); if (otherPositions.size() > 2) { Position newHeadPosition = otherPositions.remove(0); setPosition(newHeadPosition); } System.out.println("TEST3: " + otherPositions.size()); }
2
public Card dealCard() { if (cardsUsed == deck.length) throw new IllegalStateException("No cards are left in the deck."); cardsUsed++; return deck[cardsUsed - 1]; // Programming note: Cards are not literally removed from the array // that represents the deck. We just keep track of how many cards // have been used. }
1
private void AddAllAttributes(String shaderText) { final String ATTRIBUTE_KEYWORD = "attribute"; int attributeStartLocation = shaderText.indexOf(ATTRIBUTE_KEYWORD); int attribNumber = 0; while(attributeStartLocation != -1) { if(!(attributeStartLocation != 0 && (Character.isWhitespace(shaderText.charAt(attributeStartLocation - 1)) || shaderText.charAt(attributeStartLocation - 1) == ';') && Character.isWhitespace(shaderText.charAt(attributeStartLocation + ATTRIBUTE_KEYWORD.length())))) { attributeStartLocation = shaderText.indexOf(ATTRIBUTE_KEYWORD, attributeStartLocation + ATTRIBUTE_KEYWORD.length()); continue; } int begin = attributeStartLocation + ATTRIBUTE_KEYWORD.length() + 1; int end = shaderText.indexOf(";", begin); String attributeLine = shaderText.substring(begin, end).trim(); String attributeName = attributeLine.substring(attributeLine.indexOf(' ') + 1, attributeLine.length()).trim(); SetAttribLocation(attributeName, attribNumber); attribNumber++; attributeStartLocation = shaderText.indexOf(ATTRIBUTE_KEYWORD, attributeStartLocation + ATTRIBUTE_KEYWORD.length()); } }
5
private Point getWorldCollision(Dynamic obj, Texture target) { Rectangle r = obj.getCollisionBox(); Point lowerLeft = new Point(r.x, r.y); Point upperRight = new Point(r.x + r.width - 1, r.y + r.height - 1); int cell = World.CELL_SIZE; //If x is negative, offset by 1. It sucks but is necessary. if (lowerLeft.x < 0) { lowerLeft.x -= cell; } if (upperRight.x < 0) { upperRight.x -= cell; } //Convert pixel coordinates to world coordinates. lowerLeft.x /= cell; lowerLeft.y /= cell; upperRight.x /= cell; upperRight.y /= cell; //Test for overlap with the target block type for (int x = (lowerLeft.x); x <= (upperRight.x); x++) { for (int y = (lowerLeft.y); y <= (upperRight.y); y++) { if (world.getCell(x, y) == target) { return new Point(x, y); } } } return null; }
5
@Override public int hashCode() { return playerName != null ? playerName.hashCode() : 0; }
1
private void process() { int picsize = source.length; result = new int[picsize]; for (int i = 0; i < picsize; i++) { int p = source[i]; int r = (p & 0xff0000) >> 16; int g = (p & 0xff00) >> 8; int b = p & 0xff; result[i] = luminance(r, g, b); } }
1
@Override @SuppressWarnings("unchecked") public List<Poll>[] getMyPollTypes(MOB mob, boolean login) { final Iterator<Poll> i=getPollList(); final List<Poll> list[]=new List[3]; for(int l=0;l<3;l++) list[l]=new Vector<Poll>(); for(;i.hasNext();) { final Poll P = i.next(); if(loadPollIfNecessary(P)) { if((P.mayIVote(mob))&&(login)&&(CMath.bset(P.getFlags(),Poll.FLAG_NOTATLOGIN))) list[1].add(P); else if(P.mayIVote(mob)) list[0].add(P); else if(P.mayISeeResults(mob)) list[2].add(P); } } return list; }
8
@Column(name = "PCA_POS_ID") @Id public BigInteger getPcaPosId() { return pcaPosId; }
0
public void removePush() { if (stack != null) instr = stack.mergeIntoExpression(instr); trueBlock.removePush(); }
1
private float[] staggeredLine( int length, int initStep, float variation, boolean sub ) { // NOTE: Length must be an exact power of 2, plus 1. float line[] = new float[length] ; int step = (initStep > 0) ? initStep : (length - 1) ; while (step > 1) { for (int i = 0 ; i < length - 1 ; i += step) { final float value = (line[i] + line[i + step]) / 2 ; final float rand = Rand.num() - (sub ? 0.5f : 0) ; line[i + (step / 2)] = value + (rand * variation) ; } step /= 2 ; variation /= 2 ; } return line ; }
4
@Override public void paint(Graphics g) { super.paint(g); Graphics2D g2 = (Graphics2D) g; int size = Math.min( MAX_SIZE, Math.min(getWidth() - this.imagePadding.left - this.imagePadding.right, getHeight() - this.imagePadding.top - this.imagePadding.bottom)); g2.translate((getWidth() / 2) - (size / 2), (getHeight() / 2) - (size / 2)); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Shape shape; if ((this.mode == ColorPicker.SAT) || (this.mode == ColorPicker.BRI)) { shape = new Ellipse2D.Float(0, 0, size, size); } else { Rectangle r = new Rectangle(0, 0, size, size); shape = r; } if (hasFocus()) { PlafPaintUtils.paintFocus(g2, shape, 3); } if (!(shape instanceof Rectangle)) { // paint a circular shadow g2.translate(2, 2); g2.setColor(new Color(0, 0, 0, 20)); g2.fill(new Ellipse2D.Float(-2, -2, size + 4, size + 4)); g2.setColor(new Color(0, 0, 0, 40)); g2.fill(new Ellipse2D.Float(-1, -1, size + 2, size + 2)); g2.setColor(new Color(0, 0, 0, 80)); g2.fill(new Ellipse2D.Float(0, 0, size, size)); g2.translate(-2, -2); } g2.drawImage(this.image, 0, 0, size, size, 0, 0, size, size, null); g2.setStroke(new BasicStroke(1)); if (shape instanceof Rectangle) { Rectangle r = (Rectangle) shape; PlafPaintUtils.drawBevel(g2, r); } else { g2.setColor(new Color(0, 0, 0, 120)); g2.draw(shape); } g2.setColor(Color.white); g2.setStroke(new BasicStroke(1)); g2.draw(new Ellipse2D.Float(this.point.x - 3, this.point.y - 3, 6, 6)); g2.setColor(Color.black); g2.draw(new Ellipse2D.Float(this.point.x - 4, this.point.y - 4, 8, 8)); g.translate(-this.imagePadding.left, -this.imagePadding.top); }
5
@Override public void execute(CommandSender sender, String[] arg1) { if (!CommandUtil.hasPermission(sender, PERMISSION_NODES)) { sender.sendMessage(plugin.NO_PERMISSION); return; } if (arg1.length < 1) { sender.sendMessage(ChatColor.RED + "/" + plugin.ipban + " (PlayerName/IP)"); return; } try { // if playername was inserted if (plugin.getUtilities().playerExists(arg1[0])) { String ip = null; try { // get players ip ip = plugin.getUtilities().getIP(arg1[0]); } catch (SQLException e) { e.printStackTrace(); } try { plugin.getUtilities().IPBanPlayer(ip); String imessage = plugin.DEFAULT_IPBAN_PLAYER; imessage = imessage.replace("%player", ip); plugin.getUtilities().sendBroadcast(imessage); } catch (SQLException | UnknownHostException e) { e.printStackTrace(); } } else { // if IP was typed in // TODO may need to add a '/' to the start plugin.getUtilities().IPBanPlayer(arg1[0]); String imessage = plugin.DEFAULT_IPBAN_PLAYER; imessage = imessage.replace("%player", arg1[0]); plugin.getUtilities().sendBroadcast(imessage); } } catch (SQLException | UnknownHostException e) { e.printStackTrace(); } }
6
public int diff_slFormat() { int size = Paid_SoLuongSP.size(); double dnum = 0.0; double dnum1 = 0.0; int return_val = 0; int inum; int diff; for(int i = 0; i < size ; i++) { dnum = Paid_SoLuongSP.get(i); inum = Paid_SoLuongSP.get(i).intValue(); dnum1 = Double.parseDouble(slFormat1.format(Paid_SoLuongSP.get(i))); if(dnum == inum ){ diff = 0; }else if(dnum == dnum1){ diff = 1; }else{ diff = 2; } if(diff > return_val){ return_val = diff; if(return_val == 2){ break; } } } return return_val; }
5
public List<MemberBean> getMemberList(int start, int end) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; List<MemberBean> memberList = null; String sql = ""; try { conn = getConnection(); sql = "select a.* from (select ROWNUM as RNUM, b.* from (select * from member" + " order by reg_date desc) b) a where a.RNUM >=? and a.RNUM <=?"; pstmt = conn.prepareStatement(sql); pstmt.setInt(1, start); pstmt.setInt(2, end); rs = pstmt.executeQuery(); if (rs.next()) { memberList = new ArrayList<MemberBean>(); do { MemberBean member = new MemberBean(); member.setId(rs.getString("id")); member.setName(rs.getString("name")); member.setNickname(rs.getString("nickname")); member.setEmail(rs.getString("email")); member.setPhone(rs.getString("phone")); member.setLocate(rs.getString("locate")); member.setPoint(rs.getInt("point")); member.setBirth_date(rs.getDate("birth_date")); member.setReg_date(rs.getTimestamp("reg_date")); member.setLast_login_ip(rs.getString("last_login_ip")); member.setLast_login_time(rs .getTimestamp("last_login_time")); member.setLv(rs.getInt("lv")); memberList.add(member); } while (rs.next()); } } catch (Exception e) { e.printStackTrace(); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (pstmt != null) { try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } return memberList; }
9
public static String encodeParameters(PostParameter[] postParams) { StringBuffer buf = new StringBuffer(); for (int j = 0; j < postParams.length; j++) { if (j != 0) { buf.append("&"); } try { buf.append(URLEncoder.encode(postParams[j].name, "UTF-8")) .append("=").append(URLEncoder.encode(postParams[j].value, "UTF-8")); } catch (java.io.UnsupportedEncodingException neverHappen) { } } return buf.toString(); }
3
public void removeMangeable(Mangeable alimentation){ List<Nourriture> alimentationLoft = new ArrayList<Nourriture>(); //alimentation.setValeurEnergie(0); alimentationLoft = this.getLoftCorrespondant().getAlimentation(); System.out.print("Liste Alimentation : \n"); for (int i = 0; i < alimentationLoft.size() ; i++) { System.out.print("Alim " + i + "\n" + alimentationLoft.get(i).getClass() + " \n"); System.out.print(alimentationLoft.get(i).getPosition().getAbscisse() + " ; " + alimentationLoft.get(i).getPosition().getOrdonnee() + " Compar� a " + alimentation.getPosition().getAbscisse() + " ; " +alimentation.getPosition().getOrdonnee() + "\n "); if (alimentationLoft.get(i).getPosition().getAbscisse() == alimentation.getPosition().getAbscisse() && alimentationLoft.get(i).getPosition().getOrdonnee() == alimentation.getPosition().getOrdonnee()) { System.out.print("\n REMOVE \n"); alimentationLoft.remove(i); } } for (int j = 0 ; j < this.getLoftCorrespondant().getGzone().getListe().size(); j++) { if (this.getLoftCorrespondant().getGzone().getListe().get(j) == alimentation) { this.getLoftCorrespondant().getGzone().getListe().remove(j); } } this.getLoftCorrespondant().setAlimentation(alimentationLoft); }
5
private boolean isNewerVersion(){ JSONObject obj = apiHome("imgurdl/version", "", "GET"); if(obj == null)return false; JSONArray data = (JSONArray) obj.get("imgurdlVersion"); JSONObject item = (JSONObject) data.get(0); String newestVer = (String)item.get("ver"); String newestLink = (String)item.get("link"); System.out.println("check newest version"); if(newerVersionBigger(newestVer, getVersion())){ newerVersionName = newestVer; newerVersionLink = newestLink; return true; }else{ return false; } }
2
@Override public void approveSelection(){ File f = getSelectedFile(); if(f.exists() && getDialogType() == SAVE_DIALOG){ int result = JOptionPane.showConfirmDialog(this, Localization.getInstance().get("messageConfirmOverwrite"), Localization.getInstance().get("messageConfirmOverwriteTitle"), JOptionPane.YES_NO_CANCEL_OPTION); switch(result){ case JOptionPane.YES_OPTION: super.approveSelection(); return; case JOptionPane.NO_OPTION: return; case JOptionPane.CLOSED_OPTION: return; case JOptionPane.CANCEL_OPTION: cancelSelection(); return; } } super.approveSelection(); }
6
public void receiveFirst() { System.out.println("-- Bob --"); if (MitM) { System.out.println("ACHTUNG: MitM aktiv!!!"); } // fingerprint werte aus datei auslesen fingerprint = new Fingerprint(new File("HashParameter")); // bob bekommt p und g von alice p = new BigInteger(Com.receive(), 16); // R1 g = new BigInteger(Com.receive(), 16); // R2 System.out.println("p: " + p); System.out.println("g: " + g); // bob bekommt öffentlichen rsa schlüssel von alice BigInteger e_A = new BigInteger(Com.receive(), 16); // R3 BigInteger n_A = new BigInteger(Com.receive(), 16); // R4 System.out.println("Alice e: " + e_A); System.out.println("Alice n: " + n_A); // bob sendet seinen öffentlichen schlüssel RSA rsa_B = new RSA(); System.out.println("RSA Bob e: " + rsa_B.e); System.out.println("RSA Bob n: " + rsa_B.n); System.out.println("RSA Bob d: " + rsa_B.d); Com.sendTo(0, rsa_B.e.toString(16)); // S5 Com.sendTo(0, rsa_B.n.toString(16)); // S6 // bob empfängt y_A BigInteger y_A = new BigInteger(Com.receive(), 16); // R7 System.out.println("y_A: " + y_A); // zufällige zahl x_B in {1,...,p-2} -> randomBetween 1 <= x_B < p-1 BigInteger x_B = BigIntegerUtil.randomBetween(ONE, p.subtract(ONE)); // bob wählt x_B = g^(x_B) mod p BigInteger y_B = g.modPow(x_B, p); // bob bestimmt schlüssel BigInteger k = y_A.modPow(x_B, p); System.out.println("k: " + k.toString()); // signatur BigInteger hash = hash(y_B, y_A); BigInteger S_B = rsa_B.getSignatur(hash); // S_B = hash^d_B mod n_B System.out.println("Signatur S_B: " + S_B); // zertifikat generieren Certificate Z_B = generateCertificate(rsa_B.e, rsa_B.n); System.out.println("Z_B"); printCertificate(Z_B); // encrypted S_B with idea BigInteger key = getIDEAKeyBasedOnK(k); BigInteger iv = new BigInteger(IV, 16); idea = new IDEA(key, iv); BigInteger S_B_encrypted = idea.encipher(S_B); // bob sendet certificate in einzelteilen Com.sendTo(0, Z_B.getID()); // send ID // S8 // String data_send = new String(Z_B.getData()); String data_send = serialize(Z_B.getData()); System.out.println("data send: " + data_send); Com.sendTo(0, data_send); // send data (pub key) // S9 Com.sendTo(0, Z_B.getSignature().toString(16)); // send signature //S10 // bob sendet y_B Com.sendTo(0, y_B.toString(16)); // S11 // bob sendet S_B_encrypted Com.sendTo(0, S_B_encrypted.toString(16)); // S12 System.out.println("Bob: Receive cert"); // bob empfängt certificate in einzelteilen Certificate Z_A = buildCertificateBasedOnStrings(Com.receive(), Com.receive(), Com.receive()); // R13,14,15 // check certificate if (checkCertificate(Z_A) == true) { System.out.println("Zertifikat Check: Zertifikat von Alice ist korrekt!"); } else { System.out.println("Zertifikat Check: Zertifikat von Alice ist NICHT korrekt! ABBRUCH!"); System.exit(0); } // bob empfängt S_A_encrypted BigInteger S_A_encrypted = new BigInteger(Com.receive(), 16); // R16 // decrypt S_A_encrypted with idea BigInteger S_A = idea.decipher(S_A_encrypted); // bob überprüft die gültigkeit von S_B BigInteger hash2 = hash(y_A, y_B); if (checkSignature(hash2, S_A, e_A, n_A) == true) { System.out.println("Signature Check: hashs h(y_A, y_B) sind gleich! Bob akzeptiert k!"); } else { System.out.println("Signature Check: Hashs nicht gleich! ABBRUCH!"); System.exit(0); } // Chat Start BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); String input = ""; while (true) { String receive = Com.receive(); BigInteger receiveInteger = new BigInteger(receive, 16); BigInteger receiveInteger_decrypted = idea.decipher(receiveInteger); System.out.println("Message from Alice: " + new String(receiveInteger_decrypted.toByteArray())); System.out.print("Enter your message (Enter q for quit): "); System.out.flush(); // empties buffer, before you input text try { input = stdin.readLine(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Your message: " + input); if (input.equalsIgnoreCase("q")) { System.exit(0); } BigInteger inputInteger = new BigInteger(input.getBytes()); BigInteger inputInteger_encrypted = idea.encipher(inputInteger); Com.sendTo(0, inputInteger_encrypted.toString(16)); } }
6
private String getShortValue(final Field field, final Object object) { Object result = getRawValue(field, object); if (result == null) { result = ""; } return result.toString(); }
1
public boolean isEventHandledByState(final StateEnum state, final EventEnum event) { for (Transition transition : transitions.getTransitions(state)) { if (transition.getEvent() == event) return true; } return false; }
2
public void checking_bfs(char[][] board, int x, int y) { Queue<Integer> que = new LinkedList<Integer>(); que.add(x * board[0].length + y); int n; while (!que.isEmpty()) { n = que.remove(); x = n / board[0].length; y = n % board[0].length; board[x][y] = '+'; if (x > 0 && board[x - 1][y] == 'O') que.add(n - board[0].length); if (x < board.length - 1 && board[x + 1][y] == 'O') que.add(n + board[0].length); if (y > 0 && board[x][y - 1] == 'O') que.add(n - 1); if (y < board[0].length - 1 && board[x][y + 1] == 'O') que.add(n + 1); } }
9
void drawShip(Ship ship, Coordinate sgc) { final int x = (int) (sgc.x - 1); final int y = (int) (sgc.y - 1); final int diameter = 3; if (Main.isFastBlinked) { g.setStroke(new BasicStroke()); g.setColor(ship.meta.color); g.fillOval(x, y, diameter, diameter); } }
1
@Override public void deserialize(Buffer buf) { barType = buf.readByte(); if (barType < 0) throw new RuntimeException("Forbidden value on barType = " + barType + ", it doesn't respect the following condition : barType < 0"); slot = buf.readInt(); if (slot < 0 || slot > 99) throw new RuntimeException("Forbidden value on slot = " + slot + ", it doesn't respect the following condition : slot < 0 || slot > 99"); }
3
public void testPrint_bufferMethods() throws Exception { Period p = new Period(1, 2, 3, 4, 5, 6, 7, 8); StringBuffer buf = new StringBuffer(); f.printTo(buf, p); assertEquals("P1Y2M3W4DT5H6M7.008S", buf.toString()); buf = new StringBuffer(); try { f.printTo(buf, null); fail(); } catch (IllegalArgumentException ex) {} }
1
protected NeuralOutputs(Element outputs, MiningSchema miningSchema) throws Exception { m_classAttribute = miningSchema.getMiningSchemaAsInstances().classAttribute(); int vals = (m_classAttribute.isNumeric()) ? 1 : m_classAttribute.numValues(); m_outputNeurons = new String[vals]; m_categoricalIndexes = new int[vals]; NodeList outputL = outputs.getElementsByTagName("NeuralOutput"); if (outputL.getLength() != m_outputNeurons.length) { throw new Exception("[NeuralOutputs] the number of neural outputs does not match " + "the number expected!"); } for (int i = 0; i < outputL.getLength(); i++) { Node outputN = outputL.item(i); if (outputN.getNodeType() == Node.ELEMENT_NODE) { Element outputE = (Element)outputN; // get the ID for this output neuron m_outputNeurons[i] = outputE.getAttribute("outputNeuron"); if (m_classAttribute.isNumeric()) { // get the single norm continuous NodeList contL = outputE.getElementsByTagName("NormContinuous"); if (contL.getLength() != 1) { throw new Exception("[NeuralOutputs] Should be exactly one norm continuous element " + "for numeric class!"); } Node normContNode = contL.item(0); String attName = ((Element)normContNode).getAttribute("field"); Attribute dummyTargetDef = new Attribute(attName); ArrayList<Attribute> dummyFieldDefs = new ArrayList<Attribute>(); dummyFieldDefs.add(dummyTargetDef); m_regressionMapping = new NormContinuous((Element)normContNode, FieldMetaInfo.Optype.CONTINUOUS, dummyFieldDefs); break; } else { // we just need to grab the categorical value (out of the NormDiscrete element) // that this output neuron is associated with NodeList discL = outputE.getElementsByTagName("NormDiscrete"); if (discL.getLength() != 1) { throw new Exception("[NeuralOutputs] Should be only one norm discrete element " + "per derived field/neural output for a nominal class!"); } Node normDiscNode = discL.item(0); String attValue = ((Element)normDiscNode).getAttribute("value"); int index = m_classAttribute.indexOfValue(attValue); if (index < 0) { throw new Exception("[NeuralOutputs] Can't find specified target value " + attValue + " in class attribute " + m_classAttribute.name()); } m_categoricalIndexes[i] = index; } } } }
8
public void setBounds(Rectangle rect) { int x = bounds.x, y = bounds.y; boolean resize = (rect.width != bounds.width) || (rect.height != bounds.height), translate = (rect.x != x) || (rect.y != y); if ((resize || translate) && isVisible()) erase(); if (translate) { int dx = rect.x - x; int dy = rect.y - y; primTranslate(dx, dy); } bounds.width = rect.width; bounds.height = rect.height; if (translate || resize) { fireFigureMoved(); repaint(); } }
8
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(PostGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(PostGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(PostGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(PostGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { /*try { new PostGUI().setVisible(true); } catch (RemoteException ex) { Logger.getLogger(PostGUI.class.getName()).log(Level.SEVERE, null, ex); }*/ System.out.println("building a new store"); Store store = new Store(); System.out.println("opening store with productCatalog.txt" + ", manager \"Anthony\", and store name \"Ziga\"\n"); try { store.open("productCatalog.txt", "Anthony", "Ziga"); } catch (IOException ex) { Logger.getLogger(PostGUI.class.getName()).log(Level.SEVERE, null, ex); } } }); }
7
public InnerClassInfo getOuterClassInfo(ClassInfo ci) { if (ci != null) { InnerClassInfo[] outers = ci.getOuterClasses(); if (outers != null) return outers[0]; } return null; }
2
private void btnOpenFileActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnOpenFileActionPerformed {//GEN-HEADEREND:event_btnOpenFileActionPerformed JFileChooser fc = new JFileChooser(); fc.setFileSelectionMode(JFileChooser.FILES_ONLY); fc.setDialogTitle("Open something interesting..."); fc.addChoosableFileFilter(new FileNameExtensionFilter("Supported file formats", /*"iso",*/ "rarc", "arc")); //fc.addChoosableFileFilter(new FileNameExtensionFilter("Wii ISO", "iso")); fc.addChoosableFileFilter(new FileNameExtensionFilter("Wii RARC archive", "rarc", "arc")); String lastfile = Preferences.userRoot().get("lastFile", null); if (lastfile != null) fc.setSelectedFile(new File(lastfile)); if (fc.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return; String selfile = fc.getSelectedFile().getPath(); Preferences.userRoot().put("lastFile", selfile); try { if (archive != null) archive.close(); } catch (IOException ex) {} archive = null; /*if (archive == null) { try { archive = new WiiIsoFilesystem(new ExternalFile(selfile)); } catch (IOException ex) { if (!ex.getMessage().startsWith("!File isn't ")) { lblStatusLabel.setText("Failed to open the file: "+ex.getMessage()); return; } archive = null; } }*/ if (archive == null) { try { archive = new RarcFilesystem(new ExternalFile(selfile)); } catch (IOException ex) { if (!ex.getMessage().startsWith("!File isn't ")) { lblStatusLabel.setText("Failed to open the file: "+ex.getMessage()); return; } archive = null; } } populateFSList(); lblStatusLabel.setText(""); selectedPath = ""; btnNewFolder.setEnabled(true); btnAddFileFolder.setEnabled(true); btnExtractItem.setEnabled(false); btnReplaceItem.setEnabled(false); btnRenameItem.setEnabled(false); btnDeleteItem.setEnabled(false); }//GEN-LAST:event_btnOpenFileActionPerformed
7
public void setReturnNearestValue(boolean returnNearestValue) { this.returnNearestValue = returnNearestValue; }
0
public boolean testMultJumps(){ // Boolean for whether or not it passed the test. boolean multJumpTest = true; /** * A high number of moves must be made for this to be set up. * A diagram was made to figure out this sequence. It is: * * For now, I'm just assuming that this is all valid. */ System.out.println( "Setting pieces to attempt mult. jump" ); System.out.println( "Attempting move: 46 to 39" ); testFacade.selectSpace( 46 ); testFacade.selectSpace( 39 ); simpleWait(); System.out.println( "Attempting move: 23 to 30" ); testFacade.selectSpace( 23 ); testFacade.selectSpace( 30 ); simpleWait(); System.out.println( "Attempting move: 42 to 35" ); testFacade.selectSpace( 42 ); testFacade.selectSpace( 35 ); simpleWait(); System.out.println( "Attempting move: 14 to 23" ); testFacade.selectSpace( 14 ); testFacade.selectSpace( 23 ); simpleWait(); System.out.println( "Attempting move: 51 to 42" ); testFacade.selectSpace( 51 ); testFacade.selectSpace( 42 ); simpleWait(); System.out.println( "Attempting move: 7 to 14 " ); testFacade.selectSpace( 7 ); testFacade.selectSpace( 14 ); simpleWait(); System.out.println( "Attempting move: 60 to 51" ); testFacade.selectSpace( 60 ); testFacade.selectSpace( 51 ); simpleWait(); System.out.println( "Attempting move: 21 to 28" ); testFacade.selectSpace( 21 ); testFacade.selectSpace( 28 ); simpleWait(); // All of that should set the stage for a multiple jump. // Make the first jump and then check for control of the board. // And location of pieces. Control should not have changed. int turn = testFacade.whosTurn(); System.out.println( "Attempting move: 35 to 21" ); testFacade.selectSpace( 35 ); testFacade.selectSpace( 21 ); simpleWait(); testBoard = testFacade.stateOfBoard(); if( testBoard.occupied( 28 ) ){ System.out.println( "Did not remove piece from 28" ); multJumpTest = false; }else if( !testBoard.occupied( 21 ) ){ System.out.println( "Did not move piece to 21" ); multJumpTest = false; } if( turn != testFacade.whosTurn() ){ System.out.println( "Prematurely ended turn." ); multJumpTest = false; } // At this point, player should still have control. // Make that second jump. System.out.println( "Attempting move: 21 to 7" ); testFacade.selectSpace( 21 ); testFacade.selectSpace( 7 ); // Check that the pieces have been moved/removed // and that control has changed hands. simpleWait(); testBoard = testFacade.stateOfBoard(); if( testBoard.occupied( 14 ) ){ System.out.println( "Did not remove piece from 14." ); multJumpTest = false; }else if( !testBoard.occupied( 7 )){ System.out.println( "Did not move piece to 7." ); multJumpTest = false; } if( turn == testFacade.whosTurn() ){ System.out.println( "Did not end turn correctly." ); multJumpTest = false; } return multJumpTest; }
6