text
stringlengths
14
410k
label
int32
0
9
public AlumneVo buscarAlumne(String User) { try { DbConnection conex= new DbConnection(); PreparedStatement consulta = conex.getConnection().prepareStatement("SELECT * FROM alumnes where nomUser='" + User + "';"); ResultSet res = consulta.executeQuery(); if (res.next()){ AlumneVo alum=(AlumneVo) Factory.factoryMethod("alumne"); alum.setNomUser((res.getString("nomUser"))); alum.setNom((res.getString("Nom"))); alum.setCognoms((res.getString("Cognoms"))); alum.setEdat((Integer.parseInt(res.getString("Edat")))); alum.setPassword((res.getString("password"))); res.close(); consulta.close(); conex.desconectar(); return alum; } } catch (Exception e) { System.out.print("La persona no existeix"); } return null; }
2
private void btnIngresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnIngresarActionPerformed if (jPContrasena.getPassword().length!=6) { JOptionPane.showMessageDialog(this, "Contraseña Incorrecta", "Error", JOptionPane.ERROR_MESSAGE); jPContrasena.requestFocus(); } else { gestionLogin.getEmpleado().setUser_Empleado(txtUsuario.getText()); try { gestionLogin.Login(); PasarDeNegocioAInterfaz(); Comparar(); } catch(SQLException ex) { JOptionPane.showMessageDialog(this, ex.getMessage()); } } }//GEN-LAST:event_btnIngresarActionPerformed
2
@Override public String load() { try { Class.forName(JDBC_DRIVER).newInstance(); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { log.fatal("Driver failed", e); } Connection connection = null; try { connection = DriverManager.getConnection(DB_URL, "app", "app"); } catch (SQLException e) { log.fatal("connection failed", e); } if (connection != null) { try { stmt = connection.createStatement(); //PreparedStatement ps = connection.prepareStatement("SELECT DESCRIPTION FROM ? WHERE (?=?)"); //ResultSet result = stmt.executeQuery("select DESCRIPTION from APP.PRODUCT where PRODUCT_ID = 988765"); //ps.setString(1, "DESCRIPTION"); //ps.setString(2, "APP.PRODUCT"); //ps.setString(3, "PRODUCT_ID"); PreparedStatement ps = connection.prepareStatement("SELECT DESCRIPTION from APP.PRODUCT where (PRODUCT_ID=?)"); ps.setString(1, "988765"); ResultSet result = ps.executeQuery(); if (result.next()) { return result.getString(1); } else { log.debug("no result"); } connection.close(); stmt.close(); } catch (SQLException ex) { log.fatal("kein Zugriff auf den Datensatz", ex); } } else { log.fatal("connection failed"); } return null; }
5
public long binHasDisk(){ return binHasDisk; }
0
@Override public void keyReleased(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_UP: System.out.println("Stop moving up"); break; case KeyEvent.VK_DOWN: currentSprite = anim.getImage(); robot.setDucked(false); break; case KeyEvent.VK_LEFT: robot.stopLeft(); break; case KeyEvent.VK_RIGHT: robot.stopRight(); break; case KeyEvent.VK_SPACE: break; } }
5
public Object getValueAt(int row, int col) { Statement m = (Statement)statements.getBusinessObjects().get(row); if (col == 0) { return m.getName(); } else if (col == 1) { return Utils.toString(m.getDate()); } else if (col == 2) { return (m.isDebit()) ? "(D) -" : "(C) +"; } else if (col == 3) { return m.getAmount(); } else if (col == 4) { return m.getCounterParty(); } else if (col == 5) { return m.getTransactionCode(); } else if (col == 6) { return m.getCommunication(); } else return ""; }
8
public void setLength(){ if(length == Double.MAX_VALUE) length = Math.sqrt( Math.pow(fromNode.getxCoord()-toNode.getxCoord(),2) + Math.pow(fromNode.getyCoord()-toNode.getyCoord(),2) ); }
1
public int readNoEof() throws IOException { int result = read(); if (result != -1) return result; else throw new EOFException("End of stream reached"); }
1
private static Method findSetterWithCompatibleParamType(final Class<?> clazz, final String setterName, final Class<?> argumentType) { Method compatibleSetter = null; for( final Method method : clazz.getMethods() ) { if( !setterName.equals(method.getName()) || method.getParameterTypes().length != 1 ) { continue; // setter must have correct name and only 1 parameter } final Class<?> parameterType = method.getParameterTypes()[0]; if( parameterType.equals(argumentType) ) { compatibleSetter = method; break; // exact match } else if( parameterType.isAssignableFrom(argumentType) ) { compatibleSetter = method; // potential match, but keep looking for exact match } } return compatibleSetter; }
8
private static void validateEmail(String email) throws TechnicalException { if (email == null || email.isEmpty() || email.length() > EMAIL_SIZE) { throw new TechnicalException(EMAIL_ERROR_MSG); } String regex = "\\w+@\\w+\\.[a-z]{2,}"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(email); if (! m.matches()) { throw new TechnicalException(EMAIL_ERROR_MSG); } }
4
public void proceed(int i, int j) { //Initializing Infofield inf = new Infofield(); mi = new Infofield(deck1); oi = new Infofield(deck2); for (int i1 = 0; i1 < new Random().nextInt(60); i1++) { //Preparing deck1 = shuffle(deck1); deck2 = shuffle(deck2); } if (pif.isShields()) { //Adding Shields, if any for (int k = 0; k < i; k++) { addToShield(deck1.pop(), k + 1, true); addToShield(deck2.pop(), k + 1, false); } } if (pif.isDraw()) { //Drawing, if any if (!(deck1.isEmpty() && deck2.isEmpty())) { for (int k = 0; k < j; k++) { draw(true); draw(false); } } } h1.showHand(); opturn = false; }
7
public double getPosY() { return posY; }
0
public GUI(Startup startup, boolean Guion){ guion = Guion; s = startup; users = new JList<String>(s.getUserNames()); channels = new JList<String>(s.getChannelNames()); userpane = new JScrollPane(users); channelpane = new JScrollPane(channels); areapane = new JScrollPane(area); lists.setLayout(new GridLayout(0,1)); lists.add(userpane); lists.add(channelpane); data.setLayout(new BorderLayout()); data.add(areapane, BorderLayout.EAST); data.add(lists, BorderLayout.CENTER); frame.setSize(500,500); frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); frame.add(data, BorderLayout.CENTER); frame.add(field, BorderLayout.SOUTH); area.setEditable(false); field.addActionListener(this); frame.setVisible(guion); updatelists.start(); try { File folder = new File("logs"); if(!folder.exists()){ folder.mkdir(); } String[] simpletime = this.getSimpleTime(); String time = ""; for(String s: simpletime){ time += "_" + s; } pwriter = new PrintWriter("logs" + File.separator + "log" + time + ".txt", "UTF-8"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println(e.getCause()); } }
3
synchronized void newSumLog(int n) { if (n >= sumLog.length) { double sumLogOld[] = sumLog; double sumLogNew[] = new double[n + 1]; // Copy old values for (int i = 0; i < sumLogOld.length; i++) sumLogNew[i] = sumLogOld[i]; // Calc new values for (int i = sumLogOld.length; i < sumLogNew.length; i++) sumLogNew[i] = sumLogNew[i - 1] + Math.log(i); sumLog = sumLogNew; } }
3
public static int triangleAsum1(int x[][]) { int sum = 0; for (int i = 0; i < x.length; i++) { System.out.println(); for (int j = 0; j < x[i].length; j++) { if (i <= j) { System.out.print(x[i][j] + " "); sum = sum + x[i][j]; } else { System.out.print(" "); } } } System.out.println(); return sum; }
3
public Value merge(final Value v, final Value w) { SourceValue dv = (SourceValue) v; SourceValue dw = (SourceValue) w; if (dv.insns instanceof SmallSet && dw.insns instanceof SmallSet) { Set s = ((SmallSet) dv.insns).union((SmallSet) dw.insns); if (s == dv.insns && dv.size == dw.size) { return v; } else { return new SourceValue(Math.min(dv.size, dw.size), s); } } if (dv.size != dw.size || !dv.insns.containsAll(dw.insns)) { Set s = new HashSet(); s.addAll(dv.insns); s.addAll(dw.insns); return new SourceValue(Math.min(dv.size, dw.size), s); } return v; }
6
@Override public List<Framedata> translateFrame( ByteBuffer buffer ) throws LimitExedeedException , InvalidDataException { List<Framedata> frames = new LinkedList<Framedata>(); Framedata cur; if( incompleteframe != null ) { // complete an incomplete frame while ( true ) { try { buffer.mark(); int available_next_byte_count = buffer.remaining();// The number of bytes received int expected_next_byte_count = incompleteframe.remaining();// The number of bytes to complete the incomplete frame if( expected_next_byte_count > available_next_byte_count ) { // did not receive enough bytes to complete the frame incompleteframe.put( buffer.array(), buffer.position(), available_next_byte_count ); buffer.position( buffer.position() + available_next_byte_count ); return Collections.emptyList(); } incompleteframe.put( buffer.array(), buffer.position(), expected_next_byte_count ); buffer.position( buffer.position() + expected_next_byte_count ); cur = translateSingleFrame( (ByteBuffer) incompleteframe.duplicate().position( 0 ) ); frames.add( cur ); incompleteframe = null; break; // go on with the normal frame receival } catch ( IncompleteException e ) { // extending as much as suggested int oldsize = incompleteframe.limit(); ByteBuffer extendedframe = ByteBuffer.allocate( checkAlloc( e.getPreferedSize() ) ); assert ( extendedframe.limit() > incompleteframe.limit() ); incompleteframe.rewind(); extendedframe.put( incompleteframe ); incompleteframe = extendedframe; return translateFrame( buffer ); } } } while ( buffer.hasRemaining() ) {// Read as much as possible full frames buffer.mark(); try { cur = translateSingleFrame( buffer ); frames.add( cur ); } catch ( IncompleteException e ) { // remember the incomplete data buffer.reset(); int pref = e.getPreferedSize(); incompleteframe = ByteBuffer.allocate( checkAlloc( pref ) ); incompleteframe.put( buffer ); break; } } return frames; }
6
@Override public void channelRead(ChannelHandlerContext context, Object message) throws Exception { if (message instanceof HttpRequest && ((HttpRequest) message).getUri().toLowerCase() .startsWith("/redirect?")) { HttpRequest request = (HttpRequest) message; QueryStringDecoder decoder = new QueryStringDecoder( request.getUri()); Map<String, List<String>> requestParameters = decoder.parameters(); String destinationUrl = ""; if (requestParameters != null && requestParameters.containsKey(uri)) { if (requestParameters.get(uri) != null && !requestParameters.get(uri).isEmpty()) { destinationUrl = requestParameters.get(uri).get(0); if (!destinationUrl.startsWith("http:") && !destinationUrl.startsWith("https:")) { destinationUrl = "//".concat(destinationUrl); } ServerReport.incrementRedirectQuantity(destinationUrl); } } FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, FOUND); response.headers().set(LOCATION, destinationUrl); context.writeAndFlush(response).addListener( ChannelFutureListener.CLOSE); } else { context.fireChannelRead(message); } }
8
protected List<Node> expand(Node node, Problem problem, List<State> generatedStates, List<State> expandedStates) { List<Node> successorNodes = new ArrayList<Node>(); Node successorNode = null; State currentState = null; State successorState = null; Node bestNode = null; //If the current node and problem aren't null if (node != null && problem != null) { //Make the current state the state kept in the node. currentState = node.getState(); //Remove current state from the list of generated states. generatedStates.remove(currentState); //Insert current state to the list of generated states. expandedStates.add(currentState); //If current state is not null if (currentState != null) { //process the list of problem operators for (Operator operator : problem.getOperators()) { //Apply the operator to the current state successorState = operator.apply(currentState); //If the operator was applicable, a new successor state was generated if (successorState != null) { //If the new node hadn't been generated before //make a new node to keep the new successor state successorNode = new Node(successorState); //initializes the best node if (bestNode == null) bestNode = successorNode; //Set values for the various node's attributes successorNode.setOperator(operator.getName()); successorNode.setParent(node); successorNode.setDepth(node.getDepth() + 1); //evaluation function = heuristic function successorNode.setH(this.getEvaluationFunction().calculateH(successorNode)); //g function = g function successorNode.setG(this.getEvaluationFunction().calculateG(successorNode)); //compares to find the node with the lowest h value if (successorNode.getH() < bestNode.getH()) bestNode = successorNode; //Insert current successor State to the list of generated states generatedStates.add(successorState); } } //add the best node to the list of successor nodes. successorNodes.add(bestNode); } } return successorNodes; }
7
public CheckResultMessage check27(int day) { return checkReport.check27(day); }
0
private String[] readTextField1() { int size = 0; String[] s; String temp = jTextArea1.getText(); char c = temp.charAt(temp.length()-1); StringReader sr = new StringReader(temp); try { LineNumberReader lr = new LineNumberReader(sr); lr.skip(Long.MAX_VALUE);//skip to the end of the file size = ((int)c == 10) ? (lr.getLineNumber() - 1) : lr.getLineNumber();//if last char is a new line character substract the last line in determining the size } catch (Exception e) { System.out.println(e); } sr.close();//close and reopen file to skip back to the beginning s = new String[size+1]; sr = new StringReader(temp); BufferedReader br = new BufferedReader(sr); try { for (int i = 0; i < s.length; i++) {//read each line and store in array of strings s[i] = br.readLine(); } } catch (Exception e) { System.out.println(e); } return s; }
4
public static ArrayList<Object> parseList(StringBuffer buf, int[] idx) { idx[0]++; ArrayList<Object> into = new ArrayList<Object>(); while (true) { skipSpace(buf, idx); if (idx[0] >= buf.length()) { System.err.println("Unexpected end"); return into; } if (buf.charAt(idx[0]) == ']') { idx[0]++; return into; // Done } if (buf.charAt(idx[0]) == ',') { idx[0]++; continue; // skip commas, don't check for errors } into.add(parseObject(buf, idx)); } }
4
protected Integer doInBackground() { Benchmark.start("UnreadNews"); int i = 0; try { BufferedReader reader = new BufferedReader(new InputStreamReader(new URL("http://feedthenuketerrorist.fr.nf/newsupdate.txt").openStream())); ArrayList<Long> timeStamps = Lists.newArrayList(); String s = reader.readLine(); s = s.trim(); String[] str = s.split(","); for (String aStr : str) { if (!timeStamps.contains(Long.valueOf(Long.parseLong(aStr)))) { timeStamps.add(Long.valueOf(Long.parseLong(aStr))); } } long l; if (Long.parseLong(Settings.getSettings().getNewsDate()) == 0L) { l = Long.parseLong(Settings.getSettings().getNewsDate()); } else { l = Long.parseLong(Settings.getSettings().getNewsDate().substring(0, 10)); } for (Long timeStamp : timeStamps) { long time = timeStamp.longValue(); if (time > l) { i++; } } Benchmark.logBenchAs("UnreadNews", "UnreadNews Init"); } catch (UnknownHostException e) { Logger.logWarn("Error while checking news: " + e.getMessage()); } catch (Exception e) { Logger.logError("Error while checking news", e); } return Integer.valueOf(i); }
7
@Test public void testSum() { System.out.println("sum"); Polynomial<Double, Double, Double> instance = this._instance; double[] values; values = new double[4]; for (int i = 0; i < values.length; i++) values[i] = i + 1.0; Polynomial<Double, Double, Double> value = new PolynomialReal(values); values = new double[4]; for (int i = 0; i < values.length; i++) values[i] = (i + 1.0); for (int i = 0; i < Math.min(values.length, instance.getDegree() + 1); i++) values[i] += instance.getCoefficient(i); Polynomial<Double, Double, Double> expResult = new PolynomialReal(values); this._tester.testSum(instance, value, expResult); values = new double[5]; for (int i = 0; i < values.length; i++) values[i] = i + 1.0; value = new PolynomialReal(values); values = new double[5]; for (int i = 0; i < values.length; i++) values[i] = (i + 1.0); for (int i = 0; i < Math.min(values.length, instance.getDegree() + 1); i++) values[i] += instance.getCoefficient(i); expResult = new PolynomialReal(values); this._tester.testSum(instance, value, expResult); values = new double[3]; for (int i = 0; i < values.length; i++) values[i] = i + 1.0; value = new PolynomialReal(values); values = new double[Math.max(values.length, instance.getDegree() + 1)]; for (int i = 0; i < 3; i++) values[i] = (i + 1.0); for (int i = 0; i < Math.min(values.length, instance.getDegree() + 1); i++) values[i] += instance.getCoefficient(i); expResult = new PolynomialReal(values); this._tester.testSum(instance, value, expResult); }
9
public void onScheduledTick (World world, int x, int y) { Tile tile = world.getTile(x, y-1); if (tile != null && !tile.solid) { if (tile.id == Tile.water.id) world.setTile(x, y-1, Tile.stone); else world.setTile(x, y-1, Tile.lava); return; } tile = world.getTile(x+1, y); if (tile != null && !tile.solid) { if (tile.id == Tile.water.id) world.setTile(x+1, y, Tile.stone); else world.setTile(x+1, y, Tile.lava); } tile = world.getTile(x-1, y); if (tile != null && !tile.solid) { if (tile.id == Tile.water.id) world.setTile(x-1, y, Tile.stone); else world.setTile(x-1, y, Tile.lava); } }
9
public void exportTMX(String path, String extention) throws IOException { StringBuilder seg1 = new StringBuilder(); StringBuilder seg2 = new StringBuilder(); path = checkPath(path, extention); try { OutputStream fout = new FileOutputStream(path); OutputStream bout = new BufferedOutputStream(fout); OutputStreamWriter output = new OutputStreamWriter(bout, "UTF-8"); output.write("<tmx version=\"1.4\">\r\n\r\n"); // ispis headera temp = "<header\t" + "creationtool=" + "\"" + "Coral" + "\"\r\n" + "\t" + "creationtoolversion=" + "\"" + "v1.0" + "\"\r\n" + "\t" + "datatype=" + "\"" + "plaintext" + "\"\r\n" + "\t" + "segtype=" + "\"" + "block" + "\"\r\n" + "\t" + "adminlang=" + "\"" + System.getProperty("user.language") + "\"\r\n" + "\t" + "srclang=" + "\"" + dataModel.getProperty("language1") + "\"\r\n" + "\t" + "o-tmf=" + "\"" + "xml" + "\">\r\n" + "</header>\r\n\r\n"; output.write(temp); // body output.write("<body>\r\n"); for (int i = 0; i < idList1.size(); i++) { if (dataModel.getConnections(idList1.get(i)).isEmpty()) { continue; } // prolazi se kroz lijevu listu if (!visited.contains(idList1.get(i))) { // traze se parovi od trenutnog elementa iz lijeve liste goDeep(idList1.get(i)); // vrsi se sortiranje dohvacenih parova ovisno o tome kojoj // listi izvorno pripadaju // takoder, ako se radi o visestrukim vezama elementi se // spajaju for (int j = 0; j < tuvPair.size(); j++) { if (idList1.contains(tuvPair.get(j))) { seg1.append(dataModel.getElement(tuvPair.get(j)) + " "); } else if (idList2.contains(tuvPair.get(j))) { seg2.append(dataModel.getElement(tuvPair.get(j)) + " "); } } // stvara se novi translation unit output.write("\t" + "<tu>\r\n"); // prethodno spojeni elementi ispisuju se u translation unit // variant output.write("\t" + "<tuv xml:lang=" + "\"" + dataModel.getProperty("language1") + "\"" + "><seg>" + seg1.toString().trim() + "</seg></tuv>\r\n"); output.write("\t" + "<tuv xml:lang=" + "\"" + dataModel.getProperty("language2") + "\"" + "><seg>" + seg2.toString().trim() + "</seg></tuv>\r\n"); output.write("\t" + "</tu>\r\n\r\n"); tuvPair.clear(); seg1.delete(0, seg1.length()); seg2.delete(0, seg2.length()); } } output.write("</body>"); output.write("</tmx>"); output.close(); visited.clear(); } catch (FileNotFoundException e) { throw new FileNotFoundException( "File could not be found!\r\n" + "- Verify that the file exists in the specified location.\r\n" + "- Check the spelling of the name of the document.\r\n\r\n" + path); } catch (UnsupportedEncodingException e) { throw new UnsupportedEncodingException("Selected encoding is not supported."); } catch (IOException e) { throw new IOException("I/O exception has occurred."); } }
9
public void insert(int key) { Node uusi = new Node(key, false); if (root == null) { root = uusi; return; } Node current = root; Node p = current; while (true) { if (key == current.key) { return; // Jos lisättävä on juuri, ei tarvitse lisätä } if (key < current.key) { // Vasemmalle jos lisättävä avain pienempi if (current.left != null) { current = current.left; } else { // jos tyhjä, asetetaan arvo ja palataan current.left = uusi; current.left.parent = current; return; } } else { // Oikealle jos lisättävä avain suurempi if (current.right != null) { current = current.right; } else { // jos tyhjä, asetetaan arvo ja palataan current.right = uusi; current.right.parent = current; return; } } } }
6
void compress(int init_bits, OutputStream outs) throws IOException { int fcode; int i /* = 0 */; int c; int ent; int disp; int hsize_reg; int hshift; g_init_bits = init_bits; clear_flg = false; n_bits = g_init_bits; maxcode = MAXCODE(n_bits); ClearCode = 1 << (init_bits - 1); EOFCode = ClearCode + 1; free_ent = ClearCode + 2; char_init(); ent = nextPixel(); hshift = 0; for (fcode = hsize; fcode < 65536; fcode *= 2) ++hshift; hshift = 8 - hshift; hsize_reg = hsize; cl_hash(hsize_reg); output(ClearCode, outs); outer_loop: while ((c = nextPixel()) != EOF) { fcode = (c << maxbits) + ent; i = (c << hshift) ^ ent; if (htab[i] == fcode) { ent = codetab[i]; continue; } else if (htab[i] >= 0) { disp = hsize_reg - i; if (i == 0) disp = 1; do { if ((i -= disp) < 0) i += hsize_reg; if (htab[i] == fcode) { ent = codetab[i]; continue outer_loop; } } while (htab[i] >= 0); } output(ent, outs); ent = c; if (free_ent < maxmaxcode) { codetab[i] = free_ent++; htab[i] = fcode; } else cl_block(outs); } output(ent, outs); output(EOFCode, outs); }
9
public void drawControlPoint(Graphics2D g){ //adjust later to center of circle = focus point g.drawOval((int)curve.getCtrlX() - 5, (int)curve.getCtrlY() - 5, 10,10); }
0
@Override public int advance(int target) throws IOException { if (scorerDocQueue.size() < minimumNrMatchers) { return currentDoc = NO_MORE_DOCS; } if (target <= currentDoc) { return currentDoc; } do { if (scorerDocQueue.topDoc() >= target) { return advanceAfterCurrent() ? currentDoc : (currentDoc = NO_MORE_DOCS); } else if (!scorerDocQueue.topSkipToAndAdjustElsePop(target)) { if (scorerDocQueue.size() < minimumNrMatchers) { return currentDoc = NO_MORE_DOCS; } } } while (true); }
7
@Override public Float get(int i) { switch (i) { case 0: return w; case 1: return x; case 2: return y; case 3: return z; default: throw new IndexOutOfBoundsException(); } }
4
public boolean onCTFCommand(CommandSender sender, Command cmd, String label, String[] args){ //admin command. commands are: session, team if (args.length == 0) { return false; //no just ctf command } if (args[0].equalsIgnoreCase("session")) { return onCTFSessionCommand(sender, cmd, label, args); } else if (args[0].equalsIgnoreCase("team")) { return onCTFTeamCommand(sender, cmd, label, args); } return false; }
3
public void testConstructor_ObjectStringEx1() throws Throwable { try { new YearMonth("T10:20:30.040"); fail(); } catch (IllegalArgumentException ex) { // expected } }
1
public static void writeSrcProperties(String projN, ArrayList<String> tl, ArrayList<String> wf){ ArrayList<String> srcPpts=rfa.readInputStream(GenerateInitScripts.class.getResourceAsStream("config/srcOds/template.properties"),"UTF-8"); StringBuffer content=new StringBuffer(); for(int i=0; i<srcPpts.size(); ++i){ if(srcPpts.get(i).contains("{db-config-generate}")){ content.append("#sqoop db config\n"); content.append("#sqoop db username\n"); content.append("data_db_username="+un+"\n"); content.append("#sqoop db password\n"); content.append("#dev\n"); content.append("data_db_password="+epwd+"\n"); content.append("#sqoop db dbURL\n"); content.append("#dev\n"); content.append("data_db_url="+dbconS+"\n"); }else if(srcPpts.get(i).contains("{start-time-config-generate}")){ content.append("job_start="+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+"T08:00+0800\n"); }else if(srcPpts.get(i).contains("{shell-scripts-config-generate}")){ for(int j=0; j<tl.size(); ++j){ String index=((j+1)<10?"0"+Integer.toString(j+1):Integer.toString(j+1)); content.append(wf.get(j)+"="+tl.get(j)+".sh\n"); } }else if(srcPpts.get(i).contains("{application-path-config-generate}")){ content.append("application_path=${namenode_address}/apps/hduser0401/Pad-dbw/"+projN+"\n"); }else content.append(srcPpts.get(i)+"\n"); } String initPath=System.getProperty("user.dir")+File.separator+projN; wfa.mkdirs(initPath); wfa.writeFromStringBuffer(initPath+File.separator+projN+".properties","UTF-8",content); }
7
public static void pdftoText(File file, String outDir) { PDFParser parser; String parsedText = null; PDFTextStripper pdfStripper = null; PDDocument pdDoc = null; COSDocument cosDoc = null; boolean filefound=false; String outFileName = null; String result=""; try { FileInputStream fis = new FileInputStream(file.getAbsolutePath()); if (file.getName().toLowerCase().endsWith(".pdf")) { filefound = true; } if (filefound) { outFileName = file.getName() + ".txt"; System.out.println("Processing :" + file.getAbsolutePath()); try { parser = new PDFParser(new FileInputStream(file)); } catch (IOException e) { System.err.println("Unable to open PDF Parser. " + e.getMessage()); } try { parser = new PDFParser(new FileInputStream(file)); parser.parse(); cosDoc = parser.getDocument(); pdfStripper = new PDFTextStripper(); pdDoc = new PDDocument(cosDoc); pdfStripper.setStartPage(1); pdfStripper.setEndPage(5); parsedText = pdfStripper.getText(pdDoc); } catch (Exception e) { System.err .println("An exception occured in parsing the PDF Document." + e.getMessage()); } finally { try { if (cosDoc != null) cosDoc.close(); if (pdDoc != null) pdDoc.close(); } catch (Exception e) { e.printStackTrace(); } } result = parsedText; File outFile = new File(outDir + "/" + outFileName); Writer output = new BufferedWriter(new FileWriter(outFile)); output.write(result); output.close(); } else { System.out.println("Skipping :" + file.getAbsolutePath() + " Not A Pdf Document"); } } catch (Exception exep) { exep.printStackTrace(); System.out.println("Exception :"); } }
8
public static SuitabilityEnumeration fromValue(String v) { for (SuitabilityEnumeration c: SuitabilityEnumeration.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); }
2
public int getY() { return loc.y; }
0
public void update() { ticks++; if (doAnimate) { if (changing) { alpha -= 0.05f; if (alpha < 0.0f) { alpha = 1.0f; changing = false; } else { changing = true; } } if (changingPause) { if (currentState != HELP) { alpha -= 0.05f; if (alpha < 0.0f) { alpha = 1.0f; changingPause = false; } else { changingPause = true; } } } } if (paused) { pauseState.update(); } else if (gameStates[currentState] != null) { gameStates[currentState].update(); } if (game.mouse.getButton() == -1) allowClick = true; GameState.setAllowClick(allowClick); }
9
public void terminated(Pipe pipe_) { int index = pipes.indexOf (pipe_); // If we are in the middle of multipart message and current pipe // have disconnected, we have to drop the remainder of the message. if (index == current && more) dropping = true; // Remove the pipe from the list; adjust number of active pipes // accordingly. if (index < active) { active--; Utils.swap (pipes, index, active); if (current == active) current = 0; } pipes.remove (pipe_); }
4
@Test public void getProjectiles(){ World w = new World(null); Projectile p1 = new Projectile(1,1,1,1, new Position(1,1),true); Projectile p2 = new Projectile(1,1,1,1, new Position(1,1),true); w.addProjectile(p1); w.addProjectile(p2); assertTrue(w.getProjectiles().size() == 2 && w.getProjectiles().contains(p1) && w.getProjectiles().contains(p2)); }
2
public static int[][] findShortestPathReturnCost(Graph g, int sourceVertex){ int n = g.getVerticesCount(); //keeping space for 1 extra cycle to detect a negative cycle int [][]cost = new int[n+1][n]; Graph.Edge[][] retrackt = new Graph.Edge[n+1][n]; for( Integer i: g.getAllVertex()) { cost[0][i] = i!=sourceVertex ? Integer.MAX_VALUE: 0; } for( int i =1; i <=n; i++) { for( int v = 0; v<n; v++ ) { Set<Graph.Edge> inboundEdges = g.getInboundEdges(v); if(inboundEdges.size() == 0){ cost[i][v] = cost[i-1][v]; } else{ cost[i][v] = Math.min(cost[i-1][v], getMinCostFromNeighbours(cost,v,g,sourceVertex, i, retrackt)); } } } //Detect negative cycle // if cost[n-1][v] != cost[n][v] that means a negative cycle is present for( int i= 0; i <n; i ++){ if(cost[n-1][i] != cost[n][i] ){ throw new RuntimeException("Negative Cycle detected"); } } return cost; }
7
@Override public Operation create(Scanner scanner) throws FactoryException { try { String metric = scanner.next(); if (metric.equals("pixelcount")) return new SearchOperation(saved, new PixelCountMetric()); else if (metric.equals("uniquechars")) return new SearchOperation(saved, new UniqueCharsMetric()); else throw new FactoryException(); } catch (Exception ex) { throw new FactoryException(); } }
3
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ItemSet other = (ItemSet) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; }
6
private static String getNumberImageFile(int num) { if((2 <= num && num <= 6) || (8 <= num && num <= 12)) { return "images/numbers/small_prob/" + num + ".png"; } else { assert false; return null; } }
4
@Override public void run() { try { @SuppressWarnings("resource") ServerSocket socketServidor = new ServerSocket(1111); while (true) { Socket socketCliente = socketServidor.accept(); System.out.println("DEBUG: Cliente encontrado!"); Runnable handler = new ClientHandler(socketCliente); Thread hilo = new Thread(handler); hilo.start(); System.out.println("DEBUG: Hilo de cliente iniciado!"); } } catch (IOException e) { e.printStackTrace(); } }
2
public static Distance getMiDistance() { if (miDistancia == null) miDistancia = new Distance(); return miDistancia; }
1
public void drawUntersumme(WindowAndDataProvider windowAndDataProvider, Graphics g) { if(drawLowerSum == true) { double hoehe; DPoint p1, p2; p1 = new DPoint(); p2 = new DPoint(); for(double i=intervalLeft; i<=intervalRight-dx+(dx/4); i+=dx) { int j1, j2; j1 = 0; while(points.get(j1).getX()<=i && j1 < points.size()-1) { j1++; } j2 = j1; while(points.get(j2).getX()<=i+dx && j2 < points.size()-1) { j2++; } hoehe = points.get(j1).getY(); for(int j=j1; j<=j2; j++) { if(points.get(j).getY()<hoehe) { hoehe = points.get(j).getY(); } } p1.setX(i); p1.setY(0); p2.setX(i+dx); p2.setY(hoehe); p1 = windowAndDataProvider.toCoordinationPoint(p1); p2 = windowAndDataProvider.toCoordinationPoint(p2); int[] x = new int[4]; int[] y = new int[4]; x[0] = (int) Math.round(p1.getX()); x[1] = (int) Math.round(p1.getX()); x[2] = (int) Math.round(p2.getX()); x[3] = (int) Math.round(p2.getX()); y[0] = (int) Math.round(p1.getY()); y[1] = (int) Math.round(p2.getY()); y[2] = (int) Math.round(p2.getY()); y[3] = (int) Math.round(p1.getY()); g.setColor(Color.green); g.fillPolygon(x, y, x.length); g.setColor(Color.black); g.drawPolygon(x, y, x.length); } } }
8
public BigDecimal convert(String startUnit, BigDecimal in, Type type, String endUnit) { if (type != null && type.isInList(startUnit) != null && type.isInList(endUnit) != null) { if (startUnit.equals(endUnit)) { return in; } else { return convertReferenceToOut(endUnit, type, convertInToReference(startUnit, type, in)); } } return null; }
4
void setColorProfile(ColorProfile profile) { if (profile.getWhitespaceColor() != null) { whitespaceColor = profile.getWhitespaceColor(); } if (profile.getLineHighlightColor() != null) { lineHighlightColor = profile.getLineHighlightColor(); } if (profile.getMatchingCharColor() != null) { matchingCharColor = profile.getMatchingCharColor(); } if (profile.getNoMatchingCharColor() != null) { noMatchingCharColor = profile.getNoMatchingCharColor(); } if (profile.getBackgroundColor() != null) { backgroundColor = profile.getBackgroundColor(); } if (profile.getDefaultFontColor() != null) { defaultFontColor = profile.getDefaultFontColor(); } }
6
public void run(){ videoIdName = getFirstPropertyValue("video-id-prop"); videoRefIdName = getFirstPropertyValue("video-reference-id-prop"); writeToken = getFirstPropertyValue("write-token"); if((videoIdName == null) && (videoRefIdName == null)){ die("One or both of 'video-id-prop' or 'video-reference-id-prop' must be specified to the VideoCloudVideoToucher actor."); } if(writeToken == null){ die("'write-token' must be specified as a property of the VideoCloudVideoToucher actor."); } if(! hasStarted()){ List<String> apiRedactStrings = new ArrayList<String>(); apiRedactStrings.add(writeToken); Logger apiLogger = LogUtils.getLogger("Brightcove Media API Wrapper", apiRedactStrings); writeApi = new WriteApi(apiLogger); } super.run(); }
4
@Override public boolean valid() { return super.valid() && (ctx.skillingInterface.getAction().equals("Smelt") && !ctx.skillingInterface.select().id(MakeSword.HEATED_INGOTS[0]).isEmpty()) || (!ctx.backpack.isFull() && (ctx.backpack.select().id(options.getIngotId()).isEmpty() && ctx.backpack.select().id(MakeSword.HEATED_INGOTS).isEmpty())); }
5
public boolean containsValue(Object value) { return this.map.containsValue(value); }
0
@Override public void updateMovement() { xxa = 0.0F; yya = 0.0F; if(keyStates[0]) { yya--; } if(keyStates[1]) { yya++; } if(keyStates[2]) { xxa--; } if(keyStates[3]) { xxa++; } jumping = keyStates[4]; running = keyStates[5]; }
4
private void walk() { setX_Point(getX_Point() + getxVel()); // for graphics if(isWalking()) { if(timer==null){ timer= new Timer(75); } if(timer.isReady()) { if(timeVar==0){ timeVarPosi=1; }else if(timeVar==3){ timeVarPosi=-1; } timeVar+=timeVarPosi; timer= new Timer(75); } } if(!flying){ setY_Point(getY_Point()+getyVel()); } }
6
public void quickSort(int left, int right) { if (right <= left) return; int lt = left, gt = right; int i = lt; int pivotIndex = (int) (Math.random() * (right - left)) + left; T pivot = this.array[pivotIndex]; swapArrayValues(left, pivotIndex); while (i <= gt) { int cmp = this.array[i].compareTo(pivot); if (cmp < 0) swapArrayValues(lt++, i++); else if (cmp > 0) swapArrayValues(gt--, i); else i++; } quickSort(left, lt - 1); quickSort(gt + 1, right); }
4
public HashMap<Character, Integer> kVecinosMasCercanos(String ficheroTest) { HashMap<Character, Integer> mapaco = new HashMap<>(); // Inicializo el vector de vecinos try { Character letra = 'A'; // Inicializo el map a 0; for (int i = 0; i < 26; i++) { mapaco.put(letra, 0); letra++; } BufferedReader brTest = new BufferedReader(new FileReader(new File( ficheroTest))); ArrayList<String> lTraining = new ArrayList<>(); ArrayList<String> lTest = new ArrayList<>(); String line; BufferedReader brTraining = null; for(int i = 0; i < 5; i++){ String fileToLoad = "salida"+i+".txt"; if(!fileToLoad.equals(ficheroTest)){ brTraining = new BufferedReader(new FileReader(new File(fileToLoad))); line = brTraining.readLine(); while (line != null) { lTraining.add(line); line = brTraining.readLine(); } } } line = brTest.readLine(); while (line != null) { lTest.add(line); line = brTest.readLine(); } char mejorEtiqueta; // knn.setTrainingSet(lTraining);; //knn.setTrainingSet(CNN(knn.getnVecinos(), lTraining)); knn.setTrainingSet(Editing(knn.getnVecinos(), lTraining)); //knn.setTrainingSet(MultiEdit(knn.getnVecinos(), lTraining)); for (String item : lTest) { mejorEtiqueta = getContourClass(item.split(" ")[1]); // System.out.println("Este tiene la etiqueta "+ item.split(" ")[0] + " y la mínima con kNN es "+ mejorEtiqueta); if (item.split(" ")[0].charAt(0) == mejorEtiqueta) { mapaco.put(item.split(" ")[0].charAt(0),mapaco.get(item.split(" ")[0].charAt(0)) + 1); } } // System.out.println(knn.getnVecinos() + "NN ha acertado un " + ((float)numAciertos/(float)lTest.size()*100)); /*//Método aplicado con bagging ArrayList<ArrayList<String>> trainingBagging = bagging(lTraining, 5, 70); for(int l = 0; l < trainingBagging.size(); l++){ char mejorEtiqueta1; // knn.setTrainingSet(lTraining);; //knn.setTrainingSet(CNN(knn.getnVecinos(), lTraining)); knn.setTrainingSet(Editing(knn.getnVecinos(), trainingBagging.get(l))); //knn.setTrainingSet(MultiEdit(knn.getnVecinos(), lTraining)); for (String item : lTest) { mejorEtiqueta1 = getContourClass(item.split(" ")[1]); // System.out.println("Este tiene la etiqueta "+ item.split(" ")[0] + " y la mínima con kNN es "+ mejorEtiqueta); if (item.split(" ")[0].charAt(0) == mejorEtiqueta1) { mapaco.put(item.split(" ")[0].charAt(0),mapaco.get(item.split(" ")[0].charAt(0)) + 1); } } } */ brTraining.close(); brTest.close(); } catch (IOException e) { e.printStackTrace(); } return mapaco; }
8
public void setContent(JPanel content) { this.content = content; }
0
private void validarCategoriaConTipoDeComprobante() throws InvalidInvoiceException, InvalidIDException{ if(tipoDocumentoDeCliente==null) throw new InvalidInvoiceClientIDTypeException("Missing ID Type"); if(categoria==null) throw new InvalidInvoiceException("Invalid Invoice Category"); if(categoria.equals(TipoCategoria.A)){ if(tipoDocumentoDeCliente.equals(TipoDocumento.OTRO)){ //si es A y no viene con tipoDeDocumento valido para a throw new InvalidInvoiceClientIDTypeException("Invoice type A must have a valid ID Type"); }else{ if(documentoDeCliente==null) throw new InvalidIDException("Missing ID number"); } }else{ if(tipoDocumentoDeCliente.equals(TipoDocumento.OTRO)){ if(!(documentoDeCliente instanceof GenericID)) throw new InvalidIDException("Invoice ID not generic type"); }else{ if(documentoDeCliente instanceof GenericID) throw new InvalidIDException("Invoice ID generic type given but " + tipoDocumentoDeCliente.getClass().getSimpleName() + " specified"); } } }
8
public boolean start() { synchronized (optOutLock) { // Did we opt out? if (isOptOut()) { return false; } // Is metrics already running? if (taskId >= 0) { return true; } // Begin hitting the server with glorious data taskId = plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() { private boolean firstPost = true; public void run() { try { // This has to be synchronized or it can collide with the disable method. synchronized (optOutLock) { // Disable Task, if it is running and the server owner decided to opt-out if (isOptOut() && taskId > 0) { plugin.getServer().getScheduler().cancelTask(taskId); taskId = -1; // Tell all plotters to stop gathering information. for (Graph graph : graphs){ graph.onOptOut(); } } } // We use the inverse of firstPost because if it is the first time we are posting, // it is not a interval ping, so it evaluates to FALSE // Each time thereafter it will evaluate to TRUE, i.e PING! postPlugin(!firstPost); // After the first post we set firstPost to false // Each post thereafter will be a ping firstPost = false; } catch (IOException e) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage()); } } }, 0, PING_INTERVAL * 1200); return true; } }
6
@Override synchronized public void init () { Game = getParameter("Game"); Games = getParameter("Games"); setLayout(new BorderLayout()); if (Games != null && !Games.equals("")) { L = new java.awt.List(); add("Center", L); Urls = new Vector(); try { BufferedReader in = null; if (Games.startsWith("http")) in = new BufferedReader(new InputStreamReader( new DataInputStream(new URL(Games).openStream()))); else in = new BufferedReader(new InputStreamReader( new DataInputStream(new URL(getDocumentBase(), Games) .openStream()))); while (true) { String name, value; name = in.readLine(); if (name == null) break; value = in.readLine(); if (value == null) break; L.add(name); Urls.addElement(value); } } catch (Exception ex) {} Panel p = new MyPanel(); p.add(B = new Button(Global.resourceString("Load"))); add("South", new Panel3D(p)); } else { add("Center", B = new Button(Global.resourceString("Load"))); } B.addActionListener(this); Global.url(getCodeBase()); Global.readparameter(".go.cfg"); Global.createfonts(); }
7
public static String StripColor(String str) { if(str == null) return ""; StringBuilder sb = new StringBuilder(); char colorChar = ColorPrefix.charAt(0); boolean colorMode = false; for(int i=0; i<str.length(); i++) { char ch = str.charAt(i); if(ch == colorChar) { colorMode = true; continue; } if(colorMode) { colorMode = false; continue; } sb.append(ch); } return sb.toString(); }
4
private void printTimeStamp(int level) { switch(level) { case ALWAYS: { psOut.print(MSG_ALWAYS+LOG_SEP); break; } case ERROR: { psOut.print(MSG_ERROR+LOG_SEP); break; } case INFO: { psOut.print(MSG_INFO+LOG_SEP); break; } case VERBOSE: { psOut.print(MSG_VERBOSE+LOG_SEP); break; } case DEBUG: { psOut.print(MSG_DEBUG+LOG_SEP); break; } } psOut.print(formatter.format(new Date())+LOG_SEP); if (logLevel >= DEBUG) { psOut.print("thread="+Thread.currentThread().getName()+LOG_SEP); } }
6
private Integer createUser(Criteria criteria, AbstractDao dao) throws DaoException{ Criteria loginCrit = new Criteria(); loginCrit.addParam(DAO_USER_LOGIN, criteria.getParam(DAO_USER_LOGIN)); Criteria emailCrit = new Criteria(); emailCrit.addParam(DAO_USER_EMAIL, criteria.getParam(DAO_USER_EMAIL)); Criteria roleCrit = new Criteria(); roleCrit.addParam(DAO_ROLE_NAME, "user"); Integer idRole = dao.findRoles(roleCrit).get(0).getIdRole(); criteria.addParam(DAO_ID_ROLE, idRole); criteria.addParam(DAO_USER_BALANCE, 0f); criteria.addParam(DAO_USER_DISCOUNT, 0); if (dao.findUsers(loginCrit).isEmpty() && dao.findUsers(emailCrit).isEmpty()) { return dao.createNewUser(criteria); } return null; }
2
public boolean updateFFmpegArgumentsName(String name, String arguments, String extension) { boolean ret = false; if (connection == null || name == null || !hasFFmpegArgumentsName(name)) return ret; try { PreparedStatement stat = connection.prepareStatement("UPDATE " + FFmpegArgumentsTableName + " SET Arguments=?, FileExtension=? WHERE Name=?"); stat.setString(1, arguments); stat.setString(2, extension); stat.setString(3, name); stat.execute(); stat.close(); stat = connection.prepareStatement("SELECT COUNT(*) FROM " + FFmpegArgumentsTableName + " WHERE Name=? AND Arguments=? AND FileExtension=?"); stat.setString(1, name); stat.setString(2, arguments); stat.setString(3, extension); ResultSet rs = stat.executeQuery(); if (rs.next() && rs.getInt(1) == 1) ret = true; rs.close(); stat.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ret; }
6
public void localModify(String local_path, java.sql.Timestamp local_update, int user) { DBLikeFileObject data = new DBLikeFileObject(local_path, local_update, user); DBLikeFileObject search = null; Iterator<DBLikeFileObject> itr = localDB.iterator(); for (int i = 0; i < localDB.size(); i++) { search = itr.next(); if (search.getLocalFilePath().equals(local_path)) { localDB.set(i, data); break; } } }
2
public GUI getGUI(String title) { for (GUI g : GUIs) { if (g.getTitle().equalsIgnoreCase(title)) { return g; } } return null; }
2
public void createNodePossibilities(ArrayList<Rod> rodList) { int currLen = 0; int priceListLength = rodList.size(); for(int index = 0; index < priceListLength; index++) { currLen = rodList.get(index).getLength(); for(int eachRod = 0; eachRod < totalLength/currLen; eachRod++) { possibilities.add(new Rod(rodList.get(index).getIndex() + eachRod, rodList.get(index).getLength(), rodList.get(index).getPrice())); } } }
2
public static void print(char[][] board,int rows, int cols){ for(int i=0;i< rows;i++){ for(int j =0;j < cols;j++){ System.out.print(board[i][j]+ " "); } System.out.println(); } }
2
public void writeInformation(Description d, int categoryID, HUD UI) { if (categoryID == 0) describeCondition(d, UI) ; if (categoryID == 1) describePersonnel(d, UI) ; if (categoryID == 2) describeStocks(d, UI) ; if (categoryID == 3) describeUpgrades(d, UI) ; }
4
protected void processGlobalResourceARList(Sim_event ev) { LinkedList regionalList = null; // regional GIS list int eventTag = AbstractGIS.GIS_INQUIRY_RESOURCE_AR_LIST; boolean result = false; // for a first time request, it needs to call the system GIS first, // then asks each regional GIS for its resource IDs. if (globalResARList_ == null) { // get regional GIS list from system GIS first regionalList = requestFromSystemGIS(); // ask a resource list from each regional GIS result = getListFromOtherRegional(regionalList, eventTag); if (result == true) { globalResARList_ = new ArrayList(); // storing global AR numAR_ = regionalList.size() - 1; // excluding GIS itself // then store the user ID Integer id = (Integer) ev.get_data(); userARList_ = new ArrayList(); userARList_.add(id); return; // then exit } } // cache the request and store the user ID if it is already sent if (numAR_ > 0 && userARList_ != null && userARList_.size() > 0) { Integer id = (Integer) ev.get_data(); userARList_.add(id); return; // then exit } result = sendListToSender(ev, globalResARList_); if (result == false) { System.out.println(super.get_name() + ".processGlobalResourceARList(): Warning - can't send a " + "resource AR list to sender."); } }
6
public void onFirstStat(Stat stat) { if (!stat.isNormalState()) onStatStateChanged(stat); }
1
*/ public 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(EmployeeAccount.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(EmployeeAccount.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(EmployeeAccount.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(EmployeeAccount.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new EmployeeAccount(db, currentUser).setVisible(true); } }); }
6
public void moveNorth() throws InterruptedException{ if (isDoor[0] && !isLocked[0]){ currentY--; currentRoom = rooms[currentY][currentX]; currentRoom.playerVisits(); setAdjacentRooms(); Game.printMessage("You walk through the northern door\n"); } else if (!isDoor[0]) Game.printMessage("There is no door in that direction\n"); else if (isLocked[0]) Game.printMessage("You try to continue, but the door is locked\n"); }
4
protected void _setDistance(Distance distance) { _distance = distance; _setTarget(_targetFromDistance(distance)); }
0
public void addDay(String weekNumber, String day, Boolean value) { Map<String, Boolean> existingInner = data.get(weekNumber); if (existingInner == null) { existingInner = new HashMap<String, Boolean>(); } existingInner.put("day-" + day, value); data.put("week-" + weekNumber, existingInner); }
1
public TernaryST() { N = 0; }
0
public String toString() { return "[Item object: id=" + this.id + " name="+ this.itemName + " desc=" + this.desc + " obtained=" + this.obtained + " cost=" + this.cost + "]"; }
0
public boolean mouseOver(int x, int y) { if (bounds.contains(x, y)) { if (!animating) { if (!beingClicked) currentIndex = 1; } } else if (buttonMode && !animating) currentIndex = 0; return false; }
5
private boolean isDirectory( String path ) { File f = new File( path ); if ( f.exists() ) { return f.isDirectory(); } else { char flag = path.charAt( path.length() - 1 ); if ( flag == '/' || flag == '\\' ) { return true; } else { return false; } } }
3
public short open_serial() { // the next line is for Raspberry Pi and gets us into the while loop and was suggested here was suggested http://www.raspberrypi.org/phpBB3/viewtopic.php?f=81&t=32186 System.setProperty("gnu.io.rxtx.SerialPorts", COM_PORT_NAME); Enumeration portEnum = CommPortIdentifier.getPortIdentifiers(); //First, Find an instance of serial port as set in PORT_NAMES. while (portEnum.hasMoreElements()) { CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement(); if (currPortId.getName().equals(COM_PORT_NAME)) { portId = currPortId; break; } } if (portId == null) { MsgAnalyzerCmnDef.WriteErrorFormatSyslog("Fail to find the COM port: %s", COM_PORT_NAME); return MsgAnalyzerCmnDef.ANALYZER_FAILURE_HANDLE_SERIAL; } try { // open serial port, and use class name for the appName. serialPort = (SerialPort) portId.open(this.getClass().getName(), TIME_OUT); // set port parameters serialPort.setSerialPortParams(COM_PORT_SPEED, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); // open the output streams input = new BufferedReader(new InputStreamReader(serialPort.getInputStream())); // add event listeners serialPort.addEventListener(this); serialPort.notifyOnDataAvailable(true); } catch (Exception e) { MsgAnalyzerCmnDef.WriteErrorFormatSyslog("Fail to open the COM port[%s] , due to: %s", COM_PORT_NAME, e.toString()); } return MsgAnalyzerCmnDef.ANALYZER_SUCCESS; }
4
private void dfs(Graph<?> G, Object v, Object w) { this.marked.put(v, true); this.path.add(v); System.out.println(path); for (Object temp : G.getAdjacentVertices(v)) { if (temp.equals(w)) continue; if (path.contains(temp)) { break; } if (!marked.get(temp)) dfs(G, temp, v); } }
5
public String getPrice() { return price; }
0
RoomOutput[][] printScheme(int i, int j, Schedule s){ RoomOutput[][] r = new RoomOutput[s.schedule[0][0].rooms.length][s.schedule[0][0].rooms[0].length]; for(int k=0; k<r.length; k++){ for(int m=0; m<r[0].length; m++){ r[k][m] = new RoomOutput(s.schedule[i][j].rooms[k][m].getCode(), s.schedule[i][j].rooms[k][m].getName(), s.schedule[i][j].rooms[k][m].getMaxStudents(), s.schedule[i][j].rooms[k][m].getGroup()); r[k][m].setEditable(false); r[k][m].setLocation(5 + 185*k, 65 + 55*m); } } return r; }
2
public InputSource resolveEntity(String pid,String sid) { if(log.isDebugEnabled()) log.debug("resolveEntity("+pid+", "+sid+")"); URL entity=null; if(pid!=null) entity=(URL)_redirectMap.get(pid); if(entity==null) entity=(URL)_redirectMap.get(sid); if(entity==null) { String dtd=sid; if(dtd.lastIndexOf('/')>=0) dtd=dtd.substring(dtd.lastIndexOf('/')+1); if(log.isDebugEnabled()) log.debug("Can't exact match entity in redirect map, trying "+dtd); entity=(URL)_redirectMap.get(dtd); } if(entity!=null) { try { InputStream in=entity.openStream(); if(log.isDebugEnabled()) log.debug("Redirected entity "+sid+" --> "+entity); InputSource is=new InputSource(in); is.setSystemId(sid); return is; } catch(IOException e) { LogSupport.ignore(log,e); } } return null; }
9
protected <T> Subject createSubject(final SudoAction<T> c) { Subject s = c.getSubject(); if(s == null) { final Set<Object> credsPrivate = new LinkedHashSet<Object>(); final Set<Object> credsPublic = new LinkedHashSet<Object>(); final Set<Principal> principals = new LinkedHashSet<Principal>(); if(c.getCallerPrincipal() != null) { principals.add(c.getCallerPrincipal()); } if(c.getGroups() != null) { principals.addAll(Arrays.asList(c.getGroups())); } switch(c.getType()) { case USERNAME_PASSWORD: { if(log.isLoggable(Level.FINE)) { log.log(Level.FINE, "[SUDO] Request: {0} (username={1}, password=********, realm={2})", new Object[]{c.getType().name(), c.getUsername(), c.getRealm()}); } PasswordCredential pwd = new PasswordCredential( c.getUsername(), c.getPassword(), c.getRealm()); credsPrivate.add(pwd); break; } case CLIENT_CERT: { if(log.isLoggable(Level.FINE)) { log.log(Level.FINE, "[SUDO] Request: {0} (cert-chain-length={1}, alias={2}, realm={3})", new Object[]{c.getType().name(), c.getCertChain().length, c.getAlias(), c.getRealm()}); } X509CertificateCredential cert = new X509CertificateCredential( c.getCertChain(), c.getAlias(), c.getRealm()); credsPrivate.add(cert); break; } default: throw new IllegalArgumentException( "[SUDO] Illegal return value for SudoAction.getType() --> " + c.getType()); } s = new Subject(false, principals, credsPublic, credsPrivate); } return s; }
7
public Node closeBra(int bras,int wasBraL,int firstbras,Node n){ if(n.getRN() == null){ int aux = wasBraL; while(true){ if(n.getnrB() > 0 && n.getownB() > aux){ n.setB(n.getnrB() - aux); n.setownB(n.getownB() - aux); break; } if(n.getnrB() > 0 && n.getownB() <= aux ){ aux -= n.getownB(); n.setB(0); n.setownB(0); } if(aux == 0) break; if(n == root){ break; } n = n.getDad(); } return n; } return closeBra(bras,wasBraL,firstbras,n.getRN()); }
8
private void loadPowerUpSprites() { // create "goal" sprite Animation anim = new Animation(); anim.addFrame(loadImage("heart1.png"), 150); anim.addFrame(loadImage("heart2.png"), 150); anim.addFrame(loadImage("heart3.png"), 150); anim.addFrame(loadImage("heart2.png"), 150); goalSprite = new PowerUp.Goal(anim); // create "star" sprite anim = new Animation(); anim.addFrame(loadImage("bottle.png"), 100); anim.addFrame(loadImage("bottle.png"), 100); coinSprite = new PowerUp.Star(anim); // create "music" sprite anim = new Animation(); anim.addFrame(loadImage("music1.png"), 150); anim.addFrame(loadImage("music2.png"), 150); anim.addFrame(loadImage("music3.png"), 150); anim.addFrame(loadImage("music2.png"), 150); musicSprite = new PowerUp.Music(anim); }
0
public static final void setup(Class<?> theClass) { BundleInfo.setDefault(new BundleInfo(theClass)); Path path; try { URI uri = theClass.getProtectionDomain().getCodeSource().getLocation().toURI(); path = Paths.get(uri).normalize().getParent().toAbsolutePath(); if (path.endsWith("support/jars")) { //$NON-NLS-1$ path = path.getParent().getParent(); } if (path.endsWith("Contents/MacOS")) { //$NON-NLS-1$ // Note: we go up 3 levels, not 2, to account for the .app dir path = path.getParent().getParent().getParent(); } } catch (Throwable throwable) { path = Paths.get("."); //$NON-NLS-1$ } APP_HOME_PATH = path.normalize().toAbsolutePath(); }
4
private boolean isBestScore(long l) { for(Map.Entry<Player, Long> entry : speeds.entrySet()) { entry.getValue(); if(l > entry.getValue()) return false; } return true; }
2
public void entrar() { try { int cedula = Integer.parseInt(usuario.getText()); String password = contraseña.getText(); DAO_Login login = new DAO_Login(cedula, password); login.conexion.conectar(); int tipoUsuario = login.login(); login.conexion.cerrarConexion(); if (tipoUsuario == 2) { RegistroEntradasInvestigacion entradas = new RegistroEntradasInvestigacion(); entradas.setVisible(true); this.dispose(); } else if (tipoUsuario == 1) { Administracion admin = new Administracion(); admin.setVisible(true); this.dispose(); } else { limpiarCampos(); } } catch (NumberFormatException e) { limpiarCampos(); } }
3
@Override boolean offerStop() { if (getPoints() >= 17) { setStop(true); System.out.println("AI stopped"); } else System.out.println("AI refused to stop"); return isStop(); }
1
public static void main(String[] args) throws InterruptedException { final int numberOfTrees= 10; final int numberOfDucks= 20; final int numberOfHunters= 10; HuntField field= new HuntField(12,24); //12x24 Swing swing = new Swing(field); for(int i=0; i<numberOfTrees; i++) new Tree(field); for(int i=0; i<numberOfDucks; i++) new Duck(field).start(); for(int i=0; i<numberOfHunters; i++) new Hunter(field).start(); while(field.getNumberOfItems('D')>0){ Thread.sleep(200); swing.show(field); printField(field); } printField(field); }
4
public void visitUCExpr(final UCExpr expr) { if (expr.expr == from) { expr.expr = (Expr) to; ((Expr) to).setParent(expr); } else { expr.visitChildren(this); } }
1
protected void setX(int _x) { this.x = _x; }
0
private void mergeListaServidores(List<InetAddress> IPServidores) { for (InetAddress IP : IPServidores) { boolean found = false; for (InetAddress IP2 : servidoresArquivo) { if (IP.equals(IP2)) { found = true; break; } } if (!found) { try { servidoresArquivo.add(IP); carregaServidoresRMI(); try (Socket iniciaHeartBeat = new Socket(IP, PainelDeControle.PORTA_SERVIDORES)) { byte[] beat = PainelDeControle.EU_ESCOLHO_VOCE.getBytes(); iniciaHeartBeat.getOutputStream().write(beat); } } catch (IOException | NotBoundException ex) { //E AGORA? O QUE FAZER? Logger.getLogger(Middleware.class.getName()).log(Level.SEVERE, null, ex); } } } }
5
protected void select( int posX, int posY ){ this.selected = boardController.select(posX, posY); if(this.selected.getUnit() != null){ // One unit if(this.selected.getUnit().getLoyalty() != this.loyalty){ // Unit 0 different loyalty try the nex one ;) if(this.selected.getUnit(1) != null){ if(this.selected.getUnit(1).getLoyalty() != this.loyalty) // Unit 1 also different loyalty = ABORT this.abort(); } else this.abort(); } } else this.abort(); }
4
public Ventana(InterfazJuego tipoJuego, int AnchoVentana, int AltoVentana, int DiametroImagen, int NumeroEnemigos, int NumeroObstaculos, int NumeroLocos) throws IOException{ //Creamos la ventana principal JFrame jf = new JFrame("Ventana Juego"); jf.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); jf.setResizable(false); INTERFAZJUEGO = tipoJuego; ANCHO_VENTANA = AnchoVentana; ALTO_VENTANA = AltoVentana; DIAMETRO_IMAGEN = DiametroImagen; NUMEROENEMIGOS = NumeroEnemigos; NUMEROBSTACULOS = NumeroObstaculos; NUMEROLOCOS = NumeroLocos; setPreferredSize(new Dimension(ANCHO_VENTANA,ALTO_VENTANA)); game = new Juego(this, INTERFAZJUEGO); game.generarObjetosYPersonajes(NUMEROENEMIGOS,NUMEROBSTACULOS,NUMEROLOCOS); //Creamos el Listener de las teclas pulsacion=false; addKeyListener(new KeyAdapter(){ public void keyPressed(KeyEvent e) { pulsacion = true; try { actualiza(e.getKeyCode(), true); } catch (IOException e1) { e1.printStackTrace(); } } public void keyReleased(KeyEvent e) { pulsacion = false; try { actualiza(e.getKeyCode(), false); } catch (IOException e1) { e1.printStackTrace(); } } private void actualiza(int keyCode, boolean pressed) throws IOException { switch (keyCode) { case KeyEvent.VK_UP: up = pressed; break; case KeyEvent.VK_DOWN: down = pressed; break; case KeyEvent.VK_LEFT: left = pressed; break; case KeyEvent.VK_RIGHT: right = pressed; break; case KeyEvent.VK_ENTER: game.cambiarTipo(new JuegoNieve()); break; case KeyEvent.VK_ALT: game.cambiarTipo(new JuegoCueva()); break; } } }); setFocusable(true); jf.setResizable(true); jf.getContentPane().add(this); jf.pack(); jf.setVisible(true); }
8
public void setCurrentPawnInfo(String pieceID) { char color = pieceID.charAt(0); if (color == 'g') { startPosition = greenStartPosition; homePosition = greenHomePosition; safetyZoneIndex = greenSafetyIndex; currentStart = greenStart; currentHomeArray = greenHomeArray; } else if (color == 'r') { startPosition = redStartPosition; homePosition = redHomePosition; safetyZoneIndex = redSafetyIndex; currentStart = redStart; currentHomeArray = redHomeArray; } else if (color == 'b') { startPosition = blueStartPosition; homePosition = blueHomePosition; safetyZoneIndex = blueSafetyIndex; currentStart = blueStart; currentHomeArray = blueHomeArray; } else if (color == 'y') { startPosition = yellowStartPosition; homePosition = yellowHomePosition; safetyZoneIndex = yellowSafetyIndex; currentStart = yellowStart; currentHomeArray = yellowHomeArray; } }
4
public static void write(String output) { Date d = new Date(); String timeStamp = String.valueOf(d.getTime()*1000); String outStep = timeStamp + ", " + output; p.println(outStep); }
0
private boolean compareParallelSequential (AbstractModel m1, AbstractModel m2) throws InterruptedException, ExecutionException{ //make steps on models for(int i = 0; i < TEST_FRAME_LIMIT; i++){ m1.step(); m2.step(); } //if lists are different sizes we can fail right away if(m1.p.size() != m2.p.size()) return false; for(Particle pPar : m1.p){ boolean foundMatch = false; for(Particle pSeq : m2.p){ if(compareParticles(pPar,pSeq)){ foundMatch = true; m2.p.remove(pSeq); break; } } if(!foundMatch) return false; } return true; }
6