text
stringlengths
14
410k
label
int32
0
9
@Override public boolean equals(Object obj) { if (obj == this) return true; if(!(obj instanceof Operation)) return false; Operation op = (Operation) obj; return (operation.equals(op.getString()) && timeStamp == op.gettimeStamp()); }
3
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Picture other = (Picture) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (url == null) { if (other.url != null) return false; } else if (!url.equals(other.url)) return false; return true; }
9
@SuppressWarnings("unchecked") <T> T getArrayForType(Class<? extends T> type) { if (!type.isArray()) { throw new IllegalArgumentException("Not an array type"); } Class cType = getArrayBaseType(type); Object o = new Parser(co.get(key(String.class, cType))).parse(0, layout, types(dims, cType)); if (o.getClass() != type) { throw new RuntimeException(o.getClass() + "!=" + type); } return (T) o; }
3
@Override public Account removeAccount(User owner, Account account) { PreparedStatement pStmt = null; Account ac = null; Integer result; ac = getAccount(account.getId()); if (ac != null){ try { pStmt = conn.prepareStatement("DELETE FROM ACCOUNT WHERE user_login = ? AND id = ?;"); pStmt.setString(1, owner.getLogin()); pStmt.setInt(2, account.getId()); result = pStmt.executeUpdate(); Set<Record> records = getRecords(ac); for(Record r:records){ removeRecord(ac, r); } } catch (SQLException e) { e.printStackTrace(); } finally { closeResource(pStmt); } } return ac; }
3
public void mouseUp(MouseEvent e, int x, int y) { // ask the associated board figure to perform its associated action based // upon the coordinates of mouse down and mouse up (move or click) if ( clickedFigure != null ) { boolean valid = clickedFigure.performAction(fStartX, fStartY, fLastX, fLastY); // if the figure's associate domain model tell the move is invalid // then move it back to its starting position. if ( ! valid && clickedFigure.isMobile() ) { // move it back int dx = fStartX - x; int dy = fStartY - y; if (draggedFigure != null ) { draggedFigure.moveBy(dx, dy); } } } // unlock the drawing's concurrency lock if (draggedFigure != null) { editor.drawing().unlock(); } clickedFigure = null; draggedFigure = null; }
5
public void volverCero(){ if(Calendar.getInstance().get(Calendar.MONTH) != mes || Calendar.getInstance().get(Calendar.YEAR) != anio){ mes = Calendar.getInstance().get(Calendar.MONTH); anio = Calendar.getInstance().get(Calendar.YEAR); for(beansMiembro miembro : miembros){ miembro.setEgresos(0); miembro.setIngresos(0); volverCeroInterior(miembro); } } }
3
public void layoutContainer(Container target) { synchronized (target.getTreeLock()) { Insets insets = target.getInsets(); int top = insets.top; int bottom = target.getHeight() - insets.bottom; int left = insets.left; int right = target.getWidth() - insets.right; int centerWidth = 0; int centerHeight = 0; boolean ltr = target.getComponentOrientation().isLeftToRight(); Component c = null; if ((c = getChild(CENTER, ltr)) != null) { c.setSize(c.getWidth(), bottom - top); Dimension d = c.getPreferredSize(); centerWidth = c.getWidth(); centerHeight = c.getHeight(); // int x = get c.setBounds((right - left) / 2 - d.width / 2, top, d.width, bottom - top); } if ((c = getChild(NORTH, ltr)) != null) { c.setSize(right - left, c.getHeight()); Dimension d = c.getPreferredSize(); c.setBounds(left, top, right - left, d.height); top += d.height + vgap; } if ((c = getChild(SOUTH, ltr)) != null) { c.setSize(right - left, c.getHeight()); Dimension d = c.getPreferredSize(); c.setBounds(left, bottom - d.height, right - left, d.height); bottom -= d.height + vgap; } if ((c = getChild(EAST, ltr)) != null) { c.setSize(c.getWidth(), bottom - top); Dimension d = c.getPreferredSize(); int x = right / 2 + centerWidth / 2; c.setBounds(x + 1, top, right - x, bottom - top); // right -= d.width + hgap; } if ((c = getChild(WEST, ltr)) != null) { c.setSize(c.getWidth(), bottom - top); Dimension d = c.getPreferredSize(); c.setBounds(left, top, (right - left) / 2 - centerWidth / 2 - 1, bottom - top); // left += d.width + hgap; } } }
5
private int getClusterInPlot(int x, int y) { int clusterId = -1; float xInPixels, yInPixels, radiusInPixels; double dist, smallerRadius = Double.MAX_VALUE; ChartItem clusterItem; for (Integer id : ChartData.getAllIds()) { clusterItem = ChartData.getItemById(id); xInPixels = getPointXInPixels(clusterItem.getPoint().x); yInPixels = getPointYInPixels(clusterItem.getPoint().y); radiusInPixels = getPointSizeInPixels(clusterItem.getSize()) / 2; // Distance dist = Math.sqrt(Math.pow(x - xInPixels, 2) + Math.pow(y - yInPixels, 2)); if (dist <= radiusInPixels) { // Select the cluster with smaller radius that the mouse is over if (radiusInPixels < smallerRadius) { clusterId = id; smallerRadius = radiusInPixels; } } } return (clusterId); }
3
public int compareTo( Object obj ) { if( obj == null ) { return( 1 ); } else if( obj instanceof GenKbContactListByUDescrIdxKey ) { GenKbContactListByUDescrIdxKey rhs = (GenKbContactListByUDescrIdxKey)obj; if( getRequiredTenantId() < rhs.getRequiredTenantId() ) { return( -1 ); } else if( getRequiredTenantId() > rhs.getRequiredTenantId() ) { return( 1 ); } { int cmp = getRequiredDescription().compareTo( rhs.getRequiredDescription() ); if( cmp != 0 ) { return( cmp ); } } return( 0 ); } else if( obj instanceof GenKbContactListBuff ) { GenKbContactListBuff rhs = (GenKbContactListBuff)obj; if( getRequiredTenantId() < rhs.getRequiredTenantId() ) { return( -1 ); } else if( getRequiredTenantId() > rhs.getRequiredTenantId() ) { return( 1 ); } { int cmp = getRequiredDescription().compareTo( rhs.getRequiredDescription() ); if( cmp != 0 ) { return( cmp ); } } return( 0 ); } else { throw CFLib.getDefaultExceptionFactory().newUnsupportedClassException( getClass(), "compareTo", "obj", obj, null ); } }
9
public void updateItems() { try { String strResult = ""+(char)6, strStore; int i; Item itmStore; LifoQueue qStore; Iterator iter=vctItems.keySet().iterator(); while(iter.hasNext()) { qStore = (LifoQueue)vctItems.get(iter.next()); if (qStore.size() > 0) { itmStore = (Item)qStore.firstElement(); if(itmStore.isArmor()) { strResult += (2+itmStore.intKind)+"\n"; } else if (itmStore.isWeapon()) { strResult += "1\n"; } else { strResult += "0\n"; } strResult += itmStore.NAME+"\n"; } } strResult += ".\n"; send(strResult); if (Game.overMerchant(intLocX,intLocY)!= null) updateSell(); if (Game.overPlayerMerchant(intLocX,intLocY)!= null) updateSell(); } catch(Exception e) { Game.LOG.printError("updateItems():"+NAME+" disconnected", e); BLN_STOP_THR = true; } BLN_SAVE_FLAG = true; }
7
@Override public void addEdge(N from, N to, W weight) { if(containsNode(from) && containsNode(to) && !containsEdge(from, to)) { nodes.get(from).add(new WeightedEdge<N, W>(from, to, weight)); if(!isDirected) { nodes.get(to).add(new WeightedEdge<N, W>(to, from, weight)); } } }
4
public Shoe(int numDecks) { this.deckCount = numDecks; this.numCards = deckCount * numDecks; if (numDecks >= minDecks) { for (int i = 1; i < 14; i++) { for (int j = 1; j < 4; j++) { Shoe.add(new Card(i, j)); } } } else { throw new IllegalStateException("Minimum decks is 4"); } Collections.shuffle(Shoe); }
3
public CheckResultMessage checkDayofMonth() { // clear message list messageList.clear(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM"); try { Date date = dateFormat.parse(monthDate); Calendar cal = Calendar.getInstance(); cal.setTime(date); maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH); cal.add(Calendar.MONTH, -1); lastMaxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH); } catch (ParseException e) { e.printStackTrace(); return error(fileName + " 期数格式不正确!应为yyyyMM"); } if (checkVersion(file).equals("2003")) { if (fileNameSections.length == 4) { int r1 = get(2, 2); int c1 = get(3, 2); if (!(getValueString(r1 + 1, c1 - 1, 0).equals(lastMaxDay + "日"))) { return error("日期设置错误!<" + fileName + ">" + " Sheet:1-1" + ", 应设为上月最后日期:" + lastMaxDay + "日"); } } } else { if (fileNameSections.length == 4) { int r1 = get(2, 2); int c1 = get(3, 2); if (!(getValueString1(r1 + 1, c1 - 1, 0).equals(lastMaxDay + "日"))) { return error("日期设置错误!<" + fileName + ">" + " Sheet:1-1" + ", 应设为上月最后日期:" + lastMaxDay + "日"); } } } // 遍历检查 // for (String sheetName : sheetNames) { // // XSSFSheet sheet = workbook.getSheet(sheetName); // if (sheet == null) { // continue; // } // // DayCell days = daysMap.get(sheetName); // if (days == null) { // System.err.println("缺少days定义,sheetName=" + sheetName); // continue; // } // XSSFRow row = sheet.getRow(days.getStartCol()); // XSSFCell cell = row.getCell(days.getStartRow()); // if ( ! (lastMaxDay + "日").equals(cell.getStringCellValue().trim())) { // messageList.add(error("日期设置错误!<" + fileName + ">" // + " Sheet:" + sheetName // // + ", 单元格" + // CellReferenceHelper.getCellReference(days.getStartCol(), // days.getStartRow()) // + "设置为" + cell.getStringCellValue() // + ", 应设为上月最后日期:" + lastMaxDay + "日")); // } // // for (int i = 1; i <= maxDay; i++) { // XSSFComment cell1 = null; // // if (days.getDirection() == DayCell.COL_DIRECTION) { // cell1 = sheet.getCellComment(days.getStartCol(), days.getStartRow() + // i); // } else if (days.getDirection() == DayCell.ROW_DIRECTION) { // cell1 = sheet.getCellComment(days.getStartCol() + i, // days.getStartRow()); // } // // if ( ! (i + "日").equals(( cell1.getString()))) { // messageList.add(error("日期设置错误!<" + fileName + ">" // + " Sheet:" + sheetName // + ", 单元格" + CellReferenceHelper.getCellReference(cell.getColumn(), // cell.getRow()) // + "设置为" + cell1.getContents() // + ", 应设为日期:" + i + "日")); // } // } // // } if (messageList.size() > 0) { return null; } return pass(reportName + " <" + fileName + "> 日期设置校验正确"); }
7
public void solve(){ int m = this.y.length; double[] w = new double[m]; // weights Arrays.fill(w, 1.0); double[][] D = new double[this.T][m]; // distribution of row's pure strategy Arrays.fill(D[0], 1.0/((double)m)); double sum = 0.0; for ( int t = 0; t < T; t++ ){ int j = getMaxJ(D[t]); sum += getValue(D[t], j); double sumW = 0.0; for ( int i = 0; i < m; i++ ){ w[i] = w[i]*Math.pow(1-this.epsilon, this.A[i][j]); sumW += w[i]; }; for ( int i = 0; i < m; i++ ){ if ( t != T - 1){ D[t+1][i] = w[i]/sumW; } } } this.value = sum/((double)T); // approximate value of the game with possible error of delta this.y = D[T-1]; // D_final }
4
public Object clone() { try { SimpleSet other = (SimpleSet) super.clone(); other.elementObjects = (Object[]) elementObjects.clone(); return other; } catch (CloneNotSupportedException ex) { throw new alterrs.jode.AssertError("Clone?"); } }
1
private static void addToVariables(Character var) throws ValidationException { for (Character c : variables) { if (c.equals(var)) { return; } } variables.add(var); if (variables.size() > MAX_VARIABLES) { throw new ValidationException("You have more than " + MAX_VARIABLES + " variables"); } }
3
public boolean isOddNumber(int num){ if(num%2 == 0) return false; else return true; }
1
public WorldMap(int sizex, int sizey) { rand = new Random(); seed = (int) (rand.nextInt(100000000) * rand.nextFloat()); System.out.println(seed); map = new ArrayList<ArrayList<Region>>(); for (int x = 0; x < sizex; x++) { map.add(new ArrayList<Region>()); for (int y = 0; y < sizey; y++) { map.get(x).add(new Region(new Point(x, y), seed)); } } }
2
public void setEntradasIdEntrada(Entradas entradasIdEntrada) { this.entradasIdEntrada = entradasIdEntrada; }
0
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) { Class<?> rawType = type.getRawType(); final boolean skipSerialize = excludeClass(rawType, true); final boolean skipDeserialize = excludeClass(rawType, false); if (!skipSerialize && !skipDeserialize) { return null; } return new TypeAdapter<T>() { /** The delegate is lazily created because it may not be needed, and creating it may fail. */ private TypeAdapter<T> delegate; @Override public T read(JsonReader in) throws IOException { if (skipDeserialize) { in.skipValue(); return null; } return delegate().read(in); } @Override public void write(JsonWriter out, T value) throws IOException { if (skipSerialize) { out.nullValue(); return; } delegate().write(out, value); } private TypeAdapter<T> delegate() { TypeAdapter<T> d = delegate; return d != null ? d : (delegate = gson.getDelegateAdapter(Excluder.this, type)); } }; }
6
private List<Generator> test1Generators() throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); List<Generator> result = new ArrayList<>(); result.add(new NumberedStringGenerator("dim1", "dim1_key", "key")); result.add(new IntegerGenerator("dim1", "num1", 0)); result.add(new IntegerGenerator("dim2", "dim2_key", 5)); result.add(new IntegerGenerator("dim3", "dim3_key", 12)); result.add(new RandomDateGenerator("dim2", "date1", sdf.parse("2013-01-01"), sdf.parse("2013-12-31"))); result.add(new RandomDateGenerator("dim3", "date3", sdf.parse("2011-01-01"), sdf.parse("2011-12-31"))); return result; }
0
void pushDuskObject(DuskObject objIn) { synchronized(objEntities) { if (objIn.intLocX < 0 || objIn.intLocY < 0 || objIn.intLocX >= MapColumns || objIn.intLocY >= MapRows) { return; } DuskObject objStore; objStore = objEntities[objIn.intLocX][objIn.intLocY]; if (objIn == objStore) // needed to add this check { // as the invis condition return; // adds the mob to update the } // the flags if (objStore == null) { objEntities[objIn.intLocX][objIn.intLocY] = objIn; }else { while (objStore.objNext != null) { if (objIn == objStore) // needed to add this check { // as the invis condition return; // adds the mob to update the } // the flags objStore = objStore.objNext; } objStore.objNext = objIn; } } }
8
private final boolean method3960(boolean bool) { int i = ((DirectxToolkit) this).anIDirect3DDevice9810.TestCooperativeLevel(); if (bool) method3880(null, null, (byte) -68); if (i == 0 || -2005530519 == i) { Class53 class53 = (Class53) ((DirectxToolkit) this).anObject7919; method3922(false); class53.method496((byte) 84); aD3DPRESENT_PARAMETERS9800.BackBufferHeight = 0; aD3DPRESENT_PARAMETERS9800.BackBufferWidth = 0; if (method3964(aD3DPRESENT_PARAMETERS9800, 0, anInt9799, anIDirect3D9793, anInt9807, ((DirectxToolkit) this).anInt8117)) { int i_53_ = ((DirectxToolkit) this).anIDirect3DDevice9810 .Reset(aD3DPRESENT_PARAMETERS9800); if (ue.a(i_53_, false)) { class53.method497(((DirectxToolkit) this) .anIDirect3DDevice9810.b(0), (byte) -107, ((DirectxToolkit) this) .anIDirect3DDevice9810.c()); method3902((byte) -42); method3882((byte) 113); return true; } } } return false; }
5
public double getKiihtyvyys2X() { double res = 0; if(getNappaimenTila(VASEN2)){ res -= KIIHTYVYYS; } if(getNappaimenTila(OIKEA2)){ res += KIIHTYVYYS; } return res; }
2
public static void main(String[] args) throws IOException { String path = "C:/Users/Frede/Desktop/fehler.txt"; String file = readFile(path); String[] lines = file.split("\n"); for(String line : lines) { if(line.contains("konnte nicht eingetragen werden.") && line.length() > 0) { line = line.replace(" konnte nicht eingetragen werden.", ""); line = line.replace("\n", "").replace("\r", ""); System.out.println(line); } } }
3
public SudokuBoard(String inputFile) throws IOException { BufferedReader in = null; try { in = new BufferedReader(new FileReader(inputFile)); String line = null; //read in rows; for(int i = 0; i < 9;i++) { line = in.readLine(); //read in a row for(int j = 0; j < 9;j++) { char c = line.charAt(j); if(c >= '1' & c <= '9') { b[i][j] = Character.getNumericValue(c); filledFields++; } } } } finally { try{in.close();} catch(Exception e) {} } }
4
public static void lerak( int[][] tabla ) { b = 1; jatekos = 0; while( b != 19 ) { AktualisRajzol.rajzol(tabla); jatekos = Jatek.melyJatekosKovetkezik(b, jatekos, 0); sor = sc.nextLine(); if( Ellenor.ellenorLerak(sor) == false ) { System.out.println( "Rossz formátumban adtál meg értéket!\n" + "Add meg, hova szeretnéd lerakni a bábúdat! Példa: A1\n" + "Probáld újra!\n" ); logger.error("Rossz formátumban megadott érték lerakáskor, újra bekérés."); continue; } else { if( Helyezz.lerak(sor, jatekos, tabla) == 0 ) continue; logger.info("Malom figyelés"); Jatek.malomCheck(jatekos, tabla); } b++; } }
3
public boolean onlyHasSolution (){ int countWeapon =0; int countPerson=0; int countRoom =0; for(Card c: seenCards){ switch (c.getType()){ case WEAPON : countWeapon++; break; case PERSON : countPerson++; break; case ROOM : countRoom++; break; default : break; } } if(countPerson==5&&countRoom==8&&countWeapon==5) //only one combination remains then return true; return false; }
7
@Override public boolean checkGrammarTree(GrammarTree grammarTree, SyntaxAnalyser syntaxAnalyser) throws GrammarCheckException { boolean firstLevelIsOk = this.checkFirstLevel(grammarTree); if (!firstLevelIsOk) { GrammarCheckException exception = new GrammarCheckException( "Error: the sentence has mutiple key-words"); syntaxAnalyser.addErrorMsg(exception.getMessage()); throw exception; } int subNodesAmount = grammarTree.getSubNodesAmount(); for (int i = 0; i < subNodesAmount; i++) { GrammarTree tree = grammarTree.getSubNode(i); Token token = tree.getValue(); if (!token.isTheType(TokenType.KEYWARD) || (WordTable.getKeyRank(token.getToken()) != 1 && WordTable .getKeyRank(token.getToken()) != 2)) { throw new GrammarCheckException(String.format( "The token([%s]) should be a key-word", token.toString())); } GrammarTreeMonitor monitor = GrammarTreeMonitorFactory .getGrammarTreeBySentenceKeyWord(token.getToken()); if (monitor == null) { GrammarCheckException exception = new GrammarCheckException( "There no suited monitor for the grammar tree. Current token is [" + token.toString() + "]"); syntaxAnalyser.addErrorMsg(exception.getMessage()); throw exception; } boolean checkResult = monitor .checkGrammarTree(tree, syntaxAnalyser); if (!checkResult) { return false; } } return true; }
7
@Override public void update() { if(++updateCount >= REGEN_TIME) { updateCount = 0; amount++; } if(amount < 0) { getWorld().removeStructure(this); } else if(amount > SPREAD) { Set<Tile> neighbours = new HashSet<Tile>(); Tile temp; temp = getWorld().getTile(getX()+-1, getY()); neighbours.add(temp); temp = getWorld().getTile(getX()+1, getY()); neighbours.add(temp); temp = (getWorld().getTile(getX(), getY()+1)); neighbours.add(temp); temp = (getWorld().getTile(getX(), getY()-1)); neighbours.add(temp); neighbours.remove(null); if(neighbours.size() > 0) { List<Tile> list = new ArrayList<Tile>(neighbours); Collections.shuffle(list); Tile t = list.get(0); if(t.getStructure() != null){ return; } if(t.getHeight() != getWorld().getTile(getX(),getY()).getHeight()){ return; } if(t.getImageName().equals("Water")){ return; } getWorld().addStructure(new Tree(t.getX(), t.getY())); } amount = HALF; } if(amount >= MAX) shouldOctoMine = true; if(amount <= MIN/2) shouldOctoMine = false; }
9
public final void Init() throws IOException { Code = 0; Range = -1; for (int i = 0; i < 5; i++) Code = (Code << 8 | Stream.read()); }
1
public static MediaCopy getMediaCopyByMediaCopyID(int copyID){ MediaCopy mc = null; try { if(conn == null || conn.isClosed()){ conn = DatabaseConnection.getConnection(); } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { PreparedStatement stmnt = conn.prepareStatement("SELECT * FROM MediaCopies mc, Media m WHERE mc.media_id = m.media_id AND mc.copy_id = ?"); stmnt.setInt(1, copyID); ResultSet res = stmnt.executeQuery(); if(res.next()) { mc = new MediaCopy(StringDateSwitcher.toDateYear(res.getString("year")), res.getString("place_of_publication"), res.getString("title"), res.getString("genre"), res.getInt("media_id"), res.getString("creator"), res.getString("producer"), res.getString("type"), res.getInt("copy_id"), res.getBoolean("lendable")); } } catch(SQLException e) { System.out.println(e); } return mc; }
5
public File getLocalFile(URI remoteUri) { if (baseURL != null) { String remote = remoteUri.toString(); if (!remote.startsWith(baseURL)) { return null; } } StringBuilder sb = new StringBuilder(); String host = remoteUri.getHost(); String query = remoteUri.getQuery(); String path = remoteUri.getPath(); String fragment = remoteUri.getFragment(); if (host != null) { sb.append(host); } if (path != null) { sb.append(path); } if (query != null) { sb.append('?'); sb.append(query); } if (fragment != null) { sb.append('#'); sb.append(fragment); } String name; final int maxLen = 250; if (sb.length() < maxLen) { name = sb.toString(); } else { name = sb.substring(0, maxLen); } name = name.replace('?', '$'); name = name.replace('*', '$'); name = name.replace(':', '$'); name = name.replace('<', '$'); name = name.replace('>', '$'); name = name.replace('"', '$'); File f = new File(cacheDir, name); return f; }
7
private void verifyTargets(final Block block, final Set targets) { Assert.isTrue(targets.size() == cfg.succs(block).size(), block + " has succs " + cfg.succs(block) + " != " + targets + " in " + block.tree().lastStmt()); final Iterator iter = targets.iterator(); while (iter.hasNext()) { final Block target = (Block) iter.next(); Assert.isTrue(block.graph().hasNode(target), target + " is not in the CFG"); Assert.isTrue(cfg.succs(block).contains(target), target + " is not a succ of " + block + " " + block.tree().lastStmt()); } }
1
@Override public void putAll(Map<? extends String, ?> m) { for (Map.Entry<? extends String, ?> entry : m.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); this.put(key, value); } }
5
public void sort(ArrayList<Integer> arr) { timeOfSorting = System.currentTimeMillis(); Random rnd = new Random(); while(true) { boolean sorted = true; for (int i = 0; i < arr.size()-1; i++) { compare_count++; if(arr.get(i) > arr.get(i+1)){ sorted = false; break; } } if (sorted) { break; } for (int i = arr.size() - 1; i > 0; i--) { int rand = rnd.nextInt(i); insert_count++; int tmp = arr.get(i); arr.set(i, arr.get(rand)); arr.set(rand, tmp); } } timeOfSorting = System.currentTimeMillis() - timeOfSorting; }
5
private static final Hashtable createFactoryStore() { Hashtable result = null; String storeImplementationClass = System.getProperty(HASHTABLE_IMPLEMENTATION_PROPERTY); if (storeImplementationClass == null) { storeImplementationClass = WEAK_HASHTABLE_CLASSNAME; } try { Class implementationClass = Class.forName(storeImplementationClass); result = (Hashtable) implementationClass.newInstance(); } catch (Throwable t) { // ignore if (!WEAK_HASHTABLE_CLASSNAME.equals(storeImplementationClass)) { // if the user's trying to set up a custom implementation, give a clue if (isDiagnosticsEnabled()) { // use internal logging to issue the warning logDiagnostic("[ERROR] LogFactory: Load of custom hashtable failed"); } else { // we *really* want this output, even if diagnostics weren't // explicitly enabled by the user. System.err.println("[ERROR] LogFactory: Load of custom hashtable failed"); } } } if (result == null) { result = new Hashtable(); } return result; }
5
private ArithmeticResult factor(Block codeBlock) throws SyntaxFormatException, IOException { ArithmeticResult designatorResult = designator(codeBlock); if (designatorResult != null) { return designatorResult; } ArithmeticResult funcCallResult = funcCall(codeBlock); if (funcCallResult != null) { return funcCallResult; } if (checkCurrentType(TokenType.NUMBER)) { int number = lexer.getCurrentToken().getNumberValue(); moveToNextToken(); return new ArithmeticResult(number); } if (checkCurrentType(TokenType.BEGIN_PARENTHESIS)) { moveToNextToken(); ArithmeticResult expressionResult = expression(codeBlock); if (expressionResult == null) { throwFormatException("factor: expression expected!"); } assertAndMoveNext(TokenType.END_PARENTHESIS); return expressionResult; } return null; }
5
public static boolean verifyPrescription(FillPrescription fillP){ if(DatabaseProcess.getDrugNames().contains(fillP.getDrugName().getText().toLowerCase())){ if(InputChecker.digits(fillP.getQuantity().getText())){ if(InputChecker.digits(fillP.getRefillCount().getText())){ if(InputChecker.dob(fillP.getFillDate())){ if(InputChecker.expiration(fillP.getExpiration())) return true; else{ fillP.getWarning().setText("invalid format for start date");} }else{fillP.getWarning().setText("wrong format for fill date");} }else{fillP.getWarning().setText("wrong format for refill count");} }else{ fillP.getWarning().setText("wrong format for qauantity");} }else{ fillP.getWarning().setText("wrong format for drug name");} return false; }
5
private void removeFoundNode(TreeNode removingNode) { TreeNode parentNode; if (removingNode.left == null || removingNode.right == null) { parentNode = removingNode; } else { parentNode = successor(removingNode); removingNode.key = parentNode.key; } TreeNode childNode; if (parentNode.left != null) { childNode = parentNode.left; } else { childNode = parentNode.right; } if (childNode != null) { childNode.parent = parentNode.parent; } if (parentNode.parent == null) { this.root = childNode; } else { if (parentNode == parentNode.parent.left) { parentNode.parent.left = childNode; } else { parentNode.parent.right = childNode; } recursiveBalance(parentNode.parent); } parentNode = null; }
6
void ComputeEmissionProbsForDoc(_Doc d) { for(int i=0; i<d.getSenetenceSize(); i++) { _Stn stn = d.getSentence(i); Arrays.fill(emission[i], 0); int start = 0, end = this.number_of_topics; if(i==0 && d.getSourceType()==2){ // first sentence is specially handled for newEgg //get the sentiment label of the first sentence int sentimentLabel = stn.getStnSentiLabel(); if(sentimentLabel==0) {// positive sentiment in the first half end = this.number_of_topics / 2; for(int k=end; k<this.number_of_topics; k++) emission[i][k] = Double.NEGATIVE_INFINITY; } else if(sentimentLabel==1) { // negative sentiment in the second half start = this.number_of_topics / 2; for(int k=0; k<start; k++) emission[i][k] = Double.NEGATIVE_INFINITY; } } for(int k=start; k<end; k++) { for(_SparseFeature w:stn.getFv()) { emission[i][k] += w.getValue() * topic_term_probabilty[k][w.getIndex()];//all in log-space } } } }
9
public static boolean equals(int[][] actual, int[][] expected) { boolean equal = true; for (int i = 0; i < expected.length; i++) { for (int j = 0; j < expected[i].length; j++) { if (expected[i][j] != actual[i][j]) { equal = false; } } } return equal; }
3
public void setKind(Integer kind) { this.kind = kind; }
0
public void update(LineEvent lineEvent) { int clipIdx = 0; boolean triggingClipFound = false; while (triggingClipFound == false && clipIdx < clipAssembly.length) { if (clipAssembly[clipIdx] == lineEvent.getSource()) { if (lineEvent.getType() == LineEvent.Type.STOP) { clipAssembly[clipIdx].setFramePosition(0); this.setChanged(); this.notifyObservers("SoundPlayed " + clipIdx); } triggingClipFound = true; } else { clipIdx++; } } }
4
public void setAnnotations(Annotation[] annotations) { ByteArrayOutputStream output = new ByteArrayOutputStream(); AnnotationsWriter writer = new AnnotationsWriter(output, constPool); try { int n = annotations.length; writer.numAnnotations(n); for (int i = 0; i < n; ++i) annotations[i].write(writer); writer.close(); } catch (IOException e) { throw new RuntimeException(e); // should never reach here. } set(output.toByteArray()); }
2
public Object invokeMethod(Reference ref, boolean isVirtual, Object cls, Object[] params) throws InterpreterException, InvocationTargetException { if (!isVirtual && cls != null) /* XXX */ throw new InterpreterException("Can't invoke nonvirtual Method " + ref + "."); Method m; try { String[] paramTypeSigs = TypeSignature.getParameterTypes(ref .getType()); Class clazz = TypeSignature.getClass(ref.getClazz()); Class[] paramTypes = new Class[paramTypeSigs.length]; for (int i = 0; i < paramTypeSigs.length; i++) { params[i] = toReflectType(paramTypeSigs[i], params[i]); paramTypes[i] = TypeSignature.getClass(paramTypeSigs[i]); } try { m = clazz.getMethod(ref.getName(), paramTypes); } catch (NoSuchMethodException ex) { m = clazz.getDeclaredMethod(ref.getName(), paramTypes); } } catch (ClassNotFoundException ex) { throw new InterpreterException(ref + ": Class not found"); } catch (NoSuchMethodException ex) { throw new InterpreterException("Method " + ref + " not found"); } catch (SecurityException ex) { throw new InterpreterException(ref + ": Security exception"); } String retType = TypeSignature.getReturnType(ref.getType()); try { return fromReflectType(retType, m.invoke(cls, params)); } catch (IllegalAccessException ex) { throw new InterpreterException("Method " + ref + " not accessible"); } }
8
protected String getPokemonName(int i) { if (getGame().getPlayer().pokeData.isCaught(i) || getGame().getPlayer().pokeData.isSeen(i)) { return cache[i - 1].name; } return "-------------------"; }
2
private static Packet getLoginPacket(String packet) { Scanner sc = new Scanner(packet); if(!sc.next().equals(Packet.PACKET_CODES.LOGIN_CMD)) return null; Packet res = new Packet(Packet.PACKET_CODES.LOGIN_CMD); HashMap<String, String> data = new HashMap<String, String>(); if(!sc.hasNext()) return null; data.put(Packet.LOGIN_KEY, sc.next()); if(!sc.hasNext()) return null; data.put(Packet.PASSWORD_KEY, sc.next()); res.setData(data); return res; }
3
@Override public void serialize(Date date, JsonGenerator gen, SerializerProvider provider) throws IOException, JsonProcessingException { String formattedDate = dateFormat.format(date); gen.writeString(formattedDate); }
0
boolean savetodatabase(String columns[], String items[]) { boolean errorfound = false; String builtstatement; Statement stmt = null; java.sql.Connection conn = null; java.sql.ResultSet rs = null; try { //get a connection Connection.initialize_Connection_SQL(); conn = Connection.getSQLConn(); //check to see if a line already exists with the primary key builtstatement = "select * from Product where " + columns[0] + " = " + items[0] + ";"; stmt = conn.createStatement(); rs = stmt.executeQuery(builtstatement); //check to see if the resultset has data - while loop and boolean check //from Adam Hardy at http://www.coderanch.com/t/296373/JDBC/databases/check-Result-set-null boolean rshasdata = false; while (rs.next()) { rshasdata = true; } if (rshasdata) { //build an update statement to overwrite database data with backup file data builtstatement = "update " + Connection.PRODUCT_TABLE_NAME + " set " + columns[1] + " = '" + items[1] + "', " + columns[2] + " = '" + items[2] + "', " + columns[3] + " = '" + items[3] + "', " + columns[4] + " = '" + items[4] + "', " + columns[5] + " = '" + items[5] + "', " + columns[6] + " = '" + items[6] + "', " + columns[7] + " = '" + items[7] + "' where " + columns[0] + " = " + items[0]; } else { //insert a new product row builtstatement = "insert into " + Connection.PRODUCT_TABLE_NAME + " (" + columns[0] + ", " + columns[1] + ", " + columns[2] + ", " + columns[3] + ", " + columns[4] + ", " + columns[5] + ", " + columns[6] + ", " + columns[7] + ") values('" + items[0] + "', '" + items[1] + "', '" + items[2] + "', '" + items[3] + "', '" + items[4] + "', '" + items[5] + "', '" + items[6] + "', '" + items[7] + "');"; } //send the SQL statement to SQL stmt.executeUpdate(builtstatement); } //end try catch (Exception e) { System.err.println(e); errorfound = true; } //end catch //close connections and statement Connection.closeSQLConn(); try { if(stmt != null) { stmt.close(); } } //end try catch (Exception e) { System.err.println(e); } //end catch return errorfound; } //end savetodatabase method
5
@Override public void startSetup(Attributes atts) { super.startSetup(atts); String path = atts.getValue(A_PATH); URL url_path = null; if (path == null) { System.out.println("WARNING: path attribute not provided for HTMLViewerMenuItem: " + getText()); } else if (path.indexOf("://") != -1) { try { url_path = new URL(path); } catch (java.net.MalformedURLException e) { System.out.println("WARNING: path for HTMLViewerMenuItem: " + getText() + " was not a valid URL: " + path); } } else { url_path = Thread.currentThread().getContextClassLoader().getResource(path); } if (url_path != null) { setResourceURL(url_path); addActionListener(this); setEnabled(true); } else { setEnabled(false); } }
4
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final OutputArCustomer other = (OutputArCustomer) obj; if (!Objects.equals(this.szCustomerId, other.szCustomerId)) { return false; } return true; }
3
public List<String> getIDList(String term) { String query = "select IDList from termidlist where term=\"" + term + "\""; ResultSet rsSet = sqLconnection.Query(query); List<String> iDList = new ArrayList<>(); try { while (rsSet.next()) { String id = rsSet.getString("IDList"); iDList = Arrays.asList(id.split(",")); } } catch (SQLException e) { e.printStackTrace(); } return iDList; }
2
public Stella_Object lookup(Stella_Object key) { { KeyValueMap self = this; { Stella_Object map = self.theMap; int crossover = self.crossoverPoint; if (crossover == 0) { return (StellaHashTable.stellaHashTableLookup(((StellaHashTable)(map)), key)); } else { { KvCons cursor = ((KvCons)(map)); if (self.equalTestP) { while (cursor != null) { if (Stella_Object.equalP(cursor.key, key)) { return (cursor.value); } cursor = cursor.rest; } } else { while (cursor != null) { if (Stella_Object.eqlP(cursor.key, key)) { return (cursor.value); } cursor = cursor.rest; } } return (null); } } } } }
6
public boolean isInField(Vector2d coord) { if ((coord.x>=position.x && coord.x<=position.x+widthHeight.x) || (coord.x<=position.x && coord.x>=position.x+widthHeight.x)) { if ((coord.y>=position.y && coord.y<=position.y+widthHeight.y) || (coord.y<=position.y && coord.y>=position.y+widthHeight.y)) { return true; } } return false; }
8
public void verify(FileInputStream ciphertext, FileInputStream cleartext) { int Lp = p.bitLength(); // bitlength of p (512 bit) int L = (Lp - 1) / 8; // blocksize // read ciphertext BigInteger C = readCipher(ciphertext); BigInteger M = readClear(cleartext, L); Boolean verified = true; while (C != null && M != null) { BigInteger r = C.mod(p); BigInteger s = C.divide(p); if ((r.compareTo(BigInteger.ONE) >= 0) && (r.compareTo(p.subtract(BigInteger.ONE)) <= 0)) { BigInteger yr = y.modPow(r, p); // y^r mod p BigInteger rs = r.modPow(s, p); // r^s mod p BigInteger v1 = yr.multiply(rs).mod(p); // y^r * r^s mod p BigInteger v2 = g.modPow(M, p); if (!v1.equals(v2)) { verified = false; } } else { System.out.println("Abbruch, da r >= 1 oder r <= p-1 nicht erfüllt ist!"); verified = false; } C = readCipher(ciphertext); M = readClear(cleartext, L); } if (verified) { System.out.println("Der Text wurde verifiziert!"); } else { System.out.println("Der Text konnte nicht verifiziert werden!!!"); } }
6
public void update(float delta) { boardTimer += delta / 1000; if (boardTimer > minSpawnTime) { Random rng = new Random(System.currentTimeMillis()); int r1 = rng.nextInt(); int spawnTime = maxSpawnTime - minSpawnTime; if ((int) r1 % spawnTime == 0 || boardTimer > (spawnTime)) { boardTimer = 0; spawn(); } } for (int i = 0; i < enemies.size(); i++) { if (enemies.get(i).getPosition().x < 0) { enemies.remove(enemies.get(i)); } } }
5
public ArrayIterator(T[] source) { this._source = source; }
0
public static void init() { }
0
@Override public void Borrar(Object value) { Session session = null; try { Equipo equipo = (Equipo) value; session = NewHibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); session.delete(equipo); session.getTransaction().commit(); } catch (HibernateException e) { System.out.println(e.getMessage()); session.getTransaction().rollback(); } finally { if (session != null) { // session.close(); } } }
2
public void act(List<Actor> newHunters) { // Move towards a source of food if found. Location newLocation = findTarget(); if(newLocation == null) { // No food found - try to move to a free location. newLocation = getField().freeAdjacentLocation(getLocation()); } // See if it was possible to move. if(newLocation != null) { setLocation(newLocation); } }
2
@Override public boolean getControls(String control){ if(control == "Age"){ return true;} if(control == "Fade"){ return true;} if(control == "Mat"){ return true;} if(control == "Orient"){ return true;} if(control == "Mirror"){ return true;} if(control == "Any"){return true;} if(control == "All"){return true;} if(control == "InMode"){return true;} if(control == "Xfact"){return true;} return false;}
9
public List<RoomEvent> findRoomEventsByEventBranchId(final Long eventBranchId) { return new ArrayList<RoomEvent>(); }
0
static float lpc_from_data(float[] data, float[] lpc, int n, int m){ float[] aut=new float[m+1]; float error; int i, j; // autocorrelation, p+1 lag coefficients j=m+1; while(j--!=0){ float d=0; for(i=j; i<n; i++) d+=data[i]*data[i-j]; aut[j]=d; } // Generate lpc coefficients from autocorr values error=aut[0]; /* if(error==0){ for(int k=0; k<m; k++) lpc[k]=0.0f; return 0; } */ for(i=0; i<m; i++){ float r=-aut[i+1]; if(error==0){ for(int k=0; k<m; k++) lpc[k]=0.0f; return 0; } // Sum up this iteration's reflection coefficient; note that in // Vorbis we don't save it. If anyone wants to recycle this code // and needs reflection coefficients, save the results of 'r' from // each iteration. for(j=0; j<i; j++) r-=lpc[j]*aut[i-j]; r/=error; // Update LPC coefficients and total error lpc[i]=r; for(j=0; j<i/2; j++){ float tmp=lpc[j]; lpc[j]+=r*lpc[i-1-j]; lpc[i-1-j]+=r*tmp; } if(i%2!=0) lpc[j]+=lpc[j]*r; error*=1.0-r*r; } // we need the error value to know how big an impulse to hit the // filter with later return error; }
8
public void run() { try { // loop until thread is terminated while (!isInterrupted() && processMsg(readInt())) ; } catch (Exception ex) { if (parent().isConnected()) { eWrapper().error(ex); } } if (parent().isConnected()) { m_parent.close(); } }
5
private void findCosineSimilarity(double[] activeUser) { // Add Logic to check that not all elements are same otherwise Wau =0 for (int user = 0; user < totalUsers; user++) { double innerProduct = 0; double lengthOfActiveUser = 1; double lengthofUser = 1; for (int movie = 0; movie < totalMovies; movie++) { if (activeUser[movie] > 0 && ratings[user][movie] > 0) { //(activeUser[movie] - activeUserAverage) add logic to rectify this to be 0 innerProduct += ((activeUser[movie]*IUF[movie]) - (activeUserAverage*IUF[movie]) )* ((ratings[user][movie]*IUF[movie]) - (averageOfUser[user]*IUF[movie])); lengthOfActiveUser += Math.pow(((activeUser[movie]*IUF[movie]) - (activeUserAverage*IUF[movie])), 2); lengthofUser += Math.pow(((ratings[user][movie]*IUF[movie]) - (averageOfUser[user]*IUF[movie])), 2); } } similarity[user] = innerProduct / (Math.sqrt(lengthOfActiveUser) * Math.sqrt(lengthofUser)); if (similarity[user] == 0 && (isElementAverageInActiveUser(activeUser) || isElementAverage(user))) { similarity[user] = cosineSimilarity(user, activeUser); } similarity[user] = applyCaseAmplification(similarity[user]); } sortUsers(); }
7
public int getPendingSaveCount() { int count = 0; for (PlayerReinforcement pr : pendingDbUpdate) { DbUpdateAction action = pr.getDbAction(); if (action == DbUpdateAction.INSERT || action == DbUpdateAction.SAVE) { ++count; } } return count; }
3
public <V> Adapter.Setter<V> makeSetter(String methodName, Class<V> _class) { try { final Method method = version.getClass().getMethod(methodName, _class); return new Adapter.Setter<V>() { public void call(V value) { try { Transaction me = Thread.getTransaction(); Transaction other = null; Set<Transaction> others = null; while (true) { synchronized (Adapter.this) { others = readWriteConflict(me); if (others == null) { other = openWrite(me); if (other == null) { method.invoke(version, value); return; } } } if (others != null) { manager.resolveConflict(me, others); } else if (other != null) { manager.resolveConflict(me, other); } } } catch (IllegalAccessException e) { throw new PanicException(e); } catch (InvocationTargetException e) { throw new PanicException(e); } }}; } catch (NoSuchMethodException e) { throw new PanicException(e); } }
8
public void DeleteAtividade(int IDatividade) throws SQLException { Connection conexao = null; PreparedStatement comando = null; ResultSet resultado = null; try { conexao = BancoDadosUtil.getConnection(); comando = conexao.prepareStatement(SQL_DELETE_ATIVIDADE); comando.setInt(1, IDatividade); comando.execute(); conexao.commit(); } catch (Exception e) { if (conexao != null) { conexao.rollback(); } throw new RuntimeException(e); } finally { if (comando != null && !comando.isClosed()) { comando.close(); } if (conexao != null && !conexao.isClosed()) { conexao.close(); } } }
6
public AnalyzeProteins() { //iterate through all dssp files on-hand int counter = 0; File dir = new File("C:/Users/Bryn/Documents/CodingProjects/dssp/"); for (File child : dir.listFiles()) { if (".".equals(child.getName()) || "..".equals(child.getName())) { continue; // Ignore the self and parent aliases. } System.out.println(child.getName()); int last = child.getName().length(); String pdbID = child.getName().substring(last - 9, last - 5); ++counter; AnalyzeOneProtein ap1 = new AnalyzeOneProtein(pdbID); if(counter > 2) { break; } // System.out.println(pdbID); // Do something with child } }
4
public void login(ActionEvent actionEvent){ RequestContext context = RequestContext.getCurrentInstance(); FacesMessage msg = null; boolean loggedIn = false; if(usuaCuenta != null && usuaCuenta.equals("admin") && usuaContrasena != null && usuaContrasena.equals("admin")){ loggedIn= true; msg = new FacesMessage(FacesMessage.SEVERITY_INFO,"Bienvenido",usuaCuenta); }else{ loggedIn = false; msg = new FacesMessage(FacesMessage.SEVERITY_ERROR,"Login Error","Credenciales Invalidas"); } FacesContext.getCurrentInstance().addMessage(null,msg); context.addCallbackParam("loggedIn",loggedIn); }
4
public static Duration available(Duration maximum, Duration current) { if (current.isLongerThan(maximum)) { return new Duration(0); } else { return maximum.minus(current); } }
1
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Utente other = (Utente) obj; if (nome == null) { if (other.nome != null) return false; } else if (!nome.equals(other.nome)) return false; return true; }
6
private void sendMessage(PaneTab selectedTab) { if (!selectedTab.getMessageField().getText().isEmpty()) { String message = selectedTab.getMessageField().getText(); if (this.view.tabs.getSelectedIndex() == 0) { // Public message int maxPublicMessageLength = this.client.MAX_PACKET_SIZE - this.client.GENERAL_HEADER_SIZE - this.client.PUBLIC_CHAT_HEADER_SIZE; int it = 0; while (it + maxPublicMessageLength < message.length()) { client.sendPublicMessage(message.substring(it, it + maxPublicMessageLength - 1)); it = it + maxPublicMessageLength; } client.sendPublicMessage(message.substring(it, message.length())); } else { // private message int maxPrivateMessageLength = this.client.MAX_PACKET_SIZE - this.client.GENERAL_HEADER_SIZE - this.client.PRIVATE_CHAT_HEADER_SIZE; int it = 0; while (it + maxPrivateMessageLength < message.length()) { client.sendPrivateMessage( message.substring(it, it + maxPrivateMessageLength - 1), selectedTab.getAddress()); it = it + maxPrivateMessageLength; } client.sendPrivateMessage( message.substring(it, message.length()), selectedTab.getAddress()); this.view.addMessage(this.client.getOwnUser().getIP(), selectedTab.getAddress(), message, Timestamp.getCurrentTimeAsLong(), true); } } selectedTab.getMessageField().setText(""); }
4
private static void validarCPF(String digits) throws ValidacaoException { try { boolean isvalid = false; if (Long.parseLong(digits) % 10 == 0) { isvalid = somaPonderadaCPF(digits) % 11 < 2; } else { isvalid = somaPonderadaCPF(digits) % 11 == 0; } if (!isvalid) { throw new ValidacaoException("CPF Inválido!"); } } catch (Exception ex) { throw new ValidacaoException("Verifique: " + ex.getMessage() + "!"); } }
3
private synchronized void readPasswd(final InputStream in) throws IOException { final BufferedReader din = new BufferedReader(new InputStreamReader(in)); String line; entries = new HashMap(); while ((line = din.readLine()) != null) { final String[] fields = new String[7]; final StringTokenizer st = new StringTokenizer(line, ":", true); try { fields[0] = st.nextToken(); // username st.nextToken(); fields[1] = st.nextToken(); // passwd if (fields[1].equals(":")) { fields[1] = ""; } else { st.nextToken(); } fields[2] = st.nextToken(); // uid if (fields[2].equals(":")) { fields[2] = ""; } else { st.nextToken(); } fields[3] = st.nextToken(); // gid if (fields[3].equals(":")) { fields[3] = ""; } else { st.nextToken(); } fields[4] = st.nextToken(); // gecos if (fields[4].equals(":")) { fields[4] = ""; } else { st.nextToken(); } fields[5] = st.nextToken(); // dir if (fields[5].equals(":")) { fields[5] = ""; } else { st.nextToken(); } fields[6] = st.nextToken(); // shell if (fields[6].equals(":")) { fields[6] = ""; } } catch (NoSuchElementException x) { continue; } entries.put(fields[0], fields); } }
8
public void RemoveTlv(int tag){ int newlen=0; if (this.OtherTlvArray != null) { Tlv[] tmp = new Tlv[OtherTlvArray.length]; for(int i=0;i<OtherTlvArray.length;i++){ if (OtherTlvArray[i].Tag != tag){ tmp[newlen]=OtherTlvArray[i]; newlen++; } } //System.out.println("newlen:"+newlen); if (newlen<OtherTlvArray.length){ Tlv[] tmp2=new Tlv[newlen]; System .arraycopy(tmp, 0, tmp2, 0, newlen); this.OtherTlvArray=tmp2; } } }
4
public static void main(String[] args) { Connection con = null;//null is used to initialize; Statement stmn = null; ResultSet rs = null; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost/gufran?" + "user=root&password=Mysql786"); stmn = con.createStatement(); //String newClasses = "Insert into classes values(5863, 'Asif','Adeel','Jamaica Ave','Jamaica')"; String Update = "Update classes SET City = 'Flushing' WHERE LastName='Asif'"; stmn.execute(Update); String sql = "Select * From classes"; rs =stmn.executeQuery(sql); while(rs.next()){ System.out.print(rs.getString(1) + "\t"); System.out.print(rs.getString(2) + "\t"); System.out.print(rs.getString(3) + "\t"); System.out.print(rs.getString(4) + "\t"); System.out.println(rs.getString(5) + "\t"); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e){ e.printStackTrace(); }finally { try{ rs.close(); stmn.close(); con.close(); } catch (SQLException e){ e.printStackTrace(); } } }
4
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); ICommand command = RequestHelper.getInstance().getCommand(request); String page = command.execute(request, response); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(page); dispatcher.forward(request, response); } catch (ServletException | IOException ex) { } }
1
public List<ParkBoy> getParkBoyList() { return parkBoyList; }
0
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Tuple2 other = (Tuple2) obj; if (_1 == null) { if (other._1 != null) return false; } else if (!_1.equals(other._1)) return false; if (_2 == null) { if (other._2 != null) return false; } else if (!_2.equals(other._2)) return false; return true; }
9
@Override public void run() { while(true) { Messages.parseForMessages(); DateTime dt = new DateTime(); System.out.println(dt.getHourOfDay()+":"+dt.getMinuteOfHour()); if(counteratlastsecond==-1) try { System.out.println("counterlastsecond is -1 so we update to the current value"); counteratlastsecond = getCurrentValue(); } catch (IOException e) { e.printStackTrace(); } else { try { double value = getCurrentValue(); if(value!=counteratlastsecond) { double change = value-counteratlastsecond; if(change<0) { change=0; } energycouter=energycouter+change; counteratlastsecond = value; System.out.println("the change is: "+change); if(change>0.2) { currentrunntime++; currentdowntime=0; energythisuptime=energythisuptime+change; laststate=state; state=STATE_ON; } else { currentrunntime=0; currentdowntime++; laststate=state; state=STATE_OFF; } } else { laststate=state; currentrunntime=0; currentdowntime++; state=STATE_OFF; } System.out.println(value); } catch (Exception e) { e.printStackTrace(); } } checkForActions(); if(laststate==STATE_ON && state == STATE_OFF) { energythisuptime=0; } sleep(); } }
9
public void setIdUsuario(Integer idUsuario) { this.idUsuario = idUsuario; }
0
public void UpdateAtividade(Atividade atividade) throws SQLException { Connection conexao = null; PreparedStatement comando = null; try { conexao = BancoDadosUtil.getConnection(); comando = conexao.prepareStatement(SQL_UPDATE_ATIVIDADE); comando.setString(1, atividade.getNome()); comando.setFloat(2, atividade.getDuracao()); comando.setInt(3, atividade.getProjeto().getIdProjeto()); comando.setInt(4, atividade.getEncarregado().getIdUsuario()); comando.setInt(5, atividade.getIdAtividade()); comando.execute(); conexao.commit(); } catch (Exception e) { if (conexao != null) { conexao.rollback(); } throw new RuntimeException(e); } finally { if (comando != null && !comando.isClosed()) { comando.close(); } if (conexao != null && !conexao.isClosed()) { conexao.close(); } } }
6
public void close() { if( blockvec != null ) { blockvec.clear(); blockvec = null; } if( (nextblock != null) && (!nextblock.equals( this )) ) { nextblock = null; } mystore = null; if( data != null ) { data.clear(); data = null; } }
4
public void delete() { if (getInstalledDirectory() != null && getInstalledDirectory().exists()) { try { FileUtils.deleteDirectory(getInstalledDirectory()); } catch (IOException ex) { Utils.getLogger().log(Level.SEVERE, ex.getMessage(), ex); } } File assets = new File(directories.getAssetsDirectory(), getName()); if (assets.exists()) { try { FileUtils.deleteDirectory(assets); } catch (IOException ex) { Utils.getLogger().log(Level.SEVERE, ex.getMessage(), ex); } } installedPackRepository.remove(getName()); installedPack = null; installedDirectory = null; }
5
@Override public void process(JCas aJCas) throws AnalysisEngineProcessException { PosTagNamedEntityRecognizer recognizer = null; try { recognizer = new PosTagNamedEntityRecognizer(); } catch (ResourceInitializationException e) { e.printStackTrace(); } String sentenceText = aJCas.getDocumentText(); Map<Integer, Integer> begin2end = recognizer.getGeneSpans(sentenceText); for (Map.Entry<Integer, Integer> entry : begin2end.entrySet()) { String entityText = sentenceText.substring(entry.getKey(), entry.getValue()); // Get the index of non-whitespace characters. int begin = sentenceText.substring(0, entry.getKey()).replaceAll("\\s", "").length(); int end = sentenceText.substring(0, entry.getValue()).replaceAll("\\s", "").length() - 1; // Remove token with single character. if (begin == end) continue; // Remove single lower-case words with length less than 5. if (end - begin < 4 && entityText.matches("[[a-z][^\\w]]+")) continue; GeneEntity geneEntity = new GeneEntity(aJCas); geneEntity.setBegin(begin); geneEntity.setEnd(end); geneEntity.setEntityText(entityText); geneEntity.addToIndexes(); } }
5
public void setCtrlCR(CtrlComptesRendus ctrlCR) { this.ctrlCR = ctrlCR; }
0
public PanelFalsaPosicion(){ c1Field = new JTextField(5); c2Field = new JTextField(5); expField= new JTextField(5); c3Field = new JTextField(5); xaField = new JTextField(5); xbField = new JTextField(5); errorField = new JTextField(5); c1Label = new JLabel("Coeficiente del termino cuadratico"); expLabel = new JLabel("Exponente del termino cuadratico"); c2Label = new JLabel("Coeficiente del termino lineal"); c3Label = new JLabel("Termino independiente"); xaLabel= new JLabel("Intervalo XA"); xbLabel= new JLabel("Intervalo XB"); errorLabel= new JLabel("Error deseado"); textArea= new JTextArea(); setLayout(new GridLayout(8,3,0,0)); add(c1Label);add(c1Field); add(expLabel);add(expField); add(c2Label);add(c2Field); add(c3Label);add(c3Field); add(xaLabel);add(xaField); add(xbLabel);add(xbField); add(errorLabel);add(errorField); ejecutar = new JButton("Ejecutar"); textArea.setEditable(false); add(ejecutar);add(textArea); ejecutar.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { c1=Double.parseDouble(c1Field.getText()); exp=Integer.parseInt(expField.getText()); c2=Double.parseDouble(c2Field.getText()); c3=Double.parseDouble(c3Field.getText()); xa=Double.parseDouble(xaField.getText()); xb=Double.parseDouble(xbField.getText()); error=Double.parseDouble(errorField.getText()); do{ cont++; fa=Funcion(exp,c1,c2,c3,xa); fb=Funcion(exp,c1,c2,c3,xb); xr=xa-((fa*(xb-xa)/(fb-fa))); fxr=Funcion(exp,c1,c2,c3,xr); System.out.println(cont+" "+"fa= "+fa+" fb="+fb+" xr="+xr+" Error="+eact); if((fa*fxr)<0){ xb=xr; } else{ xa=xr; } eact=Math.abs((xr-eaux)/xr); eaux=Math.abs(xr); if(fxr==0){ System.out.println("Raiz exacta es: "+xr); System.exit(0); } }while (eact>error); textArea.append("La ultima aproximacion fue: "+xr+"\n"); textArea.append("Numero de iteraciones: "+cont); } }); }
3
@Test public void equals_test() { try{ double []vec1= {1.0,2.0,3.0}; double []vec2= {1.0,2.0,3.0}; boolean result= Vector.equals(vec1, vec2); Assert.assertTrue(result); } catch (Exception e) { // TODO Auto-generated catch block fail("Not yet implemented"); } }
1
public void openDevice(int index) { // Opens the device takes in index you // want to use deviceIndex = index; // Sets the index to the parameter try { // beginning of a try catch block sender = JpcapSender.openDevice(devices[deviceIndex]); // Opens the // selected // device } catch (IOException e) { // catches an input output error // TODO Auto-generated catch block e.printStackTrace(); // prints the throwable } }
1
public boolean shouldOutputCoords() { if (this.elementType == ElementType.BLOCK || this.elementType == ElementType.IMAGEBLOCK || this.elementType == ElementType.TEXTBLOCK || this.elementType == ElementType.TEXTLINE) { return true; } else { return false; } }
4
public void setjTextFieldAdresse(JTextField jTextFieldAdresse) { this.jTextFieldAdresse = jTextFieldAdresse; }
0
private void displayUsersTasks(){ //find tasks for user logged in try { Project tempProject = null; ResultSet dbUsersTasks = null; Statement statement; statement = connection.createStatement(); dbUsersTasks = statement.executeQuery( "SELECT Staff.staffID, Task.taskID, Task.projectID, Task.responsiblePerson, Task.taskPriority," + " Task.status, Task.taskName, Task.assetID FROM Staff INNER JOIN Task ON " + "Staff.staffID = Task.responsiblePerson WHERE Staff.staffID =" + UserLoggedIn.getUserID() + ";"); while(dbUsersTasks.next()) { //get Project from SetOfProjects where projectID = int tempProjectID = dbUsersTasks.getInt("Task.projectID"); for (int i=0; i<allProjects.size();i++){ if(allProjects.get(i).getProjectID()==(tempProjectID)) { tempProject = (allProjects.get(i)); } } //Task task = new Task(dbUsersTasks.getInt("Task.taskID"), UserLoggedIn, dbUsersTasks.getString("Task.TaskName"), dbUsersTasks.getInt("Task.taskPriority"), //dbUsersTasks.getString("Task.taskStatus"), tempProject); //usersTasks.addTask(task); jList1.setListData(usersTasks); } } catch (SQLException ex) { Logger.getLogger(testFrame3Tim.class.getName()).log(Level.SEVERE, null, ex); } }
4
@Override protected void setUp() throws Exception { buffy = allocateAlignedByteBuffer(2 * PAGE_SIZE, PAGE_SIZE); buffy.position(PAGE_SIZE + offset); buffy.limit(buffy.position() + 32); buffy = buffy.slice().order(ByteOrder.nativeOrder()); String host = "localhost"; int port = 12345; final ServerSocketChannel serverSocket = ServerSocketChannel.open(); serverSocket.socket().bind(new InetSocketAddress(host, port)); final CountDownLatch waitForAccept = new CountDownLatch(1); Thread t = new Thread(new Runnable() { public void run() { SocketChannel server = null; try { serverSocket.socket().setReceiveBufferSize(PAGE_SIZE); server = serverSocket.accept(); server.socket().setSendBufferSize(PAGE_SIZE); server.socket().setTcpNoDelay(true); server.configureBlocking(false); serverSocket.close(); waitForAccept.countDown(); ByteBuffer spike = allocateAlignedByteBuffer(2 * PAGE_SIZE, PAGE_SIZE); spike.position(PAGE_SIZE + offset); spike.limit(spike.position() + 32); spike = spike.slice().order(ByteOrder.nativeOrder()); while (!Thread.interrupted()) { spike.clear(); do { if (server.read(spike) == -1) return; } while (spike.hasRemaining()); spike.flip(); do { server.write(spike); } while (spike.hasRemaining()); } } catch (Exception e) { // TODO Auto-generated catch block failed = e; waitForAccept.countDown(); } finally { if (server != null) { try { server.close(); } catch (IOException e) { e.printStackTrace(); } } } } }); t.start(); client = SocketChannel.open(); client.socket().setTcpNoDelay(true); client.configureBlocking(false); client.socket().setReceiveBufferSize(PAGE_SIZE); client.connect(new InetSocketAddress(host, port)); while (!client.finishConnect()) ; waitForAccept.await(); if (failed != null) { throw failed; } }
9
private void isolateSubgraph(Subgraph subgraph, Node member) { Edge edge = null; for (int i = 0; i < member.incoming.size(); i++) { edge = member.incoming.getEdge(i); if (!subgraph.isNested(edge.source) && !edge.flag) removeEdge(edge); } for (int i = 0; i < member.outgoing.size(); i++) { edge = member.outgoing.getEdge(i); if (!subgraph.isNested(edge.target) && !edge.flag) removeEdge(edge); } if (member instanceof Subgraph) { NodeList members = ((Subgraph) member).members; for (int i = 0; i < members.size(); i++) isolateSubgraph(subgraph, members.getNode(i)); } }
8
public void testMultipleNotifyingFutures() throws Exception { MethodCall sleep=new MethodCall("sleep", new Object[]{100L}, new Class[]{long.class}); List<CompletableFuture<RspList<Long>>> listeners=new ArrayList<>(); RequestOptions options=new RequestOptions(ResponseMode.GET_ALL, 30000L); for(int i=0; i < 10; i++) { CompletableFuture<RspList<Long>> f=da.callRemoteMethodsWithFuture(null, sleep, options); listeners.add(f); } Util.sleep(1000); for(int i=0; i < 10; i++) { boolean all_done=true; for(CompletableFuture<RspList<Long>> listener: listeners) { boolean done=listener.isDone(); System.out.print(done? "+ " : "- "); if(!listener.isDone()) all_done=false; } if(all_done) break; Util.sleep(500); System.out.println(""); } for(CompletableFuture<RspList<Long>> listener: listeners) assert listener.isDone(); }
7
private String getComponentNameFromInfo(InfoPacket info){ Iterator<Pair<?>> pairIt = info.namedValues.iterator(); Pair<?> pair = null; String name = null; while(pairIt.hasNext() && name==null){ pair = pairIt.next(); if(pair.getLabel() == Label.cNme){ name = (String) pair.second(); } } return name; }
5
@Override public boolean containsBooleanArray(String name) { JOSObject<? , ?> raw = this.getObject(name); if(raw == null) return false; if(raw.getName().equalsIgnoreCase(BOOLEAN_ARRAY_NAME)) return true; return false; }
4
private void listen() throws IOException, InterruptedException { reply(200); String line = null; while ((line = reader.readLine()) != null) { StringTokenizer st = new StringTokenizer(line); String command = st.nextToken().toLowerCase(); int code = 0; if (command.equals("register-peer")) { code = register(st); } else if (command.equals("upload")) { code = upload(st); } else if (command.equals("query")) { code = query(st); } else if (command.equals("download")) { code = download(st); } else if (command.equals("port")) { code = setPort(st); } else if (command.equals("quit")) { code = quit(); } if (code == 221 || code == 0) return; } }
9