text
stringlengths
14
410k
label
int32
0
9
@Override public boolean equals(final Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; MoreMethodStatistics other = (MoreMethodStatistics) obj; if (count != other.count) return false; if (max != other.max) return false; if (min != other.min) return false; return true; }
6
private void switchCommand(String[] cmd) { if (cmd[0].equals("exit")) { Exit e = new Exit(); e.execute(wd, cmd); } else if(cmd[0].equals("pwd")) { PWD pwd = new PWD(); pwd.execute(wd, cmd); } else if(cmd[0].equals("cd")) { CD cd = new CD(); wd = cd.execute(wd, cmd); } else if(cmd[0].equals("ls")) { LS ls = new LS(); ls.execute(wd, cmd); } else if(cmd[0].equals("mv")) { MV mv = new MV(); mv.execute(wd, cmd); } else if(cmd[0].equals("cat")) { CAT cat = new CAT(); cat.execute(wd, cmd); } else if(cmd[0].equals("wc")) { WC wc = new WC(); wc.execute(wd, cmd); } else System.out.println("Invalid input, try again!"); }
7
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ChefNode other = (ChefNode) obj; if (ip == null) { if (other.ip != null) return false; } else if (!ip.equals(other.ip)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; }
9
public void addToGrid(String code) //Afegim un nou valor al Grid { String[] values = code.split("&"); for(String value : values) { String[] component = value.split(","); int x = Integer.parseInt(component[0]); int y = Integer.parseInt(component[1]); int val = Integer.parseInt(component[2]); int state = Integer.parseInt(component[3]); Print("New Contribution at the Position [" + x + "][" + y + "] with the value: " + val); SetValueAndState(x, y, val, state); } }
1
private static void close() { try { if (resultSet != null) { resultSet.close(); } if (statement != null) { statement.close(); } if (connect != null) { connect.close(); } } catch (Exception e) { e.printStackTrace(); } }
4
public static SpecialChar check(char charValue){ for(SpecialChar specialChar: SpecialChar.values()){ if(specialChar.value == charValue) return specialChar; } return null; }
2
private void GetSubParam(String diValue) { int Indexfrom = 0; int Indexto = 0; String paraSpace = null; String trimValue = null; //check if(diValue.length() <= directiveName.length()){ //do not have param return; } this.SetNameupspace(diValue); //setUpSpace use Indexfrom = diValue.indexOf(directiveName)+directiveName.length(); //editValue= StringParameter1 StringParameter3 StringParameter4 String editValue = diValue.substring(Indexfrom,diValue.length()-1); // Directive_name Option=9 StringParameter $Variable String temdi = diValue.substring(Indexfrom).trim(); String divalueOutlast = temdi.substring(0, temdi.length()-1); String[] lineArray=divalueOutlast.split(" "); for(int i=0;i<lineArray.length;i++){ if(lineArray[i].length() == 0){ continue; } // System.out.println("lineArray[i]:"+lineArray[i]); // setUpSpace use start: //trimValue=StringParameter3 StringParameter4 trimValue = editValue.trim(); Indexto = editValue.length()-trimValue.length(); paraSpace = editValue.substring(0,Indexto); //editValue= StringParameter4 editValue = editValue.substring(Indexto+lineArray[i].length()); // setUpSpace use end // System.out.println("Indexto:"+Indexto); if(lineArray[i].contains("=")){ RecOption objOption = new RecOption(); String[] lineOption=lineArray[i].split("="); objOption.setName(lineOption[0]); objOption.setValue(lineOption[1]); objOption.setUpSpace(paraSpace); listParam.add(objOption); }else if(lineArray[i].contains("$")){ RecVariable objVariable = new RecVariable(); objVariable.setName(lineArray[i].substring(1, lineArray[i].length()-1)); objVariable.setUpSpace(paraSpace); listParam.add(objVariable); }else if(lineArray[i].length() == 0){ }else{ RecStringParameter objStringParameter = new RecStringParameter(); objStringParameter.setValue(lineArray[i]); objStringParameter.setUpSpace(paraSpace); // System.out.println("StringParameter:"+lineArray[i]); listParam.add(objStringParameter); } } }
6
@Override public long solve() throws IOException { final List<List<Node>> nodes = new ArrayList<List<Node>>(80); try (final BufferedReader reader = FileUtils.readInput(this)) { String line = null; int y = 0; while ((line = reader.readLine()) != null) { // Parse the line! final String[] numbers = line.split(","); final List<Node> currentNodes = new ArrayList<Node>(80); for (int x = 0; x < numbers.length; x++) { final int number = Integer.parseInt(numbers[x]); currentNodes.add(new Node(number, x, y)); } nodes.add(currentNodes); y++; } // Link all the nodes, first horizontal for (final List<Node> list : nodes) { Node curr = null; for (final Node next : list) { if (curr != null) { curr.addNeighbor(next); next.addNeighbor(curr); } curr = next; } } // Now vertical List<Node> curr = null; for (final List<Node> next : nodes) { if (curr != null) { for (int x = 0; x < Math.min(next.size(), curr.size()); x++) { curr.get(x).addNeighbor(next.get(x)); next.get(x).addNeighbor(curr.get(x)); } } curr = next; } } final Node start = nodes.get(0).get(0); final List<Node> goalList = nodes.get(nodes.size() - 1); final Node goal = goalList.get(goalList.size() - 1); final ShortestPathSolver solver = new AStar(start, new Guide() { @Override public long estimateDistanceToGoal(Node from) { final int dx = Math.abs(from.getX() - goal.getX()); final int dy = Math.abs(from.getY() - goal.getY()); return dx + dy; } @Override public boolean isGoal(Node node) { return node.equals(goal); } }); final List<Node> shortestPath = solver.findShortestPath(); long totalLength = 0; for (final Node n : shortestPath) { totalLength += n.getValue(); } return totalLength; }
9
public Set getDeclarables() { if (exceptionLocal != null) return Collections.singleton(exceptionLocal); return Collections.EMPTY_SET; }
1
public void testToStandardSeconds() { Hours test = Hours.hours(3); Seconds expected = Seconds.seconds(3 * 60 * 60); assertEquals(expected, test.toStandardSeconds()); try { Hours.MAX_VALUE.toStandardSeconds(); fail(); } catch (ArithmeticException ex) { // expected } }
1
@Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { req.setCharacterEncoding("utf-8"); super.doFilter(req, res, chain); }
0
public String getDescription() { return description; }
0
@Override public Message build() { try { Message record = new Message(); record.to = fieldSetFlags()[0] ? this.to : (java.lang.CharSequence) defaultValue(fields()[0]); record.from = fieldSetFlags()[1] ? this.from : (java.lang.CharSequence) defaultValue(fields()[1]); record.body = fieldSetFlags()[2] ? this.body : (java.lang.CharSequence) defaultValue(fields()[2]); return record; } catch (Exception e) { throw new org.apache.avro.AvroRuntimeException(e); } }
4
@Override public int rename(String from, String to) throws FuseException { try { if (fileSystem.isReadOnly()) return Errno.EROFS; fileSystem.rename(from, to); } catch (PathNotFoundException e) { return Errno.ENOENT; } catch (DestinationAlreadyExistsException e) { return Errno.EEXIST; } catch (AccessDeniedException e) { return Errno.EACCES; } return 0; }
4
public final void dispatchEvent(final NativeInputEvent e) { eventExecutor.execute(new Runnable() { public void run() { if (e instanceof NativeKeyEvent) { processKeyEvent((NativeKeyEvent) e); } else if (e instanceof NativeMouseWheelEvent) { processMouseWheelEvent((NativeMouseWheelEvent) e); } else if (e instanceof NativeMouseEvent) { processMouseEvent((NativeMouseEvent) e); } } }); }
3
public boolean hasFolderFile(SPFolder spFoler) { int i = 0; boolean found = false; while(i < files.size() && !found) { if(files.get(i).getParent().equals(spFoler)) { found = true; } i++; } return true; }
3
public Card(JSONObject data) throws JSONException, IOException { // Populate object properties ID = data.getInt("id"); Points = data.getInt("points"); sImage = data.getString("src"); sMatch = data.getString("match"); sMisMatch = data.getString("mismatch"); sReveal = data.getString("reveal"); MatchSound = sMatch.equals("") ? null : makeOGG("mob/" + sMatch); MisMatchSound = sMisMatch.equals("") ? null : makeOGG("mob/" + sMisMatch); RevealSound = sReveal.equals("") ? null : makeOGG("mob/" + sReveal); Image = new ImageIcon(Program.getAsset("img/mob/" + sImage)); }
3
public void updateProgress() { setStage(getStage() + 1); if (getStage() == 1) player.getInterfaceManager().sendSettings(); else if (getStage() == 2) player.getPackets().sendConfig(1021, 0); // unflash else if (getStage() == 5) { player.getInterfaceManager().sendInventory(); player.getInventory().unlockInventoryOptions(); player.getHintIconsManager().removeUnsavedHintIcon(); } else if (getStage() == 6) player.getPackets().sendConfig(1021, 0); // unflash else if (getStage() == 7) player.getHintIconsManager().removeUnsavedHintIcon(); else if (getStage() == 10) player.getInterfaceManager().sendSkills(); else if (getStage() == 11) player.getPackets().sendConfig(1021, 0); // unflash else if (getStage() == 13 || getStage() == 21) player.getHintIconsManager().removeUnsavedHintIcon(); refreshStage(); }
9
@Override public void restoreTemporaryToDefault(){tmp = def;}
0
@Override public String toString() { StringBuilder sb = new StringBuilder("codon." + name + ": "); ArrayList<String> codons = new ArrayList<String>(); codons.addAll(codon2aa.keySet()); Collections.sort(codons); for (String codon : codons) sb.append(" " + codon + "/" + aa(codon) + (isStart(codon) ? "+" : "") + ","); sb.deleteCharAt(sb.length() - 1); // Remove last comma return sb.toString(); }
2
public List<Animation> getAnimations() { List<Animation> old = new LinkedList<>(animations); animations.clear(); for (Animation a : old) { if (a.isAlive()) { animations.add(a); } } return animations; }
2
public int ginjectEncPayload(byte[] info, int start) { int i, j, n_ent, k = start; if (isInput()) { return 0; } // Create vector and array of the correct size n_ent = 1 << n_inputs; encrypted_truth_table = new Vector<byte[]>(n_ent); encrypted_perm = new byte[n_ent]; // Inject all data into appropriate structures for (i = 0 ; i < n_ent; i++, k++) // Encrypted perm bytes encrypted_perm[i] = info[k]; for (i = 0; i < n_ent; i++) { // Encrypted truth table byte[] temp = new byte[NBYTESG] ; for (j = 0; j < NBYTESG; j++, k++) temp[j] = info[k] ; encrypted_truth_table.add(temp) ; } if (isAliceOutput()) { // Hashes of Alice codes hcode0 = new byte[NBYTESG]; for (j = 0; j < NBYTESG; j++, k++) hcode0[j] = info[k] ; hcode1 = new byte[NBYTESG]; for (j = 0; j < NBYTESG; j++, k++) hcode1[j] = info[k] ; } return (k - start); // Number of bytes consumed by this gate }
7
protected void sendMergeView(Collection<Address> coords, MergeData combined_merge_data, MergeId merge_id) { if(coords == null || combined_merge_data == null) return; View view=combined_merge_data.view; Digest digest=combined_merge_data.digest; if(view == null || digest == null) { log.error(Util.getMessage("ViewOrDigestIsNullCannotSendConsolidatedMergeView/Digest")); return; } int size=0; if(gms.flushProtocolInStack) { gms.merge_ack_collector.reset(coords); size=gms.merge_ack_collector.size(); } long start=System.currentTimeMillis(); for(Address coord: coords) { Message msg=new Message(coord).setBuffer(GMS.marshal(view, digest)) .putHeader(gms.getId(),new GMS.GmsHeader(GMS.GmsHeader.INSTALL_MERGE_VIEW).mergeId(merge_id)); gms.getDownProtocol().down(msg); } //[JGRP-700] - FLUSH: flushing should span merge; if flush is in stack wait for acks from subview coordinators if(gms.flushProtocolInStack) { try { gms.merge_ack_collector.waitForAllAcks(gms.view_ack_collection_timeout); log.trace("%s: received all ACKs (%d) for merge view %s in %d ms", gms.local_addr, size, view, (System.currentTimeMillis() - start)); } catch(TimeoutException e) { log.warn("%s: failed to collect all ACKs (%d) for merge view %s after %d ms, missing ACKs from %s", gms.local_addr, size, view, gms.view_ack_collection_timeout, gms.merge_ack_collector.printMissing()); } } }
8
public void stepPhysics(double timeStep) { // Collision for (int i = 0; i < COLLISION_ITERATIONS; i++) { collisionBroadphase.updateCollisionPairs(timeStep); processCollisions(timeStep); } // Velocity update for (int i = 0; i < rigidBodies.size(); i++) { RigidBody rigidBody = rigidBodies.get(i); if (rigidBody.dynamicsType == RigidBody.DYNAMIC) { rigidBody.clearForces(); // Effects for (int j = i + 1; j < rigidBodies.size(); j++) { RigidBody rigidBody2 = rigidBodies.get(j); if (rigidBody2.getEffect() != null) { Matrix3d rotation = new Matrix3d(); rotation.set(rigidBody2.getRotation()); Vector3d force = rigidBody2.getEffect().getForceAt( rigidBody2.getPosition(), rotation, rigidBody.getPosition()); rigidBody.addForce(force); } } // Gravity Vector3d force = new Vector3d(gravity); force.scale(rigidBody.getMass()); rigidBody.addForce(force); // Step rigidBody.stepVelocity(timeStep); } } // Contact for (int i = 0; i < CONTACT_ITERATIONS; i++) { collisionBroadphase.updateCollisionPairs(timeStep); processContacts(timeStep); } // Position update for (Iterator<RigidBody> it = rigidBodies.iterator(); it.hasNext();) { RigidBody rigidBody = (RigidBody) it.next(); if (rigidBody.dynamicsType == RigidBody.DYNAMIC) { rigidBody.stepPosition(timeStep); } } // Cleanup collisionBroadphase.clearCollisionPairs(); }
8
public Vector3f checkCollision(Vector3f oldPos, Vector3f newPos, float objectWidth, float objectLength) { Vector2f collisionVector = new Vector2f(1,1); Vector3f movementVector = newPos.sub(oldPos); if(movementVector.length() > 0) { Vector2f blockSize = new Vector2f(SPOT_WIDTH, SPOT_LENGTH); Vector2f objectSize = new Vector2f(objectWidth, objectLength); Vector2f oldPos2 = new Vector2f(oldPos.getX(), oldPos.getZ()); Vector2f newPos2 = new Vector2f(newPos.getX(), newPos.getZ()); for(int i = 0; i < level.getWidth(); i++) for(int j = 0; j < level.getHeight(); j++) if((level.getPixel(i,j) & 0xFFFFFF) == 0) collisionVector = collisionVector.mul(rectCollide(oldPos2, newPos2, objectSize, blockSize.mul(new Vector2f(i,j)), blockSize)); for (Door door : doors) { Vector2f doorSize = door.getDoorSize(); Vector2f doorPos; Vector3f doorPos3 = door.getTransform().getTranslation(); doorPos = new Vector2f(doorPos3.getX(), doorPos3.getZ()); collisionVector = collisionVector.mul(rectCollide(oldPos2, newPos2, objectSize, doorPos, doorSize.normalized())); } } return new Vector3f(collisionVector.getX(), 0, collisionVector.getY()); }
5
private void displayPrevious() { try { refresh(ekd.previous(ek)); } catch (NoPreviousEmailKontaktFoundException e) { JOptionPane.showMessageDialog(this, e.getMessage()); e.printStackTrace(); } }
1
@Test public void runTestActivityLifecycle2() throws IOException { InfoflowResults res = analyzeAPKFile("Lifecycle_ActivityLifecycle2.apk"); Assert.assertEquals(1, res.size()); }
0
private boolean getFirstPlayerTurn() { boolean playersTurn = false; if (gameType == GameType.FairGo) { //Get the user input console = new Scanner(System.in); //Determine whether the player wants to go first System.out.println("Do you want to go first? [Y|N]?\n"); String playFirst = console.next(); System.out.println("<" + playFirst + ">\n"); //Perform error checking for invalid entry while (!playFirst.equalsIgnoreCase("Y") && !playFirst.equalsIgnoreCase("N")) { System.out.println("Error: Please enter either Y or N"); System.out.print("Do you want to go first? [Y|N]?\n"); playFirst = console.next(); System.out.println("<" + playFirst + ">\n"); } //Set whose turn it is playersTurn = (playFirst.equalsIgnoreCase("Y")) ? true : false; } else { //Ask the computer if he wants to go first playersTurn = (gameType == GameType.MissionImpossible) ? !computerFirstTurn(gameType) : true; } String message = (playersTurn) ? "You go first." : "I go first."; System.out.println(message); //Re-initialise the scanner to prevent issues with reading input console = new Scanner(System.in); return playersTurn; }
6
public void removeRole(User user, Role role) throws Exception { try { session = HibernateUtil.getSessionFactory().openSession(); Query q = session.getNamedQuery(getNamedQueryToRemoveRoleUser()); q.setString("role", Integer.toString(role.getId())); q.executeUpdate(); } catch (HibernateException e) { throw new Exception(e.getCause().getLocalizedMessage()); } finally { releaseSession(session); } }
1
public void setMemory(double memory, int index){ this.memory[index] = memory; }
0
public void genBFSEdges() { ArrayList<Edge> tempEdges = new ArrayList<Edge>(); Collection<Node> pairedNodes = new HashSet<Node>(); int radius = 2 * (int) Math.sqrt(widthBound * heightBound / nodes.size()); // Find all local edges by BFS for (Node n : nodes) { for (int x = n.x - radius; x < n.x + radius; x++) { for (int y = n.y - radius; y < n.y + radius; y++) { Node temp = nodeAt(x, y); if (temp != null && !temp.equals(n)) { tempEdges.add(new Edge(n, temp)); pairedNodes.add(n); } } } } // All unpaired nodes make edges to all other nodes for (int i = 0; i < nodes.size(); i++) { Node n = nodes.get(i); if (!pairedNodes.contains(n)) { for (int j = i+1; j < nodes.size(); j++){ tempEdges.add(new Edge(n, nodes.get(j))); } } } // ArrayList -> Array edges = tempEdges.toArray(edges); }
8
public static BookCategoryDO bo2do(BookCategory bookCategory) { if (bookCategory == null) { return null; } BookCategoryDO bookCategoryDO = new BookCategoryDO(); BeanUtils.copyProperties(bookCategory, bookCategoryDO, IGNORE_PARAM); if (bookCategory.getParent() != null) { bookCategoryDO.setParentId(bookCategory.getParent().getId()); } return bookCategoryDO; }
2
public int getUniqueChars() { String uniques = ""; for (int x = 0; x < getWidth(); ++x) { for (int y = 0; y < getHeight(); ++y) { char c = getPixel(x, y); if (!uniques.contains("" + c)) uniques += c; } } return uniques.length(); }
3
private void message(CommandSender sender, String[] args) { if (!sender.hasPermission("graveyard.command.message")) { noPermission(sender); return; } else if (args.length == 1) { commandLine(sender); sender.sendMessage(ChatColor.GRAY + "/graveyard" + ChatColor.WHITE + " message " + ChatColor.RED + "Spawn Message"); sender.sendMessage(ChatColor.WHITE + "Changes the respawn message of the closest spawn point."); commandLine(sender); return; } Player player = (Player) sender; String message = GraveyardUtils.makeString(args); Spawn closest = SpawnPoint.getClosestAllowed(player); if (closest == null) { commandLine(sender); sender.sendMessage(ChatColor.GRAY + "/graveyard" + ChatColor.WHITE + " message " + ChatColor.RED + "Spawn Message"); sender.sendMessage(ChatColor.WHITE + "Changes the respawn message of the closest spawn point."); commandLine(sender); return; } closest.setSpawnMessage(message); player.sendMessage(ChatColor.GRAY + closest.getName() + ChatColor.WHITE + " respawn message set to " + ChatColor.GREEN + message); SpawnPoint.save(closest); return; }
3
@Override public Object clone() throws CloneNotSupportedException { ObjectGroup clone = (ObjectGroup) super.clone(); clone.objects = new LinkedList<MapObject>(); for (MapObject object : objects) { final MapObject objectClone = (MapObject) object.clone(); clone.objects.add(objectClone); objectClone.setObjectGroup(clone); } return clone; }
1
public final void cleanUp() { Bucket died; while ((died = (Bucket) queue.poll()) != null) { int diedSlot = Math.abs(died.hash % buckets.length); if (buckets[diedSlot] == died) buckets[diedSlot] = died.next; else { Bucket b = buckets[diedSlot]; while (b.next != died) b = b.next; b.next = died.next; } size--; } }
3
public boolean canDo(char symbol) { if (symbol == '}') return true; return false; }
1
private void search(int k) { if(k == 0) { results.clear(); active = true; } if(k == max - known || (root.getLeft() == root && root.getRight() == root)) { active = false; for(Node n: results) out.add(new Node(n.getRow(), n.getRoot())); return; } Node col = root.getRight(); cover(col); for(Node rowNode = col.getDown(); rowNode != col && active; rowNode = rowNode.getDown()) { results.add(rowNode); for(Node rightNode = rowNode.getRight(); rightNode != rowNode; rightNode = rightNode.getRight()) cover(rightNode.getRoot()); search(k + 1); for(Node rightNode = rowNode.getRight(); rightNode != rowNode; rightNode = rightNode.getRight()) uncover(rightNode.getRoot()); results.remove(rowNode); } uncover(col); }
9
public int play() { int clipIdx = -1; // Check if there are currently any free clips to play if (clipAssembly[nextPlaybackIdx].isRunning() == false) { clipIdx = nextPlaybackIdx; clipAssembly[clipIdx].setFramePosition(0); // If needed alter the playback volume if (alterNextClipVolume) { if (clipAssembly[clipIdx].isControlSupported( FloatControl.Type.MASTER_GAIN) == false) { throw new IllegalStateException("SoundAssetAssembly.play: " + "The stored clip does not support volume changes."); } FloatControl gainControl = (FloatControl) clipAssembly[clipIdx].getControl( FloatControl.Type.MASTER_GAIN ); float volumeRange = gainControl.getMaximum() - gainControl.getMinimum(); float newGain = volumeRange * nextClipVolume + gainControl.getMinimum(); gainControl.setValue(newGain); } // If needed alter the playback pan if (alterNextClipPan) { if (clipAssembly[clipIdx].isControlSupported(FloatControl.Type.PAN)) { FloatControl panControl = (FloatControl) clipAssembly[clipIdx].getControl( FloatControl.Type.PAN ); panControl.setValue(nextClipPan); } else if (clipAssembly[clipIdx].isControlSupported( FloatControl.Type.BALANCE)) { FloatControl balControl = (FloatControl) clipAssembly[clipIdx].getControl( FloatControl.Type.BALANCE ); balControl.setValue(nextClipPan); } else { throw new IllegalStateException("" + "SoundAssetAssembly.play: " + "Cannot change pan or balance on loaded clip."); } } clipAssembly[clipIdx].start(); // Move onto the next clip in the playback sequence nextPlaybackIdx = (nextPlaybackIdx + 1) % clipAssembly.length; } else { // If the next clip is already playing, then it is stopped and // the play request reissued. clipAssembly[nextPlaybackIdx].stop(); clipIdx = play(); } // Irrespective of weither a clip was selected for playback, reset the // next clip and next pan changes to false. alterNextClipVolume = false; alterNextClipPan = false; return clipIdx; }
6
public void genererLabel() { Iterator it = listeBus.iterator(); int compteurCritique = 0; int compteurInte = 0; while(it.hasNext()) { Bus myBus = (Bus) it.next(); if(myBus.getVitesse() < 10) compteurCritique++; else if(myBus.getVitesse() < 30) compteurInte++; JLabel lab = new JLabel(new ImageIcon("res/icon_autobus.gif")); lab.setSize(50,50); lab.setLocation((myBus.getPosition()[0])-(lab.getWidth()/2), (myBus.getPosition()[1])-(lab.getHeight()/2)); labelBus.add(lab); } if(compteurCritique >= 2) this.setEtatTraffic("Critique"); else if(compteurInte >= 2) this.setEtatTraffic("Intermediaire"); else this.setEtatTraffic("Normal"); System.out.println("nb Bus : "+labelBus.size()); }
5
protected CoderResult encodeLoop(CharBuffer in, ByteBuffer out) { while (in.remaining() > 0) { if (out.remaining() < 1) { return CoderResult.OVERFLOW; } final char c = in.get(); if (c >= 0 && c < 256) { out.put((byte) c); } else { return CoderResult.unmappableForLength(1); } } return CoderResult.UNDERFLOW; }
4
static boolean isOverridden(Method method, Method other) { if (method.getDeclaringClass() == other.getDeclaringClass()) { return false; } if (other.getDeclaringClass().isAssignableFrom(method.getDeclaringClass()) == false) { return false; } if (Objects.equals(method.getName(), other.getName()) == false) { return false; } if (Arrays.equals(method.getParameterTypes(), other.getParameterTypes()) == false) { return false; } if (Modifier.isPrivate(other.getModifiers())) { return false; } if (Modifier.isProtected(other.getModifiers()) == false && Modifier.isPublic(other.getModifiers()) == false && Objects.equals(method.getDeclaringClass().getPackage(), other.getDeclaringClass().getPackage()) == false) { return false; } return true; }
8
public static int spaceCount(String s) { if (s.length() == 0) { return 0; } int count = 0; char c[] = s.toCharArray(); for (int i = 0; i < s.length(); i++) { if (c[i] == ' ') { count++; } } return count; }
3
public void addEffect(Player p, PotionEffectType potion) { if (!isValidWorld(p) || isExempt(p) || !isEnabled()) return; ConfigurationSection section = plugin.getConfig().getConfigurationSection("effects." + potion.getName().toLowerCase()); if (section == null) return; // If the hunger isn't the right amount, return. if (p.getFoodLevel() != section.getInt("hunger-at-activation")) return; int amplifier = section.getInt("amplifier"); // Multiply by 20 because potion effect duration is in ticks. int duration = section.getInt("duration") * 20; // If either of the numbers are "null" (0), set them to a default. if (duration == 0) duration = 100; if (amplifier == 0) amplifier = 1; p.addPotionEffect(new PotionEffect(potion, duration, amplifier)); p.playSound(p.getLocation(), Sound.AMBIENCE_THUNDER, 2.5F, 2.5F); p.sendMessage(ChatColor.translateAlternateColorCodes('&', section.getString("message"))); }
7
final void method1524() { int i = getSpriteWidth(); int i_113_ = getIndexHeightTotal(); if (((ImageSprite) this).indexWidth != i || ((ImageSprite) this).indexHeight != i_113_) { byte[] is = new byte[i * i_113_]; if (((ImageSprite) this).alphaIndex != null) { byte[] is_114_ = new byte[i * i_113_]; for (int i_115_ = 0; i_115_ < ((ImageSprite) this).indexHeight; i_115_++) { int i_116_ = i_115_ * ((ImageSprite) this).indexWidth; int i_117_ = ((i_115_ + ((ImageSprite) this).heightOffset) * i + ((ImageSprite) this).widthOffset); for (int i_118_ = 0; i_118_ < ((ImageSprite) this).indexWidth; i_118_++) { is[i_117_] = ((ImageSprite) this).colorIndex[i_116_]; is_114_[i_117_++] = ((ImageSprite) this).alphaIndex[i_116_++]; } } ((ImageSprite) this).alphaIndex = is_114_; } else { for (int i_119_ = 0; i_119_ < ((ImageSprite) this).indexHeight; i_119_++) { int i_120_ = i_119_ * ((ImageSprite) this).indexWidth; int i_121_ = ((i_119_ + ((ImageSprite) this).heightOffset) * i + ((ImageSprite) this).widthOffset); for (int i_122_ = 0; i_122_ < ((ImageSprite) this).indexWidth; i_122_++) is[i_121_++] = ((ImageSprite) this).colorIndex[i_120_++]; } } ((ImageSprite) this).widthOffset = ((ImageSprite) this).widthPadding = ((ImageSprite) this).heightOffset = ((ImageSprite) this).heightPadding = 0; ((ImageSprite) this).indexWidth = i; ((ImageSprite) this).indexHeight = i_113_; ((ImageSprite) this).colorIndex = is; } }
7
public PrefixTree(char[] letter, double frequency[]) { pq = new PriorityQueue<PrefixTreeNode>(); for (int i = 0; i < letter.length; i++) pq.add(new PrefixTreeLeaf(letter[i], frequency[i])); while (pq.size() > 1) { PrefixTreeNode left = pq.remove(); PrefixTreeNode right = pq.remove(); pq.add(new PrefixTreeNode(left, right)); } root = pq.remove(); code = new HashMap<Character, String>(); calculatePrefixCode(root, new String("")); }
2
public static BaseProperties stringToProperties(String propString){ BaseProperties result = new BaseProperties(); if (null == propString) return result; InputStream is = new ByteArrayInputStream(propString.getBytes()); try { result.load(is); } catch (IOException e) { LOG.error("Caught IO exception while trying to load properties from record:" + e.getLocalizedMessage() + " because of:" + e.getCause()); } return result; }
2
public void visitInsn(final int opcode) { minSize += 1; maxSize += 1; if (mv != null) { mv.visitInsn(opcode); } }
1
public LinkedList<instant> getMicrobiologicalInstants(int subject_id, int itemid1, int itemid2, int itemid3, String tableName, boolean negated, LinkedList<Attribute> attributes, IntervalDescription intDesc) throws ParseException { LinkedList<instant> instants = new LinkedList<instant>(); if(!meetsAttributes(subject_id, attributes)) { return instants; } Statement stmt = null; ResultSet rs = null; //String sqlQuery = "select * from microbiologyevents where subject_id = " + subject_id + " and spec_itemid = " + itemid1 + " and org_itemid = " + itemid2 + " and ab_itemid = " + itemid3; String sqlQuery = "select * from microbiologyevents where subject_id = " + subject_id + " and spec_itemid = " + itemid1; String colName = ""; if(!intDesc.category.equalsIgnoreCase("ANY")) { if(intDesc.category.equalsIgnoreCase("POSITIVE")) { sqlQuery = sqlQuery + " and isolate_num > 0"; } else { sqlQuery = sqlQuery + " and isolate_num = 0"; } } sqlQuery += " order by charttime asc"; System.out.println(sqlQuery); try { stmt = connection.createStatement(); rs = stmt.executeQuery(sqlQuery); // or alternatively, if you don't know ahead of time that // the query will be a SELECT... if (stmt.execute(sqlQuery)) { rs = stmt.getResultSet(); } while (rs.next()) { //labresult(String name, double result, String date, double lower_limit, double upper_limit) SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss"); String dateInString = rs.getString("charttime"); java.util.Date date = sdf.parse(dateInString); int isolation_num = rs.getInt("isolate_num"); String category = "POSITIVE"; if(isolation_num == 0) { category = "NEGATIVE"; } String instantIdentifier = rs.getString("spec_itemid") + " - " + rs.getString("org_itemid") + " - " + rs.getString("ab_itemid"); instant instant = new instant(subject_id, instantIdentifier, category, null, date, intDesc); instants.add(instant); } } catch (SQLException ex) { // handle any errors System.out.println("SQLException on GetMicrobiologicalInstants"); System.out.println("SQLException: " + ex.getMessage()); System.out.println("SQLState: " + ex.getSQLState()); System.out.println("VendorError: " + ex.getErrorCode()); System.out.println(sqlQuery); } finally { // it is a good idea to release // resources in a finally{} block // in reverse-order of their creation // if they are no-longer needed if (rs != null) { try { rs.close(); } catch (SQLException sqlEx) { } // ignore rs = null; } } return instants; }
9
public void close() throws IOException { isClosed = true; }
0
private static void buildValidationUriMsgPane(File file){ if(!file.exists()){ JOptionPane.showMessageDialog( null,"l'uri renseignée n'est pas valide" ,"Validation de l'uri", JOptionPane.INFORMATION_MESSAGE); }else if (!file.isDirectory()){ JOptionPane.showMessageDialog( null,"l'uri renseignée ne désigne pas un repertoire","Validation de l'uri", JOptionPane.INFORMATION_MESSAGE); }else{ JOptionPane.showMessageDialog( null,"l'uri renseignée désigne bien un repertoire","Validation de l'uri", JOptionPane.INFORMATION_MESSAGE); } }
2
private void btnEditarFuncionarioSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarFuncionarioSalvarActionPerformed try { if (JOptionPane.showConfirmDialog(rootPane, "Deseja Salvar?") == 0) { carregaObjeto(); if (dao.Salvar(funcionario,0)) { JOptionPane.showMessageDialog(rootPane, "Salvo com sucesso!"); //Chamar NOVAMENTE a janela de listagem de Produtos frmFuncionarioListar janela = new frmFuncionarioListar(); this.getParent().add(janela); janela.setVisible(true); this.setVisible(false); } else { JOptionPane.showMessageDialog(rootPane, "Falha ao salvar! Consulte o administrador do sistema!"); } } else { JOptionPane.showMessageDialog(rootPane, "Operação cancelada!"); } } catch (Exception ex) { JOptionPane.showMessageDialog(rootPane, "Erro ao salvar! Consulte o administrador do sistema!"); } }//GEN-LAST:event_btnEditarFuncionarioSalvarActionPerformed
3
public void addItemDesc(int i, String in, int size) { if (item_desc == null) { item_desc = new String[size]; } item_desc[i] = in; }
1
private static void checkTokenName(String namedOutput) { if (namedOutput == null || namedOutput.length() == 0) { throw new IllegalArgumentException( "Name cannot be NULL or emtpy"); } for (char ch : namedOutput.toCharArray()) { if ((ch >= 'A') && (ch <= 'Z')) { continue; } if ((ch >= 'a') && (ch <= 'z')) { continue; } if ((ch >= '0') && (ch <= '9')) { continue; } throw new IllegalArgumentException( "Name cannot be have a '" + ch + "' char"); } }
9
private static int rpnParse(Object[] parsedQuery, int position) throws ParseException { Object curr = parsedQuery[position]; int tokens = 1; if (curr instanceof Expression) { int numArgs = ((Expression) curr).getArgumentCount(); List args = new ArrayList(numArgs); for (int a = 0; a < numArgs; a++) { int currArgIndex = position + tokens; if ((currArgIndex) >= parsedQuery.length) { throw new ParseException("Token at position " + position + " has argument " + (a+1) + " of " + numArgs + " which is calculated to be at position " + currArgIndex + ", which beyond the parsed list of query tokens"); } tokens += rpnParse(parsedQuery, currArgIndex); args.add(new Integer(currArgIndex)); } if (curr instanceof Operator) { Operator op = (Operator) curr; Expression[] eargs = new Expression[numArgs]; for(int a = 0; a < numArgs; a++) { Integer index = (Integer) args.get(a); Object arg = parsedQuery[index.intValue()]; if (!(arg instanceof Expression)) throw new ParseException("Token at position " + position + " has argument " + (a+1) + " of " + numArgs + ", calculated to be at position " + index + ", which is expected to be an expression token, but is instead a literal string: " + arg); eargs[a] = (Expression) arg; } op.setChildExpressions(eargs); } else if (curr instanceof Function) { Function func = (Function) curr; String[] sargs = new String[numArgs]; for(int a = 0; a < numArgs; a++) { Integer index = (Integer) args.get(a); Object arg = parsedQuery[index.intValue()]; if (arg instanceof Expression) throw new ParseException("Token at position " + position + " has argument " + (a+1) + " of " + numArgs + ", calculated to be at position " + index + ", which is expected to be literal string, but is instead an expression token: " + arg); sargs[a] = arg.toString(); } func.setArguments(sargs); } } return tokens; }
9
public static boolean is_win() throws FileNotFoundException { if (ifWin == 0) { return false; } else if (win) { return true; } if ((FieldGame.unknown == 0 && ifWin == -1) || (FieldGame.objects == ifWin)) { System.out.println("main: game is finish"); Gui.writeStatus(); win = true; return true; } return false; }
5
private static void fillOneDimArray(Object array, String[] values, IAutoConfigParser<?> parser, IAutoConfigValidator<?> validator) throws Exception { for (int i = 0;i < values.length;++ i) { String valueString = PATTERN_ELEMENT_ESCAPES.matcher(values[i]).replaceAll("$1"); Object value; if (parser.getClass() != NullParser.class) { value = parser.parse(valueString); } else { value = doValueOfConversion(valueString, array.getClass().getComponentType()); } if (validator.getClass() != NullValidator.class) { validator.getClass().getMethod("validate", array.getClass().getComponentType()).invoke(validator, value); } Array.set(array, i, value); } }
5
private void btnSaveMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnSaveMousePressed ArrayList<String> errors = getValidationErrors(); if (!errors.isEmpty()){ String errorMsg = "Please fix the following errors:\n"; for (String error : errors) { errorMsg += error + ", \n"; } JOptionPane.showMessageDialog(null, errorMsg); return; } else { //Create the new profile String username = txtUsername.getText(); boolean isRightHanded = ((String)cbHanded.getSelectedItem()).compareTo("Left Handed") != 0; Manager.getInstance().getProfiles().put(username, new Profile( username, txtDisplayName.getText(), new Date(Integer.parseInt(txtStartDate.getText())), isRightHanded, txtFavoriteDisc.getText(), txtFavoriteCourse.getText(), 0, (int) spnHolesInOne.getValue(), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 )); } }
2
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(frmPitagoras.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(frmPitagoras.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(frmPitagoras.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(frmPitagoras.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 frmPitagoras().setVisible(true); } }); }
6
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Organism)) { return false; } Organism other = (Organism) object; if ((this.key == null && other.key != null) || (this.key != null && !this.key.equals(other.key))) { return false; } return true; }
5
public static void main(String args[]) { System.out.println("Client..."); try { AuctionClient client = new AuctionClient(AuctionServer.SERVER_HOST); String CurLine, ownerName, itemName, itemDesc, tmp; double bid, maxbid; int auctionTime, strategy; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); while (true) { client.printHelp(); System.out.print("> "); CurLine = in.readLine(); switch (CurLine) { case "1": System.out.println("Put Owner name"); ownerName = in.readLine(); System.out.println("Put Item name"); itemName = in.readLine(); System.out.println("Put Item description"); itemDesc = in.readLine(); System.out.println("Put Starting bid"); bid = Double.parseDouble(in.readLine()); System.out.println("Put Maximum bid"); maxbid = Integer.parseInt(in.readLine()); System.out.println("Put Time of auction (sec)"); auctionTime = Integer.parseInt(in.readLine()); client.placeItemForBid(ownerName, itemName, itemDesc, bid, maxbid, auctionTime); break; case "2": System.out.println("Put Owner name"); ownerName = in.readLine(); System.out.println("Put Item name"); itemName = in.readLine(); System.out.println("Put bid"); bid = Double.parseDouble(in.readLine()); client.bidOnItem(ownerName, itemName, bid); break; case "3": client.getItems(); break; case "4": System.out.println("Put Item name"); itemName = in.readLine(); System.out.println("Choose one of the bidding strategies:"); System.out.println("0 - Manual"); System.out.println("1 - BidAndRoll"); System.out.println("2 - WaitAndBid"); strategy = Integer.parseInt(in.readLine()); client.registerListener(itemName, strategy); break; } } } catch (MalformedURLException ex) { System.err.println(args[0] + " is not a valid RMI URL"); System.err.println("Quitting the application..."); System.exit(1); } catch (RemoteException ex) { System.err.println("Remote object threw exception " + ex.getCause()); System.err.println("Quitting the application..."); System.exit(1); } catch (NotBoundException ex) { System.err.println("Could not find the requested remote object on the server"); System.err.println("Quitting the application..."); System.exit(1); } catch (IOException ex) { System.err.println("Error while IO operation."); System.err.println("Quitting the application..."); System.exit(1); } }
9
protected void addHelpFileContents(Content contentTree) { Content heading = HtmlTree.HEADING(HtmlConstants.TITLE_HEADING, false, HtmlStyle.title, getResource("doclet.Help_line_1")); Content div = HtmlTree.DIV(HtmlStyle.header, heading); Content line2 = HtmlTree.DIV(HtmlStyle.subTitle, getResource("doclet.Help_line_2")); div.addContent(line2); contentTree.addContent(div); HtmlTree ul = new HtmlTree(HtmlTag.UL); ul.addStyle(HtmlStyle.blockList); if (configuration.createoverview) { Content overviewHeading = HtmlTree.HEADING(HtmlConstants.CONTENT_HEADING, getResource("doclet.Overview")); Content liOverview = HtmlTree.LI(HtmlStyle.blockList, overviewHeading); Content line3 = getResource("doclet.Help_line_3", getHyperLink(DocPaths.OVERVIEW_SUMMARY, configuration.getText("doclet.Overview"))); Content overviewPara = HtmlTree.P(line3); liOverview.addContent(overviewPara); ul.addContent(liOverview); } Content packageHead = HtmlTree.HEADING(HtmlConstants.CONTENT_HEADING, getResource("doclet.Package")); Content liPackage = HtmlTree.LI(HtmlStyle.blockList, packageHead); Content line4 = getResource("doclet.Help_line_4"); Content packagePara = HtmlTree.P(line4); liPackage.addContent(packagePara); HtmlTree ulPackage = new HtmlTree(HtmlTag.UL); ulPackage.addContent(HtmlTree.LI( getResource("doclet.Interfaces_Italic"))); ulPackage.addContent(HtmlTree.LI( getResource("doclet.Classes"))); ulPackage.addContent(HtmlTree.LI( getResource("doclet.Enums"))); ulPackage.addContent(HtmlTree.LI( getResource("doclet.Exceptions"))); ulPackage.addContent(HtmlTree.LI( getResource("doclet.Errors"))); ulPackage.addContent(HtmlTree.LI( getResource("doclet.AnnotationTypes"))); liPackage.addContent(ulPackage); ul.addContent(liPackage); Content classHead = HtmlTree.HEADING(HtmlConstants.CONTENT_HEADING, getResource("doclet.Help_line_5")); Content liClass = HtmlTree.LI(HtmlStyle.blockList, classHead); Content line6 = getResource("doclet.Help_line_6"); Content classPara = HtmlTree.P(line6); liClass.addContent(classPara); HtmlTree ul1 = new HtmlTree(HtmlTag.UL); ul1.addContent(HtmlTree.LI( getResource("doclet.Help_line_7"))); ul1.addContent(HtmlTree.LI( getResource("doclet.Help_line_8"))); ul1.addContent(HtmlTree.LI( getResource("doclet.Help_line_9"))); ul1.addContent(HtmlTree.LI( getResource("doclet.Help_line_10"))); ul1.addContent(HtmlTree.LI( getResource("doclet.Help_line_11"))); ul1.addContent(HtmlTree.LI( getResource("doclet.Help_line_12"))); liClass.addContent(ul1); HtmlTree ul2 = new HtmlTree(HtmlTag.UL); ul2.addContent(HtmlTree.LI( getResource("doclet.Nested_Class_Summary"))); ul2.addContent(HtmlTree.LI( getResource("doclet.Field_Summary"))); ul2.addContent(HtmlTree.LI( getResource("doclet.Constructor_Summary"))); ul2.addContent(HtmlTree.LI( getResource("doclet.Method_Summary"))); liClass.addContent(ul2); HtmlTree ul3 = new HtmlTree(HtmlTag.UL); ul3.addContent(HtmlTree.LI( getResource("doclet.Field_Detail"))); ul3.addContent(HtmlTree.LI( getResource("doclet.Constructor_Detail"))); ul3.addContent(HtmlTree.LI( getResource("doclet.Method_Detail"))); liClass.addContent(ul3); Content line13 = getResource("doclet.Help_line_13"); Content para = HtmlTree.P(line13); liClass.addContent(para); ul.addContent(liClass); //Annotation Types Content aHead = HtmlTree.HEADING(HtmlConstants.CONTENT_HEADING, getResource("doclet.AnnotationType")); Content liAnnotation = HtmlTree.LI(HtmlStyle.blockList, aHead); Content aline1 = getResource("doclet.Help_annotation_type_line_1"); Content aPara = HtmlTree.P(aline1); liAnnotation.addContent(aPara); HtmlTree aul = new HtmlTree(HtmlTag.UL); aul.addContent(HtmlTree.LI( getResource("doclet.Help_annotation_type_line_2"))); aul.addContent(HtmlTree.LI( getResource("doclet.Help_annotation_type_line_3"))); aul.addContent(HtmlTree.LI( getResource("doclet.Annotation_Type_Required_Member_Summary"))); aul.addContent(HtmlTree.LI( getResource("doclet.Annotation_Type_Optional_Member_Summary"))); aul.addContent(HtmlTree.LI( getResource("doclet.Annotation_Type_Member_Detail"))); liAnnotation.addContent(aul); ul.addContent(liAnnotation); //Enums Content enumHead = HtmlTree.HEADING(HtmlConstants.CONTENT_HEADING, getResource("doclet.Enum")); Content liEnum = HtmlTree.LI(HtmlStyle.blockList, enumHead); Content eline1 = getResource("doclet.Help_enum_line_1"); Content enumPara = HtmlTree.P(eline1); liEnum.addContent(enumPara); HtmlTree eul = new HtmlTree(HtmlTag.UL); eul.addContent(HtmlTree.LI( getResource("doclet.Help_enum_line_2"))); eul.addContent(HtmlTree.LI( getResource("doclet.Help_enum_line_3"))); eul.addContent(HtmlTree.LI( getResource("doclet.Enum_Constant_Summary"))); eul.addContent(HtmlTree.LI( getResource("doclet.Enum_Constant_Detail"))); liEnum.addContent(eul); ul.addContent(liEnum); if (configuration.classuse) { Content useHead = HtmlTree.HEADING(HtmlConstants.CONTENT_HEADING, getResource("doclet.Help_line_14")); Content liUse = HtmlTree.LI(HtmlStyle.blockList, useHead); Content line15 = getResource("doclet.Help_line_15"); Content usePara = HtmlTree.P(line15); liUse.addContent(usePara); ul.addContent(liUse); } if (configuration.createtree) { Content treeHead = HtmlTree.HEADING(HtmlConstants.CONTENT_HEADING, getResource("doclet.Help_line_16")); Content liTree = HtmlTree.LI(HtmlStyle.blockList, treeHead); Content line17 = getResource("doclet.Help_line_17_with_tree_link", getHyperLink(DocPaths.OVERVIEW_TREE, configuration.getText("doclet.Class_Hierarchy")), HtmlTree.CODE(new StringContent("java.lang.Object"))); Content treePara = HtmlTree.P(line17); liTree.addContent(treePara); HtmlTree tul = new HtmlTree(HtmlTag.UL); tul.addContent(HtmlTree.LI( getResource("doclet.Help_line_18"))); tul.addContent(HtmlTree.LI( getResource("doclet.Help_line_19"))); liTree.addContent(tul); ul.addContent(liTree); } if (!(configuration.nodeprecatedlist || configuration.nodeprecated)) { Content dHead = HtmlTree.HEADING(HtmlConstants.CONTENT_HEADING, getResource("doclet.Deprecated_API")); Content liDeprecated = HtmlTree.LI(HtmlStyle.blockList, dHead); Content line20 = getResource("doclet.Help_line_20_with_deprecated_api_link", getHyperLink(DocPaths.DEPRECATED_LIST, configuration.getText("doclet.Deprecated_API"))); Content dPara = HtmlTree.P(line20); liDeprecated.addContent(dPara); ul.addContent(liDeprecated); } if (configuration.createindex) { Content indexlink; if (configuration.splitindex) { indexlink = getHyperLink(DocPaths.INDEX_FILES.resolve(DocPaths.indexN(1)), configuration.getText("doclet.Index")); } else { indexlink = getHyperLink(DocPaths.INDEX_ALL, configuration.getText("doclet.Index")); } Content indexHead = HtmlTree.HEADING(HtmlConstants.CONTENT_HEADING, getResource("doclet.Help_line_21")); Content liIndex = HtmlTree.LI(HtmlStyle.blockList, indexHead); Content line22 = getResource("doclet.Help_line_22", indexlink); Content indexPara = HtmlTree.P(line22); liIndex.addContent(indexPara); ul.addContent(liIndex); } Content prevHead = HtmlTree.HEADING(HtmlConstants.CONTENT_HEADING, getResource("doclet.Help_line_23")); Content liPrev = HtmlTree.LI(HtmlStyle.blockList, prevHead); Content line24 = getResource("doclet.Help_line_24"); Content prevPara = HtmlTree.P(line24); liPrev.addContent(prevPara); ul.addContent(liPrev); Content frameHead = HtmlTree.HEADING(HtmlConstants.CONTENT_HEADING, getResource("doclet.Help_line_25")); Content liFrame = HtmlTree.LI(HtmlStyle.blockList, frameHead); Content line26 = getResource("doclet.Help_line_26"); Content framePara = HtmlTree.P(line26); liFrame.addContent(framePara); ul.addContent(liFrame); Content allclassesHead = HtmlTree.HEADING(HtmlConstants.CONTENT_HEADING, getResource("doclet.All_Classes")); Content liAllClasses = HtmlTree.LI(HtmlStyle.blockList, allclassesHead); Content line27 = getResource("doclet.Help_line_27", getHyperLink(DocPaths.ALLCLASSES_NOFRAME, configuration.getText("doclet.All_Classes"))); Content allclassesPara = HtmlTree.P(line27); liAllClasses.addContent(allclassesPara); ul.addContent(liAllClasses); Content sHead = HtmlTree.HEADING(HtmlConstants.CONTENT_HEADING, getResource("doclet.Serialized_Form")); Content liSerial = HtmlTree.LI(HtmlStyle.blockList, sHead); Content line28 = getResource("doclet.Help_line_28"); Content serialPara = HtmlTree.P(line28); liSerial.addContent(serialPara); ul.addContent(liSerial); Content constHead = HtmlTree.HEADING(HtmlConstants.CONTENT_HEADING, getResource("doclet.Constants_Summary")); Content liConst = HtmlTree.LI(HtmlStyle.blockList, constHead); Content line29 = getResource("doclet.Help_line_29", getHyperLink(DocPaths.CONSTANT_VALUES, configuration.getText("doclet.Constants_Summary"))); Content constPara = HtmlTree.P(line29); liConst.addContent(constPara); ul.addContent(liConst); Content divContent = HtmlTree.DIV(HtmlStyle.contentContainer, ul); Content line30 = HtmlTree.SPAN(HtmlStyle.emphasizedPhrase, getResource("doclet.Help_line_30")); divContent.addContent(line30); contentTree.addContent(divContent); }
7
@Override public void open() throws MidiUnavailableException { if (!initialized) throw new MidiUnavailableException(); for (Synthesizer s : theSynths) s.open(); }
2
public static RefType forID(int refTypeID) { for (RefType refType : values()) { if (refType.getId() == refTypeID) return refType; } return null; }
2
public void evaluate(int trainItem, int testItem){ String DataDirectory = "RandomPieces_200"; String opticsFilename = "ids200_" + trainItem + "-" + testItem + ".optics"; ArrayList<ReachabilityPoint> ordering = OpticsOrderingReader.readFile(DataDirectory + File.separatorChar+opticsFilename); int minpts = 200; double xi = 0.2; ArrayList<SteepArea> areas1 = findSteepAreas2(ordering, minpts ,xi); ArrayList<SteepArea> clusters = extractClusters(areas1, ordering, minpts, xi); OpticsPlot.plotGraphAreas("Clusters", ordering, clusters); for (int i = 0; i < areas1.size(); i++) { System.out.println("Area "+i+ "\tS:" + areas1.get(i).startIndex + "\tE:"+ areas1.get(i).endIndex + "\tsize: "+( areas1.get(i).endIndex- areas1.get(i).startIndex+1)); } for (int i = 0; i < clusters.size(); i++) { System.out.println(i+"\t" + clusters.get(i).startIndex + "\t" + + clusters.get(i).endIndex); } if(true) return; MinHeap SteepAreaList = findSteepAreas(ordering, 0.1); //assigns value to SteepAreaList //write to file ArrayList<SteepArea> areas = getAreas(SteepAreaList); //areas including flat areas /**PRINT AREAS**/ for (int i = 0; i < areas.size(); i++) { SteepArea steeparea = areas.get(i); System.out.print("SteepArea: \t"+steeparea.startIndex+" \t" + steeparea.endIndex + "\t"); if(steeparea.isFlat){ System.out.println("FLAT"); }else if(steeparea.isSteepUp && !steeparea.isFlat){ System.out.println("UP"); }else if(!steeparea.isSteepUp && !steeparea.isFlat){ System.out.println("DOWN"); } } OpticsPlot.plotGraphAreas("Eval", ordering, areas); // ordering = assignToCluster(ordering,areas); //fill values of assignedLabel Field // // // getAccuracy(ordering); // // System.out.println("Accuracy"); // //write to file //evaluate accuracy }
9
public static void write(final INode node, final Writer writer) throws IOException { if (node == null) { return; } if (node instanceof Text) { writeText((Text)node, writer); return; } if (node instanceof Element) { writeElement((Element)node, writer); return; } if (node instanceof Comment) { writeComment((Comment)node, writer); return; } if (node instanceof CDATASection) { writeCDATASection((CDATASection)node, writer); return; } if (node instanceof DocType) { writeDocType((DocType)node, writer); return; } if (node instanceof Document) { writeDocument((Document)node, writer); return; } if (node instanceof XmlDeclaration) { writeXmlDeclaration((XmlDeclaration)node, writer); return; } if (node instanceof ProcessingInstruction) { writeProcessingInstruction((ProcessingInstruction)node, writer); return; } }
9
public void removeSettingsGuiListener(SettingsGuiListener listener_) { settingsGuiListener.remove(listener_); }
0
static String getInput(Scanner scanner){ StringBuilder a=new StringBuilder(); String temp=null; scanner.nextLine();//忽略掉开始的start while (!"END".equals((temp=scanner.nextLine()))){ a.append(temp).append('\n'); } return a.toString(); }
1
private static void readData() { try { b = new BufferedReader(new FileReader(fileDirectory + dataFile)); String line; while ((line = b.readLine()) != null) { String[] s = line.split(":"); int usr = Integer.parseInt(s[0]); int mov = Integer.parseInt(s[2]); int rat = Integer.parseInt(s[4]); if (userMovieRatings.containsKey(usr)) { userMovieRatings.get(usr).put(mov, rat); } else { HashMap<Integer, Integer> ratings = new HashMap<Integer, Integer>(); ratings.put(mov, rat); userMovieRatings.put(usr, ratings); } if (ratingsByMovie.containsKey(mov)) { ratingsByMovie.get(mov).add(rat); } else { ArrayList<Integer> ratings = new ArrayList<Integer>(); ratings.add(rat); ratingsByMovie.put(mov, ratings); } if (usersByMovie.containsKey(mov)) { usersByMovie.get(mov).add(usr); } else { HashSet<Integer> raters = new HashSet<Integer>(); raters.add(usr); usersByMovie.put(mov, raters); } } b.close(); } catch (FileNotFoundException e) { System.err.println("Couldn't read the parameter file. Check the file name: " + dataFile); e.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } }
6
@Override public void setValue(int row, int col, double value) throws MatrixIndexOutOfBoundsException { if ((row < 0) || (col < 0) || (row >= mas.size()) || (col >= mas.get(0).size())) { throw new MatrixIndexOutOfBoundsException("Inadmissible value of an index."); } mas.get(row).set(col, (double) value); }
4
public static Cons idlTranslateMethodParameters(MethodSlot method) { { Cons result = Stella.NIL; Cons directions = Stella.NIL; if (method.methodParameterDirections().emptyP()) { { Symbol name = null; Cons iter000 = method.methodParameterNames().rest(); Cons collect000 = null; for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) { name = ((Symbol)(iter000.value)); name = name; if (collect000 == null) { { collect000 = Cons.cons(Stella.SYM_STELLA_IN, Stella.NIL); if (directions == Stella.NIL) { directions = collect000; } else { Cons.addConsToEndOfConsList(directions, collect000); } } } else { { collect000.rest = Cons.cons(Stella.SYM_STELLA_IN, Stella.NIL); collect000 = collect000.rest; } } } } } else { directions = method.methodParameterDirections().rest(); } { Symbol name = null; Cons iter001 = method.methodParameterNames().rest(); StandardObject type = null; Cons iter002 = method.methodParameterTypeSpecifiers().rest(); Stella_Object direction = null; Cons iter003 = directions; Cons collect001 = null; for (;(!(iter001 == Stella.NIL)) && ((!(iter002 == Stella.NIL)) && (!(iter003 == Stella.NIL))); iter001 = iter001.rest, iter002 = iter002.rest, iter003 = iter003.rest) { name = ((Symbol)(iter001.value)); type = ((StandardObject)(iter002.value)); direction = iter003.value; if (collect001 == null) { { collect001 = Cons.cons(Symbol.idlTranslateMethodParameter(name, type, ((Symbol)(direction))), Stella.NIL); if (result == Stella.NIL) { result = collect001; } else { Cons.addConsToEndOfConsList(result, collect001); } } } else { { collect001.rest = Cons.cons(Symbol.idlTranslateMethodParameter(name, type, ((Symbol)(direction))), Stella.NIL); collect001 = collect001.rest; } } } } return (result); } }
9
public CheckResultMessage checkJ04(int day) { int r1 = get(17, 2); int c1 = get(18, 2); int r2 = get(20, 2); int c2 = get(21, 2); BigDecimal b = new BigDecimal(0); if (checkVersion(file).equals("2003")) { try { in = new FileInputStream(file); hWorkbook = new HSSFWorkbook(in); b = getValue(r2 + day, c2 + 19, 4).add( getValue(r2 + day, c2 + 21, 4)).add( getValue(r2 + day, c2 + 23, 4)); if (0 != getValue(r1 + 3, c1 + 1 + day, 3).compareTo(b)) { return error("支付机构单个账户报表<" + fileName + ">系统未减少银行已减少未达账项余额 J04:" + day + "日错误"); } in.close(); } catch (Exception e) { } } else { try { in = new FileInputStream(file); hWorkbook = new HSSFWorkbook(in); b = getValue1(r2 + day, c2 + 19, 4).add( getValue1(r2 + day, c2 + 21, 4)).add( getValue1(r2 + day, c2 + 23, 4)); if (0 != getValue1(r1 + 3, c1 + 1 + day, 3).compareTo(b)) { return error("支付机构单个账户报表<" + fileName + ">系统未减少银行已减少未达账项余额 J04:" + day + "日错误"); } in.close(); } catch (Exception e) { } } return pass("支付机构单个账户报表<" + fileName + ">系统未减少银行已减少未达账项余额 J04:" + day + "日正确"); }
5
public void setPortServer(int port){ this.portServer = port; }
0
public static Integer[] getImageData(BufferedImage image) { final byte[] pixels = ((DataBufferByte)image.getRaster().getDataBuffer()).getData(); final int width = image.getWidth(); final int height = image.getHeight(); final boolean hasAlphaChannel = image.getAlphaRaster() != null; Integer[] result = new Integer[height * width]; if (hasAlphaChannel){ for (int pixel = 0, row = height - 1, col = 0; pixel < pixels.length; pixel += 4) { int argb = 0; argb += (((int)pixels[pixel] & 0xff) << 24); // alpha argb += ((int)pixels[pixel + 1] & 0xff); // blue argb += (((int)pixels[pixel + 2] & 0xff) << 8); // green argb += (((int)pixels[pixel + 3] & 0xff) << 16); // red result[row * width + col] = argb; col++; if (col == width) { col = 0; row--; } } }else { for (int pixel = 0, row = height - 1, col = 0; pixel < pixels.length; pixel += 3) { int argb = 0; argb += -16777216; // 255 alpha argb += ((int) pixels[pixel] & 0xff); // blue argb += (((int) pixels[pixel + 1] & 0xff) << 8); // green argb += (((int) pixels[pixel + 2] & 0xff) << 16); // red result[row * width + col] = argb; col++; if (col == width) { col = 0; row--; } } } return result; }
5
public static void addLinkInfor(LinkInfo li) { if(!_HEAVY_SCIENCE || (li.getDestinationNode() != 1||li.getSourceNode()!=2)) return; if(labelsSave==null) labelsSave = new LinkedList<String>(); splitUpMetaInfo(li); String name = ""+li.getSourceNode()+"-"+li.getDestinationNode(); if(!informations.containsKey(name)) informations.put(name, new HashMap<Long,HashMap<String,Object>>()); if(!informations.get(name).containsKey(li.getTimestamp())) informations.get(name).put(li.getTimestamp(), new HashMap<String, Object>()); for(Map.Entry<String, Object> s:li.getMetaData().entrySet()) { //System.out.println("Read "+ name + "ts:"+li.getTimestamp() +"s.key:"+s.getKey() + " s.value:"+s.getValue()); if(s.getValue()==null) continue; informations.get(name).get(li.getTimestamp()).put(s.getKey(),s.getValue().toString()); } }
8
private void render() { BufferStrategy bs = getBufferStrategy(); if (bs == null) { createBufferStrategy(3); return; } currentScreen.clear(); currentScreen.render(); for (int i = 0; i < currentScreen.pixels.length; i++) { pixels[i] = currentScreen.pixels[i]; } Graphics g = bs.getDrawGraphics(); g.drawImage(image, 0, 0, getWidth(), getHeight(), null); g.dispose(); bs.show(); }
2
public String getTitle() { return title; }
0
@ Override public boolean writeToFile(final File file, T object, boolean replaceIfExists) { skipRemaining = false; // Delete file if it exists if (file.exists () && replaceIfExists) { file.delete (); } else return false; Path path = Paths.get (file.getAbsolutePath ()); BufferedWriter writer = null; try { // Use BufferedWriter to write to file writer = Files.newBufferedWriter (path, encoding); writer.write (toWriteableString (object)); } catch (IOException e) { e.printStackTrace (); return false; } finally { // Close BufferedWriter if (writer != null) { try { writer.close (); } catch (IOException e) {} } } return true; }
5
private Long getSmallestIdLargerThan(Long currentId) throws SQLException { StringBuilder statement = new StringBuilder(100); statement.append("SELECT "); statement.append(Defaults.ID_COL); statement.append(" FROM "); statement.append(sourceObjectTableName); statement.append(" WHERE "); statement.append(Defaults.ID_COL); statement.append(">"); statement.append(currentId); statement.append(" ORDER BY "); statement.append(Defaults.ID_COL); statement.append(" ASC "); String limitString = source.getAdapter().getLimitString(); limitString = limitString.replaceAll("\\?", "1"); if (source.getAdapter().isPutLimitOffsetBeforeColumns()) { statement.insert(7, limitString); } else { statement.append(limitString); } PreparedStatement ps = sourceCw.prepareStatement(statement.toString()); try { ResultSet res = ps.executeQuery(); if (res.next()) { return res.getLong(1); } return null; } finally { ps.close(); } }
2
public static byte[][][] computeParityTilesFromTileCube(byte[][][] tileCube) { byte[][][] parityTiles = new byte[3][tileCube.length][tileCube.length]; // tile 1 for (int tileIdx = 0; tileIdx < tileCube.length; tileIdx++) { for (int row = 0; row < tileCube.length; row++) { byte parity = 0; for (int col = 0; col < tileCube.length; col++) { parity = (byte)((parity + tileCube[tileIdx][row][col]) & (byte)1); } parityTiles[0][row][tileIdx] = parity; } } // tile 2 for (int row = 0; row < tileCube.length; row++) { for (int col = 0; col < tileCube.length; col++) { byte parity = 0; for (int tileIdx = 0; tileIdx < tileCube.length; tileIdx++) { parity = (byte)((parity + tileCube[tileIdx][row][col]) & (byte)1); } parityTiles[1][row][col] = parity; } } // tile 3 for (int tileIdx = 0; tileIdx < tileCube.length; tileIdx++) { for (int col = 0; col < tileCube.length; col++) { byte parity = 0; for (int row = 0; row < tileCube.length; row++) { parity = (byte)((parity + tileCube[tileIdx][row][col]) & (byte)1); } parityTiles[2][tileIdx][col] = parity; } } return parityTiles; }
9
private Printer03() { }
0
@Override public void setTmp(String value) {this.tmp = value;}
0
private ILevel chooseLevel() { if (getFirstLevels() == null || getFirstLevels().size() == 0) { return null; } if (getFirstLevels().size() == 1) { return getFirstLevels().get(0); } Integer poll = null; printLevels(); while (poll == null || poll < 0 || poll >= getFirstLevels().size()) { poll = InputReader.readInteger(); if (poll < 0 || poll >= getFirstLevels().size()) { Printer.print(Settings_Output.OUT_ERROR, "Option Error", 0, "Option Error", "Option out of index"); continue; } } return getFirstLevels().get(poll); }
8
@Override public StringBuffer getOOXML( String catAxisId, String valAxisId, String serAxisId ) { StringBuffer cooxml = new StringBuffer(); // chart type: contains chart options and series data cooxml.append( "<c:area3DChart>" ); cooxml.append( "\r\n" ); cooxml.append( "<c:grouping val=\"" ); if( is100PercentStacked() ) { cooxml.append( "percentStacked" ); } else if( isStacked() ) { cooxml.append( "stacked" ); } else { cooxml.append( "standard" ); } cooxml.append( "\"/>" ); cooxml.append( "\r\n" ); // vary colors??? // *** Series Data: ser, cat, val for most chart types cooxml.append( getParentChart().getChartSeries().getOOXML( getChartType(), false, 0 ) ); // chart data labels, if any //TODO: FINISH //cooxml.append(getDataLabelsOOXML(cf)); // TODO: get real value int gapdepth = getGapDepth(); // 150 is default if( (gapdepth != 0) && (gapdepth != 150) ) { cooxml.append( "<c:gapDepth val=\"" + gapdepth + "\"/>" ); } //DropLines ChartLine cl = cf.getChartLinesRec(); if( cl != null ) { cooxml.append( cl.getOOXML() ); } // axis ids - unsigned int strings cooxml.append( "<c:axId val=\"" + catAxisId + "\"/>" ); cooxml.append( "\r\n" ); cooxml.append( "<c:axId val=\"" + valAxisId + "\"/>" ); cooxml.append( "\r\n" ); cooxml.append( "<c:axId val=\"" + serAxisId + "\"/>" ); cooxml.append( "\r\n" ); cooxml.append( "</c:area3DChart>" ); cooxml.append( "\r\n" ); return cooxml; }
5
boolean checkValue(int Red, int Green, int Blue){ int maxValue = 1; for(int i = 0; i < bitPerPixel/numOfColorComponents; i++){ int temp = 2; maxValue = maxValue*temp; } maxValue = maxValue - 1 ; if(Red < 0 || Green < 0 || Blue < 0){ System.out.println("�G���[:RGB�l�ɕ��̒l�͎g���Ȃ�"); return false; } if(Red > maxValue || Green > maxValue || Blue > maxValue){ System.out.println("�G���[�F" + bitPerPixel +"bpp�Ȃ̂�RGB�l�̍ő�l��" + maxValue); return false; } return true; }
7
private static void TexasHoldEm() { Table tbl = new Table(); int iPlayers = 5; Deck dStud = new Deck(); // Add the players, give them empty hands for (int i = 0; i < iPlayers; i++) { Player p = new Player("Joe",null); p.SetPlayerNbr(i+1); p.SetHand(new Hand()); tbl.AddTablePlayer(p); } // Two Card in each hand for (int i = 0; i < 2; i++) { for (Player p: tbl.GetTablePlayers()) { Hand h = p.GetHand(); h.setPlayerID(p.GetPlayerID()); h.AddCardToHand(dStud.drawFromDeck()); p.SetHand(h); } } // Draw Community Cards 3 cards. ArrayList<Card> Community = new ArrayList<Card>(); dStud.drawFromDeck(); Community.add(dStud.drawFromDeck()); Community.add(dStud.drawFromDeck()); Community.add(dStud.drawFromDeck()); // Community.add(new Card(eSuit.JOKER,eRank.JOKER)); // Community.add(new Card(eSuit.JOKER,eRank.JOKER)); // Hand BestCommunityHand = Hand.EvalHand(Community); for (Player p: tbl.GetTablePlayers()) { Hand playerHand = new Hand(); if (Community.size() == 3) { for (Card c : Community) { playerHand.AddCardToHand(c); } Hand pHand = p.GetHand(); for (Card c: pHand.getCards()) { playerHand.AddCardToHand(c); } } } }
7
private void fxInitCallbacks() { webEngine.titleProperty().addListener(new ChangeListener<String>() { @Override public void changed( ObservableValue<? extends String> observable, String oldValue, final String newValue ) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if( frameOrDialog == null ) return; String suffix = newValue; if( newValue == null ) suffix = "Verbinde ..."; if( frameOrDialog instanceof Dialog ) { ((Dialog)frameOrDialog).setTitle(titlePrefix + suffix); } else if( frameOrDialog instanceof Frame ) { ((Frame)frameOrDialog).setTitle(titlePrefix + suffix); } } }); } }); webEngine.setOnStatusChanged(new EventHandler<WebEvent<String>>() { @Override public void handle(final WebEvent<String> event) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if( statusLabel == null ) return; statusLabel.setText(event.getData()); } }); } }); }
6
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(JPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(JPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(JPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(JPrincipal.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 JPrincipal().setVisible(true); } }); }
6
public void play(int row, int col) { if (Othello.isReversed(player, opponent, row, col)) { myCanvas.repaint(); score.setText(Othello.getScore()); comment.setText(" "); //Get turn switchPlayer(); if (!Othello.isPossible(player, opponent)) { if (!Othello.isPossible(opponent, player)) { endGame(); return; } else { comment.setText("Oops, "+player+" has no valid move."); switchPlayer(); } } turn.setText("It's "+player+"'s turn."); //Get computer's move if ((computer == 'b' && player == "black") || (computer == 'w' && player == "white")) { getCompMove(); } } else comment.setText("Invalid move. Please try again."); }
7
public List<String> getSampleNames() { if (sampleNames != null) return sampleNames; // Split header String headerLines[] = header.toString().split("\n"); // Find "#CHROM" line in header for (String line : headerLines) { if (line.startsWith("#CHROM")) { chromLine = true; // This line contains all the sample names (starting on column 9) String titles[] = line.split("\t"); // Create a list of names sampleNames = new ArrayList<String>(); for (int i = 9; i < titles.length; i++) sampleNames.add(titles[i]); // Done return sampleNames; } } // Not found return null; }
4
public ArrayList<AreaConhecimento> listar(String condicao) throws Exception { ArrayList<AreaConhecimento> listaAreaConhecimento = new ArrayList<AreaConhecimento>(); String sql = "SELECT * FROM areaconhecimento " + condicao; try { PreparedStatement stmt = ConnectionFactory.getConnection().prepareStatement(sql); ResultSet rs = stmt.executeQuery(); while (rs.next()) { AreaConhecimento areaconhecimento = new AreaConhecimento(); areaconhecimento.setId(rs.getLong("id")); areaconhecimento.setNome(rs.getString("nome")); areaconhecimento.setCiencia(rs.getString("ciencia")); areaconhecimento.setAreaAvaliacao(rs.getString("areaAvaliacao")); listaAreaConhecimento.add(areaconhecimento); } rs.close(); } catch (SQLException e) { throw e; } return listaAreaConhecimento; }
2
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(Acertijo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Acertijo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Acertijo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Acertijo.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 Acertijo().setVisible(true); } }); }
6
private void checkPosition() { StreamsterApiInterfaceProxy proxy = new StreamsterApiInterfaceProxy(); Position[] positions = new Position[0]; try { positions = proxy.getPositions(); } catch (RemoteException ex) { Logger.getLogger(JobTradeUp.class.getName()).log(Level.SEVERE, null, ex); } state = false; for (Position position : positions) { if (position.getStatus().equalsIgnoreCase("OPEN")) { state = true; } } }
3
private static Date getStartDate(HashMap<String, Object> map) { Long startDay = (Long) map.get("startDay"); Long startMon = (Long) map.get("startMonth"); Long startYear = (Long) map.get("startYear"); Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); if (startDay == null) startDay = 1L; cal.set(Calendar.DAY_OF_MONTH, startDay.intValue()); if (startMon == null) startMon = 1L; cal.set(Calendar.MONTH, startMon.intValue() - 1); if (startYear != null) { // No year => no date cal.set(Calendar.YEAR, startYear.intValue()); return cal.getTime(); } return null; }
3
protected void trainModel(InstanceStream trainStream, AbstractClassifier model) { ClassificationPerformanceEvaluator evaluator = new BasicClassificationPerformanceEvaluator(); evaluator.reset(); long instancesProcessed = 0; System.out.println("Started learning the model..."); while (trainStream.hasMoreInstances() && ((MaxInstances < 0) || (instancesProcessed < MaxInstances))) { model.trainOnInstance(trainStream.nextInstance()); instancesProcessed++; if (instancesProcessed % INSTANCES_BETWEEN_MONITOR_UPDATES == 0) { long estimatedRemainingInstances = trainStream .estimatedRemainingInstances(); if (MaxInstances > 0) { long maxRemaining = MaxInstances - instancesProcessed; if ((estimatedRemainingInstances < 0) || (maxRemaining < estimatedRemainingInstances)) { estimatedRemainingInstances = maxRemaining; } } } } }
7
public ArrayList<Person> getPersons() { return Persons; }
0
public GameMaster(Combination<Colors> target) { this.target = target; System.out.print("The target is : "); target.print(); }
0
public final NewFoodContext newFood() throws RecognitionException { NewFoodContext _localctx = new NewFoodContext(_ctx, getState()); enterRule(_localctx, 6, RULE_newFood); int _la; try { enterOuterAlt(_localctx, 1); { setState(56); match(16); setState(57); match(3); setState(60); _errHandler.sync(this); _la = _input.LA(1); do { { setState(60); switch ( getInterpreter().adaptivePredict(_input,5,_ctx) ) { case 1: { setState(58); omistamine(); } break; case 2: { setState(59); match(String); } break; } } setState(62); _errHandler.sync(this); _la = _input.LA(1); } while ( (((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << 5) | (1L << 10) | (1L << 15) | (1L << 17) | (1L << 19) | (1L << 21) | (1L << 23) | (1L << String))) != 0) ); setState(65); _la = _input.LA(1); if (_la==1 || _la==11) { { setState(64); _la = _input.LA(1); if ( !(_la==1 || _la==11) ) { _errHandler.recoverInline(this); } consume(); } } setState(67); match(13); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; }
9
private void generateHardwareSystemAlternativesGeneration() { int alternatives = 1; int possibilities[] = new int[project.getHardwareSets().size()]; int repetitions[] = new int[project.getHardwareSets().size()]; int i = 0; for (HardwareSet hws : project.getHardwareSets()) { alternatives *= hws.getHardwareSetAlternatives().size(); possibilities[i] = hws.getHardwareSetAlternatives().size(); repetitions[i++] = alternatives / hws.getHardwareSetAlternatives().size(); } generateHardwareSystemsGeneration(alternatives, possibilities, repetitions); }
1
public boolean isSameTree(TreeNode p, TreeNode q) { // Start typing your Java solution below // DO NOT write main() function if (p == null && q == null) return true; if (p == null || q == null) return false; if (p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right)) return true; return false; }
7