method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
8b1ed9ab-9a21-46d1-a5c3-b49dc1897b0b
4
public void calculateLineStatistics() { if (codeLineCount == 0) { for (int i = 1; i < lines.size(); i++) if (lines.get(i) != null) { codeLineCount++; if (lines.get(i) > 0) codeLinesCoveredCount++; } } }
434544c2-ede6-4d33-b465-49b9a17a74e8
6
public static double estimateCardinalityOfExtension(NamedDescription description) { if ((description == null) || (!NamedDescription.relationSupportsExtensionP(description))) { return (Stella.NULL_FLOAT); } { int estimate = Description.accessObservedCardinality(description); if ((estimate == Stella.NULL_INTEGER) && (description.extension != null)) { estimate = description.extension.estimatedLength(); } if (estimate == Stella.NULL_INTEGER) { estimate = 0; } return (((double)(Stella.integer_max(estimate, (NamedDescription.classDescriptionP(description) ? ((int)(Logic.ESTIMATED_SIZE_OF_CLASS_EXTENSION)) : ((int)(Logic.ESTIMATED_NUMBER_OF_PREDICATE_BINDINGS * Logic.ESTIMATED_NUMBER_OF_PREDICATE_BINDINGS * Logic.ESTIMATED_NUMBER_OF_PREDICATE_BINDINGS))))))); } }
9e60753b-673f-4fc6-bdd6-b3654ff9619b
7
private static int[] merge(int[] a, int[] b) { int[] c = new int[a.length + b.length]; int indexA = 0, indexB = 0; for (int indexC = 0; indexC < c.length; indexC++) { if (indexA < a.length && (indexB == b.length || a[indexA] <= b[indexB])) c[indexC] = a[indexA++]; else if (indexB < b.length && (indexA == a.length || a[indexA] > b[indexB])) c[indexC] = b[indexB++]; } return c; }
cc381d6a-02ed-4eef-82d1-8e44c826dc18
5
static final private AbsValueNode possible_infixed_expression() throws ParseException, CompilationException { Token t; AbsValueNode v; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case NUMBER: t = jj_consume_token(NUMBER); v = infixed_expression(new NumberVNode(t.image,currentLine)); {if (true) return v;} break; case TOKENWORD: t = jj_consume_token(TOKENWORD); v = infixed_expression(new ThingVNode(t.image,currentLine)); {if (true) return v;} break; default: jj_la1[14] = jj_gen; jj_consume_token(-1); throw new ParseException(); } throw new Error("Missing return statement in function"); }
25bf6a3e-20bf-4565-9b90-8fe412245725
8
private void createEnderPortal(int par1, int par2) { byte var3 = 64; BlockEndPortal.bossDefeated = true; byte var4 = 4; for (int var5 = var3 - 1; var5 <= var3 + 32; ++var5) { for (int var6 = par1 - var4; var6 <= par1 + var4; ++var6) { for (int var7 = par2 - var4; var7 <= par2 + var4; ++var7) { double var8 = (double)(var6 - par1); double var10 = (double)(var7 - par2); double var12 = (double)MathHelper.sqrt_double(var8 * var8 + var10 * var10); if (var12 <= (double)var4 - 0.5D) { if (var5 < var3) { if (var12 <= (double)(var4 - 1) - 0.5D) { this.worldObj.setBlockWithNotify(var6, var5, var7, Block.bedrock.blockID); } } else if (var5 > var3) { this.worldObj.setBlockWithNotify(var6, var5, var7, 0); } else if (var12 > (double)(var4 - 1) - 0.5D) { this.worldObj.setBlockWithNotify(var6, var5, var7, Block.bedrock.blockID); } else { this.worldObj.setBlockWithNotify(var6, var5, var7, Block.endPortal.blockID); } } } } } this.worldObj.setBlockWithNotify(par1, var3 + 0, par2, Block.bedrock.blockID); this.worldObj.setBlockWithNotify(par1, var3 + 1, par2, Block.bedrock.blockID); this.worldObj.setBlockWithNotify(par1, var3 + 2, par2, Block.bedrock.blockID); this.worldObj.setBlockWithNotify(par1 - 1, var3 + 2, par2, Block.torchWood.blockID); this.worldObj.setBlockWithNotify(par1 + 1, var3 + 2, par2, Block.torchWood.blockID); this.worldObj.setBlockWithNotify(par1, var3 + 2, par2 - 1, Block.torchWood.blockID); this.worldObj.setBlockWithNotify(par1, var3 + 2, par2 + 1, Block.torchWood.blockID); this.worldObj.setBlockWithNotify(par1, var3 + 3, par2, Block.bedrock.blockID); this.worldObj.setBlockWithNotify(par1, var3 + 4, par2, Block.dragonEgg.blockID); BlockEndPortal.bossDefeated = false; }
76090275-e3a7-4b79-837d-9b28dc72852c
6
@Override public int numberOfLivingNeighbors(int x, int y) { int numberOfLivingNeighbors = 0; for (int i = -1; i < 2; i++) { for (int j = -1; j < 2; j++) { if (!(i == 0 && j == 0)) { int xCoordinate = x + i; int yCoordinate = y + j; if (cellExists(xCoordinate, yCoordinate) && board[xCoordinate][yCoordinate].isAlive()) { numberOfLivingNeighbors++; } } } } return numberOfLivingNeighbors; }
262661ed-f03f-42ae-b5e4-ca2fe3779e41
9
public static String formatTime3(long secs) { int seconds = (int) secs; int minutes = 0; int hours = 0; int days = 0; days = seconds / (60 * 60 * 24); hours = seconds / (60 * 60) % 24; minutes = (seconds / 60) % 60; seconds %= 60; StringBuffer buf = new StringBuffer(); if (days > 0) { buf.append(days).append(days != 1 ? " days, " : " day, "); } if (days > 0 || hours > 0) { buf.append(hours).append(hours != 1 ? " hours, " : " hour, "); } if (hours > 0 || minutes > 0) { buf.append(minutes).append(minutes != 1 ? " minutes, " : " minute, "); } buf.append(seconds).append(seconds != 1 ? " seconds" : " second"); return buf.toString(); }
918766ce-222f-468b-9670-116f46b95f4a
4
private static double _targetFromDistance(Distance distance) { if(distance == Distance.NEAR) { return StringPot.VAL_NEAR; } else if(distance == Distance.CENTER) { return StringPot.VAL_CENTER; } else if(distance == Distance.OPPONENT_AUTO) { return StringPot.VAL_OPPAUTO; } else if(distance == Distance.FEEDER) { return StringPot.VAL_FEEDER; } return -1; }
ffaa45f4-32cc-42fd-99c3-32300bb5c373
7
private BufferedImage getDiceImage(int size) { if (diceImages == null) return null; switch(size) { case 4: return diceImages[0]; case 6: return diceImages[1]; case 8: return diceImages[2]; case 10: return diceImages[3]; case 12: return diceImages[4]; case 20: return diceImages[5]; } return null; // no image for that size }
4349e71d-5fbc-4313-ab87-0ad210c5ff48
1
private File forres(String nm) { File res = base; String[] comp = nm.split("/"); for(int i = 0; i < comp.length - 1; i++) { res = new File(res, comp[i]); } return(new File(res, comp[comp.length - 1] + ".cached")); }
448e8b55-789a-4ff1-b6e6-cf79c344d9ef
8
public static void getLongestSubString() { // 两个需要对比的字符串 String x = "abcdehpoi"; String y = "bcdehfpoidfdegsfet"; int substringLength1 = x.length(); int substringLength2 = y.length(); // 第一步:构造需要遍历的二位数组 int opt[][] = new int[substringLength1 + 1][substringLength2 + 1]; // 定义三个临时变量:最大值,最大值横坐标和竖坐标 int max = opt[0][0]; int xCoordinate = 0, yCoordinate = 0; // 第二步:横向竖向对比字符,填充上面构造的二位数组。 for (int i = 1; i <= substringLength1; i++) { for (int j = 1; j <= substringLength2; j++) { if (x.charAt(i - 1) == y.charAt(j - 1)) { // 横向和竖向的字符相同,改变改位置的值为左上角的值加1。 opt[i][j] = opt[i - 1][j - 1] + 1; // 这里需要记录下最大值的值和坐标 if (max < opt[i][j]) { max = opt[i][j]; xCoordinate = i; yCoordinate = j; } } } } System.out.println("x = " + x); System.out.println("y = " + y); System.out.println("max = " + max); // 第四步:取出最大子串序列,并且展示。。。 StringBuffer sb = new StringBuffer(); for (int i = xCoordinate, j = yCoordinate; i >= 1 && j >= 1; i--, j--) { if (opt[i][j] > 0) { sb.append(x.charAt(i - 1)); } } String result = sb.toString(); // 上面的字符串是反的,这里反转输出结果 for (int i = result.length() - 1; i >= 0; i--) { System.out.print(result.charAt(i)); } }
cd93bc01-aa07-4cbc-9280-e78c485bf678
7
public boolean canBePillaged(Unit attacker) { return !hasStockade() && attacker.hasAbility("model.ability.pillageUnprotectedColony") && !(getBurnableBuildingList().isEmpty() && getShipList().isEmpty() && (getLootableGoodsList().isEmpty() || !attacker.getType().canCarryGoods() || !attacker.hasSpaceLeft()) && !canBePlundered()); }
b83b4183-d660-4f7d-859b-b74fa34ab4aa
2
public void addItemsToSupplierCombobox(ArrayList<Person> list) { supplierComboboxItems.clear(); String item = "<html><font color='red'>Add New Supplier</font></html>"; supplierComboboxItems.add(item); if (driver.getPersonDB().getSupplierList().size() > 0) { for (Person person : list) { item = "\t" + person.getId() + " \t - \t " + person.getName(); supplierComboboxItems.add(item); } supplierComboBox.setSelectedIndex(driver.getPersonDB().getSupplierList().size()); } else { supplierComboBox.setSelectedItem(null); } revalidate(); repaint(); }
885332fe-37a1-4b0b-9f46-8d900093838f
4
public static void main(String argv[]) throws Exception { PORT = Integer.parseInt(argv[0]); FILENAME = argv[1]; WINDOW = Integer.parseInt(argv[2]); serverSocket = new DatagramSocket(PORT); ByteArrayOutputStream baos = new ByteArrayOutputStream(); boolean eof = false; ArrayList<byte[]> packet_buffer = new ArrayList<byte[]>(); PacketReceptor receptor = new PacketReceptor(packet_buffer, 0, WINDOW); Thread receiver = new Thread(receptor); receiver.start(); /** * Checks to the write buffer in the receptor thread can be managed * through the introduction of a thread sleep within this loop */ ArrayList<byte[]> write_to_baos = new ArrayList<byte[]>(); do { /** * Pop the write buffer from the receptor thread so that the main * thread can write the data to memory */ write_to_baos = receptor.popWriteBuffer(); for (byte[] x : write_to_baos) { //IF WINDOW IS LARGER THAN NUM OF EOF if(Utilities.isEOF(x)){ if(receptor.getSOW() > Utilities.getPacketNum(x)){ eof = true; } } baos.write(Utilities.getData(x)); } } while (eof == false); receptor.stop(); FileOutputStream writeToFile = new FileOutputStream(FILENAME); System.out.println("Transmission complete! Writing to file..."); writeToFile.write(baos.toByteArray()); }
696f592a-292c-4ca3-af28-05ce40cc77a1
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 TaxonObservationDownloadStatisticsPK)) { return false; } TaxonObservationDownloadStatisticsPK other = (TaxonObservationDownloadStatisticsPK) object; if (this.filterID != other.filterID) { return false; } if ((this.datasetKey == null && other.datasetKey != null) || (this.datasetKey != null && !this.datasetKey.equals(other.datasetKey))) { return false; } return true; }
66618124-f3a9-4ff3-8add-60f551e6a467
1
public void disconnect(){ try { instream.close(); outstream.close(); } catch(IOException e) { } }
6c2cbc45-c39f-4a24-aa91-5e5981c312e6
7
protected Integer coerceToInteger(Object value) { if (value == null || "".equals(value)) { return Integer.valueOf(0); } if (value instanceof Integer) { return (Integer)value; } if (value instanceof Number) { return Integer.valueOf(((Number)value).intValue()); } if (value instanceof String) { try { return Integer.valueOf((String)value); } catch (NumberFormatException e) { throw new ELException(LocalMessages.get("error.coerce.value", value, value.getClass(), Integer.class)); } } if (value instanceof Character) { return Integer.valueOf((short)((Character)value).charValue()); } throw new ELException(LocalMessages.get("error.coerce.type", value, value.getClass(), Integer.class)); }
07bdfd31-ad30-47fe-83ca-4dcea96891f0
0
public int getColsCount() { return m_colsCount; }
82a3ced6-e266-4682-b8eb-adae42b8d819
5
private List<String> getImageNames(boolean sameSize) { List<String> imagens = new ArrayList<String>(); for (JInternalFrame frame : getDskCenter().getAllFrames()) if (frame instanceof ImagemIFrame) { if (sameSize) { BufferedImage selected = getSelectedFrame().getImage(); BufferedImage other = ((ImagemIFrame) frame).getImage(); if (other.getWidth() != selected.getWidth() || other.getHeight() != selected.getHeight()) continue; } imagens.add(frame.getTitle()); } return imagens; }
831b19fc-910f-43ed-a571-0c99529650bf
0
@Basic @Column(name = "sale_estado") public String getEstadoMovimiento() { return estadoMovimiento; }
97d214a1-f876-4cfe-ac13-3b0019a0bbcd
0
public Configuration[] getSelected() { return (Configuration[]) selected.toArray(new Configuration[0]); }
c44cd948-fda0-4e48-87de-6ff81d94d60a
1
private static byte[] joinQuartetsToBytes(byte[] quartets) { byte[] block = new byte[quartets.length / 2]; for (int i = 0; i < quartets.length; i += 2) { block[i/2] = ByteHelper.joinBlocks(quartets[i], quartets[i + 1]); } return block; }
319d05cc-fb5f-46fc-8284-2d4b4914ee6f
1
public void allDFS(Graph G) { // find a vertex to serve as the starting point for a DFS search in each // component. 'componentCount' will not only keep a count of the // components but will // also serve as the id to use for all vertices of that component for (int v = 0; v < G.V(); v++) { dfs(G, v); postEachSourceDFS(v); } }
0bb018ee-50cd-4a80-8e36-8c9a0be67549
5
private void boutonDeumeureDesElfesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_boutonDeumeureDesElfesMouseClicked // TODO add your handling code here: if (partie.getDde().isActif()) { if (!partie.getDieuActuel().isaJoueurEnDeumeureDesElfes() || ((partie.getDieuActuel().getNom().compareTo("Freyja") == 0 && ((Freyja) partie.getDieuActuel()).getaJoueurEnDeumeureDesElfes() < 2)&&Dieu.pouvoirDieu)) { partie.jouerEnDemeureDesElfes(page); verifFinTour(); } else { JOptionPane.showMessageDialog(page, "Vous avez déjà joué dans ce monde", "Yggdrasil", JOptionPane.INFORMATION_MESSAGE); } } else { JOptionPane.showMessageDialog(page, "Un géant bloc l'accés à ce monde", "Yggdrasil", JOptionPane.INFORMATION_MESSAGE); } }//GEN-LAST:event_boutonDeumeureDesElfesMouseClicked
ebc11ec4-e344-4334-b4c3-4b22a1331d83
5
protected void layout(List<Object> parallels) { Object edge = parallels.get(0); mxIGraphModel model = graph.getModel(); mxGeometry src = model.getGeometry(model.getTerminal(edge, true)); mxGeometry trg = model.getGeometry(model.getTerminal(edge, false)); // Routes multiple loops if (src == trg) { double x0 = src.getX() + src.getWidth() + this.spacing; double y0 = src.getY() + src.getHeight() / 2; for (int i = 0; i < parallels.size(); i++) { route(parallels.get(i), x0, y0); x0 += spacing; } } else if (src != null && trg != null) { // Routes parallel edges double scx = src.getX() + src.getWidth() / 2; double scy = src.getY() + src.getHeight() / 2; double tcx = trg.getX() + trg.getWidth() / 2; double tcy = trg.getY() + trg.getHeight() / 2; double dx = tcx - scx; double dy = tcy - scy; double len = Math.sqrt(dx * dx + dy * dy); double x0 = scx + dx / 2; double y0 = scy + dy / 2; double nx = dy * spacing / len; double ny = dx * spacing / len; x0 += nx * (parallels.size() - 1) / 2; y0 -= ny * (parallels.size() - 1) / 2; for (int i = 0; i < parallels.size(); i++) { route(parallels.get(i), x0, y0); x0 -= nx; y0 += ny; } } }
5eb01917-7f3d-4c57-97d1-f9300d80a19f
7
@Override public boolean activateProfile(Profile profile) { // Save the directories String dataDir = getDir(); String saveDir = dataDir + getGameSaveDir(); String profilesDir = dataDir + getSave() + File.separator; // Find the currently active profile ProfileFactory pf = ProfileFactory.getInstance(); Profile[] profiles = pf.getProfiles(getId()); Profile currentProfile = null; for(int x=0; x<profiles.length; x++){ if(profiles[x].isActive()){ currentProfile = profiles[x]; break; } } // Create the Files that need to be renamed File saveFolder = new File(saveDir); File profileSaves = new File(profilesDir + profile.getSaveDir()); // See if there is an active profile if(currentProfile == null){ // No profile is active delete the saves folder if( saveFolder.exists() && !saveFolder.delete()){ Main.handleException("Unable to activate the profile because the save folder contains saves from an unkown or de-activated profile.", null, Main.WARN_LEVEL); return false; } } else { // Rename the saved games folder to the previous profile's saveDir if( !saveFolder.renameTo( new File(profilesDir + currentProfile.getSaveDir())) ) { Main.handleException("Unable to move the saved game folder.", null, Main.WARN_LEVEL); return false; } } // Rename the profile's save game directory to the morrowind save directory if( profileSaves.renameTo(new File(saveDir)) ) { pf.setActive(profile); return true; } else { Main.handleException("Unable to move the profile's saved games into the save game folder.", null, Main.WARN_LEVEL); return false; } }
4cfe542d-48e5-47fb-be74-bbae5ba65058
1
public JList<String> getListUsuarios() { if (listUsuarios == null) { listUsuarios = new JList<String>(); } return listUsuarios; }
aef6443a-cf54-4570-978c-f989d4737b70
1
private void setupWorldWind() { BasicModel model = new BasicModel(); globeRound = model.getGlobe(); wwCanvas.setModel(model); // highlightController = new HighlightController(wwCanvas, SelectEvent.ROLLOVER); // ttController = new ToolTipController(wwCanvas); // Register a rendering exception listener that's notified when // exceptions occur during rendering. wwCanvas.addRenderingExceptionListener(new RenderingExceptionListener() { public void exceptionThrown(Throwable t) { if (t instanceof WWAbsentRequirementException) { StringBuilder message = new StringBuilder( "Computer does not meet minimum graphics requirements.\n"); message.append("Please install up-to-date graphics driver and try again.\n"); message.append("Reason: ").append(t.getMessage()); message.append("\nThis program will end when you press OK."); JOptionPane.showMessageDialog(MainFrame.this, message, "Unable to Start Program", JOptionPane.ERROR_MESSAGE); System.exit(-1); } else { System.err.println("WorldWind library rendering problem!"); t.printStackTrace(); } } }); // add a StatusLayer StatusLayer slayer = new StatusLayer(); slayer.setEventSource(wwCanvas); slayer.setDefaultFont(chPlaces.getFont()); wwCanvas.getModel().getLayers().add(slayer); // add the shape drawing layer wwCanvas.getModel().getLayers().add((Layer) gmlLayer); }
2dfb6c05-8137-48b0-b97e-6f4a60213b22
6
public static void main(String[] args) { Scanner scanIn = new Scanner(System.in); System.out.println("Please key in number for following algorithms:"); System.out.println("[1] Depth-First-Search"); System.out.println("[2] Breadth-First-Search"); System.out.println("[3] Best-First-Search"); System.out.println("[4] Hill Climbing Search"); System.out.println("[5] A* Search"); System.out.println("[6] Custom Search"); int input = scanIn.nextInt(); if (input==1) { DFS dfs = new DFS("maze.txt"); dfs.compute(); } else if (input==2) { BFS bfs = new BFS("maze.txt"); bfs.compute(); } else if (input==3) { Best best = new Best("maze.txt"); best.compute(); } else if (input==4) { HillClimbing hill = new HillClimbing("maze.txt"); hill.compute(); } else if (input==5) { AStar a = new AStar("maze.txt"); a.compute(); } else if (input==6) { Custom aheadTwoSteps = new Custom("maze.txt"); aheadTwoSteps.compute(); } }
5c66d674-ab19-478a-ad16-4882ae70cfa3
8
public void checkCoupon(Service service, int position) { Calendar today = Calendar.getInstance(); long todaysTime = this.expiryDate.getTimeInMillis(); long serviceTime = service.serviceDate.getTimeInMillis(); long oneDay = 1000 * 60 * 60 * 24; int difference = (int) ((todaysTime - serviceTime) / oneDay); if (service instanceof EngineOil) { // 5 Months if (difference >= 150) { System.out.println("-----------------------------"); System.out.println("Service #: " + position); System.out.println("Date of last service: " + service.serviceDate.get(service.serviceDate.MONTH) + "/" + service.serviceDate.get(service.serviceDate.DAY_OF_MONTH) + "/" + service.serviceDate.get(service.serviceDate.YEAR)); System.out.println("Days since last service: " + difference); System.out.println("Days needed to qualify for coupon: " + 150); service.coupon = new EngineServiceCoupon(5); } } if (service instanceof RadiatorFlush) { // 5 Years if (difference >= 1825) { System.out.println("-----------------------------"); System.out.println("Service #: " + position); System.out.println("Date of last service: " + service.serviceDate.get(service.serviceDate.MONTH) + "/" + service.serviceDate.get(service.serviceDate.DAY_OF_MONTH) + "/" + service.serviceDate.get(service.serviceDate.YEAR)); System.out.println("Days since last service: " + difference); System.out.println("Days needed to qualify for coupon: " + 1825); service.coupon = new RadiatorFlushCoupon(15); } } if (service instanceof TireService) { // 3 Years if (difference >= 1095) { System.out.println("-----------------------------"); System.out.println("Service #: " + position); System.out.println("Date of last service: " + service.serviceDate.get(service.serviceDate.MONTH) + "/" + service.serviceDate.get(service.serviceDate.DAY_OF_MONTH) + "/" + service.serviceDate.get(service.serviceDate.YEAR)); System.out.println("Days since last service: " + difference); System.out.println("Days needed to qualify for coupon: " + 1095); service.coupon = new TireServiceCoupon(); } } if (service instanceof BrakeService) { // 3 Years if (difference >= 1095) { System.out.println("-----------------------------"); System.out.println("Service #: " + position); System.out.println("Date of last service: " + service.serviceDate.get(service.serviceDate.MONTH) + "/" + service.serviceDate.get(service.serviceDate.DAY_OF_MONTH) + "/" + service.serviceDate.get(service.serviceDate.YEAR)); System.out.println("Days since last service: " + difference); System.out.println("Days needed to qualify for coupon: " + 1095); service.coupon = new BrakeServiceCoupon(30); } } }
768a3f49-55cf-4b77-9f74-9f3cb1e5eba1
1
public void destroy() { for(BaseComponent bc : components.values()) { bc.destroy(); } components.clear(); }
c84dd24b-574e-4ae2-b12f-80a052aab30e
0
@Override public PermissionType getType() { return PermissionType.WORLD; }
9387d656-d157-4dac-80aa-0d92d41e2aab
8
@SuppressWarnings("deprecation") @EventHandler public void click(InventoryClickEvent event) { Player player = (Player) event.getView().getPlayer(); OpenQuestLog oql = getOpenQuestLog(player); if(oql == null)return; event.setCancelled(true); if(event.getView() != oql.getInventoryView()) { player.updateInventory(); return; } if(event.getCurrentItem() == null) { player.updateInventory(); return; } Quest sel = oql.getSelected(); if(sel == null) { if(event.getSlot() == 27) { oql.setViewingCompleted(!oql.isViewingCompleted()); oql.update(); } else { int index = (oql.getPage() - 1)*27 + event.getSlot(); Quest[] q = oql.isViewingCompleted() ? oql.getCurrentCompletedList() : oql.getCurrentQuestList(); if(index < q.length) { oql.setSelected(q[index]); oql.update(); } } } else if(event.getSlot() == 27) { oql.setSelected(null); oql.update(); } player.updateInventory(); }
dee3ebfe-28fb-40ee-a987-0b59c93df8af
4
public static void main(String[] args) throws InterruptedException { final int numberOfTrees = 20; final int numberOfDucks = 20; final int numberOfHunters = 20; HuntField f = new HuntField(21, 70); for (int i = 0; i < numberOfTrees; i++) new Tree(f); for (int i = 0; i < numberOfDucks; i++) new Duck(f).start(); for (int i = 0; i < numberOfHunters; i++) new Hunter(f).start(); while(f.getNumberOfItems('D')>0){ Thread.sleep(200); printField(f); } printField(f); }
84ad43a5-d5d2-4d0d-9743-1fa4994b8280
5
public void ge_relation(TextArea area,SimpleNode node,String prefix,int cur_end_num,int if_or_while,int con)throws SemanticErr{ if(node.toString().equals("Relation_expression")) { SimpleNode left = (SimpleNode) node.jjtGetChild(0).jjtGetChild(0).jjtGetChild(0); SimpleNode rel = (SimpleNode) node.jjtGetChild(1); SimpleNode right = (SimpleNode) node.jjtGetChild(2).jjtGetChild(0).jjtGetChild(0); //if() if (and_last == 0 || and_last == 1) { String sub_prefix = prefix.substring(0, prefix.length() - 2); String instr = sub_prefix + "land.lhs.true" + String.valueOf(true_num) + ":\n"; true_num = true_num + 1; area.append(instr); } pair left_pair = ge_add_expression(area, left, prefix); pair right_pair = ge_add_expression(area, right, prefix); ge_cmp(area, rel.jjtGetFirstToken().toString(), left_pair.var, right_pair.var, prefix,con); } else if(node.toString().equals("Function_call_expression")) { pair func = ge_call(area,node,prefix); ge_cmp(area, "!=", func.var, "0", prefix,con); } if (if_or_while == 0) { ge_if_jump(area, prefix, cur_end_num); } else { ge_while_jump(area, prefix, cur_end_num); } }
64359a9a-7150-41c1-8cbd-19fa424dc2d8
4
public String getCurrentPuzzle() { String currentPuzzle = ""; int i = 0, j = 0; for(i = 0; i < 16; i++) { for(j = 0; j < 16; j++) { if(entries[i][j].isEditable()) { currentPuzzle = currentPuzzle +"E "; } else { currentPuzzle = currentPuzzle +"N "; } if(entries[i][j].getText().equals("")) { currentPuzzle = currentPuzzle + "0 "; } else { currentPuzzle = currentPuzzle + entries[i][j].getText() + " "; } } } System.out.println("Current Puzzle is" + currentPuzzle); return currentPuzzle; }
a6ea9cb8-1c0a-4cda-8cba-cdeb66816775
4
private static void checkForBlackjack(Dealer dealer, Player player) { boolean playerHasBlackjack = player.getHasBlackjack(); boolean dealerHasBlackjack = dealer.getHasBlackjack(); // End round if both have blackjack. Tie situation. if(playerHasBlackjack && dealerHasBlackjack) { System.out.println("Both have 21, but both dealer and player have blackjack so tie!"); tieSituation(player); continueRound=false; } // If player has blackjack, then declare player the winner. else if(playerHasBlackjack) { System.out.println("Both have 21, but dealer doesn't have blackjack so player wins!"); playerWon(player); continueRound=false; } // This means that the player doesn't have blackjack, so the dealer will win. else if(dealerHasBlackjack){ System.out.println("Both have 21, but player doesn't have blackjack so dealer wins!"); dealerWon(dealer); continueRound=false; } // Both don't have blackjack, but they both have 21, so they will tie. else { System.out.println("Both have 21, but neither one has blackjack so tie!"); tieSituation(player); continueRound=false; } }
a49bbc20-16a0-45a7-b10a-6099d6290bcd
3
public JSONObject putOnce(String key, Object value) throws JSONException { if (key != null && value != null) { if (this.opt(key) != null) { throw new JSONException("Duplicate key \"" + key + "\""); } this.put(key, value); } return this; }
e19dc6a7-86c5-4a31-9f06-13afcc35d49b
3
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if(plugin.hasPermission(sender, "authy")){ if(args.length==0){ }else{ if(args[0].equalsIgnoreCase("register")){ this.register(sender, cmd, commandLabel, args); } } } return true; }
b65d5742-eb36-4cb6-bc40-6b6edd2fa17a
1
private ArrayList<String> getValidationErrors() { ArrayList<String> errors = new ArrayList<String>(); String username = txtUsername.getText(); if (username.isEmpty()) { errors.add("Username field is blank"); } return errors; }
34afcc30-569c-442f-b2ba-6762a14f906e
9
public void nextQuestion(){ Scanner input = new Scanner(System.in); question=new Test(); Random random = new Random(); number = random.nextInt(4); while(check.contains(number)) { number = random.nextInt(4); } check.add(number); switch(number) { case 0: System.out.println(question.question1(questions)); break; case 1: System.out.println(question.question2(questions)); break; case 2: System.out.println(question.question3(questions)); break; case 3: System.out.println(question.question4(questions)); break; } String answer = input.nextLine(); if(answer.equalsIgnoreCase("a")) userAnswer = 0; else if(answer.equalsIgnoreCase("b")) userAnswer = 1; else if(answer.equalsIgnoreCase("c")) userAnswer = 2; else if(answer.equalsIgnoreCase("d")) userAnswer = 3; checkTrue(); }
1de5f5cb-9b8f-4ae3-93e2-41cc5c1d30ba
3
@Override public Object getAsObject(FacesContext facesContext, UIComponent component, String value) { if (value == null || value.length() == 0 || JsfUtil.isDummySelectItem(component, value)) { return null; } return this.ejbFacade.find(getKey(value)); }
6ef994db-dc23-4f5e-a2f8-8003900a4db3
5
@Override public Movement getMove(Board b) { List<PosibleWord> movements = b.getPosibleWords(); Dictionary dic = b.getDic(); SortedSet<WordInfo> words = new TreeSet<WordInfo>(); for (PosibleWord pw : movements) { Iterator<String> it = dic.iterator(pw.getPattern()); while (it.hasNext()) { String word = it.next(); if (pw.matches(word, dic) && compatibleWithHand(b,word,pw)) { words.add(new WordInfo(word,pw,b.scoreWord(word, letters, pw.i, pw.j, pw.direction))); } } } if (words.isEmpty()) { throw new RuntimeException("No moves D:"); } WordInfo finalWord = words.last(); return new Movement(finalWord.pw.i, finalWord.pw.j, finalWord.pw.direction, finalWord.word); }
d6481158-7e0e-4091-bb49-79b378d003dd
3
@Get public Set<Intervention> readAll() { Set<Intervention> interventions = null; String userkey = (String) getRequest().getAttributes().get("userid"); if (userkey == null) return null; User target = null; try { long userid = Long.valueOf(userkey); EntityManager em = emf.createEntityManager(); target = em.find(User.class, userid); if (target != null) { interventions = target.getIntervention(); } else { return null; } } catch (Exception e) { System.out.println(e); } return interventions; }
ea48ffec-99aa-49fa-ae20-6efd71d70546
2
public static boolean isString(String line){ if(line.charAt(0) == '"' && line.charAt(line.length()-1) == '"'){ return true; } return false; }
c19fb5d6-4e71-42c3-8591-8fab831552f6
1
public boolean matches(Operator loadop) { return loadop instanceof GetFieldOperator && ((GetFieldOperator) loadop).ref.equals(ref); }
e086dcce-e67a-44e3-8ced-1cd86f50f71d
7
public void registerCommand(Object obj) { Method methods[] = obj.getClass().getDeclaredMethods(); for(Method m: methods) { if(m.isAnnotationPresent(DBCommand.class)) { Class<?> params[] = m.getParameterTypes(); if(params.length == 2 && params[0] == CommandSender.class && params[1] == Iterator.class && m.getReturnType() == Boolean.TYPE) { String name = m.getName().toLowerCase(); commands.put(name, obj); } } } }
421f41ff-5ba2-4343-b849-5c7bcaa2af52
9
public void respawn(final boolean force) { if (force) { final int numShouldSpawn = monsterSpawn.size() - spawnedMonstersOnMap.get(); if (numShouldSpawn > 0) { int spawned = 0; for (Spawns spawnPoint : monsterSpawn) { spawnPoint.spawnMonster(this); spawned++; if (spawned >= numShouldSpawn) { break; } } } } else { if (getCharactersSize() <= 0) { return; } final int numShouldSpawn = maxRegularSpawn - spawnedMonstersOnMap.get(); if (numShouldSpawn > 0) { int spawned = 0; final List<Spawns> randomSpawn = new ArrayList<Spawns>(monsterSpawn); Collections.shuffle(randomSpawn); for (Spawns spawnPoint : randomSpawn) { if (spawnPoint.shouldSpawn()) { spawnPoint.spawnMonster(this); spawned++; } if (spawned >= numShouldSpawn) { break; } } } } }
d70bebab-24f4-4eb8-8f9e-7e0f09c822cb
7
@Override public void fill(Parameter parameter, Type type, Annotation[] annotations) { Class clazz; Class reader; if (type instanceof Class) { reader = ((Class)type); clazz = ((Class)type); } else if (type instanceof ParameterizedType) { reader = ((Class)((ParameterizedType)type).getRawType()); Type[] typeArgs = ((ParameterizedType)type).getActualTypeArguments(); if (typeArgs.length != 1) { throw new UnsupportedOperationException("Only exactly one generic Parameter Type is supported"); } clazz = ((Class)typeArgs[0]); } else { throw new UnsupportedOperationException("Type is not supported: " + type); } if (reader == type && Enum.class.isAssignableFrom(clazz)) { reader = Enum.class; // Use default enum reader } for (Annotation annotation : annotations) { if (annotation instanceof Reader) { reader = ((Reader)annotation).value(); } } parameter.offer(Properties.TYPE, clazz); parameter.offer(Properties.READER, reader); }
1d5ca197-3dc9-41a6-8ecf-9fe086fb4fcd
8
private void expand1(byte[] src, byte[] dst) { for (int i = 1, n = dst.length; i < n; i += 8) { int val = src[1 + (i >> 3)] & 255; switch (n - i) { default: dst[i + 7] = (byte) ((val) & 1); case 7: dst[i + 6] = (byte) ((val >> 1) & 1); case 6: dst[i + 5] = (byte) ((val >> 2) & 1); case 5: dst[i + 4] = (byte) ((val >> 3) & 1); case 4: dst[i + 3] = (byte) ((val >> 4) & 1); case 3: dst[i + 2] = (byte) ((val >> 5) & 1); case 2: dst[i + 1] = (byte) ((val >> 6) & 1); case 1: dst[i] = (byte) ((val >> 7)); } } }
dabd19aa-e3e7-45e7-b61c-09eb05f8d1d6
3
private void showAllNodesOnTree(UrlNode node , int i ){ System.out.println("Level : " + i + " , Path : " + node.selfUrl + " , parentUrl : " + node.parentUrl + " , childNum :" + node.childNodes.size() ); if( node.childNodes == null || node.childNodes.size() == 0) return ; for(UrlNode nodes : node.childNodes){ showAllNodesOnTree(nodes , i + 1) ; } }
0e86d850-c466-4cfc-8896-1b9248c47419
9
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String cmd = request.getParameter(CMD_PARAM); UserGame game = (UserGame) request.getSession().getAttribute(USER_GAME); boolean refresh = false; if (REFRESH_CMD.equals(cmd)) { refresh = true; game.refresh(); } else if (FLIGHT_LEVEL_CMD.equals(cmd)) { String planeId = request.getParameter(PLANE_PARAM); String flightLevelId = request.getParameter(FLIGHT_LEVEL_PARAM); game.sendFlightLevel(planeId, flightLevelId); } else if (HOLD_CMD.equals(cmd)) { String planeId = request.getParameter(PLANE_PARAM); String condId = request.getParameter(CONDITION_PARAM); game.sendHold(planeId, condId); } else if (LAND_CMD.equals(cmd)) { String planeId = request.getParameter(PLANE_PARAM); String locationId = request.getParameter(LOCATION_PARM); game.sendClearToLand(planeId, locationId); } else if (TURN_CMD.equals(cmd)) { String planeId = request.getParameter(PLANE_PARAM); String locationId = request.getParameter(LOCATION_PARM); String condId = request.getParameter(CONDITION_PARAM); game.sendTurnTo(planeId, locationId, condId); } else if (EXIT_CMD.equals(cmd)) { game.exitGame(); } else { log.error("Unrecognized command cmd=" + cmd); } // Prepare response RefreshData refreshData = new RefreshData(); if (refresh) refreshData.setCommand(game.isGameOver() ? "setGameOver()" : "refreshLater()"); refreshData.setPlanePane(game.getPlaneListLog()); refreshData.setLogPane(game.getLogRows()); List<JsonPlane> planes = refreshData.getPlaneList(); planes.clear(); for (Plane plane : game.getPlaneList()) { JsonPlane jPlane = new JsonPlane(); jPlane.setId(plane.getId()); jPlane.setFlightLevel(plane.getFlightLevelId()); jPlane.setHeading(plane.getHeading()); jPlane.setX(plane.getPosition().getX()); jPlane.setY(plane.getPosition().getY()); jPlane.setSpeed(plane.getSpeed()); jPlane.setClassId(plane.getClassId()); planes.add(jPlane); } // Output reponse Gson gson = new Gson(); response.setContentType("application/json"); response.getWriter().write(gson.toJson(refreshData)); }
e6e708a0-278a-4b80-a90c-9bef45bd0511
5
public void Update(double timeDelta) { m_collidedLastFrame = false; if (m_interType == InteractionType.Kinetic || m_interType == InteractionType.Ghost || m_velocityX != 0.0 || m_velocityY != 0.0) m_physicsModel.PerformCollisionFor(this); double dX = m_velocityX * timeDelta + m_accelX * timeDelta * timeDelta * 0.5, dY = m_velocityY * timeDelta + m_accelY * timeDelta * timeDelta * 0.5, friction = Math.pow(m_physicsModel.m_friction, timeDelta); if (m_bounds.m_boundsType == BoundsType.Circle) { m_bounds.m_circle.X += dX; m_bounds.m_circle.Y += dY; } else { m_bounds.m_rect.m_x += dX; m_bounds.m_rect.m_y += dY; m_bounds.m_rect.m_right = m_bounds.m_rect.m_x + m_bounds.m_rect.m_width; m_bounds.m_rect.m_bottom = m_bounds.m_rect.m_y + m_bounds.m_rect.m_height; } m_posX += dX; m_posY += dY; m_velocityX = m_velocityX * friction + m_accelX * timeDelta; m_velocityY = m_velocityY * friction + m_accelY * timeDelta; m_accelX = m_accelY = 0; }
1c7ef7e4-6501-450d-b58c-4cc1245ee791
1
public static void AddIndividualReport(String TestPath, String Testname) { FileWriter fstream =null; BufferedWriter out =null; try { fstream = new FileWriter(TestPath); out = new BufferedWriter(fstream); out.write("<html>"); out.write("<head>"); out.write("<title>"); out.write(Testname + " Detailed Reports"); out.write("</title>"); out.write("</head>"); out.write("<body>"); out.write("<h4> <FONT COLOR=660000 FACE=Arial SIZE=4.5>" +Testname + " Detailed Report :</h4>"); out.write("<table border=1 cellspacing=1 cellpadding=1 width=100%>"); out.write("<tr> "); //out.write("<td align=center width=10% align=center bgcolor=#153E7E><FONT COLOR=#E0E0E0 FACE=Arial SIZE=2><b>Step/Row#</b></td>"); out.write("<td align=center width=60% align=center bgcolor=#153E7E><FONT COLOR=#E0E0E0 FACE=Arial SIZE=2><b>Description</b></td>"); out.write("<td align=center width=10% align=center bgcolor=#153E7E><FONT COLOR=#E0E0E0 FACE=Arial SIZE=2><b>Keyword</b></td>"); out.write("<td align=center width=15% align=center bgcolor=#153E7E><FONT COLOR=#E0E0E0 FACE=Arial SIZE=2><b>Result</b></td>"); out.write("<td align=center width=15% align=center bgcolor=#153E7E><FONT COLOR=#E0E0E0 FACE=Arial SIZE=2><b>Screen Shot</b></td>"); out.write("</tr>"); out.write("</table>\n"); out.write("</body>\n"); out.write("</html>\n"); out.close(); } catch(Throwable t) { } }
febfc764-3e78-41b2-bb53-c576be4d83d6
9
private static void mergeSort(Branch[] src, Branch[] dest, int low, int high, int off) { int length = high - low; // Insertion sort on smallest arrays if (length < INSERTIONSORT_THRESHOLD) { for (int i = low; i < high; i++) for (int j = i; j > low && (dest[j - 1]).compareTo(dest[j].getC()) > 0; j--) swap(dest, j, j - 1); return; } // Recursively sort halves of dest into src int destLow = low; int destHigh = high; low += off; high += off; int mid = (low + high) >>> 1; mergeSort(dest, src, low, mid, -off); mergeSort(dest, src, mid, high, -off); // If list is already sorted, just copy from src to dest. This // is an // optimization that results in faster sorts for nearly ordered // lists. if (src[mid - 1].compareTo(src[mid].getC()) <= 0) { System.arraycopy(src, low, dest, destLow, length); return; } // Merge sorted halves (now in src) into dest for (int i = destLow, p = low, q = mid; i < destHigh; i++) { if (q >= high || p < mid && src[p].compareTo(src[q].getC()) <= 0) dest[i] = src[p++]; else dest[i] = src[q++]; } }
5e4af300-e70a-48bd-813c-8296c6da95b6
6
@Deprecated private static String checkNFE(String operation, String[] arguments) { if(!operationNFEArgs.containsKey(operation)) { return "VALID"; } String[] argsNums = operationNFEArgs.get(operation).split("&"); for(String s : argsNums) { if(s.contains("...")) { for(int x = Integer.valueOf(s.substring(0,1)); x < arguments.length; x++) { if(!isInteger(arguments[x])) { return "Error: Expected argument " + x + " to be a number."; } } } if(!isInteger(arguments[Integer.valueOf(s)])) { return "Error: Expected argument " + s + " to be a number."; } } return "VALID"; }
88a86c7b-96b1-4ccb-976c-1e825538fa22
2
public Worker(int workerPriority,BlockingQueue<Worker> idleWorkers){ Integer bufferSize = Config.getInt(READ_BUFFER); if(bufferSize == null){ bufferSize = 10; } this.charBuffer = ByteBuffer.allocateDirect(1024 * bufferSize);// 创建读取缓冲区 this.idleWorkers = idleWorkers; handoffBox = new ArrayBlockingQueue<Object>(1); noStopRequested = true; Runnable r = new Runnable(){ public void run(){ try{ runWork(); }catch(Exception e){ e.printStackTrace(); } } }; this.internalThread = new Thread(r); this.internalThread.setName("请求参数读取线程" + threadIndex.getAndIncrement()); this.internalThread.setPriority(workerPriority); this.internalThread.start(); }
200e4de5-30ca-4ea4-be20-7b897ebd167c
7
public Field() { Point[][] res = new Point[FIELD_SIZE][FIELD_SIZE]; Scanner sc = new Scanner(System.in); char letter; while (true) { System.out.println("Please, enter one letters from matrix:"); for (int i = 0; i < FIELD_SIZE; i++) { for (int j = 0; j < FIELD_SIZE; j++) { try { System.out.println("a[" + i + "][" + j + "] = "); letter = sc.next().charAt(0); res[i][j] = new Point(letter, i, j); } catch (Exception e) { e.printStackTrace(); } } } for (int i = 0; i < FIELD_SIZE; i++) { for (int j = 0; j < FIELD_SIZE; j++) { System.out.print(res[i][j].getLetter()); } System.out.println(); } System.out.println("Matrix is OK? (y/n)"); letter = sc.next().charAt(0); if (letter == 'y'){ this.points = res; return; } } }
dc036fea-cdc1-4c09-8575-e67045257615
1
private int getEhtoX(Pelihahmo h){ if (h==h1){ return ehtoh1x; } else { return ehtoh2x; } }
96c516b2-c039-4842-aa62-a0ceacc3ec5f
0
public SharingPeer(String ip, int port, ByteBuffer peerId, SharedTorrent torrent) { super(ip, port, peerId); this.torrent = torrent; this.listeners = new HashSet<PeerActivityListener>(); this.availablePieces = new BitSet(this.torrent.getPieceCount()); this.exchangeLock = new Object(); this.reset(); this.requestedPiece = null; }
5065a081-2cd9-4c92-b145-7f98a9981575
8
private double findChange(Expr old, Expr nu) { if (old == null || nu == null) return 0; if (old.type != nu.type) return 0; if (nu instanceof ExprNumber) { return Math.abs(((ExprNumber) old).doubleValue() - ((ExprNumber) nu).doubleValue()); } if (nu instanceof ExprArray) { Expr[] oldA = ((ExprArray) old).getInternalArray(); Expr[] nuA = ((ExprArray) nu).getInternalArray(); double change = 0; for (int i = 0; i < oldA.length && i < nuA.length; i++) { double c = findChange(oldA[i], nuA[i]); if (c > change) change = c; } return change; } return 0; }
ef14ea8a-d1c9-4b08-abae-839471dbf13a
1
void init(){ if(volume<200){ days=0; }else{ days=Math.min(5,volume/200); } }
e6c41b1e-8782-44be-aaa7-ad0bbedd61fe
0
public String getDefinition() { return definition; }
fe94467f-7354-4651-8103-7a7406fd710d
3
private boolean binarySearch(int[] num, int target, int s, int e) { int mid = 0; while (s <= e) { mid = s + ((e - s) >> 1); if (num[mid] == target) { return true; } else if (num[mid] > target) { e = mid - 1; } else { s = mid + 1; } } return false; }
55452649-7369-4a05-8732-9b048234688e
4
public ArrayList<Node> successors() { ArrayList<Node> temp = new ArrayList<Node>(); State left = state.goLeft(); State up = state.goUp(); State right = state.goRight(); State down = state.goDown(); if(up != null) { temp.add(new Node(up, this, cost+1, Grid.Direction.UP)); } if(down != null) { temp.add(new Node(down, this, cost+1, Grid.Direction.DOWN)); } if(left != null) { temp.add(new Node(left, this, cost+1, Grid.Direction.LEFT)); } if(right != null) { temp.add(new Node(right, this, cost+1, Grid.Direction.RIGHT)); } return temp; }
e6c87052-296a-4088-923e-a1c3d6a06a1e
0
public RemoteClientConnection(String serverIP, int port) { this.serverIP = serverIP; this.port = port; }
5a57fa0b-9adf-4e25-9590-6ab6f44adcfe
2
public void visitInnerClass(final String name, final String outerName, final String innerName, final int access) { checkState(); CheckMethodAdapter.checkInternalName(name, "class name"); if (outerName != null) { CheckMethodAdapter.checkInternalName(outerName, "outer class name"); } if (innerName != null) { CheckMethodAdapter.checkIdentifier(innerName, "inner class name"); } checkAccess(access, Opcodes.ACC_PUBLIC + Opcodes.ACC_PRIVATE + Opcodes.ACC_PROTECTED + Opcodes.ACC_STATIC + Opcodes.ACC_FINAL + Opcodes.ACC_INTERFACE + Opcodes.ACC_ABSTRACT + Opcodes.ACC_SYNTHETIC + Opcodes.ACC_ANNOTATION + Opcodes.ACC_ENUM); cv.visitInnerClass(name, outerName, innerName, access); }
5d78515d-e53d-476b-8d10-39f9f4fb29dd
7
void checaColision() { //System.out.println("Entro checaColision"); if(oro.getPosY() - oro.getAlto() > getHeight()) { //Colision de oro con borde clickOro = false; oro.setPosX(0); oro.setPosY(ALTO - oro.getAlto()); if(suena) borde.play(); if (auxvidas == 2){ if (vidas > 0){ vidas--; velocidadDragon--; auxvidas = 0; if (vidas == 0){ gameover = !gameover; } } else{ gameover = !gameover; } } auxvidas++; } else if(dragon.intersecta(oro)) { //colision de dragon con oro clickOro = false; if(suena) cBueno.play(); mensDESAPARECE = true; contVDesap = 0; score += 2; oro.setPosX(0); //posision x oro.setPosY(getHeight() - oro.getAlto()-10); //posision y } }
8a804a5c-a187-4cbc-9987-a36d01ccaa61
1
public Reading() { // TODO Auto-generated constructor stub try { doc = Jsoup.connect(DOKUMENT_ADRESSE).get(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
5b582288-5639-4b6e-83c4-0f17dce1200a
3
public byte[] read_multiple(short address, int length) throws IOException { if ((this.mode==0) || (this.mode==SET_MODE_I2C_SERIAL)) this.set_mode(SET_MODE_I2C_100); byte[] data=new byte[3]; data[0]=(byte)RW_MULTIPLE; data[1]=(byte)address; data[2]=(byte)length; byte[] result = this.sendAndReceive(data, COM_TIMEOUT, length); if (result.length!=length) throw new IOException("no answer from device"); return result; }
82f72521-2003-4ed7-afc0-0f1275faec0e
1
public boolean jumpMayBeChanged() { return subBlock.jump != null || subBlock.jumpMayBeChanged(); }
91a0188c-fec9-41ee-8311-a8d8aa56210d
4
private void getRootInfo() { new Thread() { @Override public void run() { setName("Root Info Thread"); setPriority(Thread.MIN_PRIORITY); while (getDeviceInfo) { // if (debug) // logger.log(Level.DEBUG, "Loading device root info..."); SU su = selectedDevice.getSU(); BusyBox busybox = selectedDevice.getBusybox(); boolean su_isInstalled = false; // Generally assume that this is false! String su_version = null; boolean busybox_isInstalled = false; // Same rules apply here! String busybox_version = null; try { su_isInstalled = su.isInstalled(); su_version = su.getSUVersion(); busybox_isInstalled = busybox.isInstalled(); busybox_version = busybox.getVersion(); } catch (IOException ex) { logger.log(Level.ERROR, "An error occurred while loading the device's root information: " + ex.toString() + "\n" + "The error stack trace will be printed to the console..."); ex.printStackTrace(System.err); interrupt(); } if (su_isInstalled) { superUserStatus_rootLabel.setText(parser.parse("superUserLabel") + " " + parser.parse("true")); superUserVersion_rootLabel.setText(parser.parse("suVersionLabel") + " " + su_version); } else { superUserStatus_rootLabel.setText(parser.parse("superUserLabel") + " " + parser.parse("false")); superUserVersion_rootLabel.setText(parser.parse("suVersionLabel") + " ---"); } if (busybox_isInstalled) { busyboxStatus_rootLabel.setText(parser.parse("busyboxLabel") + " " + parser.parse("true")); busyboxVersion_rootLabel.setText(parser.parse("busyboxVersionLabel") + " " + busybox_version); } else { busyboxStatus_rootLabel.setText(parser.parse("busyboxLabel") + " " + parser.parse("false")); busyboxVersion_rootLabel.setText(parser.parse("busyboxVersionLabel") + " ---"); } } } }.start(); }
37b07547-0214-493a-a5e7-1bf949652a87
7
public void doHDMA() { if (frameDisabled || !hdmaEnabled) return; if (doTransfer) { if (direction == false) hdmaWritePPU(); else hdmaReadPPU(); } rlc = Util.limit(Size.BYTE, rlc-1); doTransfer = isRepeat(); if (getLineCounter() == 0) { rlc = Core.mem.get(Size.BYTE, srcBank, tableAddr); tableAddr++; if (addressMode == true) { // Indirect transferSize = Core.mem.get(Size.SHORT, srcBank, tableAddr); tableAddr += 2; } // Handle special case if rlc == 0(rlc is $43xA) // SEE: http://wiki.superfamicom.org/snes/show/DMA+%26+HDMA if (rlc == 0) { frameDisabled = true; } doTransfer = true; } }
d3e7ff4b-3b08-49ce-ad3b-9ef56c09e5bc
0
public void Read(RandomAccessFile raf) throws Exception { this.id = raf.readInt(); this.Name = raf.readUTF(); this.height = raf.readDouble(); }
370a4c4b-c104-4e0d-ab7c-e07c2049c500
2
public static double power(double number, int power) { if (power < 0) { throw new IllegalArgumentException("Error: int cannot be < 0!"); } double answer = 1; for (int j = 0; j < power; j++) { answer *= number; } return answer; }
2753481f-d4dc-4ec5-93db-a2d8d0a4b4b3
3
private void freePlayerAction(Player user, FreePlayerData data) { if(user.getPosition() instanceof Jail) { if(data.isUseJailbreak() && user.hasJailbreak()) { user.useJailbreak(); } else { ((Jail) user.getPosition()).payFine(user); } } }
800a72d9-bf39-4fa2-abd5-5146aa04351c
6
public static void addConnection(String nom, String hashtag) { Connection con = null; try { Class.forName("org.sqlite.JDBC"); con = DriverManager.getConnection("jdbc:sqlite:" + Parametre.workspace + "/bdd_models"); Statement stmt = con.createStatement(); ResultSet rs; ResultSet rs2; ResultSet rs3; rs = stmt.executeQuery("select nom from modeles where nom='" + nom + "'"); if (rs.next() != false && rs.getString("nom").equals(nom)) { insertTag(hashtag); rs3 = stmt.executeQuery("select nom from correspondances where nom='" + nom + "' and tag='" + hashtag + "'"); if (rs3.next() != false && rs3.getString("nom").equals(nom)) { System.out.println("cette correspondace existe deja"); } else { System.out.println("insertion dan la table de correspondances"); stmt.executeUpdate("insert into correspondances values('" + hashtag + "', '" + nom + "')"); } } else { System.out.println("ce modele n'existe pas"); } } catch (Exception e) { e.printStackTrace(); } finally { try { con.close(); } catch (Exception e) { e.printStackTrace(); } } }
859a0a1f-876e-4e8e-adc2-de75262a3dd5
2
public final synchronized void close(){ if(fileFound){ try{ input.close(); }catch(java.io.IOException e){ System.out.println(e); } } }
39632ddb-ee9f-4175-a3dd-caa961941da0
5
private static void doImportFromXML() throws MVDException { try { if ( xmlFile != null && new File(xmlFile).exists() && textFile == null && !new File(mvdFile).exists() ) { // importing from XML to MVD File xml = new File( xmlFile ); MVD m = MVDXMLFile.internalise( xml ); MVDFile.externalise( m, new File(mvdFile), folderId, Utilities.loadDBProperties(dbConn) ); } } catch ( Exception e ) { throw new MVDToolException( e ); } }
475ec605-6769-4085-b946-3fb74fa398b1
9
public boolean equals(Object object) { if(object == this) { return true; } if(!(object instanceof Persoon)) { return false; } Persoon cobj = (Persoon) object; return ( cobj.bsn==this.bsn && cobj.voornaam.equals(this.voornaam) && cobj.achternaam.equals(this.achternaam) && cobj.dag == this.dag && cobj.maand == this.maand && cobj.jaar == this.jaar && cobj.geslacht == this.geslacht && cobj.dienblad == this.dienblad ); }
4de595a7-ba9d-403e-9bf4-7e61b22de226
7
public List<String> readBdbLogFile(String bdbLogFilePath) throws LogAnalyseException { if (StringUtils.isBlank(bdbLogFilePath)) { throw new LogAnalyseException("bdb log file path is null"); } File bdbLogFile = new File(bdbLogFilePath); if (!bdbLogFile.exists()) { throw new LogAnalyseException(String.format("bdb log file(path:%s) is not exist!", bdbLogFilePath)); } BufferedReader fis = null; try { fis = new BufferedReader(new FileReader(bdbLogFile)); String line = null; List<String> bdbFileLogContentList = new ArrayList<String>(); while ((line = fis.readLine()) != null) { String hadoopLogFileLine = transferBdbToHadoopLine(line); if (hadoopLogFileLine != null) { bdbFileLogContentList.addAll(Arrays.asList(hadoopLogFileLine.split(AnalyseConstants.MULTI_LINE_SPLITTER))); } } mergeReachedBdbLogData(bdbFileLogContentList); return bdbFileLogContentList; } catch (FileNotFoundException e) { throw new LogAnalyseException(e); } catch (IOException e) { throw new LogAnalyseException(e); } finally { try { fis.close(); } catch (IOException e) { } } }
b7a63df4-c9bc-42b4-8c6c-21ff7cac564a
7
@Override public Object clone() { mxCellState clone = new mxCellState(view, cell, style); if (label != null) { clone.label = label; } if (absolutePoints != null) { clone.absolutePoints = new ArrayList<mxPoint>(); for (int i = 0; i < absolutePoints.size(); i++) { clone.absolutePoints.add((mxPoint) absolutePoints.get(i) .clone()); } } if (origin != null) { clone.origin = (mxPoint) origin.clone(); } if (absoluteOffset != null) { clone.absoluteOffset = (mxPoint) absoluteOffset.clone(); } if (labelBounds != null) { clone.labelBounds = (mxRectangle) labelBounds.clone(); } if (boundingBox != null) { clone.boundingBox = (mxRectangle) boundingBox.clone(); } clone.terminalDistance = terminalDistance; clone.segments = segments; clone.length = length; clone.x = x; clone.y = y; clone.width = width; clone.height = height; return clone; }
8bd5d4d5-e42b-4a01-8f11-7b20efc7cc15
3
@Override public boolean equals(Object obj) { if(obj instanceof Item) { Item i = (Item) obj; if(this.name.equals(i.name)) if(this.weight == i.weight) return true; } return false; }
6431d7b7-9dc6-4bbf-9c9c-51dc06d48f41
3
protected void setUp() throws Exception{ super.setUp(); unAuto = new Auto(); unTodoTerreno = new TodoTerreno(); unaMoto = new Moto(); unControlPolicial = new ControlPolicial(); if (unControlPolicial.numeroActual()<50){puntosAuto = 3;} if (unControlPolicial.numeroActual()<30){puntosTodoTerreno =3;} if (unControlPolicial.numeroActual()<80){puntosMoto =3;} }
f0912d83-95ba-4d13-b00f-376bc5cb25b2
4
public void copyToPencilMode() { for(int i = 0; i < 16; i++) { for(int j = 0; j < 16; j++) { if((pencilEntries[i][j].isEditable()) && (pencilEntries[i][j].getText().equals(""))) { pencilEntries[i][j].setText(entries[i][j].getText()); } } } }
935b51fa-9a7f-4ee6-a297-ef3c52113d15
9
@Override public boolean tick(Tickable ticking, int tickID) { if(tickID==Tickable.TICKID_MOB) { if((affected!=null) &&(affected instanceof MOB) &&(invoker!=null)) { final MOB mob=(MOB)affected; if(((mob.amFollowing()!=invoker) ||(mob.amDead()) ||(mob.amFollowing().getGroupMembers(new HashSet<MOB>()).size()>2) ||(mob.charStats().getMyRace() != invoker.charStats().getMyRace()) ||(mob.location()!=invoker.location()))) unInvoke(); } } return super.tick(ticking,tickID); }
e2622a9b-fede-4c54-a20f-578dbd6bca50
5
public String preCreateAssignment() { topics = topicModel.getAll(false); classs = classModel.getAll(); boolean check = true; if (topics.isEmpty()) { addFieldError("asmo.topicId", "Topic List is empty"); check = false; } if (classs.isEmpty()) { addFieldError("asmo.classname", "Class List is empty"); check = false; } if (check) { for (TopicObj topicObj : topics) { mTopic.put(topicObj.getTopicId(), topicObj.getName()); } for (ClassObj classObj : classs) { mClass.put(classObj.getClassname(), classObj.getClassname()); } } return SUCCESS; }
22636589-70ab-41a6-b052-01df67fa52ef
0
@Override public long sizeOf() { return mContent.length(); }
6413112a-ab9f-41c2-a8fe-12f2b6c0d447
7
public static BigDecimal toDecimal(int precision, int scale, byte[] value) { // final boolean positive = (value[0] & 0x80) == 0x80; value[0] ^= 0x80; if (!positive) { for (int i = 0; i < value.length; i++) { value[i] ^= 0xFF; } } // final int x = precision - scale; final int ipDigits = x / DIGITS_PER_4BYTES; final int ipDigitsX = x - ipDigits * DIGITS_PER_4BYTES; final int ipSize = (ipDigits << 2) + DECIMAL_BINARY_SIZE[ipDigitsX]; int offset = DECIMAL_BINARY_SIZE[ipDigitsX]; BigDecimal ip = offset > 0 ? BigDecimal.valueOf(CodecUtils.toInt(value, 0, offset)) : BigDecimal.ZERO; for(; offset < ipSize; offset += 4) { final int i = CodecUtils.toInt(value, offset, 4); ip = ip.movePointRight(DIGITS_PER_4BYTES).add(BigDecimal.valueOf(i)); } // int shift = 0; BigDecimal fp = BigDecimal.ZERO; for (; shift + DIGITS_PER_4BYTES <= scale; shift += DIGITS_PER_4BYTES, offset += 4) { final int i = CodecUtils.toInt(value, offset, 4); fp = fp.add(BigDecimal.valueOf(i).movePointLeft(shift + DIGITS_PER_4BYTES)); } if(shift < scale) { final int i = CodecUtils.toInt(value, offset, DECIMAL_BINARY_SIZE[scale - shift]); fp = fp.add(BigDecimal.valueOf(i).movePointLeft(scale)); } // return positive ? POSITIVE_ONE.multiply(ip.add(fp)) : NEGATIVE_ONE.multiply(ip.add(fp)); }
313b25e5-3e43-44db-a353-6a07e611ffe1
5
protected String makeIndentStr(int indent) { String tabSpaceString = /* (tab x 20) . (space x 20) */ "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t "; if (indent < 0) return "NEGATIVEINDENT" + indent; int tabs = indent / tabWidth; indent -= tabs * tabWidth; if (tabs <= 20 && indent <= 20) { /* The fast way. */ return tabSpaceString.substring(20 - tabs, 20 + indent); } else { /* the not so fast way */ StringBuffer sb = new StringBuffer(tabs + indent); while (tabs > 20) { sb.append(tabSpaceString.substring(0, 20)); tabs -= 20; } sb.append(tabSpaceString.substring(0, tabs)); while (indent > 20) { sb.append(tabSpaceString.substring(20)); indent -= 20; } sb.append(tabSpaceString.substring(40 - indent)); return sb.toString(); } }
577bb5b4-898d-4c4d-9cc2-286f00abf0a3
9
static public ObjectFlag fromLetter(final char c) { switch (c) { case 'B': return BANK; case 'D': return DARK; case 'G': return GUEST; case 'F': return FORGE; case 'H': return HOUSE; case 'M': return MERCHANT; case 'S': return SILENT; case 'Q': return QUIET; case 'V': return VENDOR; default: throw new IllegalArgumentException("Invalid ObjectFlag letter: " + c); } }
2c31e818-2f0d-4233-824a-abb7072472f0
6
public static String changeXY(String str) { if(str.length()==0){ return str; } else if(str.length()==1 && str.equals("x")){ String s=str.replace(str.substring(str.length()-1),"y"); return s; } else if(str.length()==1 && ! str.equals("x")){ return str; } else{ if(str.substring(str.length()-1).equals("x")){ String s=str.replace(str.substring(str.length()-1),"y"); return changeXY(s)+ str.substring(str.length()-1); } else{ return changeXY(str.substring(0,str.length()-1))+str.substring(str.length()-1); } } }
849509e9-b592-4889-9b4c-81ea6a0ae2dd
6
public SystemUI() { _instance = this; _timeSheetCtrl = new TimeSheetCtrl(); _clientCtrl = new ClientCtrl(); _searchCtrl = new SearchCtrl(); setIconImage(Toolkit.getDefaultToolkit().getImage(SystemUI.class.getResource("/icons/48x48/app.png"))); setTitle(SystemInformation.systemInformation(1) + " (" + SystemInformation.systemInformation(2) + " - build " + SystemInformation.systemInformation(3) + ")"); setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); WindowListener exitListener = new WindowAdapter() { public void windowClosing(WindowEvent e) { applicationExit(); } }; addWindowListener(exitListener); setBounds(0,0,1024,768); setLocationRelativeTo(null); setMinimumSize(new Dimension(1024,768)); setResizable(false); JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenu mnFiles = new JMenu("Filer"); mnFiles.setFont(new Font("Dialog", Font.PLAIN, 12)); menuBar.add(mnFiles); JMenuItem mntmPrint = new JMenuItem("Udskriv"); mntmPrint.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { printSheet(); } }); mnFiles.add(mntmPrint); JSeparator separator = new JSeparator(); mnFiles.add(separator); JMenuItem mntmLogout = new JMenuItem("Logud"); mntmLogout.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { applicationLogout(); } }); mnFiles.add(mntmLogout); JMenuItem mntmExit = new JMenuItem("Afslut"); mntmExit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { applicationExit(); } }); mnFiles.add(mntmExit); JMenu mnTimeSheet = new JMenu("Time-sag"); mnTimeSheet.setFont(new Font("Dialog", Font.PLAIN, 12)); menuBar.add(mnTimeSheet); JMenuItem mntmNewTimeSheet = new JMenuItem("Ny time-sag"); mntmNewTimeSheet.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { CreateTimeSheetUI.createWindow(); } }); mnTimeSheet.add(mntmNewTimeSheet); JMenu mnClient = new JMenu("Klient"); mnClient.setFont(new Font("Dialog", Font.PLAIN, 12)); menuBar.add(mnClient); JMenuItem mntmNewClient = new JMenuItem("Ny klient"); mntmNewClient.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { CreateClientUI.createWindow(); } }); mnClient.add(mntmNewClient); JMenuItem mntmEditClient = new JMenuItem("Rediger klient"); mntmEditClient.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); mnClient.add(mntmEditClient); JMenu mnSettings = new JMenu("Indstillinger"); mnSettings.setFont(new Font("Dialog", Font.PLAIN, 12)); menuBar.add(mnSettings); JMenuItem mntmPrintSettings = new JMenuItem("Udskrift"); mntmPrintSettings.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { PrintSettingsUI.createWindow(); } }); mnSettings.add(mntmPrintSettings); JMenu mnAbout = new JMenu("Om"); mnAbout.setFont(new Font("Dialog", Font.PLAIN, 12)); menuBar.add(mnAbout); JMenuItem mntmAboutThis = new JMenuItem("Applikationen"); mntmAboutThis.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { AboutUI.createWindow(); } }); mnAbout.add(mntmAboutThis); pnlSystemLayout = new JPanel(); pnlSystemLayout.setBorder(new EmptyBorder(5,5,5,5)); setContentPane(pnlSystemLayout); pnlSystemLayout.setLayout(null); JPanel pnlQuickAccess = new JPanel(); pnlQuickAccess.setBounds(5,0,1014,37); pnlSystemLayout.add(pnlQuickAccess); pnlQuickAccess.setLayout(null); JLabel lblNewTimeSheet = new JLabel("Ny time-sag"); lblNewTimeSheet.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { CreateTimeSheetUI.createWindow(); } }); lblNewTimeSheet.setFont(new Font("Dialog", Font.PLAIN, 12)); lblNewTimeSheet.setCursor(new Cursor(Cursor.HAND_CURSOR)); lblNewTimeSheet.setIcon(new ImageIcon(SystemUI.class.getResource("/icons/16x16/new_timesheet.png"))); lblNewTimeSheet.setBounds(5,12,95,16); pnlQuickAccess.add(lblNewTimeSheet); JLabel lblNewDataEntry = new JLabel("Ny registrering"); lblNewDataEntry.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { newDataEntry(); } }); lblNewDataEntry.setFont(new Font("Dialog", Font.PLAIN, 12)); lblNewDataEntry.setCursor(new Cursor(Cursor.HAND_CURSOR)); lblNewDataEntry.setIcon(new ImageIcon(SystemUI.class.getResource("/icons/16x16/new_dataentry.png"))); lblNewDataEntry.setBounds(115,12,114,16); pnlQuickAccess.add(lblNewDataEntry); JLabel lblNewClient = new JLabel("Ny klient"); lblNewClient.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { CreateClientUI.createWindow(); } }); lblNewClient.setFont(new Font("Dialog", Font.PLAIN, 12)); lblNewClient.setCursor(new Cursor(Cursor.HAND_CURSOR)); lblNewClient.setIcon(new ImageIcon(SystemUI.class.getResource("/icons/16x16/new_client.png"))); lblNewClient.setBounds(244,12,75,16); pnlQuickAccess.add(lblNewClient); JLabel lblPrintOverview = new JLabel("Udskriv"); lblPrintOverview.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { printSheet(); } }); lblPrintOverview.setFont(new Font("Dialog", Font.PLAIN, 12)); lblPrintOverview.setCursor(new Cursor(Cursor.HAND_CURSOR)); lblPrintOverview.setIcon(new ImageIcon(SystemUI.class.getResource("/icons/16x16/print_overview.png"))); lblPrintOverview.setBounds(333,12,68,16); pnlQuickAccess.add(lblPrintOverview); JLabel lblSortOverview = new JLabel("Sort" + "\u00e9" + "r"); lblSortOverview.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { SortUI.createWindow(); } }); lblSortOverview.setFont(new Font("Dialog", Font.PLAIN, 12)); lblSortOverview.setCursor(new Cursor(Cursor.HAND_CURSOR)); lblSortOverview.setIcon(new ImageIcon(SystemUI.class.getResource("/icons/16x16/sort_overview.png"))); lblSortOverview.setBounds(416,12,60,16); pnlQuickAccess.add(lblSortOverview); JLabel lblPermission = new JLabel("Rettigheder"); lblPermission.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { editRights(); } }); lblPermission.setFont(new Font("Dialog", Font.PLAIN, 12)); lblPermission.setCursor(new Cursor(Cursor.HAND_CURSOR)); lblPermission.setIcon(new ImageIcon(SystemUI.class.getResource("/icons/16x16/permission_timesheet.png"))); lblPermission.setBounds(493,12,114,16); pnlQuickAccess.add(lblPermission); JLabel lblSearchOverview = new JLabel(); lblSearchOverview.setCursor(new Cursor(Cursor.HAND_CURSOR)); lblSearchOverview.setIcon(new ImageIcon(SystemUI.class.getResource("/icons/16x16/search_overview.png"))); lblSearchOverview.setBounds(833,12,16,16); pnlQuickAccess.add(lblSearchOverview); txtSearchOverview = new JTextField(); txtSearchOverview.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { txtSearchOverview.setText(""); } @Override public void focusLost(FocusEvent e) { txtSearchOverview.setText("S\u00F8g"); } }); txtSearchOverview.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { try { SearchUI.createWindow(_searchCtrl.search(txtSearchOverview.getText())); } catch (Exception ex) { ex.printStackTrace(); } } } }); txtSearchOverview.setText("S\u00F8g"); txtSearchOverview.setBounds(854,9,155,22); pnlQuickAccess.add(txtSearchOverview); txtSearchOverview.setColumns(10); JPanel pnlOverviewSelection = new JPanel(); pnlOverviewSelection.setBounds(5,36,215,675); pnlSystemLayout.add(pnlOverviewSelection); pnlOverviewSelection.setLayout(null); // START OF TIMESHEETS PANEL pnlTimeSheet = new JPanel(); pnlTimeSheet.setBounds(220,36,799,675); pnlSystemLayout.add(pnlTimeSheet); pnlTimeSheet.setLayout(null); // START OF TS_INFO PANEL JPanel pnlTimeSheetInfo = new JPanel(); pnlTimeSheetInfo.setBorder(new LineBorder(Color.LIGHT_GRAY)); pnlTimeSheetInfo.setBackground(Color.WHITE); pnlTimeSheetInfo.setBounds(3,2,790,86); pnlTimeSheet.add(pnlTimeSheetInfo); pnlTimeSheetInfo.setLayout(null); lblClientName_ts = new JLabel(); lblClientName_ts.setForeground(UIManager.getColor("CheckBoxMenuItem.acceleratorForeground")); lblClientName_ts.setFont(new Font("Dialog", Font.PLAIN, 18)); lblClientName_ts.setBounds(5,5,500,20); pnlTimeSheetInfo.add(lblClientName_ts); lblCaseId_ts = new JLabel(); lblCaseId_ts.setHorizontalAlignment(SwingConstants.RIGHT); lblCaseId_ts.setForeground(UIManager.getColor("CheckBoxMenuItem.acceleratorForeground")); lblCaseId_ts.setFont(new Font("Dialog", Font.PLAIN, 18)); lblCaseId_ts.setBounds(535,5,250,20); pnlTimeSheetInfo.add(lblCaseId_ts); lblClientAddress_ts = new JLabel(); lblClientAddress_ts.setForeground(Color.GRAY); lblClientAddress_ts.setFont(new Font("Dialog", Font.PLAIN, 12)); lblClientAddress_ts.setBounds(5,25,500,15); pnlTimeSheetInfo.add(lblClientAddress_ts); lblClientPhoneNo_ts = new JLabel(); lblClientPhoneNo_ts.setFont(new Font("Dialog", Font.PLAIN, 12)); lblClientPhoneNo_ts.setBounds(5,52,450,15); pnlTimeSheetInfo.add(lblClientPhoneNo_ts); lblClientEmail_ts = new JLabel(); lblClientEmail_ts.setFont(new Font("Dialog", Font.PLAIN, 12)); lblClientEmail_ts.setBounds(5,66,450,15); pnlTimeSheetInfo.add(lblClientEmail_ts); lblTimeSheetOwner_ts = new JLabel(); lblTimeSheetOwner_ts.setHorizontalAlignment(SwingConstants.RIGHT); lblTimeSheetOwner_ts.setFont(new Font("Dialog", Font.PLAIN, 12)); lblTimeSheetOwner_ts.setBounds(485,66,300,15); pnlTimeSheetInfo.add(lblTimeSheetOwner_ts); // END OF TS_INFO PANEL // START OF NOTE PANEL JPanel pnlTimeSheetNote = new JPanel(); pnlTimeSheetNote.setBackground(Color.WHITE); pnlTimeSheetNote.setBorder(new LineBorder(Color.LIGHT_GRAY)); pnlTimeSheetNote.setBounds(3,99,790,65); pnlTimeSheet.add(pnlTimeSheetNote); pnlTimeSheetNote.setLayout(null); txtNoteField = new JTextArea(); txtNoteField.setBounds(5,5,780,55); txtNoteField.setEditable(false); pnlTimeSheetNote.add(txtNoteField); // END OF NOTE PANEL // START OF SHEETGRID JPanel pnlTimeSheetOverview = new JPanel(); pnlTimeSheetOverview.setBounds(3,170,790,498); pnlTimeSheet.add(pnlTimeSheetOverview); sheetColumn = new String[]{"P" + "\u00e5" + "begyndt", "Afsluttet", "Opgave", "Registrator", "Bem" + "\u00e6" + "rkning", " "}; sheetTable = new JTable() { public boolean isCellEditable(int data, int columns) { if(columns == 5 || columns == 6) return true; return false; } }; sheetModel = new DefaultTableModel(); sheetTable.setModel(sheetModel); sheetTable.setFillsViewportHeight(true); JScrollPane sheetDataScroll = new JScrollPane(sheetTable); sheetTable.setBorder(new LineBorder(Color.LIGHT_GRAY)); sheetTable.setPreferredScrollableViewportSize(new Dimension(790,493)); sheetDataScroll.setPreferredSize(new Dimension(790,493)); sheetDataScroll.setBorder(BorderFactory.createEmptyBorder()); pnlTimeSheetOverview.add(sheetDataScroll); // END OF SHEETGRID // END OF TIMESHEETS PANEL // START OF CLIENTS PANEL pnlClients = new JPanel(); pnlClients.setBounds(220,36,799,675); pnlSystemLayout.add(pnlClients); pnlClients.setLayout(null); // START OF CL_INFO PANEL JPanel pnlClientInfo = new JPanel(); pnlClientInfo.setLayout(null); pnlClientInfo.setBorder(new LineBorder(Color.LIGHT_GRAY)); pnlClientInfo.setBackground(Color.WHITE); pnlClientInfo.setBounds(3,2,790,86); pnlClients.add(pnlClientInfo); lblClientName_cl = new JLabel(); lblClientName_cl.setForeground(UIManager.getColor("CheckBoxMenuItem.acceleratorForeground")); lblClientName_cl.setFont(new Font("Dialog", Font.PLAIN, 18)); lblClientName_cl.setBounds(5,5,500,20); pnlClientInfo.add(lblClientName_cl); lblClientAddress_cl = new JLabel(); lblClientAddress_cl.setForeground(Color.GRAY); lblClientAddress_cl.setFont(new Font("Dialog", Font.PLAIN, 12)); lblClientAddress_cl.setBounds(5,25,500,15); pnlClientInfo.add(lblClientAddress_cl); lblClientPhoneNo_cl = new JLabel(); lblClientPhoneNo_cl.setFont(new Font("Dialog", Font.PLAIN, 12)); lblClientPhoneNo_cl.setBounds(5,52,450,15); pnlClientInfo.add(lblClientPhoneNo_cl); lblClientEmail_cl = new JLabel(); lblClientEmail_cl.setFont(new Font("Dialog", Font.PLAIN, 12)); lblClientEmail_cl.setBounds(5,66,450,15); pnlClientInfo.add(lblClientEmail_cl); // END OF CL_INFO PANEL // START OF CLIENTGRID JPanel pnlClientOverview = new JPanel(); pnlClientOverview.setBounds(3,94,790,574); pnlClients.add(pnlClientOverview); clientColumn = new String[]{"Sags nr", "Oprettet", "Ansvarlig", "Note", " "}; clientTable = new JTable() { public boolean isCellEditable(int data, int columns) { if(columns == 4 || columns == 5) return true; return false; } }; clientModel = new DefaultTableModel(); clientTable.setModel(clientModel); clientTable.setFillsViewportHeight(true); JScrollPane clientDataScroll = new JScrollPane(clientTable); clientTable.setBorder(new LineBorder(Color.LIGHT_GRAY)); clientTable.setPreferredScrollableViewportSize(new Dimension(790,569)); clientDataScroll.setPreferredSize(new Dimension(790,569)); clientDataScroll.setBorder(BorderFactory.createEmptyBorder()); pnlClientOverview.add(clientDataScroll); // END OF CLIENTGRID // END OF CLIENTS PANEL // START OF TAB SECTION JTabbedPane tabSelection = new JTabbedPane(JTabbedPane.TOP); tabSelection.setFont(new Font("Dialog", Font.PLAIN, 12)); tabSelection.setBounds(5, 0, 202, 668); tabSelection.addChangeListener(this); pnlOverviewSelection.add(tabSelection); // START OF CASE TAB JPanel pnlTimeSheetTab = new JPanel(); tabSelection.addTab("Time-sager", null, pnlTimeSheetTab, null); pnlTimeSheetTab.setLayout(null); JPanel pnlSheetList = new JPanel(); pnlSheetList.setBounds(5,5,187,605); pnlSheetList.setLayout(null); pnlTimeSheetTab.add(pnlSheetList); lstTimeSheets = new JList<String>(); lstTimeSheets.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { dbInfo.setVisible(true); addSheetData(); } }); lstTimeSheets.setListData(populateSheetList()); lstTimeSheets.setFont(new Font("Dialog", Font.PLAIN, 12)); lstTimeSheets.setBorder(new LineBorder(Color.LIGHT_GRAY)); lstTimeSheets.setBounds(0,0,187,605); JScrollPane sheetListScroll = new JScrollPane(lstTimeSheets); pnlSheetList.add(sheetListScroll); pnlSheetList.add(lstTimeSheets); chkUsersSheetsOnly = new JCheckBox("Vis kun mine sager"); chkUsersSheetsOnly.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { checkUserSheetsOnly(); } }); chkUsersSheetsOnly.setFont(new Font("Dialog", Font.PLAIN, 12)); chkUsersSheetsOnly.setBounds(5,614,160,23); pnlTimeSheetTab.add(chkUsersSheetsOnly); JLabel lblRefreshTs = new JLabel(); lblRefreshTs.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { refreshList(); } }); lblRefreshTs.setCursor(new Cursor(Cursor.HAND_CURSOR)); lblRefreshTs.setIcon(new ImageIcon(SystemUI.class.getResource("/icons/16x16/list_refresh.png"))); lblRefreshTs.setBounds(170,617,16,16); pnlTimeSheetTab.add(lblRefreshTs); // END OF CASE TAB // START OF CLIENT TAB JPanel pnlClientTab = new JPanel(); tabSelection.addTab("Klienter", null, pnlClientTab, null); pnlClientTab.setLayout(null); JPanel pnlClientList = new JPanel(); pnlClientList.setBounds(5,5,187,605); pnlClientList.setLayout(null); pnlClientTab.add(pnlClientList); lstClients = new JList<String>(); lstClients.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { dbInfo.setVisible(true); addClientData(); } }); lstClients.setListData(populateClientList()); lstClients.setFont(new Font("Dialog", Font.PLAIN, 12)); lstClients.setBorder(new LineBorder(Color.LIGHT_GRAY)); lstClients.setBounds(0,0,187,605); JScrollPane clientListScroll = new JScrollPane(lstClients); pnlClientList.add(clientListScroll); pnlClientList.add(lstClients); JLabel lblRefreshCli = new JLabel(); lblRefreshCli.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { refreshList(); } }); lblRefreshCli.setCursor(new Cursor(Cursor.HAND_CURSOR)); lblRefreshCli.setIcon(new ImageIcon(SystemUI.class.getResource("/icons/16x16/list_refresh.png"))); lblRefreshCli.setBounds(170,617,16,16); pnlClientTab.add(lblRefreshCli); // END OF CLIENT TAB // END OF TAB SECTION }
9a5e3dc1-cd8b-4192-b3f4-8ebd1541c3b5
9
public String numeroALetra(String numero, boolean mayusculas) { String literal = ""; String parte_decimal; //si el numero utiliza (.) en lugar de (,) -> se reemplaza numero = numero.replace(".", ","); //si el numero no tiene parte decimal, se le agrega ,00 if (numero.indexOf(",") == -1) { numero = numero + ",00"; } //se valida formato de entrada -> 0,00 y 999 999 999,00 if (Pattern.matches("\\d{1,9},\\d{1,2}", numero)) { //se divide el numero 0000000,00 -> entero y decimal String Num[] = numero.split(","); //de da formato al numero decimal parte_decimal = "con " + (Num[1].length() <= 1 ? Num[1] + "0" : Num[1]) + "/100 Nuevos Soles."; //se convierte el numero a literal if (Integer.parseInt(Num[0]) == 0) {//si el valor es cero literal = "cero "; } else if (Integer.parseInt(Num[0]) > 999999) {//si es millon literal = getMillones(Num[0]); } else if (Integer.parseInt(Num[0]) > 999) {//si es miles literal = getMiles(Num[0]); } else if (Integer.parseInt(Num[0]) > 99) {//si es centena literal = getCentenas(Num[0]); } else if (Integer.parseInt(Num[0]) > 9) {//si es decena literal = getDecenas(Num[0]); } else {//sino unidades -> 9 literal = getUnidades(Num[0]); } //devuelve el resultado en mayusculas o minusculas if (mayusculas) { return (literal).toUpperCase(); } else { return (literal); } } else {//error, no se puede convertir return literal = null; } }
cec2f131-4541-4a0f-8c6b-79728588bbc8
1
public String getUpdate(String appKey, String userKey, String version) { try { appKey = URLEncoder.encode(appKey, "UTF-8"); userKey = URLEncoder.encode(userKey, "UTF-8"); version = URLEncoder.encode(version, "UTF-8"); } catch (UnsupportedEncodingException e) { BmLog.error(e); } return String.format("%s/api/rest/blazemeter/jmeter_plugin_update/?app_key=%s&user_key=%s&current_version=%s", SERVER_URL, appKey, userKey, version); }
bf603108-3188-4437-b3f0-3b503c43d301
3
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof User)) { return false; } final User user = (User) o; return !(username != null ? !username.equals(user.getUsername()) : user.getUsername() != null); }
2b5d3480-d888-490c-a534-fff530adae4f
7
public MapleCustomQuest(int id) { try { this.id = id; startActs = new LinkedList<MapleQuestAction>(); completeActs = new LinkedList<MapleQuestAction>(); startReqs = new LinkedList<MapleQuestRequirement>(); completeReqs = new LinkedList<MapleQuestRequirement>(); PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("SELECT * FROM questrequirements WHERE questid = ?"); ps.setInt(1, id); ResultSet rs = ps.executeQuery(); MapleQuestRequirement req; MapleCustomQuestData data; while (rs.next()) { Blob blob = rs.getBlob("data"); ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(blob.getBytes(1, (int) blob.length()))); data = (MapleCustomQuestData) ois.readObject(); req = new MapleQuestRequirement(this, MapleQuestRequirementType.getByWZName(data.getName()), data); final byte status = rs.getByte("status"); if (status == 0) { startReqs.add(req); } else if (status == 1) { completeReqs.add(req); } } rs.close(); ps.close(); ps = DatabaseConnection.getConnection().prepareStatement("SELECT * FROM questactions WHERE questid = ?"); ps.setInt(1, id); rs = ps.executeQuery(); MapleQuestAction act; while (rs.next()) { Blob blob = rs.getBlob("data"); ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(blob.getBytes(1, (int) blob.length()))); data = (MapleCustomQuestData) ois.readObject(); act = new MapleQuestAction(MapleQuestActionType.getByWZName(data.getName()), data, this); final byte status = rs.getByte("status"); if (status == 0) { startActs.add(act); } else if (status == 1) { completeActs.add(act); } } rs.close(); ps.close(); } catch (Exception ex) { ex.printStackTrace(); System.err.println("Error loading custom quest from SQL." + ex); } }
877e7487-606a-4aac-9fd4-2c79fac0ed60
4
public int FantasmaX(int n){ Query q2; Variable a = new Variable("X"); Variable b = new Variable("Y"); switch(n){ case 0: q2 = new Query("blinky", new Term[]{a,b}); return java.lang.Integer.parseInt(q2.oneSolution().get("X").toString()); case 1: q2 = new Query("clyde", new Term[]{a,b}); return java.lang.Integer.parseInt(q2.oneSolution().get("X").toString()); case 2: q2 = new Query("inky", new Term[]{a,b}); return java.lang.Integer.parseInt(q2.oneSolution().get("X").toString()); case 3: q2 = new Query("pinky", new Term[]{a,b}); return java.lang.Integer.parseInt(q2.oneSolution().get("X").toString()); default: return 0; } }
e99c1806-8119-48cc-ac13-2d72e4fdf7be
7
public static Term fromString(String str){ String temp = new String(str); TermImp result = null; if (temp.contains("x^")){ // handle term with the form ax^n StringTokenizer strTok = new StringTokenizer(temp, "x^"); List<String> list = new ArrayList<String>(2); while(strTok.hasMoreElements()){ list.add((String) strTok.nextElement()); } if (list.size() == 0){ throw new IllegalArgumentException("Argument string is formatter illegally."); } else if (list.size() == 1){ // term if of the form x^n, where n is the exponent Integer expo = Integer.parseInt(list.get(0)); result = new TermImp(1, expo); } else { // term if of the form ax^n, where a, (a != 1) is the coefficient and n is the exponent Double coeff = Double.parseDouble(list.get(0)); Integer expo = Integer.parseInt(list.get(1)); result = new TermImp(coeff, expo); } } else if (temp.contains("x")){ // handle value with exponent == 1 StringTokenizer strTok = new StringTokenizer(temp, "x"); List<String> list = new ArrayList<String>(2); while(strTok.hasMoreElements()){ list.add((String) strTok.nextElement()); } if (list.size() == 0){ // term is of the form x, with coefficient = 1 and exponent = 1 result = new TermImp(1.0, 1); } else { // term is of the form ax, with coefficient = a and exponent = 1 Double coeff = Double.parseDouble(list.get(0)); result = new TermImp(coeff, 1); } } else { // handle numeric value result = new TermImp(Double.parseDouble(temp), 0); } return result; }
1ee64af4-6379-4954-afb5-cca623a54242
0
@SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { txt2 = new javax.swing.JTextField(); txt3 = new javax.swing.JTextField(); txt4 = new javax.swing.JTextField(); txt5 = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); btnCerrar = new javax.swing.JButton(); btnRegistrar = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); txt1 = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel5.setText("Precio Unitario:"); jLabel4.setText("Cantidad:"); jLabel3.setText("Descripcion:"); jLabel2.setText("Nombre:"); btnCerrar.setText("Cerrar"); btnCerrar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCerrarActionPerformed(evt); } }); btnRegistrar.setText("Registrar"); btnRegistrar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRegistrarActionPerformed(evt); } }); jLabel1.setText("Codigo:"); txt1.setEditable(false); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel3) .addComponent(jLabel4) .addComponent(jLabel5) .addComponent(jLabel1)) .addGap(39, 39, 39) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(txt2) .addComponent(txt3) .addComponent(txt4) .addComponent(txt5, javax.swing.GroupLayout.DEFAULT_SIZE, 118, Short.MAX_VALUE) .addComponent(txt1)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(btnRegistrar) .addComponent(btnCerrar)) .addContainerGap(27, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(txt1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txt2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnRegistrar))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(txt3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txt4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnCerrar))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel5) .addComponent(txt5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents