text
stringlengths
14
410k
label
int32
0
9
@Override public int symlink(String from, String to) throws FuseException { try { if (fileSystem.isReadOnly()) return Errno.EROFS; /*if (!from.startsWith("/")) from = "/" + from;*/ if (!to.startsWith("/")) to = "/" + to; fileSystem.createSymbolicLink(to, from); } catch (PathNotFoundException e) { return Errno.ENOENT; } catch (SourceAlreadyExistsException e) { return Errno.EEXIST; } catch (AccessDeniedException e) { return Errno.EACCES; } catch (UnsupportedFeatureException e) { return Errno.ENOSYS; } return 0; }
6
private void cancelKeys() { if (cancelQueue.isEmpty()) { return; } Selector selector = this.selector; for (;;) { CancellationRequest request = cancelQueue.poll(); if (request == null) { break; } ServerSocketChannel ssc = channels.remove(request.address); // close the channel try { if (ssc == null) { request.exception = new IllegalArgumentException( "Address not bound: " + request.address); } else { SelectionKey key = ssc.keyFor(selector); request.registrationRequest = (RegistrationRequest) key .attachment(); key.cancel(); selector.wakeup(); // wake up again to trigger thread death ssc.close(); } } catch (IOException e) { ExceptionMonitor.getInstance().exceptionCaught(e); } finally { request.done.countDown(); if (request.exception == null) { getListeners().fireServiceDeactivated(this, request.address, request.registrationRequest.handler, request.registrationRequest.config); } } } }
6
@Override public void monsterAttackPlaceable(Monster source, Rectangle attackRect, int meleeDamage) { int dmg = 0; Placeable placeable = null; try { for (String key : placeables.keySet()) { placeable = (Placeable) placeables.get(key); dmg = placeable.attackDamage(source, attackRect, meleeDamage); if (dmg > 0) { break; } } } catch (ConcurrentModificationException concEx) { //another thread was trying to modify placeables while iterating //we'll continue and the new item can be grabbed on the next update } }
3
public InputFrame(String source, Point sourcePoint){ this.frame = new JFrame(""); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setLocation(new Point(sourcePoint.x + 150, sourcePoint.y + 150)); this.source = source; switch(source){ case "artist": ArtistPanel aPanel = new ArtistPanel(); frame.setContentPane(aPanel.makeArtistPane(frame)); frame.setTitle("Add artist"); frame.setSize(new Dimension(300,200)); break; case "stage": StagePanel sPanel = new StagePanel(); frame.setContentPane(sPanel.makeStagePane(frame)); frame.setTitle("Add stage"); frame.setSize(new Dimension(275, 150)); break; case "performance": PerformancePanel pPanel = new PerformancePanel(); frame.setContentPane(pPanel.makePerformancePane(frame)); frame.setTitle("Add performance"); frame.setSize(new Dimension(400,307)); break; case "editArtist": frame.setContentPane(makeSelector()); frame.setTitle("Edit artist"); break; case "editStage": frame.setContentPane(makeSelector()); frame.setTitle("Edit stage"); break; case "editPerformance": frame.setContentPane(makeSelector()); frame.setTitle("Edit performance"); break; default: frame.setContentPane(makeErrorPane()); frame.setTitle("Error"); break; } frame.setVisible(true); }
6
public List getSaveList() { ArrayList var1 = new ArrayList(); File[] var2 = this.savesDirectory.listFiles(); File[] var3 = var2; int var4 = var2.length; for (int var5 = 0; var5 < var4; ++var5) { File var6 = var3[var5]; if (var6.isDirectory()) { String var7 = var6.getName(); WorldInfo var8 = this.getWorldInfo(var7); if (var8 != null && (var8.getSaveVersion() == 19132 || var8.getSaveVersion() == 19133)) { boolean var9 = var8.getSaveVersion() != this.func_48431_c(); String var10 = var8.getWorldName(); if (var10 == null || MathHelper.stringNullOrLengthZero(var10)) { var10 = var7; } long var11 = 0L; var1.add(new SaveFormatComparator(var7, var10, var8.getLastTimePlayed(), var11, var8.getGameType(), var9, var8.isHardcoreModeEnabled())); } } } return var1; }
7
static final private ArrayList<ThingVNode> argument_list() throws ParseException, CompilationException { ArrayList<ThingVNode> args = new ArrayList<ThingVNode>(); ArrayList<ThingVNode> value; Token t; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case ACCESSOP: jj_consume_token(ACCESSOP); t = jj_consume_token(TOKENWORD); value = argument_list(); args.add(new ThingVNode(t.image,currentLine));args.addAll(value);{if (true) return args;} break; default: jj_la1[2] = jj_gen; currentLine = currentLine.intValue()+1; {if (true) return args;} } throw new Error("Missing return statement in function"); }
4
private boolean shouldWait(int txnId, Set<Integer> dependetTxns) { Set<BlockPtr> ptrList = blockPtrsInTxn.get(txnId); Iterator<Integer> iter = blockPtrsInTxn.keySet().iterator(); while (iter.hasNext()) { int txn = iter.next(); if (txn == txnId) { continue; } Set<BlockPtr> list = blockPtrsInTxn.get(txn); Iterator<BlockPtr> txnPtrIter = ptrList.iterator(); while (txnPtrIter.hasNext()) { BlockPtr ptr = txnPtrIter.next(); if (list.contains(ptr) && !committingTxns.contains(txn)) { dependetTxns.clear(); return true; } if (list.contains(ptr) && committingTxns.contains(txn)) { dependetTxns.add(txn); } } } return false; }
7
@EventHandler public void SpiderSpeed(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getSpiderConfig().getDouble("Spider.Speed.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if (plugin.getSpiderConfig().getBoolean("Spider.Speed.Enabled", true) && damager instanceof Spider && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, plugin.getSpiderConfig().getInt("Spider.Speed.Time"), plugin.getSpiderConfig().getInt("Spider.Speed.Power"))); } }
6
public static String checkPosition(String username, String pass){ Employee bean = new Employee(); bean.setUsername(username); bean = (Employee)DatabaseProcess.getRow(bean); //if username cannot be found in the database if(bean == null){ return "not found"; } if(bean.getUsername().equals(username)&&bean.getPass().equals(pass)){ return bean.getPosition().toLowerCase(); }else{ return "incorrect username and password combination"; } }
3
@Override protected Authentication doAuthentication(Authentication authentication) throws AuthenticationException { if (!(authentication instanceof CustomAuthenticationToken)) { throw new IllegalArgumentException("Only CustomAuthenticationManager is supported"); } CustomAuthenticationToken authenticationToken = (CustomAuthenticationToken) authentication; final String userName = (String) authenticationToken.getPrincipal(); final String password = (String) authenticationToken.getCredentials(); final String company = (String) authenticationToken.getCompany(); if (AppUtil.isNullOrEmpty(userName) || AppUtil.isNullOrEmpty(password) || AppUtil.isNullOrEmpty(company)) { throw new BadCredentialsException("Invalid username/password"); } User user = null; try { //Actual service call user = loginAppSvc.login(userName, password, company); } catch (AppSvcException ase) { throw new BadCredentialsException(ase.getMessage()); } List<GrantedAuthority> grantedAuthoritiesList = new ArrayList<GrantedAuthority>(); grantedAuthoritiesList.add(new GrantedAuthorityImpl("ROLE_USER")); return createSuccesssAuthentication(user, authenticationToken, grantedAuthoritiesList); }
5
public void addToCanvas(Component comp, Integer i) { if (comp != statusPanel && !(comp instanceof JMenuItem) && !(comp instanceof FreeColDialog<?>) && statusPanel.isVisible()) { removeFromCanvas(statusPanel); } try { if (i == null) { super.add(comp); } else { super.add(comp, i); } } catch(Exception e) { logger.warning("add component failed with layer " + i); e.printStackTrace(); } }
7
@Override public boolean hasNext() { if (in == null) return false; // No file? => We are done if (binRead != null) return true; try { binRead = readerObject.read(in); if (binRead == null) close();// Nothing more to read? } catch (IOException e) { binRead = null; } return (binRead != null); }
4
@Override public void undo(UndoQueueEvent e) { if (e.getDocument() == Outliner.documents.getMostRecentDocumentTouched()) { calculateEnabledState(e.getDocument()); } }
1
public void GenerateIcons() { images = new ImageIcon[2]; for (int a = 0; a < 2; a++) { images[a] = new ImageIcon(new BufferedImage(28, 32, BufferedImage.TYPE_4BYTE_ABGR)); Graphics g; try { g = images[a].getImage().getGraphics(); } catch (NullPointerException e) { System.out.println("Could not get Graphics pointer to " + getClass() + " Image"); return; } Graphics2D g2 = (Graphics2D) g; g2.setBackground(Color.black); g2.clearRect(0, 0, 28, 32); if (a == 0) { g2.setColor(Color.white); } else { g2.setColor(new Color(255, 128, 0)); } switch (rotation) { case ROT_UP: g2.fillRect(2, 10, 24, 6); g2.fillRect(10, 0, 8, 10); break; case ROT_RIGHT: g2.fillRect(12, 4, 6, 24); g2.fillRect(18, 12, 10, 8); break; case ROT_DOWN: g2.fillRect(2, 16, 24, 6); g2.fillRect(10, 22, 8, 10); break; case ROT_LEFT: g2.fillRect(10, 4, 6, 24); g2.fillRect(0, 12, 10, 8); break; } } }
7
public static String doubleToString(double d) { if (Double.isInfinite(d) || Double.isNaN(d)) { return "null"; } // Shave off trailing zeros and decimal point, if possible. String string = Double.toString(d); if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) { while (string.endsWith("0")) { string = string.substring(0, string.length() - 1); } if (string.endsWith(".")) { string = string.substring(0, string.length() - 1); } } return string; }
7
public void setContactList(ArrayList<EmailKontakt> contactList) { this.contactList = contactList; }
0
@Override public void execute(FileSearchBean task) throws Exception { final FileInputStream fileInputStream = new FileInputStream(task.getInputFile()); final BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream, bufferSize); try { // Naive substring matching algorithm int buff; while ((buff = bufferedInputStream.read()) != -1) { if (buff == (patternBytes[0] & 0xff)) { bufferedInputStream.mark(patternBytes.length); int k = 1; while (k < patternBytes.length && (buff = bufferedInputStream.read()) != -1 && (patternBytes[k] & 0xff) == buff) { k++; } if (k == patternBytes.length) { // We found whole pattern resultCollector.push(task); break; } bufferedInputStream.reset(); } } } finally { try { bufferedInputStream.close(); } catch (IOException ioe) { /* ignore silently */ } try { fileInputStream.close(); } catch(IOException ioe) { /* ignore silently */ } } }
8
public static void addKampf(JSONObject fight, JSONObject data, String method) { if (isHtmlOutput()) { try { // Taktik speichern add(new TacticsLogFile(getInstance().htmlPath, data)); // Dateinamen generieren String filename = String.valueOf(new Date().getTime()) + fight.getJSONObject("opponent").getString("name") .replaceAll("[^a-zA-Z0-9]", "_") + ".html"; fight.put("fightData", data); // Kampf-Daten schreiben add(new KampfFile(fight, getInstance().htmlPath + Output.DIR_HTML + filename)); // Log generieren JSONObject log = LogFile.getLog(method, fight.getJSONObject( "opponent").getString("name")); log.put("file", "." + DIR_HTML + filename); log.put("good", fight.getJSONObject("results").getBoolean( "fightWasWon")); // Log schreiben Output.addLog(log); } catch (JSONException e) { } } }
2
@Override public void paintComponent(Graphics g) { super.paintComponent(g); setBackground(this.c); try { switch(random) { case 0: image = makeImageIcon("/images/Ingress_Green.png").getImage(); g.drawImage(image, (this.getWidth() - image.getWidth(null)) / 2, (this.getHeight() - image.getHeight(null)) / 2, this); clip = new OggClip("sounds/speech_faction_choice_enlightened_alt.ogg"); break; case 1: image = makeImageIcon("/images/Enlightened_Green.png").getImage(); g.drawImage(image, (this.getWidth() - image.getWidth(null)) / 2, (this.getHeight() - image.getHeight(null)) / 2, this); clip = new OggClip("sounds/speech_faction_choice_enlightened.ogg"); break; case 2: image = makeImageIcon("/images/Resistance_Blue.png").getImage(); g.drawImage(image, (this.getWidth() - image.getWidth(null)) / 2, (this.getHeight() - image.getHeight(null)) / 2, this); clip = new OggClip("sounds/speech_faction_choice_humanist_alt.ogg"); break; default: image = makeImageIcon("/images/Ingress_Dual.png").getImage(); g.drawImage(image, ((this.getWidth() - image.getWidth(null)) / 2), (this.getHeight() - image.getHeight(null)) / 2, this); int gap = image.getWidth(null) / 2 + 150; image = makeImageIcon("/images/Enlightened_Green.png").getImage(); g.drawImage(image, ((this.getWidth() - image.getWidth(null)) / 2) - gap, (this.getHeight() - image.getHeight(null)) / 2, this); image = makeImageIcon("/images/Resistance_Blue.png").getImage(); g.drawImage(image, ((this.getWidth() - image.getWidth(null)) / 2) + gap, (this.getHeight() - image.getHeight(null)) / 2, this); clip = new OggClip("sounds/ada_intro.ogg"); break; } } catch(IOException ignored) { } if(clip != null && !clipplayed) clip.play(); clipplayed = true; g.dispose(); }
6
void clearLegacyEditingSetup() { if (!getControl().isDisposed() && getCellEditors() != null) { int count = doGetColumnCount(); for (int i = 0; i < count || i == 0; i++) { Widget owner = getColumnViewerOwner(i); if (owner != null && !owner.isDisposed()) { ViewerColumn column = (ViewerColumn) owner .getData(ViewerColumn.COLUMN_VIEWER_KEY); if (column != null) { EditingSupport e = column.getEditingSupport(); // Ensure that only EditingSupports are wiped that are // setup // for Legacy reasons if (e != null && e.isLegacySupport()) { column.setEditingSupport(null); } } } } } }
9
public void draw() { if (y > -yNull && y < yNull && x < xNull && x > -xNull) { bits[(yNull - y) * pw + x + xNull] = GUIStandarts.figureColor; } }
4
@Override public List<? extends PictureI> searchfromTags(String search){ if(!(search.equals(""))){ List<Tag> tags = this.tagDao.findByLike("tag", search); List<? extends PictureI> pictures = new ArrayList<Picture>(); if(!(tags.isEmpty())){ for(TagI t: tags){ try{ for(TagI tag: this.tagDao.getAll()){ if(tag.getTag().equals(t.getTag())){ pictures = tag.getPictures(); } } }catch(Exception e){ } } return pictures; } } return null; }
8
public static void main(String[] args) { try { UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (InstantiationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IllegalAccessException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (UnsupportedLookAndFeelException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } File inputFile = null; if(args.length > 0) { inputFile = new File(args[0]); if(! inputFile.exists()) { inputFile = openDialog(); } } else { inputFile = openDialog(); } logger.debug("Selected SQM Mission: " + inputFile.getAbsolutePath()); Arma2MapConverter a2mc = new Arma2MapConverter(); SQM sqm = a2mc.openSQM(inputFile); SQF sqf = sqm.toSQF(); File outputFile = null; if(args.length > 1) { outputFile = new File(args[1]); if(! outputFile.exists()) { outputFile = saveDialog(); } } else { outputFile = saveDialog(); } logger.debug("Selected SQF File: " + outputFile.getAbsolutePath()); try { sqf.save(outputFile); } catch (IOException e) { // TODO Auto-generated catch block logger.error("Could not write to output file: " + e.getLocalizedMessage(), e); } }
9
@Override public int compareTo(Object obj) { if (!(obj instanceof TimeInteger)) { return -1; } TimeInteger other = (TimeInteger) obj; if ((this.time < other.time) || (this.time == other.time && this.isStartingTime && !other.isStartingTime)){ return -1; } else if ((this.time > other.time) || (this.time == other.time && !this.isStartingTime && other.isStartingTime)){ return 1; } else { return 0; } }
9
public void deal(Hand[] playerHand, int numPlayer, int numCard) { for (int i = 0; i < numCard; i++) { for (int j = 0; j < numPlayer; j++) { playerHand[j].add(dealCard()); } } }
2
public void setColumns(String ... columns) { columnNames = Arrays.asList(columns); for (int i = 0; i < columnNames.size(); i++) { info.put(i+1, new LinkedHashMap<String, String>(new HashMap<String, String>())); } }
1
public static void main(String[] args) { Scanner in = new Scanner(System.in); int inputCount = 0; Map<String, Integer> book = new HashMap<String, Integer>(); if (in.hasNext()) { inputCount = in.nextInt(); } for (int i = 0; i < inputCount; i++) { String callNumOri = in.next(); String callNum = decodePhoneNumber(callNumOri); if (book.containsKey(callNum)) { book.put(callNum, book.get(callNum) + 1); } else { book.put(callNum, 1); } } Map<String, Integer> bookTree = new TreeMap<String, Integer>(book); Iterator<Entry<String, Integer>> iter = bookTree.entrySet().iterator(); boolean flag = true; while (iter.hasNext()) { Entry<String, Integer> entry = iter.next(); if (entry.getValue() > 1) { System.out.println(entry.getKey() + " " + entry.getValue()); flag = false; } } if (flag) { System.out.println("No duplicates."); } }
6
@Override public void setValueAt(Object value, int row, int col) { Movement movement = rekening.getBusinessObjects().get(row); if (col == 1) { Calendar oudeDatum = movement.getDate(); Calendar nieuweDatum = Utils.toCalendar((String) value); if (nieuweDatum != null) movement.setDate(nieuweDatum); else setValueAt(Utils.toString(oudeDatum), row, col); } else if (col == 4) { movement.setDescription((String) value); } }
3
public void visit_invokespecial(final Instruction inst) { final MemberRef method = (MemberRef) inst.operand(); final Type type = method.nameAndType().type(); pop(type.paramTypes().length); pop(); // Pop receiver if (type.returnType() != Type.VOID) { push(inst); } }
1
public static Stella_Object walkVerbatimTree(Cons tree, Object [] MV_returnarray) { { PropertyList self000 = PropertyList.newPropertyList(); self000.thePlist = tree.rest; { PropertyList options = self000; Stella_Object verbatimtree = options.lookup(((Keyword)(Stella.$TRANSLATOROUTPUTLANGUAGE$.get()))); if (verbatimtree == null) { verbatimtree = options.lookup(Stella.KWD_OTHERWISE); if (verbatimtree == null) { { Object old$PrintreadablyP$000 = Stella.$PRINTREADABLYp$.get(); try { Native.setBooleanSpecial(Stella.$PRINTREADABLYp$, true); Stella.signalTranslationError(); if (!(Stella.suppressWarningsP())) { Stella.printErrorContext(">> ERROR: ", Stella.STANDARD_ERROR); { Stella.STANDARD_ERROR.nativeStream.println(); Stella.STANDARD_ERROR.nativeStream.println(" Verbatim statement has no `" + ((Keyword)(Stella.$TRANSLATOROUTPUTLANGUAGE$.get())) + "' option.."); } ; } } finally { Stella.$PRINTREADABLYp$.set(old$PrintreadablyP$000); } } { Stella_Object _return_temp = null; MV_returnarray[0] = Stella.SGT_STELLA_UNKNOWN; return (_return_temp); } } if (!(verbatimtree == Stella.SYM_STELLA_NULL)) { return (Stella_Object.walkATree(verbatimtree, MV_returnarray)); } } if (verbatimtree == Stella.SYM_STELLA_NULL) { { Stella_Object _return_temp = null; MV_returnarray[0] = Stella.SGT_STELLA_UNKNOWN; return (_return_temp); } } if (Surrogate.subtypeOfStringP(Stella_Object.safePrimaryType(verbatimtree))) { { StringWrapper verbatimtree000 = ((StringWrapper)(verbatimtree)); options.insertAt(((Keyword)(Stella.$TRANSLATOROUTPUTLANGUAGE$.get())), VerbatimStringWrapper.newVerbatimStringWrapper(verbatimtree000.wrapperValue)); } } else { } { Stella_Object _return_temp = tree; MV_returnarray[0] = Stella.SGT_STELLA_UNKNOWN; return (_return_temp); } } } }
6
private void cssNthChild(boolean backwards, boolean ofType) { String argS = tq.chompTo(")").trim().toLowerCase(); Matcher mAB = NTH_AB.matcher(argS); Matcher mB = NTH_B.matcher(argS); final int a, b; if ("odd".equals(argS)) { a = 2; b = 1; } else if ("even".equals(argS)) { a = 2; b = 0; } else if (mAB.matches()) { a = mAB.group(3) != null ? Integer.parseInt(mAB.group(1).replaceFirst("^\\+", "")) : 1; b = mAB.group(4) != null ? Integer.parseInt(mAB.group(4).replaceFirst("^\\+", "")) : 0; } else if (mB.matches()) { a = 0; b = Integer.parseInt(mB.group().replaceFirst("^\\+", "")); } else { throw new Selector.SelectorParseException("Could not parse nth-index '%s': unexpected format", argS); } if (ofType) if (backwards) evals.add(new Evaluator.IsNthLastOfType(a, b)); else evals.add(new Evaluator.IsNthOfType(a, b)); else { if (backwards) evals.add(new Evaluator.IsNthLastChild(a, b)); else evals.add(new Evaluator.IsNthChild(a, b)); } }
9
public static byte[] generatePELock( int serviceID, String PEList ) { if( PEList == null ) return null; if( PEList.length() == 0 ) return null; String[] pieces = PEList.split(","); //6567,451 int length = pieces.length; if(length == 0) return null; if( _longArrayList == null ) _longArrayList = new ArrayList<Long>(); else _longArrayList.clear(); for( int i = 0; i < length; i++ ) { String sValue = pieces[ i ]; try { Long numericValue = Long.parseLong( sValue ); _longArrayList.add( numericValue ); } catch(Exception e) { } } // copy from ArrayList to long[] long vPEList[] = new long[ _longArrayList.size() ]; for( int i = 0; i < _longArrayList.size(); i++ ) { vPEList[i] = _longArrayList.get(i); } // create DACS lock try { AuthorizationLock authLock = new AuthorizationLock( serviceID, AuthorizationLock.OR, vPEList ); byte[] dacsLock = authLock.getAuthorizationLock(); return dacsLock; } catch (AuthorizationException e) { System.out.println("DACS Lock Error! "+e.toString() ); return null; } }
8
@Override public boolean equals(Object other) { if(other == null || !((other instanceof CaseInsensitiveString) || (other instanceof String))) { return false; } if(other instanceof String) { return value.equalsIgnoreCase((String)other); } else { return value.equalsIgnoreCase(((CaseInsensitiveString)other).value); } }
4
private Object readResolve() throws ObjectStreamException { RectangleAnchor result = null; if (this.equals(RectangleAnchor.CENTER)) { result = RectangleAnchor.CENTER; } else if (this.equals(RectangleAnchor.TOP)) { result = RectangleAnchor.TOP; } else if (this.equals(RectangleAnchor.BOTTOM)) { result = RectangleAnchor.BOTTOM; } else if (this.equals(RectangleAnchor.LEFT)) { result = RectangleAnchor.LEFT; } else if (this.equals(RectangleAnchor.RIGHT)) { result = RectangleAnchor.RIGHT; } else if (this.equals(RectangleAnchor.TOP_LEFT)) { result = RectangleAnchor.TOP_LEFT; } else if (this.equals(RectangleAnchor.TOP_RIGHT)) { result = RectangleAnchor.TOP_RIGHT; } else if (this.equals(RectangleAnchor.BOTTOM_LEFT)) { result = RectangleAnchor.BOTTOM_LEFT; } else if (this.equals(RectangleAnchor.BOTTOM_RIGHT)) { result = RectangleAnchor.BOTTOM_RIGHT; } return result; }
9
public static void checkCollision(ActorSet actors, int start, int stride){ // TODO it would be nice use a single list for all our threads List<Actor> actorsList = actors.getCopyList(); // Check our guy we stride to against all the others for(int i = start; i < actorsList.size(); i += stride){ Actor a = actorsList.get(i); // Don't collide with actors we added this frame to prevent or minimize runaway collision if(a.getAge() == 0) continue; for(int j = i + 1; j < actorsList.size(); ++j){ Actor b = actorsList.get(j); if(b.getAge() == 0) continue; if(a.isColliding(b)){ a.handleCollision(b); b.handleCollision(a); } } } }
5
@Override /** * Verifica se o Tracker esta online */ public void run() { while (true) { if (!processo.knowTracker) { eleicao(); }else{ try { byte[] buf = new byte[1024]; DatagramPacket pack = new DatagramPacket(buf, buf.length); multicastSocket.setSoTimeout(5000); multicastSocket.receive(pack); byte[] messgage = Arrays.copyOfRange(buf, 0, Funcoes.getKeyIndex() - 1); byte[] key = Arrays.copyOfRange(buf, Funcoes.getKeyIndex(), buf.length); String resposta = new String(messgage); String respostaEsperada = "Peer id:"; //System.out.println("MULTiCAST DO PEER <- " + resposta); // System.out.println( new String("\tFrom: " + pack.getAddress().getHostAddress() + ":" + pack.getPort()) ); String data = resposta.substring(0,respostaEsperada.length()); if(data.equals(respostaEsperada)){ //System.out.println("MULTiCAST DO PEER <- " + resposta); int tempID = Integer.parseInt(resposta.substring(8,10)); if(!peersHasID(tempID)){ PublicKey keyRecebida = KeyFactory.getInstance("RSA", "BC").generatePublic(new X509EncodedKeySpec(key)); Peer newPeer = new Peer(tempID, keyRecebida, pack.getAddress(),pack.getPort()); peers.add(newPeer); String peer = "Peer id:"+processo.getId()+";porta:"+processo.getSocketUnicast().getLocalPort()+";"; multicastSocket.enviarMensagem(peer, processo.getPublicKey()); System.out.println("Novo peer: "+newPeer.getSettings()); } } respostaEsperada = Funcoes.TRACKER_HELLO; data = resposta.substring(0,respostaEsperada.length()); if(data.equals(respostaEsperada)){ //atualiza o tracker atual System.out.println("MULTiCAST DO PEER <- " + resposta); String str = resposta.substring(30); int id = Integer.parseInt(resposta.substring(21,23)); PublicKey keyRecebida = KeyFactory.getInstance("RSA", "BC").generatePublic(new X509EncodedKeySpec(key)); int porta = Integer.parseInt(str.substring(0, str.indexOf(";"))); Peer peer = new Peer(id, keyRecebida, pack.getAddress(), porta); processo.updateTracker(peer); } } catch(SocketTimeoutException ex){ System.out.println("Tracker caiu!"); processo.knowTracker = false; processo.isReady = false; processo.changePanel = true; }catch (SocketException ex) { Logger.getLogger(MultiCastPeer.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException | InvalidKeySpecException ex) { Logger.getLogger(MultiCastPeer.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException | NoSuchProviderException ex) { Logger.getLogger(MultiCastPeer.class.getName()).log(Level.SEVERE, null, ex); } } } }
9
public static List<String> getPluginInventory() { List<String> pluginList = new ArrayList<String>(); try { File jarLocation = new File(ControllerEngine.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()); String parentDirName = jarLocation.getParent(); // to get the parent dir name File folder = new File(parentDirName + "/plugins"); if(folder.exists()) { File[] listOfFiles = folder.listFiles(); for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile()) { //System.out.println("Found Plugin: " + listOfFiles[i].getName()); //<pluginName>=<pluginVersion>, String pluginPath = listOfFiles[i].getAbsolutePath(); System.out.println("Found Plugin=" + ControllerEngine.commandExec.getPluginName(pluginPath) + "=" + ControllerEngine.commandExec.getPluginVersion(pluginPath)); pluginList.add(ControllerEngine.commandExec.getPluginName(pluginPath) + "=" + ControllerEngine.commandExec.getPluginVersion(pluginPath)); //pluginList = pluginList + getPluginName(pluginPath) + "=" + getPluginVersion(pluginPath) + ","; //pluginList = pluginList + listOfFiles[i].getName() + ","; } } if(pluginList.size() > 0) { return pluginList; } } } catch(Exception ex) { System.out.println(ex.toString()); } return null; }
5
public void getListDetails(String id) { float total = 0; float totalInterest = 0; float payment1 = 0; float payment2 = 0; try { String tempQuery = "select TO_DATE(amordate, 'YYYY-MM-DD') as monthly_schedule,mon_amort as monthly_payment,mon_interest as interest, mon_premium as premium from loan_dtl where loanid="+id+" order by amordate"; Statement stmt = null; this.connect(); conn = this.getConnection(); try { stmt = conn.createStatement(); } catch (SQLException e) { e.printStackTrace(); } ResultSet rs; ResultSet ps; try { rs = stmt.executeQuery(tempQuery); try { commonUtils.updateTableModelData((DefaultTableModel) listDetails.getModel(), rs, 4); } catch (Exception ex) { Logger.getLogger(ViewMember.class.getName()).log(Level.SEVERE, null, ex); } } catch(Exception e) { } try { ps = stmt.executeQuery(tempQuery); while(ps.next()) { total += ps.getFloat("monthly_payment"); totalInterest += ps.getFloat("interest"); payment1 = total; payment2 = totalInterest; } } catch(Exception e) { } finally { this.disconnect(); } } catch(Exception e) { } payment1 = (float) (Math.round(payment1 * 100.00) / 100.00); payment2 = (float) (Math.round(payment2 * 100.00) / 100.00); textPayment.setText(String.valueOf(payment1)); textPayment1.setText(String.valueOf(payment2)); }
6
public static void main(String[] args) { InputStream r=null; OutputStream os = null; File file = new File("F://c.txt"); try{ r = new FileInputStream(file); // BOMInputStream bis = new BOMInputStream(r,false); os = new FileOutputStream("f://b.txt"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] b = new byte[1]; int len; byte by=(byte)0xbf; byte ef=(byte)0xef; byte bb=(byte)0xbb; while((len=r.read(b,0,1))>0){ if(by!=b[0] && bb!=b[0] && ef!=b[0]) { bos.write(b,0,len); bos.flush(); //os.write(b,0,len); // os.flush(); } } //byte[] result=bos.toByteArray(); String str = bos.toString(); Pattern p = Pattern.compile("0xbf"); Matcher m = p.matcher(str); System.out.println(m.group(1)); ByteArrayInputStream bis = new ByteArrayInputStream(str.getBytes()); FileInputStream f = new FileInputStream("f://b.txt"); bos.close(); org.jsoup.nodes.Document doc = Jsoup.parse(bis, "utf-8", ""); Elements headELEs = doc.getElementsByTag("head"); org.jsoup.nodes.Element headELE = headELEs.first(); System.out.println(headELE); }catch(Exception e){ e.printStackTrace(); }finally{ try { os.close(); r.close(); } catch (IOException e) { e.printStackTrace(); } } }
6
public static String convertTypeToLocation(ContactLocation type) { switch (type) { case DIALLED_CALLS: return "DC"; case MISSED_CALLS: return "MC"; case PHONE_ENTRIES: return "ME"; case SIM_ENTRIES: return "SM"; case ALL_ENTRIES: return "MT"; default: return ""; } }
5
public TeleporterGridFactory(Grid grid, FullGridFactory factory) { if (grid == null) throw new IllegalArgumentException("Grid can't be null!"); if (factory == null) throw new IllegalArgumentException("Factory can't be null!"); this.factory = factory; this.grid = grid; }
2
public void generate(String fileName) { try{ BufferedWriter bw = new BufferedWriter(new FileWriter(fileName)); bw.write("<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">"); bw.newLine(); // Write the maze for(Edge e: svgLines){ bw.write("<line x1=\"" + e.c1.x*10 + "\" y1=\"" + e.c1.y*10 + "\" x2=\"" + e.c2.x*10 + "\" y2=\"" + e.c2.y*10 + "\" stroke=\"#000000\" stroke-width=\"2\" stroke-linejoin=\"miter\" />"); bw.newLine(); } bw.write("</svg>"); bw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
2
private void checkFile() throws GOLException, IOException { if (fileTypeIsNotGol()) { throw new GOLException("Datei muss vom Typ .gol sein."); } if (fileSizeTooBig()) { throw new GOLException("Dateigröße darf maximal 250kb betragen."); } if (fileIsEmpty()) { throw new GOLException("Datei darf nicht leer sein."); } if (boardDimensionsWrong()) { throw new GOLException("Das Spielbrett muss in jeder Zeile gleich viele Zellen haben."); } }
4
boolean isSystemObjectDifferent(SystemObjectProperties property, SystemObject systemObject) { final SystemObjectType propertyType = getType(property.getType()); // Typ vergleichen if(propertyType != systemObject.getType()) { _debug.finer("Der Typ des konkreten Objekts " + systemObject.getPidOrNameOrId() + " passt nicht", systemObject.getType().getPidOrNameOrId()); return true; } final ConfigurationConfigurationObject configProperty = (ConfigurationConfigurationObject)property; final List<ConfigurationDataset> datasets = new LinkedList<ConfigurationDataset>(); final List<ConfigurationObjectSet> objectSets = new LinkedList<ConfigurationObjectSet>(); for(ConfigurationObjectElements elements : configProperty.getDatasetAndObjectSet()) { if(elements instanceof ConfigurationDataset) { datasets.add((ConfigurationDataset)elements); } else if(elements instanceof ConfigurationObjectSet) { objectSets.add((ConfigurationObjectSet)elements); } } // Datensätze prüfen if(isDatasetsDifferent(datasets, systemObject)) { _debug.finer("Die Datensätze am Objekt sind unterschiedlich", systemObject.getPidOrNameOrId()); return true; } // wenn es sich um ein konfigurierendes Objekt handelt ... if(propertyType.isConfigurating()) { // Mengen prüfen if(isSystemObjectSetsDifferent(objectSets, (ConfigurationObject)systemObject)) { _debug.finer("Die Mengen am Objekt sind unterschiedlich", systemObject.getPidOrNameOrId()); return true; } // Default-Parameter-Datensätze if(isDefaultParameterDifferent(configProperty.getDefaultParameters(), systemObject)) { _debug.finer("Die Default-Parameter-Datensätze sind unterschiedlich", systemObject.getPidOrNameOrId()); return true; } } return false; }
8
public Audio(HtmlMidNode parent, HtmlAttributeToken[] attrs){ super(parent, attrs); for(HtmlAttributeToken attr:attrs){ String v = attr.getAttrValue(); switch(attr.getAttrName()){ case "autoplay": autoplay = Autoplay.parse(this, v); break; case "controls": controls = Controls.parse(this, v); break; case "loop": loop = Loop.parse(this, v); break; case "muted": muted = Muted.parse(this, v); break; case "preload": preload = Preload.parse(this, v); break; case "src": src = Src.parse(this, v); break; } } }
7
@Override public void move(Excel start, Excel finish) { // TODO Auto-generated method stub for(int i=0;i<allex.size();i++) { if (start.getX() == allex.get(i).getX() && start.getY() == allex.get(i).getY()) { allex.remove(i); allex.add(i, finish); setColoredExes(); break; } } }
3
private void killPanda() { if (panda.getX()==fire.getX() && panda.getY()==fire.getY() && !fire.isHide() && !panda.isDied()) { panda.die(); spandadie.play(); } if (panda.getX()==arrow.getX() && panda.getY()==arrow.getY() && !arrow.isHide() && !panda.isDied()) { panda.die(); spandadie.play(); } }
8
public Object arbitrary(Random random, long size) { int arraySize = (int) Arbitrary.random(random, 0, Math.min(Integer.MAX_VALUE, size)); int[] dimensions = new int[dimension]; for (int i = 0; i < dimension; ++i) { dimensions[i] = arraySize; } Object array = Array.newInstance(componentClass, dimensions); fillArray(array, random, (int)size); return array; }
1
private int partition(int[] arrayIn, int lhs, int rhs, SorterParams.SortDirection sortDir) { int pivot = arrayIn[lhs + (rhs - lhs) / 2]; int i = lhs; int j = rhs; MemoryUsage.addMem(3); while(i <= j) { if(sortDir == SorterParams.SortDirection.ASCENDING) { while(arrayIn[i] < pivot) { i++; } while(arrayIn[j] > pivot) { j--; } } else { while(arrayIn[i] > pivot) { i++; } while(arrayIn[j] < pivot) { j--; } } if(i <= j) { Swap(arrayIn, i, j); i++; j--; } } MemoryUsage.removeMem(3); return i; }
7
private static FrequencyTable getFrequencies(byte[] b) { FrequencyTable freq = new SimpleFrequencyTable(new int[3]); // InputStream input = new BufferedInputStream(new FileInputStream(file)); for (byte x : b) { freq.increment(x & 0xFF); } freq.increment(2); // try { // while (true) { // int b = input.read(); // if (b == -1) // break; // freq.increment(b); // } // } finally { // input.close(); // } return freq; }
1
private void relockBootloader_fastbootButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_relockBootloader_fastbootButtonActionPerformed JOptionPane.showMessageDialog(null, parser.parse("relockBootldr:msg"), parser.parse("lockBootldr:msgTitle"), JOptionPane.INFORMATION_MESSAGE); String serial = deviceManager.getSelectedFastbootDevice(); if (serial == null || serial.equals("")) { logger.log(Level.ERROR, "No device was found! Please connect and select an Android device booted into Fastboot-mode!"); return; } try { adbController.getFastbootController().executeFastbootCommand(serial, new String[]{"oem-lock"}); } catch (IOException ex) { logger.log(Level.ERROR, "An error occurred while attempting to re-lock " + serial + ":" + ex.toString() + "\n" + "The error stack trace will be printed to the console..."); ex.printStackTrace(System.err); } }//GEN-LAST:event_relockBootloader_fastbootButtonActionPerformed
3
public Set<Task> getTasks() { return tasks; }
0
public void insertRandom(List<Element> items){ firstFitItems(shuffleList(items)); }
0
private final void parseEndTag() throws IOException { int pos; read(); // '<' read(); // '/' mName = readName(); pos = mStack.size() - 1; if (pos < 0) { fail("element stack empty"); //$NON-NLS-1$ } if (mName.equals(mStack.get(pos))) { mStack.remove(pos); } else { fail("expected: " + mStack.get(pos)); //$NON-NLS-1$ } skip(); read('>'); }
2
* The type of the LocalExpr */ public LocalExpr newStackLocal(final int index, final Type type) { if (index >= nextIndex) { nextIndex = index + 1; } return new LocalExpr(index, true, type); }
1
public void setUndefinedIds(Long id,long hash) { for (InsertionObject i : buffer) { if (i.getParentId() == null && i.getParentHash()==hash) { i.setParentId(id); } } }
3
public void spawnRateMedium() { if (spawnCounter > 300) { spawnCounter = 0; double spawnRandom = Math.random(); if (spawnRandom <= 0.33) { Boat b1 = new Boat(30,1,600,exit1); addObject(b1,800,61); } else if (spawnRandom >= 0.33 && spawnRandom <= 0.66) { Boat b2 = new Boat(20,2,450,exit2); addObject(b2, 800, 61); } else { Boat b3 = new Boat(10,3,300,exit3); addObject(b3, 800, 61); } spawnRandom = 0; } spawnCounter++; }
4
public WorldChunk getChunkAt(int x, int y, boolean b) { int chunkID =(int) Math.floor(((float)x/16f)); WorldChunk chunk = this.chunksList.get(chunkID); if(chunk == null && b) { chunk = new WorldServerChunk(this, chunkID); ((WorldServerChunk)chunk).stopUpdate = true; chunksList.put(chunkID, chunk); boolean flag = false; if(chunkFolder != null) { File f = new File(chunkFolder, chunkID+".chunk"); if(f.exists()) { try { InputStream in = new BufferedInputStream(new FileInputStream(f)); byte[] bytes = IO.read(in); in.close(); TaggedStorageChunk storageChunk = BlockyMain.saveSystem.readChunk(bytes); chunk.readStorageChunk(storageChunk); if(BlockyMain.isDevMode) BlockyMain.console("Getting chunk infos from files"); flag = true; } catch(Exception e) { e.printStackTrace(); } } else { if(BlockyMain.isDevMode) BlockyMain.console("File \""+f.getName()+"\"doesn't exist"); } } if(!flag) WorldGenerator.instance.generateChunk(this, chunk.chunkID, chunk, worldType); ((WorldServerChunk)chunk).stopUpdate = false; } return chunk; }
8
private void handleKeys(ArrayList<KeyButtons> keyPressed, boolean setter) { if (keyPressed.contains(KeyButtons.LEFT)) { mario.setLeft(setter); } if (keyPressed.contains(KeyButtons.RIGHT)) { mario.setRight(setter); } if (keyPressed.contains(KeyButtons.JUMP)) { if (setter == true) { mario.setJump(setter); } } if (keyPressed.contains(KeyButtons.DOWN)) { mario.setDown(setter); } if (keyPressed.contains(KeyButtons.SHOOT)) { if ((System.currentTimeMillis() - fireBallTimer) > fireBallTime) { if (setter == true && mario.isFlowerPower()) { fireBallTimer = System.currentTimeMillis(); getMapObjects().add(new Fireball(this, mario.getX() - 2, mario.getY() + 20, 12, 12, mario.getDirection())); } } } }
9
public FileSystemFind() { crawler = new DirectoryCrawler(); }
0
void onArrowLeft (int stateMask) { if (horizontalOffset == 0) return; int newSelection = Math.max (0, horizontalOffset - SIZE_HORIZONTALSCROLL); update (); GC gc = new GC (this); gc.copyArea ( 0, 0, clientArea.width, clientArea.height, horizontalOffset - newSelection, 0); gc.dispose (); if (header.getVisible ()) { header.update (); Rectangle headerClientArea = header.getClientArea (); gc = new GC (header); gc.copyArea ( 0, 0, headerClientArea.width, headerClientArea.height, horizontalOffset - newSelection, 0); gc.dispose(); } horizontalOffset = newSelection; ScrollBar hBar = getHorizontalBar (); if (hBar != null) hBar.setSelection (horizontalOffset); }
3
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { String[] queue = plugin.queue; if (args.length == 0) { if (sender.hasPermission("SimpleQueues.addself")) { if (Arrays.asList(queue).contains(sender.getName())) { sender.sendMessage("You are already in the queue."); } else { queue[nextEmpty(queue)] = sender.getName(); sender.sendMessage("You have been added to the queue."); } } else { sender.sendMessage("You don't have permission to do this."); } return true; } else if (args.length == 1) { if (sender.hasPermission("SimpleQueues.addother")) { Player player = plugin.getServer().getPlayer(args[1]); if (player == null) { sender.sendMessage(args[1] + " is not online or is not a valid player."); } else if (Arrays.asList(queue).contains(args[0])) { sender.sendMessage(args[1] + " is already in the queue."); } else { queue[nextEmpty(queue)] = player.getName(); sender.sendMessage(args[1] + " has been added to the queue."); player.sendMessage("You have been added to the queue by " + sender.getName() + "."); } } else { sender.sendMessage("You don't have permission to do this."); } return true; } return false; }
7
@EventHandler(priority = EventPriority.MONITOR) public void adminJoin(PlayerJoinEvent event) { try { if(!enabled || !lock.compareAndSet(false, true)) return; Player p = event.getPlayer(); String[] out; if(needUpdate) { if(hasPermission(p, "autoupdate.announce")) { out = new String[] { COLOR_INFO+"["+plugin.getName()+"] New "+type+" available!", COLOR_INFO+"If you want to update from "+av+" to "+updateVersion+" use /update "+plugin.getName(), COLOR_INFO+"See "+pluginURL+" for more information." }; } else out = null; } else if(updatePending) { if(hasPermission(p, "autoupdate.announce")) { out = new String[] { COLOR_INFO+"Please restart the server to finish the update of "+plugin.getName(), COLOR_INFO+"See "+pluginURL+" for more information." }; } else out = null; } else out = null; lock.set(false); if(out != null) plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new SyncMessageDelayer(p.getName(), out)); } catch(Throwable t) { printStackTraceSync(t, false); } }
8
public static BufferedReader queryCDD (String dataType, String query) throws Exception { URL url = new URL(CDD_BATCH_URL); String queryString = CDD_BATCH_QUERY+"&tdata="+dataType+query; // System.out.println("Querying "+CDD_BATCH_URL+" with query: \n-->"+queryString); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoOutput(true); con.setDoInput(true); con.setRequestMethod("POST"); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(queryString); wr.flush(); wr.close(); int status = -1; String cdsid = null; BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String line; while ((line = in.readLine()) != null) { String[] record = line.split("\\s"); // if (record[0].equals("#status")) status = Integer.parseInt(record[1]); if (record[0].equals("#cdsid")) cdsid = record[1]; } in.close(); // System.out.println("cdsid = "+cdsid); while (status != 0) { Thread.sleep(500); url = new URL(CDD_BATCH_URL+"?cdsid="+cdsid); con = (HttpURLConnection) url.openConnection(); con.setDoInput(true); in = new BufferedReader(new InputStreamReader(con.getInputStream())); while ((line = in.readLine()) != null) { String[] record = line.split("\\s"); try { if (record[0].equals("#status")) status = Integer.parseInt(record[1]); } catch (NumberFormatException e) {} if (status == 0) break; } if (status != 0) in.close(); } return in; }
8
public static void addData(float x, float y, float size, int id) { data.put(id, new ChartItem(new PVector(x, y), size, id)); // Update MAX and MIN values minX = (x < minX) ? x : minX; minY = (y < minY) ? y : minY; minSize = (size < minSize) ? size : minSize; maxX = (x > maxX) ? x : maxX; maxY = (y > maxY) ? y : maxY; maxSize = (size > maxSize) ? size : maxSize; }
6
public String[] copy(String[] board){ String[] newboard = new String[board.length]; for(int i = 0 ; i<board.length ; i++){ newboard[i] = board[i].substring(0); } return newboard; }
1
private void ensurePossible(int x, int y) { int newCharSize1 = charSize1; int newCharSize2 = charSize2; while (x >= newCharSize1) { newCharSize1 *= 2; } while (y >= newCharSize2) { newCharSize2 *= 2; } if (newCharSize1 != charSize1 || newCharSize2 != charSize2) { final char newChars[][] = new char[newCharSize1][newCharSize2]; for (int i = 0; i < newCharSize1; i++) { for (int j = 0; j < newCharSize2; j++) { char c = ' '; if (i < charSize1 && j < charSize2) { c = chars[i][j]; } newChars[i][j] = c; } } this.chars = newChars; this.charSize1 = newCharSize1; this.charSize2 = newCharSize2; } }
8
public Admin() { // initializing components setTitle("Conference Room Booking System"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); SpringLayout sl_contentPane = new SpringLayout(); contentPane.setLayout(sl_contentPane); JLabel lblAdministrator = new JLabel("Administrator"); sl_contentPane.putConstraint(SpringLayout.SOUTH, lblAdministrator, -218, SpringLayout.SOUTH, contentPane); sl_contentPane.putConstraint(SpringLayout.EAST, lblAdministrator, -38, SpringLayout.EAST, contentPane); lblAdministrator.setFont(new Font("Arial Unicode MS", Font.BOLD, 15)); contentPane.add(lblAdministrator); txtPass = new JTextField(); contentPane.add(txtPass); txtPass.setColumns(10); txtFname = new JTextField(); sl_contentPane.putConstraint(SpringLayout.NORTH, txtFname, 125, SpringLayout.NORTH, contentPane); sl_contentPane.putConstraint(SpringLayout.WEST, txtPass, 0, SpringLayout.WEST, txtFname); sl_contentPane.putConstraint(SpringLayout.EAST, txtPass, 0, SpringLayout.EAST, txtFname); sl_contentPane.putConstraint(SpringLayout.WEST, txtFname, 189, SpringLayout.WEST, contentPane); sl_contentPane.putConstraint(SpringLayout.EAST, txtFname, -52, SpringLayout.EAST, contentPane); contentPane.add(txtFname); txtFname.setColumns(10); JLabel lblNewLabel = new JLabel("User ID"); sl_contentPane.putConstraint(SpringLayout.NORTH, lblNewLabel, 36, SpringLayout.NORTH, contentPane); sl_contentPane.putConstraint(SpringLayout.WEST, lblNewLabel, 20, SpringLayout.WEST, contentPane); sl_contentPane.putConstraint(SpringLayout.SOUTH, lblNewLabel, -190, SpringLayout.SOUTH, contentPane); contentPane.add(lblNewLabel); JLabel lblDepartment = new JLabel("First Name"); sl_contentPane.putConstraint(SpringLayout.WEST, lblDepartment, 20, SpringLayout.WEST, contentPane); sl_contentPane.putConstraint(SpringLayout.EAST, lblDepartment, -279, SpringLayout.EAST, contentPane); contentPane.add(lblDepartment); JButton btnAdd = new JButton("Add User"); sl_contentPane.putConstraint(SpringLayout.WEST, btnAdd, 0, SpringLayout.WEST, contentPane); sl_contentPane.putConstraint(SpringLayout.EAST, btnAdd, -313, SpringLayout.EAST, contentPane); btnAdd.setFont(new Font("Tahoma", Font.BOLD, 11)); btnAdd.addActionListener(new ActionListener() {//add user button actions public void actionPerformed(ActionEvent e) { //assign the variable values to text boxes int id = Integer.valueOf(txtUserid.getText()); newUser.setUserId(id); newUser.setUserName(txtUsername.getText()); newUser.setPassWord(txtPass.getText()); newUser.setFName(txtFname.getText()); newUser.setLName(txtLname.getText()); newUser.setUserType(txtUtype.getText()); // get the values int userid = newUser.getUserId(); String username = newUser.getUserName(); String pass = newUser.getPassWord(); String fname = newUser.getFirstName(); String lname = newUser.getLastName(); String userType = newUser.getUserType(); try {//call the method to add new user actions.addUser(userid, username, pass, fname, lname, userType); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); contentPane.add(btnAdd); JButton btnDelete = new JButton("Delete"); sl_contentPane.putConstraint(SpringLayout.NORTH, btnDelete, 0, SpringLayout.NORTH, btnAdd); sl_contentPane.putConstraint(SpringLayout.WEST, btnDelete, 6, SpringLayout.EAST, btnAdd); btnDelete.setFont(new Font("Tahoma", Font.BOLD, 11)); btnDelete.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) {//delete button actions String name = txtUsername.getText(); try { sqlaction.deleteUser(name);//call the delete user method } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); contentPane.add(btnDelete); JButton btnExit = new JButton("Exit"); sl_contentPane.putConstraint(SpringLayout.EAST, btnDelete, -109, SpringLayout.WEST, btnExit); sl_contentPane.putConstraint(SpringLayout.NORTH, btnExit, 0, SpringLayout.NORTH, btnAdd); sl_contentPane.putConstraint(SpringLayout.SOUTH, btnExit, 23, SpringLayout.NORTH, btnAdd); sl_contentPane.putConstraint(SpringLayout.WEST, btnExit, 325, SpringLayout.WEST, contentPane); sl_contentPane.putConstraint(SpringLayout.EAST, btnExit, 0, SpringLayout.EAST, contentPane); btnExit.setFont(new Font("Tahoma", Font.BOLD, 11)); btnExit.addActionListener(new ActionListener() {//exit button actions public void actionPerformed(ActionEvent e) { System.exit(0); } }); contentPane.add(btnExit); JLabel lblLastName = new JLabel("Last Name"); sl_contentPane.putConstraint(SpringLayout.NORTH, lblLastName, 153, SpringLayout.NORTH, contentPane); sl_contentPane.putConstraint(SpringLayout.WEST, lblLastName, 20, SpringLayout.WEST, contentPane); sl_contentPane.putConstraint(SpringLayout.SOUTH, lblLastName, -75, SpringLayout.SOUTH, contentPane); sl_contentPane.putConstraint(SpringLayout.SOUTH, lblDepartment, -6, SpringLayout.NORTH, lblLastName); contentPane.add(lblLastName); txtLname = new JTextField(); sl_contentPane.putConstraint(SpringLayout.NORTH, txtLname, 151, SpringLayout.NORTH, contentPane); sl_contentPane.putConstraint(SpringLayout.WEST, txtLname, 189, SpringLayout.WEST, contentPane); sl_contentPane.putConstraint(SpringLayout.EAST, txtLname, -52, SpringLayout.EAST, contentPane); sl_contentPane.putConstraint(SpringLayout.EAST, lblLastName, -39, SpringLayout.WEST, txtLname); contentPane.add(txtLname); txtLname.setColumns(10); JLabel lblUserType = new JLabel("User Type"); sl_contentPane.putConstraint(SpringLayout.NORTH, btnAdd, 18, SpringLayout.SOUTH, lblUserType); sl_contentPane.putConstraint(SpringLayout.NORTH, lblUserType, 182, SpringLayout.NORTH, contentPane); sl_contentPane.putConstraint(SpringLayout.SOUTH, lblUserType, -49, SpringLayout.SOUTH, contentPane); sl_contentPane.putConstraint(SpringLayout.WEST, lblUserType, 20, SpringLayout.WEST, contentPane); contentPane.add(lblUserType); txtUtype = new JTextField(); sl_contentPane.putConstraint(SpringLayout.NORTH, txtUtype, 177, SpringLayout.NORTH, contentPane); sl_contentPane.putConstraint(SpringLayout.WEST, txtUtype, 0, SpringLayout.WEST, txtPass); sl_contentPane.putConstraint(SpringLayout.EAST, txtUtype, 0, SpringLayout.EAST, txtPass); contentPane.add(txtUtype); txtUtype.setColumns(10); sl_contentPane.putConstraint(SpringLayout.NORTH, lblAdministrator, -7, SpringLayout.NORTH, comboBox); sl_contentPane.putConstraint(SpringLayout.WEST, lblAdministrator, 113, SpringLayout.EAST, comboBox); sl_contentPane.putConstraint(SpringLayout.SOUTH, comboBox, -221, SpringLayout.SOUTH, contentPane); sl_contentPane.putConstraint(SpringLayout.EAST, lblNewLabel, -10, SpringLayout.EAST, comboBox); sl_contentPane.putConstraint(SpringLayout.WEST, comboBox, 10, SpringLayout.WEST, contentPane); sl_contentPane.putConstraint(SpringLayout.EAST, comboBox, -303, SpringLayout.EAST, contentPane); contentPane.add(comboBox); JLabel lblUserName = new JLabel("User Name"); sl_contentPane.putConstraint(SpringLayout.NORTH, lblUserName, 72, SpringLayout.NORTH, contentPane); sl_contentPane.putConstraint(SpringLayout.WEST, lblUserName, 20, SpringLayout.WEST, contentPane); sl_contentPane.putConstraint(SpringLayout.EAST, lblUserName, 0, SpringLayout.EAST, lblNewLabel); contentPane.add(lblUserName); JLabel lblPassword = new JLabel("Password"); sl_contentPane.putConstraint(SpringLayout.WEST, lblPassword, 20, SpringLayout.WEST, contentPane); sl_contentPane.putConstraint(SpringLayout.EAST, lblPassword, -44, SpringLayout.WEST, txtPass); sl_contentPane.putConstraint(SpringLayout.SOUTH, lblUserName, -17, SpringLayout.NORTH, lblPassword); sl_contentPane.putConstraint(SpringLayout.NORTH, txtPass, -3, SpringLayout.NORTH, lblPassword); sl_contentPane.putConstraint(SpringLayout.NORTH, lblDepartment, 6, SpringLayout.SOUTH, lblPassword); sl_contentPane.putConstraint(SpringLayout.NORTH, lblPassword, 103, SpringLayout.NORTH, contentPane); contentPane.add(lblPassword); txtUsername = new JTextField(); sl_contentPane.putConstraint(SpringLayout.WEST, txtUsername, 0, SpringLayout.WEST, txtPass); sl_contentPane.putConstraint(SpringLayout.SOUTH, txtUsername, -11, SpringLayout.NORTH, txtPass); sl_contentPane.putConstraint(SpringLayout.EAST, txtUsername, 0, SpringLayout.EAST, txtFname); contentPane.add(txtUsername); txtUsername.setColumns(10); txtUserid = new JTextField(); sl_contentPane.putConstraint(SpringLayout.WEST, txtUserid, 78, SpringLayout.EAST, lblNewLabel); sl_contentPane.putConstraint(SpringLayout.SOUTH, txtUserid, -11, SpringLayout.NORTH, txtUsername); sl_contentPane.putConstraint(SpringLayout.EAST, txtUserid, 0, SpringLayout.EAST, txtPass); txtUserid.setColumns(10); contentPane.add(txtUserid); JButton btnGet = new JButton("Get"); sl_contentPane.putConstraint(SpringLayout.EAST, btnGet, -49, SpringLayout.WEST, lblAdministrator); btnGet.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) {// get button actions....i could not find a method //to get the nemes directly by combobox action method. //then jumped to a button try { String userlist = sqlaction.getAllUsers();// call the method System.out.println(userlist.toString()); String[] available = userlist.split(",");//split the string int j=0; comboBox.removeAllItems();// to clear for (String s:available){ comboModel.addElement(s); //add users j=j++; } } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); btnGet.setFont(new Font("Tahoma", Font.BOLD, 11)); sl_contentPane.putConstraint(SpringLayout.NORTH, btnGet, 6, SpringLayout.NORTH, lblAdministrator); contentPane.add(btnGet); comboBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0)//action to selecting of an item of comboBox { try { String name = (String) comboBox.getSelectedItem(); newUser = sqlaction.getUserbyName(name);// call the method } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); }//assign the variable values to the textboxes String id= String.valueOf(newUser.getUserId()); txtUserid.setText(id); txtUsername.setText(newUser.getUserName()); txtPass.setText(newUser.getPassWord()); txtFname.setText(newUser.getFirstName()); txtLname.setText(newUser.getLastName()); txtUtype.setText(newUser.getUserType()); } }); JButton btnClear = new JButton("Clear"); sl_contentPane.putConstraint(SpringLayout.WEST, btnClear, 6, SpringLayout.EAST, btnDelete); sl_contentPane.putConstraint(SpringLayout.EAST, btnClear, -6, SpringLayout.WEST, btnExit); btnClear.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) {//clear button actions txtUserid.setText(""); txtUsername.setText(""); txtPass.setText(""); txtFname.setText(""); txtLname.setText(""); txtUtype.setText(""); } }); btnClear.setFont(new Font("Tahoma", Font.BOLD, 11)); sl_contentPane.putConstraint(SpringLayout.NORTH, btnClear, 0, SpringLayout.NORTH, btnAdd); contentPane.add(btnClear); }
5
private final void acceptConnection(final SelectionKey key, MMOConnection<T> con) { ServerSocketChannel ssc = (ServerSocketChannel) key.channel(); SocketChannel sc; try { while ((sc = ssc.accept()) != null) { if ((_acceptFilter == null) || _acceptFilter.accept(sc)) { sc.configureBlocking(false); SelectionKey clientKey = sc.register(_selector, SelectionKey.OP_READ); con = new MMOConnection<>(this, sc.socket(), clientKey, TCP_NODELAY); con.setClient(_clientFactory.create(con)); clientKey.attach(con); } else { sc.socket().close(); } } } catch (IOException e) { e.printStackTrace(); } }
4
public ListNode getIntersectionNode(ListNode headA, ListNode headB) { if (headA == null || headB == null) return null; ListNode tempA = headA; while (tempA.next != null) { tempA = tempA.next; } tempA.next = headB; ListNode fast = headA; ListNode slow = headA; while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; if (fast == slow) break; } if (fast == null || fast.next == null) { tempA.next = null; // recover original structure return null; } ListNode start = headA; while (start != fast) { fast = fast.next; start = start.next; } tempA.next = null; // recover original structure return fast; }
9
private CoastlineNode getNodeInformation(Attributes attributes) { String idStr = attributes.getValue("id"); String latStr = attributes.getValue("lat"); String lonStr = attributes.getValue("lon"); // Avoid null pointer reference! if (idStr != null && latStr != null && lonStr != null) { int id = Integer.parseInt(idStr); try { double lat = Double.parseDouble(latStr); double lon = Double.parseDouble(lonStr); double easting = GeoConvert.toUtmX(32, lon, lat)[0]; double northing = GeoConvert.toUtmX(32, lon, lat)[1]; return new CoastlineNode(id, easting, northing); } catch (NumberFormatException ex) { Logger.getLogger(CoastlineXMLHandler.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(CoastlineXMLHandler.class.getName()).log(Level.SEVERE, null, ex); } } return null; }
5
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(janResultados.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(janResultados.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(janResultados.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(janResultados.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 janResultados().setVisible(true); } }); }
6
public void dir(){ try{ if( file.exists() && file.isDirectory() ){ File files[] = file.listFiles(); int cf = 0, cd =0; long slengths = 0; for( File f : files ){ Date ultima = new Date( f.lastModified() ); System.out.print(ultima + "\t"); if( f.isDirectory() ){ System.out.print("<DIR>\t "); cd++; } if( f.isFile()){ System.out.print(" \t"); System.out.print(f.length() + " "); cf++; slengths += f.length(); } System.out.println(f.getName()); } System.out.printf("(%d) Archivo(s) %d Bytes \n(%d) Directorio(s)", cf,slengths,cd); } else System.out.println("NO EXISTE O NO ES ARCHIVO"); } catch(NullPointerException e){ System.out.println("COnfigure el archivo primero"); } }
6
public void shrink(final Object o, final Method m, final Object[] args) { try { Object r = m.invoke(o, args); if(r instanceof SingleTestResult) { SingleTestResult result = (SingleTestResult)r; if(!result.isDiscarded && (result.expect != result.ok)) { } } } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
6
final public void run() { server.clientConnected(this); // This loop reads the input stream and responds to messages // from clients try { // The message from the client Object msg; while (!readyToStop) { // This block waits until it reads a message from the client // and then sends it for handling by the server msg = input.readObject(); server.receiveMessageFromClient(msg, this); } } catch (Exception exception) { if (!readyToStop) { try { closeAll(); } catch (Exception ex) { } server.clientException(this, exception); } } }
4
public static String dumpByteArray(byte[] bytes) { StringBuilder sb = new StringBuilder(); for(int i = 0; i < bytes.length; i++) { byte b = bytes[i]; int iVal = b & 0xFF; int byteN = Integer.parseInt(Integer.toBinaryString(iVal)); sb.append(String.format("%1$02d: %2$08d %3$1c %3$d\n" , i, byteN, iVal)); } return sb.toString(); }
1
void notifyRefreshFiles(File[] files) { if (files != null && files.length == 0) return; if ((deferredRefreshRequested) && (deferredRefreshFiles != null) && (files != null)) { // merge requests File[] newRequest = new File[deferredRefreshFiles.length + files.length]; System.arraycopy(deferredRefreshFiles, 0, newRequest, 0, deferredRefreshFiles.length); System.arraycopy(files, 0, newRequest, deferredRefreshFiles.length, files.length); deferredRefreshFiles = newRequest; } else { deferredRefreshFiles = files; deferredRefreshRequested = true; } handleDeferredRefresh(); }
5
public void reset() { start(); }
0
public void draw(Graphics2D g2) { if (bImage == null) { File imageFile = new File(baseDir + imageFileName); try { bImage = ImageIO.read(imageFile); } catch (IOException e) { e.printStackTrace(); } } if(firing) frames = 2; else frames = 3; if (xIncrement > frames) { xIncrement = 0; } //This calculates the amount of offset to animate between tiles (40px/SPEED = 0.8px per tick) if(pixels < 40-(40/SPEED) && getLoc() != null) pixels += (double)40./SPEED; else resetPixels(); if(getLoc().nextTile != null) tempSubImage = bImage.getSubimage(xIncrement * WIDTH, yIncrement * HEIGHT + 40, WIDTH, HEIGHT); else { firing = true; tempSubImage = bImage.getSubimage(xIncrement * (WIDTH*3), yIncrement * HEIGHT, WIDTH, HEIGHT*2); } //We need to slow down the animation frames so they aren't firing every tick! Use Count%5 so they're 1/5 as fast if(count%6 == 0) xIncrement++; count++; // AffineTransform will help us manipulate sprites AffineTransform at = new AffineTransform(); // calculate offset per tick at.translate(getLoc().getCoordinates().x * WIDTH + offset("x"), getLoc().getCoordinates().y * HEIGHT + offset("y")); // calculate direction they should be facing at.rotate(checkTransform(), tempSubImage.getWidth() / 2, tempSubImage.getHeight() / 2); g2.drawImage(tempSubImage, at, null); }
8
public void saveConfig() { if (fileConfiguration == null || configFile == null) { return; } else { try { getConfig().save(configFile); } catch (IOException ex) { plugin.getLogger().log(Level.SEVERE, "Could not save config to " + configFile, ex); } } }
3
public Location getCorner(int i) { switch (i) { case 1: return loc1; case 2: return loc2; case 3: return loc3; case 4: return loc4; } return null; }
4
public List<String> letterCombinations(String digits) { String[] mapping = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; List<String> result = new ArrayList<String>(); if (digits == null || digits.length() == 0) { return result; } int a = digits.charAt(0) - '0' - 2; String s = mapping[a]; List<String> rt = letterCombinations(digits.substring(1)); for (char c : s.toCharArray()) { if (rt.isEmpty()) { result.add(String.valueOf(c)); } else { for (String ss : rt) { result.add(c + ss); } } } return result; }
5
private String loginUser(String name, String cmd,String pass) throws InterruptedException, IOException { readUntil(GosLink2.prps("puser")); write(name); readUntil(GosLink2.prps("ppass")); write(pass+"\r\n"); readUntil(GosLink2.prps("pmenu")); if (ghost == 1){ write("=x\n"); ghost=0; return "reload"; } else {write(cmd);} readUntil(GosLink2.prps("pmud")); write("e"); write("\n"); return "blah"; }
1
public int removexattr(ByteBuffer path, ByteBuffer name) { if (xattrSupport == null) { return handleErrno(Errno.ENOTSUPP); } String pathStr = cs.decode(path).toString(); String nameStr = cs.decode(name).toString(); if (log != null && log.isDebugEnabled()) { log.debug("removexattr: path= " + pathStr + ", name=" + nameStr); } try { return handleErrno(xattrSupport.removexattr(pathStr, nameStr)); } catch(Exception e) { return handleException(e); } }
4
private void writeImage() throws IOException { int pImage[] = new int[height * height]; for (int row = 0, count = 0; row < height; row++) { for (int col = 0; col < width; col++) { pImage[count] = rgbArray[row][col]; count++; } } img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); img.setRGB(0, 0, width, height, pImage, 0, width); ImageIO.write(img, "bmp", new FileOutputStream("RESULT.bmp")); // save image }
2
public ItemID setType(int t) throws ShellLinkException { if (t == TYPE_CLSID) { type = t; clsid = mycomputer; return this; } if (t == TYPE_FILE || t == TYPE_DIRECTORY || t == TYPE_DRIVE || t == TYPE_DRIVE_OLD) { type = t; return this; } throw new ShellLinkException("wrong type"); }
5
public String getDescription() { return description; }
0
public ArrayList<Pizza> haePizzat() throws DAOPoikkeus { ArrayList<Pizza> pizzat = new ArrayList<Pizza>(); // avataan yhteys Connection yhteys = avaaYhteys(); try { // Haetaan tietokannasta Pizzat ja täytteet String pizzaSQL = "select Tuote.nimi, Tuote.numero, Tuote.hinta, Tuote.tuoteID, Tuote.aktiivinen from Tuote WHERE Tuote.tuoteryhmaID ='1' AND Tuote.aktiivinen = '1' order by numero asc"; String taytteetSQL = "select Tayte.nimi, Tayte.TayteID from Tayte INNER JOIN TuotteenTayte ON TuotteenTayte.tayteID = Tayte.tayteID INNER JOIN Tuote ON Tuote.tuoteID = TuotteenTayte.tuoteID where Tuote.tuoteID = ?;"; PreparedStatement lause = yhteys.prepareStatement(taytteetSQL); Statement haku = yhteys.createStatement(); ResultSet pizzaResult = haku.executeQuery(pizzaSQL); while(pizzaResult.next()) { int numero = pizzaResult.getInt("numero"); String nimi = pizzaResult.getString("nimi"); double hinta = pizzaResult.getDouble("hinta"); int id = pizzaResult.getInt("tuoteID"); boolean aktiivinen = pizzaResult.getBoolean("aktiivinen"); // lisätään Pizza ArrayListiin Pizza pizza = new Pizza(numero, nimi, hinta, id, aktiivinen); pizzat.add(pizza); } for (int i = 0; i < pizzat.size(); i++) { ArrayList<Tayte> lista = new ArrayList<Tayte>(); lause.setInt(1, pizzat.get(i).getId()); ResultSet tayteResult = lause.executeQuery(); while(tayteResult.next()) { String nimi = tayteResult.getString("nimi"); int id = tayteResult.getInt("TayteID"); // lisätään Pizza väliaikaiseen listaan Tayte tayte = new Tayte(nimi,id); lista.add(tayte); } pizzat.get(i).setTaytteet(lista); System.out.println(pizzat.get(i)); } } catch(Exception e) { // Tapahtui jokin virhe? throw new DAOPoikkeus("Tietokantahaku aiheutti virheen.", e); } finally { // Lopulta aina suljetaan yhteys! suljeYhteys(yhteys); } return pizzat; }
4
public boolean setShutdownButtonWidth(int width) { boolean ret = true; if (width < 0) { this.buttonShutdown_Width = UISizeInits.SHD_BTN.getWidth(); ret = false; } else { this.buttonShutdown_Width = width; } somethingChanged(); return ret; }
1
private void visitParameterLoad(Parameter parameter) throws JavaBytecodeCompilerException { if (parameter instanceof ObjectParameter) { Object value = parameter.evaluate(); Integer intValue = (Integer) value; switch (intValue) { case 0: methodVisitor.visitInsn(ICONST_0); break; case 1: methodVisitor.visitInsn(ICONST_1); break; case 2: methodVisitor.visitInsn(ICONST_2); break; case 3: methodVisitor.visitInsn(ICONST_3); break; case 4: methodVisitor.visitInsn(ICONST_4); break; case 5: methodVisitor.visitInsn(ICONST_5); break; default: methodVisitor.visitIntInsn(SIPUSH, intValue); break; } } else if (parameter instanceof VariableParameter) { VariableParameter variableParameter = (VariableParameter) parameter; Variable valueVariable = variableParameter.getVariable(); if (!definedVariables.contains(valueVariable.getName().toLowerCase())) throw new JavaBytecodeCompilerException("Trying to use an undefined variable"); visitVariableLoad(valueVariable); } else throw new JavaBytecodeCompilerException("Parameter type is not supported"); }
9
public static void main(String[] args) { if (System.getProperty("os.name").indexOf("Mac") == -1) { try { for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (Exception e) { // If Nimbus is not available, you can set the GUI to another look and feel. } } JPopupMenu.setDefaultLightWeightPopupEnabled(false); Tasks.loadSettings(); sketch = new Sketch(); mainFrame = new MainFrame(); mainFrame.setLocationRelativeTo(null); try { Library.i().scan(); } catch (Exception e) { e.printStackTrace(); } Library.i().computeMissingHashes(); Library.i().fixModelFileNames(); Library.i().cacheThumbnails(); Library.i().deleteUselessThumbnails(); libraryFrame = new LibraryFrame(); libraryFrame.getModel().add(Library.i().getModels()); libraryFrame.getModel().refresh(); libraryFrame.showMe(); resizeModelFrame = new ResizeModelFrame(); replaceColorFrame = new ReplaceColorFrame(); preferencesFrame = new PreferencesFrame(); preferencesFrame.showMe(); //Main.mainFrame.setVisible(true); }
5
public int getBoardCommentaryCount(int idx) throws Exception{ Connection conn = null; PreparedStatement pstmt = null; ResultSet rs =null; int result = 0; String sql = ""; try{ conn = getConnection(); sql = "select count(*) from foodcommentary where idx=?"; pstmt = conn.prepareStatement(sql); pstmt.setInt(1, idx); rs = pstmt.executeQuery(); if(rs.next()){ result = rs.getInt(1); } }catch(Exception ex ){ ex.printStackTrace(); }finally{ if(rs != null){ try{rs.close();} catch(SQLException e){e.printStackTrace();} } if(pstmt != null){ try{pstmt.close();} catch(SQLException e){e.printStackTrace();} } if(conn != null){ try{conn.close();} catch(SQLException e){e.printStackTrace();} } } return result; }
8
private static Set<Class<?>> getAllRelatedClassesOf(Class<?> c) { Set<Class<?>> a = new LinkedHashSet<>(); a.add(c); for (Class<?> class1 : c.getInterfaces()) a.addAll(getAllRelatedClassesOf(class1)); Class<?> superClass = c.getSuperclass(); if (superClass != null) a.add(superClass); // System.out.println( a.stream().map(x -> // x.getSimpleName()).collect(Collectors.toList())); return a; }
7
final private boolean jj_3R_25() { Token xsp; xsp = jj_scanpos; if (jj_3R_27()) { jj_scanpos = xsp; if (jj_3R_28()) { jj_scanpos = xsp; if (jj_3R_29()) return true; if (jj_la == 0 && jj_scanpos == jj_lastpos) return false; } else if (jj_la == 0 && jj_scanpos == jj_lastpos) return false; } else if (jj_la == 0 && jj_scanpos == jj_lastpos) return false; return false; }
9
public static String simpleFormatted(byte[] data){ if(data == null) return null; String simpleStr; simpleStr = ""; String binary = getBinary(data); String hex = getHex(data); byte[] bytes = data; int len = hex.length() / 2; int step = 4; int count = (int) Math.ceil(len / step); for(int i = 0; i < count; i++){ for(int j = 0; j < step; j++){ int pos = i * step + j; if(pos < len) simpleStr = simpleStr + binary.substring(pos * 8, pos * 8 + 8) + " "; else simpleStr = simpleStr + " "; } simpleStr = simpleStr + "\t"; for(int j = 0; j < step; j++){ int pos = i * step + j; if(pos < len) simpleStr = simpleStr + hex.substring(pos * 2, pos * 2 + 2) + " "; else simpleStr = simpleStr + " "; } simpleStr = simpleStr + "\t"; for(int j = 0; j < step; j++){ int pos = i * step + j; if(pos < len) simpleStr = simpleStr + (char)bytes[pos]; else simpleStr = simpleStr + " "; } simpleStr = simpleStr + "\n"; } return simpleStr; }
8
public boolean sendMessage(String mobileNumber, String message) { if(message.length()>140) return false; Map params=new HashMap(); params.put("Token", this.token); nav.setReferer(nav.getCurrentDomain().toExternalForm()+"Main.action?id="+this.token); Response response=nav.get("jsp/SingleSMS.jsp", params); String m_15_b=this.findHtml(response.getResponseData(),"m_15_b"); String t_15_k_5=this.findHtml(response.getResponseData(), "t_15_k_5"); String diffNo=this.findHtml(response.getResponseData(), "diffNo"); try { message=URLEncoder.encode(message, "utf-8"); diffNo=URLEncoder.encode(diffNo, "utf-8"); } catch(Exception e) { e.printStackTrace(); } String nonce=".setAttribute(\"name\","; for(Iterator i=response.getResponseData().iterator();i.hasNext();) { String line=(String)i.next(); if(line.indexOf(nonce)>0) { line=line.substring(line.indexOf(nonce)+nonce.length(), line.indexOf(')')).trim(); nonce=line.substring(1, line.length()-1); break; } } String cookie="setCookie(\""; for(Iterator i=response.getResponseData().iterator();i.hasNext();) { String line=(String)i.next(); int index=line.indexOf(cookie); if(index>0) { line=line.substring(index+cookie.length()); cookie=line.substring(0, line.indexOf('"')); break; } } //if(!cookie.isEmpty()) nav.addCookie(cookie+"="+cookie); nav.addCookie("12489smssending34908=67547valdsvsikerexzc435457"); Map post=new HashMap<String,String>(); post.put("m_15_b", m_15_b); post.put(m_15_b, mobileNumber); post.put("t_15_k_5", t_15_k_5); post.put(t_15_k_5, this.token); post.put("i_m", "sndsms"); post.put("txtLen", 140-message.length()); post.put("textArea", message); post.put("kriya", this.findHtml(response.getResponseData(), "kriya")); post.put("chkall", "on"); post.put("diffNo", diffNo); post.put(nonce, ""); post.put("catnamedis", "Birthday"); nav.setReferer(nav.getCurrentDomain().toExternalForm()+"jsp/SingleSMS.jsp?Token="+this.token); response=nav.post("jsp/sndsms2usr.action", post, false); if(response.isRedirect()) { String loc=response.getHeaderValue("Location"); try { URL url=new URL(loc); nav.setCurrentDomain(url); nav.get(url.getPath(), null); return true; } catch(IOException e) { e.printStackTrace(); return false; } } else return false; }
8
public GUI(Sprinkles s){ super("Sprinkles"); this.s = s; this.setSize(200, 200); this.setTitle("Sprinkles"); this.setJMenuBar(createMenubar()); this.s = s; this.s.setGui( this ); left = new JScrollPane( new JPanel() ); right = new JScrollPane( new JPanel() ); left.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS ); left.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS ); p = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, left, right); p.setDividerLocation(150); p.setOneTouchExpandable( true ); pb = new JProgressBar(0, 100); pb.setVisible( false ); guiContents = new JPanel(); BoxLayout b = new BoxLayout(guiContents , BoxLayout.Y_AXIS); guiContents.setLayout( b ); guiContents.add( p ); guiContents.setPreferredSize( new Dimension(640, 480)); this.getContentPane().add( guiContents, BorderLayout.CENTER ); this.getContentPane().add( pb, BorderLayout.SOUTH ); try { UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()); } catch (UnsupportedLookAndFeelException e) { // handle exception e.printStackTrace(); } catch (ClassNotFoundException e) { // handle exception e.printStackTrace(); } catch (InstantiationException e) { // handle exception e.printStackTrace(); } catch (IllegalAccessException e) { // handle exception e.printStackTrace(); } this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); }
4
@Override public String breakOutMaskString(String s, List<String> p) { String mask=""; int x=s.toUpperCase().lastIndexOf("MASK="); if(x>=0) { mask=s.substring(x+5).trim(); int i=0; while((i<p.size())&&(p.get(i).toUpperCase().indexOf("MASK=")<0)) i++; if(i<=p.size()) { final String pp=p.get(i); x=pp.toUpperCase().indexOf("MASK="); if((x>0)&&(pp.substring(0,x).trim().length()>0)) { p.set(i,pp.substring(0,x).trim()); i++; } while(i<p.size()) p.remove(i); } } return mask.trim(); }
7
@Override @RequestMapping(value = "/beers", method = RequestMethod.GET) @ResponseBody public BeerResponseList list() { Collection<Beer> beers = persistenceService.list(Beer.class); return BeerResponseList.create(beers); }
0
private void matchStereochemistryToAtomsAndBonds(Element stereoChemistryEl) throws StructureBuildingException, StereochemistryException { String stereoChemistryType =stereoChemistryEl.getAttributeValue(TYPE_ATR); if (stereoChemistryType.equals(R_OR_S_TYPE_VAL)){ assignStereoCentre(stereoChemistryEl); } else if (stereoChemistryType.equals(E_OR_Z_TYPE_VAL)){ assignStereoBond(stereoChemistryEl); } else if (stereoChemistryType.equals(CISORTRANS_TYPE_VAL)){ if (!assignCisTransOnRing(stereoChemistryEl)){ assignStereoBond(stereoChemistryEl); } } else if (stereoChemistryType.equals(ALPHA_OR_BETA_TYPE_VAL)){ assignAlphaBetaXiStereochem(stereoChemistryEl); } else if (stereoChemistryType.equals(ENDO_EXO_SYN_ANTI_TYPE_VAL)){ throw new StereochemistryException(stereoChemistryType + " stereochemistry is not currently interpretable by OPSIN"); } else if (stereoChemistryType.equals(RELATIVECISTRANS_TYPE_VAL)){ throw new StereochemistryException(stereoChemistryType + " stereochemistry is not currently interpretable by OPSIN"); } else if (stereoChemistryType.equals(AXIAL_TYPE_VAL)){ throw new StereochemistryException(stereoChemistryType + " stereochemistry is not currently interpretable by OPSIN"); } else if (stereoChemistryType.equals(OPTICALROTATION_TYPE_VAL)){ state.addWarning(OpsinWarningType.STEREOCHEMISTRY_IGNORED, "Optical rotation cannot be algorithmically used to assign stereochemistry. This term was ignored: " + stereoChemistryEl.getValue()); } else{ throw new StructureBuildingException("Unexpected stereochemistry type: " +stereoChemistryType); } stereoChemistryEl.detach(); }
9