text
stringlengths
14
410k
label
int32
0
9
public void drawState(Graphics g, State state) { if (selected.contains(state)) { getStateDrawer().drawState(g, getAutomaton(), state, state.getPoint(), SELECTED_COLOR); if (doesDrawStateLabels()) getStateDrawer().drawStateLabel(g, state, state.getPoint(), StateDrawer.STATE_COLOR); } else super.drawState(g, state); }
2
private void func_48430_a(File par1File, File par2File, WorldChunkManager par3WorldChunkManager, int par4, int par5, IProgressUpdate par6IProgressUpdate) { try { String var7 = par2File.getName(); RegionFile var8 = new RegionFile(par2File); RegionFile var9 = new RegionFile(new File(par1File, var7.substring(0, var7.length() - ".mcr".length()) + ".mca")); for (int var10 = 0; var10 < 32; ++var10) { int var11; for (var11 = 0; var11 < 32; ++var11) { if (var8.isChunkSaved(var10, var11) && !var9.isChunkSaved(var10, var11)) { DataInputStream var12 = var8.getChunkDataInputStream(var10, var11); if (var12 == null) { System.out.println("Failed to fetch input stream"); } else { NBTTagCompound var13 = CompressedStreamTools.read(var12); var12.close(); NBTTagCompound var14 = var13.getCompoundTag("Level"); AnvilConverterData var15 = ChunkLoader.load(var14); NBTTagCompound var16 = new NBTTagCompound(); NBTTagCompound var17 = new NBTTagCompound(); var16.setTag("Level", var17); ChunkLoader.convertToAnvilFormat(var15, var17, par3WorldChunkManager); DataOutputStream var18 = var9.getChunkDataOutputStream(var10, var11); CompressedStreamTools.write(var16, var18); var18.close(); } } } var11 = (int)Math.round(100.0D * (double)(par4 * 1024) / (double)(par5 * 1024)); int var20 = (int)Math.round(100.0D * (double)((var10 + 1) * 32 + par4 * 1024) / (double)(par5 * 1024)); if (var20 > var11) { par6IProgressUpdate.setLoadingProgress(var20); } } var8.close(); var9.close(); } catch (IOException var19) { var19.printStackTrace(); } }
7
public static void pprintDescriptionsAsRule(Description head, Description tail, Proposition rule, org.powerloom.PrintableStringWriter stream) { { Vector headvariables = null; Vector tailvariables = null; boolean forwardruleP = ((BooleanWrapper)(KeyValueList.dynamicSlotValue(rule.dynamicSlots, OntosaurusUtil.SYM_LOGIC_FORWARD_ONLYp, Stella.FALSE_WRAPPER))).wrapperValue; String operatorprefix = Proposition.chooseImplicationOperator(rule, forwardruleP).symbolName; int operatorindent = operatorprefix.length() + 2; if (head.deletedP() || tail.deletedP()) { { Object old$PrintreadablyP$000 = Stella.$PRINTREADABLYp$.get(); try { Native.setBooleanSpecial(Stella.$PRINTREADABLYp$, false); OntosaurusUtil.pprintObject(StringWrapper.wrapString("(=> <DeLeTeD ArGuMeNt(S)>)"), stream); } finally { Stella.$PRINTREADABLYp$.set(old$PrintreadablyP$000); } } return; } if (forwardruleP) { { Description temp = head; head = tail; tail = temp; } } if ((tail.proposition == null) && (head.proposition == null)) { OntosaurusUtil.pprintNamedDescriptionsAsRule(((NamedDescription)(head)), ((NamedDescription)(tail)), operatorprefix, stream); return; } headvariables = head.ioVariables; tailvariables = tail.ioVariables; if (tail.proposition == null) { tailvariables = headvariables; } else if (head.proposition == null) { headvariables = tailvariables; } OntosaurusUtil.REUSABLE_SKOLEM_MAPPING_TABLE.clear(); { PatternVariable tailvbl = null; Vector vector000 = tailvariables; int index000 = 0; int length000 = vector000.length(); PatternVariable headvbl = null; Vector vector001 = headvariables; int index001 = 0; int length001 = vector001.length(); for (;(index000 < length000) && (index001 < length001); index000 = index000 + 1, index001 = index001 + 1) { tailvbl = ((PatternVariable)((vector000.theArray)[index000])); headvbl = ((PatternVariable)((vector001.theArray)[index001])); OntosaurusUtil.REUSABLE_SKOLEM_MAPPING_TABLE.insertAt(headvbl, tailvbl); } } stream.print("(" + OntosaurusUtil.operatorToString(OntosaurusUtil.SGT_PL_KERNEL_KB_FORALL) + " "); Native.setIntSpecial(OntosaurusUtil.$PPRINT_INDENT$, ((Integer)(OntosaurusUtil.$PPRINT_INDENT$.get())).intValue() + 8); OntosaurusUtil.pprintQuantifiedVariables(tailvariables, false, stream); Native.setIntSpecial(OntosaurusUtil.$PPRINT_INDENT$, ((Integer)(OntosaurusUtil.$PPRINT_INDENT$.get())).intValue() - 5); OntosaurusUtil.pprintNewline(stream); stream.print("("); { Object old$PrintreadablyP$001 = Stella.$PRINTREADABLYp$.get(); try { Native.setBooleanSpecial(Stella.$PRINTREADABLYp$, false); OntosaurusUtil.pprintObject(StringWrapper.wrapString(operatorprefix), stream); } finally { Stella.$PRINTREADABLYp$.set(old$PrintreadablyP$001); } } stream.print(" "); Native.setIntSpecial(OntosaurusUtil.$PPRINT_INDENT$, ((Integer)(OntosaurusUtil.$PPRINT_INDENT$.get())).intValue() + operatorindent); { Object old$Skolemnamemappingtable$000 = Logic.$SKOLEMNAMEMAPPINGTABLE$.get(); try { Native.setSpecial(Logic.$SKOLEMNAMEMAPPINGTABLE$, OntosaurusUtil.REUSABLE_SKOLEM_MAPPING_TABLE); OntosaurusUtil.helpPprintDescriptionsAsRule(head, stream); } finally { Logic.$SKOLEMNAMEMAPPINGTABLE$.set(old$Skolemnamemappingtable$000); } } OntosaurusUtil.REUSABLE_SKOLEM_MAPPING_TABLE.clear(); OntosaurusUtil.pprintNewline(stream); OntosaurusUtil.helpPprintDescriptionsAsRule(tail, stream); Native.setIntSpecial(OntosaurusUtil.$PPRINT_INDENT$, ((Integer)(OntosaurusUtil.$PPRINT_INDENT$.get())).intValue() - operatorindent); Native.setIntSpecial(OntosaurusUtil.$PPRINT_INDENT$, ((Integer)(OntosaurusUtil.$PPRINT_INDENT$.get())).intValue() - 3); stream.print("))"); } }
9
public static void recoverTree(TreeNode root) { List<TreeNode> nodes = new ArrayList<TreeNode>(); traversal(root, nodes); for (TreeNode tn : nodes) {System.out.print(tn.val + " ");} int i = 0; int index1 = -1; int index2 = -1; for (i = 0; i < nodes.size() - 1; i++) { if (nodes.get(i).val > nodes.get(i + 1).val) { index1 = i; i++; break; } } for (; i < nodes.size() - 1; i++) { if (nodes.get(i).val > nodes.get(i + 1).val) { index2 = i + 1; break; } } if (-1 == index1) return; if (-1 == index2) index2 = index1 + 1; TreeNode r1 = nodes.get(index1); TreeNode r2 = nodes.get(index2); int val = r1.val; r1.val = r2.val; r2.val = val; nodes.clear(); traversal(root, nodes); System.out.println(); for (TreeNode tn : nodes) {System.out.print(tn.val + " ");} }
8
public static String convertToUnix(String text) { // Convert \r\n -> \n text = Replace.replace(text,"\r\n","\n"); // Convert \r -> \n text = Replace.replace(text,"\r","\n"); return text; }
0
public void paintContent(Graphics2D g) { int w = getWidth(); int h = getHeight(); g.setColor(Color.LIGHT_GRAY); g.fillRect(0, 0, w, h); g.setColor(Color.BLACK); int xFactor = 5; int yFactor = 3; g.setColor(Color.BLACK); backWall = new Rectangle(w / xFactor, -1, w - w / xFactor * 2, h - h / yFactor + 1); g.drawLine(0, backWall.y + backWall.height + h / yFactor / 2, backWall.x, backWall.y + backWall.height); g.drawLine(w, backWall.y + backWall.height + h / yFactor / 2, backWall.x + backWall.width, backWall.y + backWall.height); g.draw(backWall); int doorWidth = w / 8; int doorHeight = h / 3; int pc = doorWidth / 4; // perspective correction for (int i = 0; i < doors.length; i++) { if (i == 0) doors[0].setBounds(backWall.x + backWall.width / 2 - doorWidth / 2, backWall.y + backWall.height - doorHeight, doorWidth, doorHeight); else if (i == 1) doors[1].setBounds(w / 4 / 2 - doorWidth / 2 - pc / 2, backWall.y + backWall.height - doorHeight + doorHeight / 8, doorWidth - pc, doorHeight + doorHeight / 4); else if (i == 2) doors[2].setBounds(w - w / 4 / 2 - pc / 2, backWall.y + backWall.height - doorHeight + doorHeight / 8, doorWidth - pc, doorHeight + doorHeight / 4); } for (RoomComponent drawable : items) { int iw, ih; if (drawable.image == null) return; double imageRatio = (double) drawable.image.getWidth() / drawable.image.getHeight(); double componentRatio = (drawable.w * w) / (drawable.h * h); if (imageRatio > componentRatio) { // iw = (int) (drawable.w * w); ih = (int) (iw / imageRatio); } else { ih = (int) (drawable.h * h); iw = (int) (imageRatio * ih); } drawable.setBounds((int) (drawable.x * getWidth()), (int) (drawable.y * getHeight()) - ih, iw, ih); } // Drawing the Zombies (if there is one!) // if (this.getZombie() != null) this.getZombie().setBounds((int) (this.getZombie().x * getWidth()), (int) (this.getZombie().y * getHeight()) - 2, 100, 20); }
8
public static boolean isEmpty(Automaton a) { if (a.getNumStates() == 0) { // Common case: no states return true; } if (a.isAccept(0) == false && a.getNumTransitions(0) == 0) { // Common case: just one initial state return true; } if (a.isAccept(0) == true) { // Apparently common case: it accepts the damned empty string return false; } LinkedList<Integer> workList = new LinkedList<>(); BitSet seen = new BitSet(a.getNumStates()); workList.add(0); seen.set(0); Transition t = new Transition(); while (workList.isEmpty() == false) { int state = workList.removeFirst(); if (a.isAccept(state)) { return false; } int count = a.initTransition(state, t); for(int i=0;i<count;i++) { a.getNextTransition(t); if (seen.get(t.dest) == false) { workList.add(t.dest); seen.set(t.dest); } } } return true; }
8
public XMLReaderSAX getSAXReader() { if (saxReader == null) { saxReader = new XMLReaderSAX(); } return saxReader; }
1
public void ordinaryChar(int ch) { if (ch >= 0 && ch < ctype.length) ctype[ch] = 0; }
2
public List<Position> getPositionsAround(Position position) { if (position == null) throw new IllegalArgumentException("Position can't be null!"); Set<Position> positions = new HashSet<Position>(); if (validPosition(position)) positions.add(position); for (Movement move : Movement.values()) { Position newPosition = move.newPosition(position); if (validPosition(newPosition)) positions.add(newPosition); } return new ArrayList<Position>(positions); }
4
public static String getCurrentTime() { Calendar c = Calendar.getInstance(); String result = ""; int temp; result += c.get( Calendar.YEAR ) + "_"; if( ( temp = c.get( Calendar.MONTH ) + 1 ) < 10 ) { result += "0"; } result += temp + "_"; if( ( temp = c.get( Calendar.DAY_OF_MONTH ) ) < 10 ) { result += "0"; } result += temp + "_"; if( ( temp = c.get( Calendar.HOUR_OF_DAY ) ) < 10 ) { result += "0"; } result += temp + "_"; if( ( temp = c.get( Calendar.MINUTE ) ) < 10 ) { result += "0"; } result += temp + "_"; if( ( temp = c.get( Calendar.SECOND ) ) < 10 ) { result += "0"; } result += temp; System.out.println( result ); return result; }
5
@SuppressWarnings("deprecation") @Override public void run() { for (int i = 0; i <= 1; i++) { if (!data.isEmpty()) { int index = r.nextInt(data.size()); RegenData rd; synchronized (lock) { rd = data.remove(index); } Block b = rd.getW().getBlockAt(rd.getX(), rd.getY(), rd.getZ()); int effectID = rd.getId() == 0 ? b.getTypeId() : rd.getId(); b.setTypeIdAndData(rd.getId(), rd.getData(), true); rd.getW().playEffect(new Location(rd.getW(), rd.getX(), rd.getY(), rd.getZ()), Effect.STEP_SOUND, effectID); rd = null; } } }
3
public static int Boruvka(Graph input) { input.setState(States.ARR_ADJ); Log.print(Log.system, "Boruvka algorithm:"); // init: int N = input.getVertexCount(); int M = input.getEdgeCount(); int[][] arr_inc = new int[N][M]; int[][] arr_adj = new int[N][N]; @SuppressWarnings("unchecked") ArrayList<ListNode>[] list_adj = new ArrayList[N]; // init data: for (int i = 0; i < N; i++) { Arrays.fill(arr_adj[i], 0); Arrays.fill(arr_inc[i], 0); list_adj[i] = new ArrayList<ListNode>(); } // Boruvka init: ArrayList<Edge> edges = input.getEdges(); ArrayList<Edge> resultEdges = new ArrayList<>(); DSF dsf = new DSF(input.getVertexCount()); Edge[] min = new Edge[input.getVertexCount()]; while (resultEdges.size() < input.getVertexCount() - 1) { Arrays.fill(min, new Edge(0, 0, 9_999_999)); for (Edge e : edges) { if (dsf.set(e.u) != dsf.set((e.v))) { if (e.w < min[e.u].w) min[e.u] = e; } } for (int i = 0; i < input.getVertexCount(); i++) { if (min[i].w != 9_999_999) { if (dsf.set(min[i].u) != dsf.set((min[i].v))) { resultEdges.add(min[i]); System.out.println("Boruvka: edge " + (min[i].u + 1) + " " + (min[i].v + 1)); } dsf.union(min[i].u, min[i].v); } } } return 0; }
8
public void setIsLocalRunMode(Boolean localRunMode) { if (this.isLocalRunMode != localRunMode) { this.isLocalRunMode = localRunMode; NotifyRunModeChanged(localRunMode); } }
1
private void preTraversal(TreeNode node,StringBuilder sb){ if(sb.length()>0) sb.append(","); if(node==null) sb.append("NULL"); else{ sb.append(node.val); preTraversal(node.left, sb); preTraversal(node.right, sb); } }
2
/* */ public synchronized void update(long elapsedTime) { /* 29 */ if (this.frames.size() > 1) { /* 30 */ this.animTime += elapsedTime; /* 31 */ if (this.animTime >= this.totalDuration) { /* 32 */ this.animTime %= this.totalDuration; /* 33 */ this.currentFrame = 0; /* */ } /* */ /* 36 */ while (this.animTime > getFrame(this.currentFrame).endTime) /* 37 */ this.currentFrame += 1; /* */ } /* */ }
3
public boolean isEmpty() { return mChildren[0] == null && mChildren[1] == null; }
1
public void deathAni() { switch (aniNum) { case 0: sprt = imgD1.getImage(); if(Game.tickCount2 == game.DELAY){ aniNum = 1; } break; case 1: sprt = imgD2.getImage(); if(Game.tickCount2 == game.DELAY){ aniNum = 2; } break; case 2: sprt = imgD5.getImage(); if(Game.tickCount2 == game.DELAY){ aniNum = 3; } break; case 3: sprt = null; break; } }
7
public static void setFieldValue(Object object, String fieldName, String value){ try { Field field = object.getClass().getDeclaredField(fieldName); field.setAccessible(true); if(field.getType().equals(String.class)){ field.set(object, value); } else if (field.getType().equals(int.class)){ field.set(object, new Integer(value)); } else if (field.getType().equals(double.class)){ field.set(object, new Double(value)); } field.setAccessible(false); } catch (SecurityException | NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) { e.printStackTrace(); } }
4
@Override public IEvent emit(IEvent event) { Iterator<Map<Class<? extends IEvent>, List<IEventListener>>> itr = this.mapListeners.values().iterator(); while (itr.hasNext()) { Map<Class<? extends IEvent>, List<IEventListener>> mapListener = itr.next(); List<IEventListener> listeners = mapListener.get(event.getClass()); if (listeners != null) { Iterator<IEventListener> itre = listeners.iterator(); while(itre.hasNext()) { event = itre.next().handleEvent(event); } } } return event; }
5
public Window(Game game) { // Game instance this.game = game; // Game and board this.setTitle("Chess"); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setLayout(new BorderLayout()); this.setResizable(true); this.setIconImage(this.iconImage.getImage()); this.pack(); // Create menu bar this.menuBar = new MenuBar(game); this.setJMenuBar(this.menuBar); // Create board this.board = new Board(game); this.add(this.board, BorderLayout.CENTER); // Key bindings this.board.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "undo"); this.board.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "redo"); this.board.getActionMap().put("undo", new ArrowAction(this.game, "undo")); this.board.getActionMap().put("redo", new ArrowAction(this.game, "redo")); // Show this.pack(); this.setVisible(true); }
0
private void initMouse() { try { if (!jTextField1.getText().equals("")) { listVarInt.put("nbSourisG", Integer.parseInt(jTextField1.getText())); } else { listVarInt.put("nbSourisG", 0); } if (!jTextField2.getText().equals("")) { listVarInt.put("nbSourisD", Integer.parseInt(jTextField2.getText())); } else { listVarInt.put("nbSourisD", 0); } } catch (NumberFormatException e) { System.err.println("Pas de souris entree"); } listVarInt.put("nbSouris", listVarInt.get("nbSourisG") + listVarInt.get("nbSourisD")); }
3
public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof LabelValue)) { return false; } LabelValue bean = (LabelValue) obj; int nil = (this.getValue() == null) ? 1 : 0; nil += (bean.getValue() == null) ? 1 : 0; if (nil == 2) { return true; } else if (nil == 1) { return false; } else { return this.getValue().equals(bean.getValue()); } }
6
void radf2(final int ido, final int l1, final double in[], final int in_off, final double out[], final int out_off, final int offset) { int i, ic, idx0, idx1, idx2, idx3, idx4; double t1i, t1r, w1r, w1i; int iw1; iw1 = offset; idx0 = l1 * ido; idx1 = 2 * ido; for (int k = 0; k < l1; k++) { int oidx1 = out_off + k * idx1; int oidx2 = oidx1 + idx1 - 1; int iidx1 = in_off + k * ido; int iidx2 = iidx1 + idx0; double i1r = in[iidx1]; double i2r = in[iidx2]; out[oidx1] = i1r + i2r; out[oidx2] = i1r - i2r; } if (ido < 2) return; if (ido != 2) { for (int k = 0; k < l1; k++) { idx1 = k * ido; idx2 = 2 * idx1; idx3 = idx2 + ido; idx4 = idx1 + idx0; for (i = 2; i < ido; i += 2) { ic = ido - i; int widx1 = i - 1 + iw1; int oidx1 = out_off + i + idx2; int oidx2 = out_off + ic + idx3; int iidx1 = in_off + i + idx1; int iidx2 = in_off + i + idx4; double a1i = in[iidx1 - 1]; double a1r = in[iidx1]; double a2i = in[iidx2 - 1]; double a2r = in[iidx2]; w1r = wtable_r[widx1 - 1]; w1i = wtable_r[widx1]; t1r = w1r * a2i + w1i * a2r; t1i = w1r * a2r - w1i * a2i; out[oidx1] = a1r + t1i; out[oidx1 - 1] = a1i + t1r; out[oidx2] = t1i - a1r; out[oidx2 - 1] = a1i - t1r; } } if (ido % 2 == 1) return; } idx2 = 2 * idx1; for (int k = 0; k < l1; k++) { idx1 = k * ido; int oidx1 = out_off + idx2 + ido; int iidx1 = in_off + ido - 1 + idx1; out[oidx1] = -in[iidx1 + idx0]; out[oidx1 - 1] = in[iidx1]; } }
7
public static void demarrer(){ String choixJeu; resterDansLeCasino = true; System.out.println("\n\nBienvenue dans le Casino !"); while (resterDansLeCasino) { if (joueur.age < 21) { System.out.println ("Vous êtes trop jeune pour jouer aux jeux de casino, vous pouvez uniquement jouer au demineur" + "\nVoulez-vous y jouer ? Dites oui pour y jouer"); choixJeu = keyboard.nextLine(); if (choixJeu == "oui") { demineur.commencer(); } else { System.out.println("A bientot dans le casino"); } } else { System.out.println("Veuillez choisir votre jeu parmis les suivants :" + "\n Pour jouer au 421 tapez 1" + "\n Pour jouer à la roulette tapez 2" + "\n Pour jouer au Jackpot tapez 3" + "\n Pour jouer au demineur tapez 4"); boolean recommencer = true; while (recommencer) { choixJeu = keyboard.nextLine(); switch (choixJeu) { case "1" : jeuDes.commencer(); recommencer = false; break; case "2" : roulette.commencer(); recommencer = false; break; case "3" : recommencer = false; jackpot.commencer(); break; case "4" : recommencer = false; demineur.commencer(); break; default : recommencer = true; System.out.println("Desole, la saisie n'est pas valide... Veuillez recommencer"); } } } rejouerOuNon(); } }
8
private void buildPostOrderTraversal(GeneralTreeNode<T> cur) { Iterator<GeneralTreeNode<T>> it = cur.getChildren(); while (it.hasNext()) { this.buildPostOrderTraversal(it.next()); } OutputQueue.add(cur); }
1
public DisconnectOnServerEvent(Object server, ISocketServerConnection clientConnection) { super(server); this.clientConnection = clientConnection; }
0
public void setDay(int d) { if (d < 1) { d = 1; } Calendar tmpCalendar = (Calendar) calendar.clone(); tmpCalendar.set(Calendar.DAY_OF_MONTH, 1); tmpCalendar.add(Calendar.MONTH, 1); tmpCalendar.add(Calendar.DATE, -1); int maxDaysInMonth = tmpCalendar.get(Calendar.DATE); if (d > maxDaysInMonth) { d = maxDaysInMonth; } int oldDay = day; day = d; if (selectedDay != null) { selectedDay.setBackground(oldDayBackgroundColor); selectedDay.repaint(); } for (int i = 7; i < 49; i++) { if (days[i].getText().equals(Integer.toString(day))) { selectedDay = days[i]; selectedDay.setBackground(selectedColor); break; } } if (alwaysFireDayProperty) { firePropertyChange("day", 0, day); } else { firePropertyChange("day", oldDay, day); } }
6
public static int readVersion(Handshakedata handshakedata) { String vers = handshakedata.getFieldValue("Sec-WebSocket-Version"); if (vers.length() > 0) { int v; try { v = new Integer(vers.trim()); return v; } catch (NumberFormatException e) { return -1; } } return -1; }
2
private void read24Bit(byte[] bdata) { // Padding bytes at the end of each scanline int padding = 0; // width * bitsPerPixel should be divisible by 32 int bitsPerScanline = width * 24; if ( bitsPerScanline%32 != 0) { padding = (bitsPerScanline/32 + 1)*32 - bitsPerScanline; padding = (int)Math.ceil(padding/8.0); } int imSize = (int)imageSize; if (imSize == 0) { imSize = (int)(bitmapFileSize - bitmapOffset); } // Read till we have the whole image byte values[] = new byte[imSize]; try { int bytesRead = 0; while (bytesRead < imSize) { bytesRead += inputStream.read(values, bytesRead, imSize - bytesRead); } } catch (IOException ioe) { // throw new RuntimeException(JaiI18N.getString("BMPImageDecoder6")); String message = JaiI18N.getString("BMPImageDecoder4"); ImagingListenerProxy.errorOccurred(message, new ImagingException(message, ioe), this, false); // throw new RuntimeException(ioe.getMessage()); } int l=0, count; if (isBottomUp) { int max = width*height*3-1; count = -padding; for (int i=0; i<height; i++) { l = max - (i+1)*width*3 + 1; count += padding; for (int j=0; j<width; j++) { bdata[l++] = values[count++]; bdata[l++] = values[count++]; bdata[l++] = values[count++]; } } } else { count = -padding; for (int i=0; i<height; i++) { count += padding; for (int j=0; j<width; j++) { bdata[l++] = values[count++]; bdata[l++] = values[count++]; bdata[l++] = values[count++]; } } } }
9
public void method1() { adaptee.method2(); }
0
public static void main(String[] args) { enumCompareTo(opConstant.SHOOT); }
0
@Override public void setName(String name) { this.name = name; }
0
public static int escapeXmlChar(Writer out, char ch, int buffIndex, char[] buff, int buffLength) throws IOException { int nextIndex; if (ch < 0xA0) { // If "?" or over, no escaping is needed (this covers // most of the Latin alphabet) if (ch >= 0x3f) { nextIndex = addToBuffer(out, buff, buffIndex, buffLength, ch); } else if (ch >= 0x27) { // If above "'"... // If between "'" and ";", no escaping is needed if (ch < 0x3c) { nextIndex = addToBuffer(out, buff, buffIndex, buffLength, ch); } else if (ch == '<') { nextIndex = addToBuffer(out, buff, buffIndex, buffLength, LT_CHARS); } else if (ch == '>') { nextIndex = addToBuffer(out, buff, buffIndex, buffLength, GT_CHARS); } else { nextIndex = addToBuffer(out, buff, buffIndex, buffLength, ch); } } else { if (ch == '&') { nextIndex = addToBuffer(out, buff, buffIndex, buffLength, AMP_CHARS); } else if (ch == '"') { nextIndex = addToBuffer(out, buff, buffIndex, buffLength, QUOT_CHARS); } else { nextIndex = addToBuffer(out, buff, buffIndex, buffLength, ch); } } } else { nextIndex = addToBuffer(out, buff, buffIndex, buffLength, ch); } return nextIndex; }
8
public ServerData( String name, String shortName, boolean force, String channel, int localDistance, boolean connectionMessages ) { this.serverName = name; this.shortName = shortName; this.forceChannel = force; if ( channel.equalsIgnoreCase( "server" ) ) { this.forcedChannel = serverName; } else if ( channel.equalsIgnoreCase( "global" ) ) { this.forcedChannel = "Global"; } else if ( channel.equalsIgnoreCase( "local" ) ) { this.forcedChannel = serverName + " Local"; } else { this.forcedChannel = channel; } this.localDistance = localDistance; this.connectionMessages = connectionMessages; }
3
public void changeLoc(int newLocX, int newLocY) { if (PRIVS != PRIVS.BANNED || (BATTLE == null && !BLN_SLEEP && Game.canMoveTo(newLocX,newLocY,this))) { if (isMob()) { if (!(Math.abs(originalX-newLocX) < Game.VIEW_RANGE && Math.abs(originalY-newLocY) < Game.VIEW_RANGE)) { return; } } changeLocBypass(newLocX,newLocY); } }
7
@Override public void configure(AbstractCommand command, String[] args) { TimeBanBanCommand banCommand = (TimeBanBanCommand) command; List<String> players = CommandLineParser.getListOfString(args[0]); String reason = stdBanReason; Calendar until = UntilStringParser.parse(stdBanDuration); if (args.length == 2) { // What did we get? reason or duration... // got a reason if (args[1].contains("\"")) { reason = CommandLineParser.getPrettyString(args[1]); until = UntilStringParser.parse(stdBanDuration); } else if (args[1].startsWith("&")) { String shortcutName = args[1].substring(1); // remove & setAttributesByShortcut(shortcutName, banCommand); banCommand.setPlayers(players); return; } else { reason = stdBanReason; until = getCalendarFromArg(args[1]); } } else if (args.length == 3) { // every parameter given reason = CommandLineParser.getPrettyString(args[2]); until = UntilStringParser.parse(args[1]); } else if (args.length > 3) { log.log(Level.SEVERE, "Error. Wrong syntax!"); } banCommand.setPlayers(players); banCommand.setReason(reason); banCommand.setUntil(until); }
5
public void testProperty() { MonthDay test = new MonthDay(6, 6); assertEquals(test.monthOfYear(), test.property(DateTimeFieldType.monthOfYear())); assertEquals(test.dayOfMonth(), test.property(DateTimeFieldType.dayOfMonth())); try { test.property(DateTimeFieldType.millisOfDay()); fail(); } catch (IllegalArgumentException ex) {} try { test.property(null); fail(); } catch (IllegalArgumentException ex) {} }
2
private static boolean isLychrel(int n){ BigInteger temp = new BigInteger(Integer.toString(n)); for(int i=0;i<50;i++){ String reverse = new StringBuilder(temp.toString()).reverse().toString(); temp = temp.add(new BigInteger(reverse)); if (isPalindrome(temp.toString())) return false; } return true; }
2
public boolean processMsg(CConnection cc) { OutStream os = cc.getOutStream(); StringBuffer username = new StringBuffer(); // JW: Launcher passes in username as property of Options object, // so there's no need to pop up a dialog asking for a username // if it is already recorded within the Options object. // Cast cc object as CConn, so we access to opts CConn cconn = (CConn) cc; if (cconn.opts.username==null || cconn.opts.username.equals("")) CConn.upg.getUserPasswd(username, null); else username.append(cconn.opts.username); // Return the response to the server os.writeU32(username.length()); try { byte[] utf8str = username.toString().getBytes("UTF8"); os.writeBytes(utf8str, 0, username.length()); } catch(java.io.UnsupportedEncodingException e) { e.printStackTrace(); } os.flush(); return true; }
3
private void monitorTouchInput() { boolean isPressed = touch.isPressed(); while (!Thread.interrupted()) { if (touch.isPressed() && !isPressed) { isPressed = true; for (TouchListener l : listeners) { l.contactInitiated(); } } else if (!touch.isPressed() && isPressed) { isPressed = false; for (TouchListener l : listeners) { l.contactStopped(); } } Thread.yield(); } }
7
private boolean hasWildCard(RedisBigTableKey key) { boolean hasWildCard = Utils.hasWildCard(key.getRow()); hasWildCard = hasWildCard && Utils.hasWildCard(key.getColumnFamily()); hasWildCard = hasWildCard && Utils.hasWildCard(key.getColumnQualifier()); return hasWildCard; }
2
private boolean matchSpaces(String sentence, int matches) { int c = 0; for (int i = 0; i < sentence.length(); i++) { if (sentence.charAt(i) == ' ') c++; if (c == matches) return true; } return false; }
3
private void loadStats() throws IOException { String line; boolean fileFound = true; int nameScoreDate = 0; ///< Names = 0, Scores = 1, Dates = 2 int j; ///< Line in leaderboard try { bfr = new BufferedReader(new FileReader(statsFile)); } catch (FileNotFoundException ex) { //File not found, it will be created when saving the stats. fileFound = false; } if (fileFound) { for (int i = 0; i < (leaderboard.length * leaderboard[0].length); i++) { j = i % 10; if (i == leaderboard.length || i == leaderboard.length * 2) { nameScoreDate++; } line = bfr.readLine(); leaderboard[j][nameScoreDate] = line; } bfr.close(); } }
5
@Override public int compareTo(RushPlayer o) { int killsA = kills; int killsB = o.getKills(); if(killsA == killsB) { int deathsA = deaths; int deathsB = o.getDeaths(); if(deathsA == deathsB) return 0; else if(deathsA > deathsB) return -1; else return 1; } else if(killsA > killsB) return 1; else return -1; //return kills - o.getKills(); }
4
public String getClientIP() { return clientIP; }
0
public static void equalizeChannel(Image original, Image image, ChannelType color) { int[] ocurrences = getColorOccurrences(original, color); int totalPixels = image.getWidth() * image.getHeight(); double[] levels = new double[totalPixels]; double s_min = 0; double s_max = Image.MAX_VAL; for (int i = 0; i < levels.length; i++) { int level = (int) Math.floor(original.getPixel( i / image.getHeight(), i % image.getWidth(), color)); double levelVal = 0; for (int k = 0; k < level; k++) { levelVal += ocurrences[k]; } levels[i] = levelVal / totalPixels; s_min = Math.min(s_min, levels[i]); s_max = Math.max(s_max, levels[i]); } for (int i = 0; i < levels.length; i++) { double aux = Image.MAX_VAL * (levels[i] - s_min) / (1 - s_min); levels[i] = Math.ceil(aux); } int i = 0; for (int x = 0; x < image.getWidth(); x++) { for (int y = 0; y < image.getHeight(); y++) { image.setPixel(x, y, color, levels[i++]); } } }
5
public int sum(TreeNode root, int top) { if (root == null) return top; if (root.left == null && root.right == null) { return top * 10 + root.val; } int sum = 0; if (root.left != null) sum += sum(root.left, top * 10 + root.val); if (root.right != null) sum += sum(root.right, top * 10 + root.val); return sum; }
5
public static void main(String[] args) { int port = defaultPort; String host = defaultHost; // Auf Eingabeparameter ueberpruefen und gegebenenfalls setzten. if (args.length > 0) { for (int i = 0; i < args.length; i++) { // Pruefen, ob ein Parameter den Port angibt. if ((args[i] = args[i].toLowerCase()).startsWith("-port=")) { try { port = Integer.parseInt(args[i].substring(args[i].indexOf("=") + 1)); } catch (NumberFormatException e) { System.out.println("Error parsing parameters!"); System.out.println("-->Exception:" + e + "\n Invalid port format! Using default port."); } } // Pruefen, ob port richtiges Format hat. if (port < 1024 || port > 9999) { System.out.println("Invalid port number! Using default port."); port = defaultPort; } // Pruefen, ob ein Parameter den Hostnamen angibt; if ((args[i] = args[i].toLowerCase()).startsWith("-host=")) { try { host = args[i].substring(args[i].indexOf("=") + 1); } catch (Exception e) { System.out.println("Error parsing parameters!"); System.out.println("-->Exception:" + e + "\n Invalid host argument."); } } if (host.length() < 4) { System.out.println("Invalid host name"); host = defaultHost; } } } // Neues Objekt von Client erzeugen. Client client = new Client(port, host); }
9
public TwoWarriorsVsTwoHobgoblins() { model = new CPModel(); // Tableau de variable représentant les dommages reçus par le premier // guerrier for (int i = 0; i < NB_OF_ROUNDS; i++) { warrior1DamageReceived[i] = makeIntVar( "warrior 1 damage received for round" + (i + 1), HOBGOBLIN_DMG); model.addVariable(warrior1DamageReceived[i]); } // Tableau de variable représentant les dommages reçus par le deuxième // guerrier for (int i = 0; i < NB_OF_ROUNDS; i++) { warrior2DamageReceived[i] = makeIntVar( "warrior 2 damage received for round" + (i + 1), HOBGOBLIN_DMG); model.addVariable(warrior2DamageReceived[i]); } // Tableau de variable représentant les dommages reçus par l'hobgoblin 1 for (int i = 0; i < NB_OF_ROUNDS; i++) { hobgoblin1DamageReceived[i] = makeIntVar( "hobgoblin 1 damage received for round" + (i + 1), WARRIOR_DMG); model.addVariable(hobgoblin1DamageReceived[i]); } // Tableau de variable représentant les dommages reçus par l'hobgoblin 2 for (int i = 0; i < NB_OF_ROUNDS; i++) { hobgoblin2DamageReceived[i] = makeIntVar( "hobgoblin 1 damage received for round" + (i + 1), WARRIOR_DMG); model.addVariable(hobgoblin2DamageReceived[i]); } // Tableau représentant les attaques du guerrier 1 for (int i = 0; i < NB_OF_ROUNDS; i++) { warrior1DamageDone[i] = makeIntVar( "warrior 1 target of damage done for round" + (i + 1), WARRIOR_TARGET); model.addVariable(warrior1DamageDone[i]); } // Tableau représentant les attaques du guerrier 2 for (int i = 0; i < NB_OF_ROUNDS; i++) { warrior2DamageDone[i] = makeIntVar( "warrior 2 target of damage done for round" + (i + 1), WARRIOR_TARGET); model.addVariable(warrior2DamageDone[i]); } // Tableau représentant les attaques du hobgoblin 1 for (int i = 0; i < NB_OF_ROUNDS; i++) { hobgoblin1DamageDone[i] = makeIntVar( "Hobgoblin 1 target of damage done for round" + (i + 1), HOBGOBLIN_TARGET); model.addVariable(hobgoblin1DamageDone[i]); } // Tableau représentant les attaques du hobgoblin 1 for (int i = 0; i < NB_OF_ROUNDS; i++) { hobgoblin2DamageDone[i] = makeIntVar( "Hobgoblin 2 target of damage done for round" + (i + 1), HOBGOBLIN_TARGET); model.addVariable(hobgoblin2DamageDone[i]); } // Contraintes qui vérifie si le guerrier est vivant après le round i for (int i = 0; i < NB_OF_ROUNDS; i++) { IntegerVariable[] tempWarrior1Arrays = Arrays.copyOf( warrior1DamageReceived, i); IntegerVariable[] tempWarrior2Arrays = Arrays.copyOf( warrior2DamageReceived, i); IntegerVariable[] tempHobgoblin1Arrays = Arrays.copyOf( hobgoblin1DamageReceived, i); IntegerVariable[] tempHobgoblin2Arrays = Arrays.copyOf( hobgoblin2DamageReceived, i); Constraint isWarrior1Dead = gt(sum(tempWarrior1Arrays), WARRIOR_MAX_HP); Constraint isWarrior2Dead = gt(sum(tempWarrior2Arrays), WARRIOR_MAX_HP); Constraint isHobgoblin1Dead = gt(sum(tempHobgoblin1Arrays), HOBGOBLIN_MAX_HP); Constraint isHobgoblin2Dead = gt(sum(tempHobgoblin2Arrays), HOBGOBLIN_MAX_HP); // dommage reçu par l'hobgoblin 1 (3) model.addConstraint(ifThenElse( and(isWarrior1Dead, isWarrior2Dead), eq(hobgoblin1DamageReceived[i], 0), ifThenElse( isHobgoblin1Dead, eq(hobgoblin1DamageReceived[i], 0), ifThenElse( and(eq(warrior1DamageDone[i], 3), eq(warrior2DamageDone[i], 3)), eq(hobgoblin1DamageReceived[i], 92), ifThenElse( or(and(eq(warrior1DamageDone[i], 3), eq(warrior2DamageDone[i], 4)), and(eq(warrior1DamageDone[i], 4), eq(warrior2DamageDone[i], 3))), eq(hobgoblin1DamageReceived[i], 46), eq(hobgoblin1DamageReceived[i], 0)))))); // dommage reçu par l'hobgoblin 2 (4) model.addConstraint(ifThenElse( and(isWarrior1Dead, isWarrior2Dead), eq(hobgoblin2DamageReceived[i], 0), ifThenElse( isHobgoblin2Dead, eq(hobgoblin2DamageReceived[i], 0), ifThenElse( and(eq(warrior1DamageDone[i], 4), eq(warrior2DamageDone[i], 4)), eq(hobgoblin2DamageReceived[i], 92), ifThenElse( or(and(eq(warrior1DamageDone[i], 3), eq(warrior2DamageDone[i], 4)), and(eq(warrior1DamageDone[i], 4), eq(warrior2DamageDone[i], 3))), eq(hobgoblin2DamageReceived[i], 46), eq(hobgoblin2DamageReceived[i], 0)))))); // dommage reçu par le guerrier 1 (1) model.addConstraint(ifThenElse( and(isHobgoblin1Dead, isHobgoblin2Dead), eq(warrior1DamageReceived[i], 0), ifThenElse( isWarrior1Dead, eq(warrior1DamageReceived[i], 0), ifThenElse( and(eq(hobgoblin1DamageDone[i], 1), eq(hobgoblin2DamageDone[i], 1)), eq(warrior1DamageReceived[i], 26), ifThenElse( or(and(eq(hobgoblin1DamageDone[i], 1), eq(hobgoblin2DamageDone[i], 2)), and(eq(hobgoblin1DamageDone[i], 2), eq(hobgoblin2DamageDone[i], 1))), eq(warrior1DamageReceived[i], 13), eq(warrior1DamageReceived[i], 0)))))); // dommage reçu par le guerrier 2 (2) model.addConstraint(ifThenElse( and(isHobgoblin1Dead, isHobgoblin2Dead), eq(warrior2DamageReceived[i], 0), ifThenElse( isWarrior2Dead, eq(warrior2DamageReceived[i], 0), ifThenElse( and(eq(hobgoblin1DamageDone[i], 2), eq(hobgoblin2DamageDone[i], 2)), eq(warrior2DamageReceived[i], 26), ifThenElse( or(and(eq(hobgoblin1DamageDone[i], 1), eq(hobgoblin2DamageDone[i], 2)), and(eq(hobgoblin1DamageDone[i], 2), eq(hobgoblin2DamageDone[i], 1))), eq(warrior2DamageReceived[i], 13), eq(warrior2DamageReceived[i], 0)))))); } // Variable représentant la vie du guerrier 1 warrior1Hp = makeIntVar("warrior 1 HP", -5000, WARRIOR_MAX_HP, Options.V_OBJECTIVE); model.addVariable(warrior1Hp); model.addConstraint(eq(warrior1Hp, minus(WARRIOR_MAX_HP, sum(warrior1DamageReceived)))); // Variable représentant la vie du guerrier 2 warrior2Hp = makeIntVar("warrior 2 HP", -5000, WARRIOR_MAX_HP, Options.V_OBJECTIVE); model.addVariable(warrior2Hp); model.addConstraint(eq(warrior2Hp, minus(WARRIOR_MAX_HP, sum(warrior2DamageReceived)))); model.addConstraint(or(gt(warrior1Hp, 0), gt(warrior1Hp, 0))); // Variable représentant la vie de l'hobgoblin hobgoblin1Hp = makeIntVar("hobgoblin 1 HP", -6300, HOBGOBLIN_MAX_HP); model.addVariable(hobgoblin1Hp); model.addConstraint(eq(hobgoblin1Hp, minus(HOBGOBLIN_MAX_HP, sum(hobgoblin1DamageReceived)))); // Variable représentant la vie de l'hobgoblin hobgoblin2Hp = makeIntVar("hobgoblin 2 HP", -6300, HOBGOBLIN_MAX_HP); model.addVariable(hobgoblin2Hp); model.addConstraint(eq(hobgoblin2Hp, minus(HOBGOBLIN_MAX_HP, sum(hobgoblin2DamageReceived)))); }
9
@Override public String toString() { return "ARGS " + new Integer(numberOfArguments).toString(); }
0
public static void removeConnection(InetSocketAddress sockaddr) { if(!isInit) { init(); } for(int i = 0; i < clientRecent.size(); i++) { if(clientRecent.get(i).equals(sockaddr)) { clientRecent.remove(i); } } }
3
private void runGame(Player p1, Player p2, Sign s1, Sign s2) { if (s1 == s2) { draw(p1, p2, s1); return; } if ((s1 == Sign.ROCK && s2 == Sign.SCISSORS) || (s1 == Sign.SCISSORS && s2 == Sign.PAPER) || (s1 == Sign.PAPER && s2 == Sign.ROCK)) finishGame(p1, p2, s1, s2); else finishGame(p2, p1, s2, s1); }
7
public static void removeCopy(int copyId){ try { if(conn == null || conn.isClosed()){ conn = DatabaseConnection.getConnection(); } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try{ conn.setAutoCommit(false); PreparedStatement stmnt = conn.prepareStatement("DELETE FROM Copies WHERE copy_id = ?"); stmnt.setInt(1, copyId); stmnt.execute(); conn.commit(); conn.setAutoCommit(true); }catch(SQLException e){ System.out.println("Remove fail: " + e); } }
4
public synchronized void stop() { running = false; }
0
public Requests() { }
0
private int parseInt(String value) throws InvalidFormatException { try { return Integer.parseInt(value); } catch (NumberFormatException e) { throw new InvalidFormatException(); } }
1
@Override public IEmailKontakt first() throws NoEmailKontaktFoundException { EmailKontaktList emailContacts = readContacts(); if (emailContacts.getContactList().size() == 0) { throw new NoEmailKontaktFoundException("Kein Kontakt gefunden!"); } else return emailContacts.getContactList().get(0); }
1
public boolean check(String userName, String password) { for (Account account : accountList) { if (account.getUserName().equals(userName) && account.getPassword().equals(password)) { return true; } } return false; }
3
public BefehlsPanel() { setLayout(null); setSize(682, 512); _labelFuerLebensenergie = new JLabel(); _labelFuerLebensenergie.setLocation(ABSTAND_NORMAL, 0); _labelFuerLebensenergie.setSize(50, BefehlsPanel.this.getHeight() - 50); _beinstellenButton = new JButton(BEINSTELLEN); _beinstellenButton.setSize(50, 50); _beinstellenButton.setLocation(ABSTAND_NORMAL, 462); _beinstellenButton.setFocusable(false); _beinstellenButton .setToolTipText("Allen Gegnern im Raum ein Bein stellen"); _beinstellenButton.setVisible(true); repaint(); _lebensenergieMaximum = 8; _lebensenergieAktuell = _lebensenergieMaximum; _nehmenButton = new JButton( StringUtils.capitalize(TextVerwalter.BEFEHL_NEHMEN)); _gibButton = new JButton( StringUtils.capitalize(TextVerwalter.BEFEHL_UNTERSUCHE)); _fuettereButton = new JButton( StringUtils.capitalize(TextVerwalter.BEFEHL_FUETTERE)); _fuettereGutButton = new JButton(GUT); _fuettereSchlechtButton = new JButton(SCHLECHT); _fuettereUnbekanntButton = new JButton(UNBEKANNT); _essenTascheButton = new JButton( StringUtils .capitalize(TextVerwalter.BEFEHL_ESSEN + " aus der ") + StringUtils.capitalize(TextVerwalter.ORT_TASCHE)); _essenTascheGutButton = new JButton(GUT); _essenTascheSchlechtButton = new JButton(SCHLECHT); _essenTascheUnbekanntButton = new JButton(UNBEKANNT); _essenBodenButton = new JButton( StringUtils.capitalize(TextVerwalter.BEFEHL_ESSEN + " vom ") + StringUtils.capitalize(TextVerwalter.ORT_BODEN)); _inventarButton = new JButton( StringUtils.capitalize(TextVerwalter.BEFEHL_INVENTAR)); _ablegenButton = new JButton( StringUtils.capitalize(TextVerwalter.BEFEHL_ABLEGEN)); _ablegenGutButton = new JButton(GUT); _ablegenSchlechtButton = new JButton(SCHLECHT); _ablegenUnbekanntButton = new JButton(UNBEKANNT); _helpButton = new JButton(new ImageIcon(getClass().getResource( "bilder/faq-icon.png"))); _quitButton = new JButton(new ImageIcon(getClass().getResource( "bilder/exitIcon.gif"))); _quitButton.setBackground(new Color(0, 175, 0)); _normalButtons = new JButton[] { _nehmenButton, _gibButton, _fuettereButton, _essenBodenButton, _essenTascheButton, _inventarButton, _ablegenButton }; // REIHENFOLGE NICHT ÄNDERN!!!! _extraButtons = new JButton[] { _fuettereGutButton, _fuettereSchlechtButton, _fuettereUnbekanntButton, _ablegenGutButton, _ablegenSchlechtButton, _ablegenUnbekanntButton, _essenTascheGutButton, _essenTascheSchlechtButton, _essenTascheUnbekanntButton }; _systemButtons = new JButton[] { _helpButton, _quitButton }; for(JButton b : _normalButtons) { b.setFocusable(false); add(b); } String[] gutschlechtunbekannt = { "Guter Krümel", "Schlechter Krümel", "Unidentifizierter Krümel" }; int c = 0; for(JButton b : _extraButtons) { b.setFocusable(false); b.setToolTipText(gutschlechtunbekannt[c % 3]); add(b); c++; } for(JButton b : _systemButtons) { b.setFocusable(false); b.setSize(50, 50); add(b); } add(_labelFuerLebensenergie); add(_beinstellenButton); addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent arg0) { int buttonhoehe = (BefehlsPanel.this.getHeight() - (ABSTAND_NORMAL * 2 * (ZEILENANZAHL))) / ZEILENANZAHL; int buttonhoeheExtra = (int) (buttonhoehe * 0.75); Dimension buttongroesse = new Dimension( (BefehlsPanel.this.getWidth() - 100) / 2 - 25, buttonhoehe); Dimension buttongroesseExtra = new Dimension( buttongroesse.width / 3, buttonhoeheExtra); // TODO for(JButton b : _normalButtons) { b.setSize(buttongroesse); } for(JButton b : _extraButtons) { b.setSize(buttongroesseExtra); } //linke Spalte int xpos_1 = 65; _nehmenButton.setLocation(xpos_1, 5); _gibButton.setLocation(xpos_1, (int) (buttongroesse.getHeight() + 10)); _essenBodenButton.setLocation(xpos_1, (int) (buttongroesse.getHeight() * 2 + 15)); _fuettereButton.setLocation(xpos_1, (int) (buttongroesse.getHeight() * 3 + 20)); _fuettereGutButton.setLocation(xpos_1, (int) (_fuettereButton.getY() + buttonhoehe + 2)); _fuettereSchlechtButton.setLocation( xpos_1 + _fuettereGutButton.getWidth() + 1, (int) (_fuettereButton.getY() + buttonhoehe + 2)); _fuettereUnbekanntButton.setLocation( _fuettereSchlechtButton.getLocation().x + _fuettereSchlechtButton.getWidth() + 1, (int) (_fuettereButton.getY() + buttonhoehe + 2)); //rechte Spalte int x = _nehmenButton.getWidth() + _nehmenButton.getLocation().x + 10; _inventarButton.setLocation(x, 5); _ablegenButton.setLocation(x, buttonhoehe + 10); _ablegenGutButton.setLocation(x, (int) (_ablegenButton.getY() + buttonhoehe + 2)); _ablegenSchlechtButton.setLocation( _ablegenGutButton.getLocation().x + buttongroesseExtra.width + 1, _ablegenButton.getY() + buttonhoehe + 2); _ablegenUnbekanntButton.setLocation( _ablegenSchlechtButton.getLocation().x + buttongroesseExtra.width + 1, _ablegenButton.getY() + buttonhoehe + 2); _essenTascheButton.setLocation(x, (int) (buttongroesse.getHeight() * 3 + 20)); _essenTascheGutButton.setLocation(x, (int) (_essenTascheButton.getY() + buttonhoehe + 2)); _essenTascheSchlechtButton.setLocation(x + buttongroesseExtra.width + 1, (int) (_essenTascheButton.getY() + buttonhoehe + 2)); _essenTascheUnbekanntButton.setLocation( _essenTascheSchlechtButton.getX() + buttongroesseExtra.width + 1, (int) (_essenTascheButton.getY() + buttonhoehe + 2)); // system buttons _helpButton.setLocation(_inventarButton.getX() + _inventarButton.getWidth() + 5, 5); _quitButton.setLocation(_inventarButton.getX() + _inventarButton.getWidth() + 5, _helpButton.getY() + _helpButton.getHeight() + 5); _labelFuerLebensenergie.setSize(50, BefehlsPanel.this.getHeight() - 50); setLebensenergie(_lebensenergieAktuell); _beinstellenButton.setSize(50, 50); _beinstellenButton.setLocation(_labelFuerLebensenergie.getX(), _labelFuerLebensenergie.getHeight()); } }); }
5
public void run() { while (true) { try { Socket socket = mServerSocket.accept(); // Wait for a new peer Log.i("PeerAccepter", "New Peer connected ->"); MessageInputStream mis = new MessageInputStream(socket.getInputStream()); Handshake handshake = mis.readHandShake(); Hash infoHash = handshake.getInfoHash(); Torrent torrent = mTorrentManager.getTorrent(infoHash); // If the torrent isn't in the TorrentManager's list if (torrent == null) { socket.close(); } else { // Create the peer and put it into the Torrent Peers' List Peer peer = new Peer(socket.getInetAddress(), socket.getPort(), torrent); peer.setID(handshake.getPeerId()); peer.setSocket(socket); peer.setEncryption(handshake.isEncryptionActivated()); torrent.addPeer(peer); } } catch (BindException e) { Log.e("PeerAccepter", "Bind Error, " + e.getMessage()); } catch (IOException e) { e.printStackTrace(); Log.e("PeerAccepter", "Error while connecting with a peer."); } try { sleep(100L); } catch (InterruptedException e) { Log.e("PeerAccepter", "Thread.sleep()"); } } }
5
@Column(name = "percent") @Id public double getPercent() { return percent; }
0
protected static byte[] decodeData(String password, BufferedImage origin, BufferedImage otp) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException { byte[] otpA = null; if (otp != null) { otpA = IDEImage.readOtp(otp); } byte[] allData = IDEImage.readData(origin, otpA); int saltLength = allData[0]; if (saltLength < 0) { saltLength += 256; } byte[] saltBytes = new byte[saltLength]; for (int i = 1; i <= saltLength; i++) { saltBytes[i - 1] = allData[i]; } String salt = new String(saltBytes, "UTF-8"); IDEKeyData key = IDEKeyFactory.generateKeyKnownSalt(password, salt); byte[] data = new byte[allData.length - saltLength - 1]; for (int i = (saltLength + 1); i < allData.length; i++) { data[i - (saltLength + 1)] = allData[i]; } byte[] decodedData = EncryptionFactory.decode(data, key.getKeyData()); return decodedData; }
4
public static RuleSet GenerateRuleSets(TransactionSet transSet, TransactionSet finalLargeItemSet,double minConfidenceLevel) { Timer timer = new Timer(); timer.startTimer(); RuleSet allRuleSets = new RuleSet(new ArrayList<Rule>()); for (Transaction itemset : finalLargeItemSet.getTransactionSet()) { ArrayList<ItemSet> possibleRules = new ArrayList<ItemSet>(); possibleRules = findRuleSubsets(itemset.getTransaction(), possibleRules); for (ItemSet subset : possibleRules) { double confidencePart1 = transSet.findSupport(itemset.getTransaction()); double confidencePart2 = transSet.findSupport(subset); double confidence = (confidencePart1 / confidencePart2); if (confidence >= minConfidenceLevel) { Rule rule = new Rule(); rule.setX(subset); ArrayList<Item> items = new ArrayList<Item>(itemset.getTransaction().getItemSet()); ItemSet consequent = new ItemSet(items); for(int j = 0; j < subset.getItemSet().size(); j++){ consequent.getItemSet().remove(subset.getItemSet().get(j)); } /*Format to 4 decimal places */ double formatConfidence = Math.round(confidence*10000.0)/10000.0; rule.setY(consequent); rule.setMinSupportLevel(transSet.findSupport(itemset.getTransaction())); rule.setActualConfidenceLevel(formatConfidence); if(rule.getX().getItemSet().size() > 0 && rule.getY().getItemSet().size() > 0){ allRuleSets.getRuleSet().add(rule); } } } } allRuleSets.setTimestamp(); System.out.println("RuleSets:\n" + allRuleSets.toString()); timer.stopTimer(); //System.out.println("Generator.GenerateRuleSets: Time in Milliseconds" + timer.getTotal()); return allRuleSets; }
6
public final void setNoOfLeds(final int NO_OF_LEDS) { int amount = NO_OF_LEDS < 5 ? 5 : NO_OF_LEDS; if (amount > noOfLeds.get()) { for (int i = 0 ; i < (amount - noOfLeds.get()) ; i++) { ledColors.get().add(Color.RED); } } if (null == noOfLeds) { _noOfLeds = amount; } else { noOfLeds.set(amount); } }
4
public String toString() { StringBuffer sb = new StringBuffer(); sb.append( versions+": " ); if ( parent != null ) { sb.append("["+parent.id+":"); sb.append( new String(parent.data) ); sb.append( "]" ); } else if ( children != null ) { sb.append("{"+id+":"); sb.append( new String(data) ); sb.append( "}" ); sb.append("; children="); for ( int i=0;i<children.size();i++ ) { Pair p = children.get( i ); sb.append(p.toString()); if ( i < children.size()-1 ) sb.append(","); } } else if ( data != null ) sb.append( new String(data) ); else sb.append("null"); return sb.toString(); }
5
public static byte[] decrypt(byte[] data, byte[] key) { if(data.length == 0) { return data; } int[] s = Util.bytesToInts(data); int[] g = Util.bytesToInts(Arrays.copyOfRange(key, 0, 16)); int d = s.length; int j = s[d - 1], l = s[0]; int o = 0x9E3779B9; int m, i, a = (int) Math.floor(6 + 52 / d); int h = a * o; boolean printed = false; while(h != 0) { i = (h >>> 2 & 3); for(int c = d - 1; c >= 0; c--) { j = s[c > 0 ? c - 1 : d - 1]; m = (j >>> 5 ^ l << 2) + (l >>> 3 ^ j << 4) ^ (h ^ l) + (g[(c & 3) ^ i] ^ j); if(!printed) { printed = true; } l = s[c] -= m; } h -= o; } return Util.intsToBytes(s); }
5
public GUI() { setBackground(Color.DARK_GRAY); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(10, 10, 745, 485); contentPane = new JPanel(); contentPane.setForeground(Color.DARK_GRAY); contentPane.setBackground(Color.DARK_GRAY); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); final JButton importPDFbtn = new JButton("Import Result PDF"); importPDFbtn.setBackground(new Color(102, 153, 204)); //importPDFbtn.setBorder(UIManager.getBorder("EditorPane.border")); try { UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); } catch (ClassNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (InstantiationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IllegalAccessException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (UnsupportedLookAndFeelException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } importPDFbtn.setFont(new Font("Arial", Font.BOLD, 20)); importPDFbtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { branchSelection branchpage = new branchSelection(db_table); branchpage.setVisible(true); } }); importPDFbtn.setBounds(164, 204, 442, 90); contentPane.add(importPDFbtn); JButton btnNewButton_1 = new JButton("View Existing Data"); btnNewButton_1.setBackground(new Color(102, 153, 204)); btnNewButton_1.setFont(new Font("Arial", Font.BOLD, 20)); btnNewButton_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { SearchScreen SearchFrame = new SearchScreen(Mainframe, db_table); SearchFrame.setVisible(true); Aggregation AggregationFrame = new Aggregation(Mainframe, db_table); AggregationFrame.setVisible(true); Mainframe.setVisible(false); dispose(); } }); btnNewButton_1.setBounds(164, 318, 216, 90); contentPane.add(btnNewButton_1); /*JButton btnNewButton_2 = new JButton("Add New Data"); btnNewButton_2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { ManualEntry ManualFrame = new ManualEntry(Mainframe, db_table); ManualFrame.setVisible(true); Mainframe.setVisible(false); dispose(); } }); btnNewButton_2.setBounds(386, 327, 197, 94); contentPane.add(btnNewButton_2); */ ImageIcon homePanel = new ImageIcon("IMG_4972.JPG"); JLabel lblNewLabel = new JLabel(homePanel); lblNewLabel.setFont(new Font("Monotype Corsiva", Font.BOLD, 50)); lblNewLabel.setText(""); lblNewLabel.setForeground(new Color(204, 204, 153)); lblNewLabel.setBounds(10, 11, 709, 160); contentPane.add(lblNewLabel); JButton btnClearExistingData = new JButton("Clear Existing Data"); btnClearExistingData.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { db_table.original_table.drop(); db_table.filtered_collection.drop(); } }); try { UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); } catch (ClassNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (InstantiationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IllegalAccessException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (UnsupportedLookAndFeelException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } btnClearExistingData.setBounds(390, 318, 216, 90); btnClearExistingData.setFont(new Font("Arial", Font.BOLD, 20)); btnClearExistingData.setBackground(new Color(102, 153, 204)); contentPane.add(btnClearExistingData); }
8
private int compareMastRecWithTransRec(AcctsRecMastRec m, AcctsRecTransRec t, Comparator<String> comp) { int result; if (t == null) { result = -1; } else if (m == null) { result = 1; } else { result = comp.compare(m.getKey(), t.getMastKey()); } return result; }
2
@Override @SuppressWarnings({ "nls", "boxing" }) protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder enc) { super.initialize(type, oldInstance, newInstance, enc); if (type != oldInstance.getClass()) { return; } Choice choice = (Choice) oldInstance; int count = choice.getItemCount(); Expression getterExp = null; for (int i = 0; i < count; i++) { getterExp = new Expression(choice, "getItem", new Object[] { i }); try { // Calculate the old value of the property Object oldVal = getterExp.getValue(); // Write the getter expression to the encoder enc.writeExpression(getterExp); // Get the target value that exists in the new environment Object targetVal = enc.get(oldVal); // Get the current property value in the new environment Object newVal = null; try { newVal = new Expression(newInstance, "getItem", new Object[] { i }).getValue(); } catch (IndexOutOfBoundsException ex) { // The newInstance has no elements, so current property // value remains null } /* * Make the target value and current property value equivalent * in the new environment */ if (null == targetVal) { if (null != newVal) { // Set to null Statement setterStm = new Statement(oldInstance, "add", new Object[] { null }); enc.writeStatement(setterStm); } } else { PersistenceDelegate pd = enc .getPersistenceDelegate(targetVal.getClass()); if (!pd.mutatesTo(targetVal, newVal)) { Statement setterStm = new Statement(oldInstance, "add", new Object[] { oldVal }); enc.writeStatement(setterStm); } } } catch (Exception ex) { enc.getExceptionListener().exceptionThrown(ex); } } }
8
@Override public Area areaLocation(CMObject E) { if(E==null) return null; if(E instanceof Area) return (Area)E; else if(E instanceof Room) return ((Room)E).getArea(); else if(E instanceof MOB) return areaLocation(((MOB)E).location()); else if(E instanceof Item) return areaLocation(((Item) E).owner()); else if((E instanceof Ability)&&(((Ability)E).affecting()!=null)) return areaLocation(((Ability)E).affecting()); else if(E instanceof Exit) return areaLocation(((Exit)E).lastRoomUsedFrom(null)); return null; }
8
@Test(expected = RuntimeException.class) public void twoInchesPlusEightOuncesShouldThrowException(){ ArithmeticQuantity two_in = new ArithmeticQuantity(2, Distance.INCHES); ArithmeticQuantity eight_oz = new ArithmeticQuantity(8, Volume.OUNCE); two_in.add(eight_oz); }
0
public void simplify() { top:for(Element elem1 : array) { for(Element elem2 : array) { if(elem1 != elem2 && elem1.getClass().getName().equals("PowerSupply") == false && elem2.getClass().getName().equals("PowerSupply") == false) { if(elem1.getConnections("first").indexOf(elem2) != -1 && elem1.getConnections("second").indexOf(elem2) != -1) { replaceParallel(elem1,elem2); break top; } else if(elem1.getConnections("second").indexOf(elem2) !=-1 && elem1.getConnections("second").size() == 1) { replaceSerial(elem1,elem2); break top; } } } } }
9
Sequence (String url_1, String url_2, String url_3) { if (url_1 == null || url_2 == null || url_3 == null || url_1.isEmpty() || url_2.isEmpty() || url_3.isEmpty()) { throw new IllegalArgumentException("Neither of the construction urls allowed to be null or empty"); } // calculate once and keep in this instance. Generally not acceptable, however this class is immutable so it is OK. hashCode = url_1.concat(url_2).concat(url_3).hashCode(); urls = Collections.unmodifiableList(Arrays.asList(new String[]{url_1, url_2, url_3})); }
6
private boolean addDeklinationSubstTable( String wikiText, int fromIndex, String baseWord ) { Properties props = BookUtils.parseRule( wikiText, "Deutsch Substantiv bersicht", fromIndex ); if( props != null ) { if( props.remove( "Bild" ) != null || props.remove( "Bild 1" ) != null ) { props.remove( "1" ); props.remove( "2" ); props.remove( "3" ); } if( props.remove( "Bild 2" ) != null ) { props.remove( "4" ); props.remove( "5" ); props.remove( "6" ); } if( props.remove( "Bild 3" ) != null ) { props.remove( "7" ); props.remove( "8" ); props.remove( "9" ); } if( props.remove( "Bild 4" ) != null ) { props.remove( "10" ); props.remove( "11" ); props.remove( "12" ); } if( props.remove( "Bild 5" ) != null ) { props.remove( "13" ); props.remove( "14" ); props.remove( "15" ); } for( Entry entry : props.entrySet() ) { String word = (String)entry.getValue(); addFormatedWordPhrase( baseWord, (String)entry.getKey(), word ); } return true; } return false; }
8
public Instantiation findOwner(final int i) { if (!subroutine.ownsInstruction(i)) { return null; } if (!dualCitizens.get(i)) { return this; } Instantiation own = this; for (Instantiation p = previous; p != null; p = p.previous) { if (p.subroutine.ownsInstruction(i)) { own = p; } } return own; }
4
public t(int nu) throws ParameterException { if (nu < 1) { throw new ParameterException("t parameter nu >= 1"); } else { this.nu = nu; chiSq = new ChiSquared(nu); norm = new Normal(0, 1); } }
1
protected void loadNBT(NBTTagCompound data) { NBTTagList list = data.getTagList("pairings", 10); for (byte entry = 0; entry < list.tagCount(); entry++) { NBTTagCompound tag = list.getCompoundTagAt(entry); int[] c = tag.getIntArray("coords"); pairings.add(new WorldCoordinate(c[0], c[1], c[2], c[3])); } this.name = data.getString("name"); if (this.name.isEmpty()) { this.name = null; } }
2
@Override public void update(GameContainer container, int delta) throws SlickException { i = container.getInput(); if (i.isKeyDown(Input.KEY_UP)) { gc.key_up(delta); } else if (i.isKeyDown(Input.KEY_DOWN)) { gc.key_down(delta); } if (i.isKeyDown(Input.KEY_RIGHT)) { gc.key_right(delta); } else if (i.isKeyDown(Input.KEY_LEFT)) { gc.key_left(delta); } gc.update(delta); }
4
public Key min() { if (minIndex != -1) return pq[minIndex]; return null; }
1
public void setPayment(boolean payment) { this.payment = payment; }
0
private static String loadPattern(String fileName) { BufferedReader in; StringBuilder b; if (fileName == null) { return null; } // if try { in = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), Charset.forName(charsetName))); } catch (FileNotFoundException e) { return null; } // catch b = new StringBuilder(); while(true) { String s; try { s = in.readLine(); } catch (IOException e) { return null; } // catch if (s == null) { if (b.length() > 0) { b.deleteCharAt(b.length() - 1); } // if break; } // if b.append(s); b.append('\r'); } // while return b.toString(); } // loadPattern
6
@Override public final void registerId(final Path parent, final String filename) { final Path p = parent == null ? Path.getPath(filename) : parent.resolve(filename); final int pathId = Deserializer_0.this.pathIdNextOut.incrementAndGet(); final byte[] idBytesPrev = writeIntRE(parent == null ? 0 : Deserializer_0.this.idMapOut.get(parent)); final byte[] idBytes = writeIntRE(pathId); final byte[] bytesName = filename.getBytes(FileSystem.UTF8); final byte[] nameLength = writeIntRE(bytesName.length); final byte[] bytes = new byte[idBytesPrev.length + idBytes.length + nameLength.length + bytesName.length]; int offset = 0; System.arraycopy(idBytesPrev, 0, bytes, offset, idBytesPrev.length); offset += idBytesPrev.length; System.arraycopy(idBytes, 0, bytes, offset, idBytes.length); offset += idBytes.length; System.arraycopy(nameLength, 0, bytes, offset, nameLength.length); offset += nameLength.length; System.arraycopy(bytesName, 0, bytes, offset, bytesName.length); try { synchronized (Deserializer_0.this.pathIdOut) { Deserializer_0.this.pathIdOut.write(bytes); } } catch (final IOException e) { e.printStackTrace(); } synchronized (Deserializer_0.this.idMapOut) { Deserializer_0.this.idMapOut.put(p, pathId); Deserializer_0.this.idMapOut.notifyAll(); } }
3
public final void callAttachments(Interface sender, String message) { ArrayList<Interface> receiver = new ArrayList<Interface>(); // Find all receiver in attachments list Iterator<Attachment> itAttach = this.attachments.iterator(); while(itAttach.hasNext()) { Interface dest = itAttach.next().getReceiver(sender); if(dest != null) { receiver.add(dest); } } // Activate all receivers Iterator<Interface> itIface = receiver.iterator(); while(itIface.hasNext()) { Interface dest = itIface.next(); dest.activate(message); } }
3
@Override public List<Race> raceQualifies(int theme) { final Vector<Race> qualRaces = new Vector<Race>(); final HashSet<String> doneRaces=new HashSet<String>(); for(final Enumeration<Race> r=CMClass.races();r.hasMoreElements();) { Race R=r.nextElement(); if(doneRaces.contains(R.ID())) continue; R=CMClass.getRace(R.ID()); doneRaces.add(R.ID()); if((CMProps.isTheme(R.availabilityCode())) &&(!CMath.bset(R.availabilityCode(),Area.THEME_SKILLONLYMASK)) &&((!CMSecurity.isDisabled(CMSecurity.DisFlag.STDRACES))||(R.isGeneric())) &&(CMath.bset(R.availabilityCode(),theme))) qualRaces.add(R); } return qualRaces; }
7
public void handleDoMPIMaster(MutationManager mutMan, int size) throws MPIException, InterruptedException { //KER: If it isn't an mpiRun start extra threads so that we can simulate //an mpiRun if(!mpiRun) MPItoThread.startThreads(this,Thread.currentThread()); CommucObj cObjArray[] = new CommucObj[size]; int numFinished = 0; int curMut = 0; for (int curProc=1; curProc<numProc; curProc++){ //distribute a single mutation per processor, for all processors if (curMut<cObjArray.length){ //more mutations to distribute System.out.println("Retrieving "+curMut+" of "+(cObjArray.length)); cObjArray[curMut] = mutMan.getNextComObj(curMut); MPItoThread.Send(cObjArray, curMut, 1, ThreadMessage.OBJECT, curProc, regTag); curMut++; System.out.println("Sent to proc "+curProc); System.out.println(); } else break; } boolean distrDACS = mutMan.getDistrDACS(); //distributed DACS computation while (numFinished<cObjArray.length){ //distribute and receive all remaining mutations CommucObj cObj[] = new CommucObj[1]; cObj[0] = new CommucObj(); //System.out.println("Receiving message on main node.."); Object s = MPItoThread.Recv(cObj, 0, 1, ThreadMessage.OBJECT, ThreadMessage.ANY_SOURCE, ThreadMessage.ANY_TAG); //System.out.println("Received message on main node: tag "+s.tag+" source "+s.source); if (distrDACS){ //DACS computation, so check if the new energy is better than the best energy so far double curBestE = mutMan.getPruningE(); if (cObj[0].pruningE<curBestE){ //the new energy is better //System.out.println("Updating best energy on main node from "+curBestE+" to "+cObj[0].pruningE+", source (partition): "+cObj[0].partIndex); mutMan.setBestScore(new BigDecimal(cObj[0].pruningE)); mutMan.setPruningE(cObj[0].pruningE); double c[] = new double[1]; c[0] = cObj[0].pruningE; for (int curProc=1; curProc<numProc; curProc++){ //update the best energy in each partition MPItoThread.Isend(c, 0, 1, ThreadMessage.FLOAT, curProc, updateTag); } } } if (MPItoThread.getStatusTag(s)==regTag){ //completed job mutMan.processFinishedMutation(cObj[0]); numFinished++; System.out.println("Finished: "+cObj[0].mutationNumber+", Time: "+(cObj[0].elapsedTime/60.0)); if (curMut<cObjArray.length){ System.out.print("Retrieving "+curMut+" of "+(cObjArray.length)); cObjArray[curMut] = mutMan.getNextComObj(curMut); MPItoThread.Send(cObjArray, curMut, 1, ThreadMessage.OBJECT, MPItoThread.getStatusSource(s), regTag); curMut++; System.out.println(", Sent to proc "+MPItoThread.getStatusSource(s)); System.out.println(); } } } }
9
private static boolean isHexNumber(String value) { int index = (value.startsWith("-") ? 1 : 0); return (value.startsWith("0x", index) || value.startsWith("0X", index) || value .startsWith("#", index)); }
3
public static void main(String args[]) { // null check Utility.printObject(null); DataBase db = new DataBase(); // null fields Utility.printObject(db); Name n = new Name(); Utility.printObject(n); n.firstName = "Aviva"; n.lastName = "Herman"; // prints a real object Utility.printObject(n); Person p = new Person(); // null fields Utility.printObject(p); p.age = 24; p.name = n; // prints a real object Utility.printObject(p); Address ad = new Address(); ad.phone = "039628532"; ad.st = new Street(); ad.st.name = "Ha'Rav Neria St."; ad.st.num = 6; p.address = ad; // prints nested "structs" Utility.printObject(p); // Test collection and array db.names = new Person[5]; db.ids = new LinkedList<>(); db.num = 0; for (int i = 0; i < db.names.length; i++) { db.num++; db.names[i] = new Person(); db.names[i].age = i + 20; db.names[i].name = new Name(); db.names[i].name.firstName = "Aviva" + i; db.names[i].name.lastName = "Herman" + i; db.names[i].address = new Address(); db.names[i].address.phone = "" + (i + 1) * 1000000; db.names[i].address.st = new Street(); db.names[i].address.st.name = "Ha'Rav Neria St."; db.names[i].address.st.num = i; Name name = new Name(); name.firstName = "a" + i; name.lastName = "b" + i; db.ids.addLast(name); } Utility.printObject(db); }
1
protected static Ptg calcPRICEMAT( Ptg[] operands ) { if( operands.length < 4 ) { // not supported by function return new PtgErr( PtgErr.ERROR_NULL ); } debugOperands( operands, "calcPRICEMAT" ); try { GregorianCalendar sDate = (GregorianCalendar) DateConverter.getCalendarFromNumber( operands[0].getValue() ); GregorianCalendar mDate = (GregorianCalendar) DateConverter.getCalendarFromNumber( operands[1].getValue() ); GregorianCalendar iDate = (GregorianCalendar) DateConverter.getCalendarFromNumber( operands[2].getValue() ); double rate = operands[3].getDoubleVal(); double yld = operands[4].getDoubleVal(); int basis = 0; if( operands.length > 5 ) { basis = operands[5].getIntVal(); } // TODO: if dates are not valid, return #VALUE! error if( (basis < 0) || (basis > 4) ) { return new PtgErr( PtgErr.ERROR_NUM ); } if( !sDate.before( mDate ) ) { return new PtgErr( PtgErr.ERROR_NUM ); } if( (rate < 0) || (yld < 0) ) { return new PtgErr( PtgErr.ERROR_NUM ); } long settlementDate = (new Double( DateConverter.getXLSDateVal( sDate ) )).longValue(); long maturityDate = (new Double( DateConverter.getXLSDateVal( mDate ) )).longValue(); long issueDate = (new Double( DateConverter.getXLSDateVal( iDate ) )).longValue(); double B = getDaysInYearFromBasis( basis, settlementDate, maturityDate ); double DSM = getDaysFromBasis( basis, settlementDate, maturityDate ); double DIM = getDaysFromBasis( basis, issueDate, maturityDate ); double A = getDaysFromBasis( basis, issueDate, settlementDate ); double result = (100 + ((DIM / B) * rate * 100)) / (1 + ((DSM / B) * yld)); result -= (A / B) * rate * 100; PtgNumber pnum = new PtgNumber( result ); log.debug( "Result from calcPRICEMAT= " + result ); return pnum; } catch( Exception e ) { } return new PtgErr( PtgErr.ERROR_VALUE ); }
8
public boolean ParseChatCommand(Session mSession, String Command) { String CommandName = SplitCommand(Command, true)[0]; if (!ChatCommands.containsKey((CommandName).toLowerCase())) { mSession.SendAlert(CommandName + " isn't a valid chat command!", null); return false; } if (mSession.GrabHabbo().Rank < ChatCommands.get(CommandName).MinimumRank()) { mSession.SendAlert("You don't have permission to execute " + CommandName, null); return false; } ChatCommands.get(CommandName).Execute(mSession, SplitCommand(Command, false)); return true; }
2
public void rotate(Direction dir) { if (dir == Direction.EAST) { Log.i("Rotating model right"); for (Level l : levels) { for (Piece p : l.pieces) { int oldY = p.y; p.y = p.x; p.x = getHeight()*2 - oldY- 1; // height pre swap p.type = PieceType.getRotation(p.type); p.x -= p.type.width*2 - 1; } l.resortPieces(); } } else if (dir == Direction.WEST) { Log.i("Rotating model left"); for (Level l : levels) { for (Piece p : l.pieces) { int oldX = p.x; p.x = p.y; p.y = getWidth()*2 - oldX - 1; // height pre swap p.type = PieceType.getRotation(p.type); p.y -= p.type.height*2 - 1; } l.resortPieces(); } } //TODO: manage swapping model width/height }
6
public static void printInfo() { Logger.logInfo("FTBLaunch starting up (version " + Constants.version + " Build: " + Constants.buildNumber + ")"); Logger.logInfo("Java version: " + System.getProperty("java.version")); Logger.logInfo("Java vendor: " + System.getProperty("java.vendor")); Logger.logInfo("Java home: " + System.getProperty("java.home")); Logger.logInfo("Java specification: " + System.getProperty("java.vm.specification.name") + " version: " + System.getProperty("java.vm.specification.version") + " by " + System.getProperty("java.vm.specification.vendor")); Logger.logInfo("Java vm: " + System.getProperty("java.vm.name") + " version: " + System.getProperty("java.vm.version") + " by " + System.getProperty("java.vm.vendor")); Logger.logInfo("OS: " + System.getProperty("os.name") + " " + System.getProperty("os.version") + " (" + (OSUtils.is64BitOS() ? "64-bit" : "32-bit") + ")"); Logger.logInfo("Launcher Install Dir: " + Settings.getSettings().getInstallPath()); Logger.logInfo("System memory: " + OSUtils.getOSFreeMemory() + "M free, " + OSUtils.getOSTotalMemory() + "M total"); //hack: I want to trigger JavaFinder here: String selectedJavaPath = Settings.getSettings().getJavaPath(); //then test if preferred and selected java paths differs if (!selectedJavaPath.equals(Settings.getSettings().getDefaultJavaPath())) { Logger.logInfo("Using Java path entered by user: " + selectedJavaPath); } if (!OSUtils.is64BitOS()) { Logger.logError("32-bit operating system. 64-bit is required for most mod packs. If you have issues, please try the FTB Lite 2 pack."); } if (OSUtils.is64BitOS() && !Settings.getSettings().getCurrentJava().is64bits) {//unfortunately the easy to find DL links are for 32 bit java Logger.logError("32-bit Java in 64-bit operating system. 64-bit Java is required for most mod packs. If you have issues, please try the FTB Lite 2 pack."); } JavaInfo java = Settings.getSettings().getCurrentJava(); if(java.getMajor() < 1 || (java.getMajor() == 1 && java.getMinor() < 7)){ Logger.logError("Java 6 detected. Java 7 is recommended for most mod packs."); } }
8
private boolean ReadConfigFile() { //read status boolean status = false; //holds each line read String data = null; //hold the name of the section of the config file String section = null; try { //open the file input stream FileInputStream inStream = new FileInputStream(System.getProperty("user.dir")+"/ConfigFile.cfg"); //get the data stream for the file DataInputStream in = new DataInputStream(inStream); //read data from the file BufferedReader br = new BufferedReader(new InputStreamReader(in)); //iterate the file line by line while((data = br.readLine()) != null) { //ensure not a blank line if(data.length() != 0) { //ensure not a comment if(data.charAt(0) != '#') { //check for section in the config file if (data.charAt(0) == '[') { //get the section name of the config file section = data.substring(1, data.length()-1); //put section in the main hash table, to hold section config configSections.put(section.toUpperCase(),new Hashtable()); } else { //split the config line based on the equal sign String []info = data.split("="); Hashtable tmpHash = (Hashtable)configSections.get(section); try { //enter config the section with the Integer values tmpHash.put(info[0].trim().toUpperCase(),Integer.parseInt((info[1].trim().toLowerCase()))); } catch(NumberFormatException e){ //enter config the section with the String values tmpHash.put(info[0].trim().toUpperCase(),info[1].trim().toLowerCase()); } } //read was successful status = true; } } } //close input in.close(); } catch(Exception e){ //get the error message //System.out.println("Error: " + e.getMessage()); status = false; } //return status of file read return status; }
6
private static void setExtendedParentPointers (final int[] array) { final int length = array.length; array[0] += array[1]; for (int headNode = 0, tailNode = 1, topNode = 2; tailNode < (length - 1); tailNode++) { int temp; if ((topNode >= length) || (array[headNode] < array[topNode])) { temp = array[headNode]; array[headNode++] = tailNode; } else { temp = array[topNode++]; } if ((topNode >= length) || ((headNode < tailNode) && (array[headNode] < array[topNode]))) { temp += array[headNode]; array[headNode++] = tailNode + length; } else { temp += array[topNode++]; } array[tailNode] = temp; } }
6
@Override public Class<?> getColumnClass(int columnIndex) { switch(columnIndex){ case 0: return String.class; case 1: return Ingredient.class; case 2: // return String.class; return Double.class; case 3: return Component.class; // return Double.class; // return String.class; default: return Object.class; } }
5
private void bindAmountScrolled() { int var1 = this.getContentHeight() - (this.bottom - this.top - 4); if(var1 < 0) { var1 /= 2; } if(this.amountScrolled < 0.0F) { this.amountScrolled = 0.0F; } if(this.amountScrolled > (float)var1) { this.amountScrolled = (float)var1; } }
3
public static boolean buildInstance(String account, String name) { //Clear progress (partially redundant) GlobalDialogs.setProgressCaption("Initializing..."); GlobalDialogs.setProgressValue(0); //Mark instance as incomplete Logger.info("Instances.buildInstance", "Updating instance status as 'incomplete'..."); setInstanceIncomplete(account, name); String instancePath = "./users/" + account + "/" + name; //Load instance config Logger.info("Instances.buildInstance", "Loading instance config..."); JSONObject instanceConfig; try { instanceConfig = Util.readJSONFile(instancePath + "/instance.json"); } catch (IOException ex) { Logger.error("Instances.buildInstance", "Failed to read instance.json!", true, ex); GlobalDialogs.showNotification("Failed to load instance!"); return false; } //Load pack config Logger.info("Instances.buildInstance", "Loading pack config..."); JSONObject packConfig; try { packConfig = Util.readJSONFile("./packs/" + instanceConfig.get("pack").toString() + "/pack.json"); } catch (IOException ex) { Logger.error("Instances.buildInstance", "Failed to read pack.json!", true, ex); GlobalDialogs.showNotification("Failed to load modpack!"); return false; } //Announce installation queue build GlobalDialogs.setProgressCaption("Building installation queue..."); GlobalDialogs.setProgressValue(0); //Get entries queued for installation Logger.info("Instances.buildInstance", "Building installation queue..."); List<String> installationQueue = getInstallationQueue(packConfig, instanceConfig.get("version").toString()); //Announce settings being loaded GlobalDialogs.setProgressCaption("Loading settings..."); GlobalDialogs.setProgressValue(0); //Set mod list settings Logger.info("Instances.buildInstance", "Adding mods to installation queue setting..."); for (String mod : installationQueue) { Variables.setSetting("mods.Installed", mod); } //Set APPDATA setting Variables.setSetting("launch.AppDataDirectory", Util.getFullPath(instancePath)); //Set all other settings Logger.info("Instances.buildInstance", "Loading settings..."); loadPackSettings(packConfig, installationQueue); //Create .minecraft directory Util.createDirectoryIfNeeded(instancePath + "/.minecraft"); //Install cache entries for (String entry : installationQueue) { //Announce entry GlobalDialogs.setProgressCaption("Installing entry '" + entry.split("-")[0] + "'..."); //Install entry Logger.info("Instances.buildInstance", "Installing entry '" + entry.split("-")[0] + "'..."); installCacheEntry(entry.split("-")[0], entry.split("-")[1], "./packs/" + instanceConfig.get("pack").toString() + "/cache", "./users/" + account + "/" + name + "/.minecraft"); //Update progress GlobalDialogs.incrementProgressValue(100 / installationQueue.size()); } //Announce Minecraft installation GlobalDialogs.setProgressCaption("Obtaining Minecraft jarfile..."); GlobalDialogs.setProgressValue(10); //Install Minecraft jarfile Logger.info("Instances.buildInstance", "Obtaining Minecraft jarfile..."); String mcVersion = packConfig.get("minecraftversion").toString(); Util.createDirectoryIfNeeded(instancePath + "/.minecraft/versions/" + mcVersion); Util.createDirectoryIfNeeded("./data/versions"); if (!(new File("./data/versions/" + mcVersion + ".jar").isFile())) { //Download file Logger.info("Instances.buildInstance", "Version not found! Will download..."); try { FileUtils.copyURLToFile(new URL("http://s3.amazonaws.com/Minecraft.Download/versions/" + mcVersion + "/" + mcVersion + ".jar"), new File("./data/versions/" + mcVersion + ".jar")); } catch (IOException ex) { Logger.error("Modpack.build", "Failed to download Minecraft jarfile!", true, ex); GlobalDialogs.showNotification("Failed to get required Minecraft version!"); return false; } //Update progress GlobalDialogs.setProgressValue(50); } Logger.info("Instances.buildInstance", "Copying Minecraft jarfile..."); try { FileUtils.copyFile(new File("./data/versions/" + mcVersion + ".jar"), new File(instancePath + "/.minecraft/versions/" + mcVersion + "/" + mcVersion + ".jar")); } catch (IOException ex) { Logger.error("Modpack.build", "Failed to copy Minecraft jarfile!", true, ex); GlobalDialogs.showNotification("Failed to install Minecraft jarfile!"); return false; } //Announce Minecraft asset installation GlobalDialogs.setProgressCaption("Obtaining Minecraft assets..."); GlobalDialogs.setProgressIndeterminate(true); Logger.info("Instances.buildInstance", "Copying Minecraft assets..."); try { FileUtils.copyDirectory(new File("./data/assets/legacy"), new File(instancePath + "/.minecraft/assets")); } catch (IOException ex) { Logger.error("Modpack.build", "Failed to copy Minecraft assets!", false, ex); } //Update progress GlobalDialogs.setProgressIndeterminate(false); GlobalDialogs.setProgressCaption("Finishing up..."); GlobalDialogs.setProgressValue(100); //Set instance complete Logger.info("Instances.buildInstance", "Updating instance status as 'complete'..."); setInstanceComplete(account, name); return true; }
8
public void removeView(AbstractView view) { registeredViews.remove(view); view.removePropertyChangeListener(this); }
0
@Override public int compareTo(Object e) { if(this.weight > ((Edge)e).weight) return 1; if(this.weight < ((Edge)e).weight) return -1; if(this.weight == ((Edge)e).weight) return 0; return 0; }
3
public SchemaEditorToolBar(final BasicGraphEditor editor, int orientation) { super(orientation); setBorder(BorderFactory.createCompoundBorder(BorderFactory .createEmptyBorder(3, 3, 3, 3), getBorder())); setFloatable(false); add(editor.bind("New", new NewAction(), "/com/mxgraph/examples/swing/images/new.gif")); add(editor.bind("Open", new OpenAction(), "/com/mxgraph/examples/swing/images/open.gif")); add(editor.bind("Save", new SaveAction(false), "/com/mxgraph/examples/swing/images/save.gif")); addSeparator(); add(editor.bind("Print", new PrintAction(), "/com/mxgraph/examples/swing/images/print.gif")); addSeparator(); add(editor.bind("Cut", TransferHandler.getCutAction(), "/com/mxgraph/examples/swing/images/cut.gif")); add(editor.bind("Copy", TransferHandler.getCopyAction(), "/com/mxgraph/examples/swing/images/copy.gif")); add(editor.bind("Paste", TransferHandler.getPasteAction(), "/com/mxgraph/examples/swing/images/paste.gif")); addSeparator(); add(editor.bind("Delete", mxGraphActions.getDeleteAction(), "/com/mxgraph/examples/swing/images/delete.gif")); addSeparator(); add(editor.bind("Undo", new HistoryAction(true), "/com/mxgraph/examples/swing/images/undo.gif")); add(editor.bind("Redo", new HistoryAction(false), "/com/mxgraph/examples/swing/images/redo.gif")); addSeparator(); final mxGraphView view = editor.getGraphComponent().getGraph() .getView(); final JComboBox zoomCombo = new JComboBox(new Object[] { "400%", "200%", "150%", "100%", "75%", "50%", mxResources.get("page"), mxResources.get("width"), mxResources.get("actualSize") }); zoomCombo.setEditable(true); zoomCombo.setMinimumSize(new Dimension(75, 0)); zoomCombo.setPreferredSize(new Dimension(75, 0)); zoomCombo.setMaximumSize(new Dimension(75, 100)); zoomCombo.setMaximumRowCount(9); add(zoomCombo); // Sets the zoom in the zoom combo the current value mxIEventListener scaleTracker = new mxIEventListener() { /** * */ public void invoke(Object sender, mxEventObject evt) { ignoreZoomChange = true; try { zoomCombo.setSelectedItem((int) Math.round(100 * view .getScale()) + "%"); } finally { ignoreZoomChange = false; } } }; // Installs the scale tracker to update the value in the combo box // if the zoom is changed from outside the combo box view.getGraph().getView().addListener(mxEvent.SCALE, scaleTracker); view.getGraph().getView().addListener(mxEvent.SCALE_AND_TRANSLATE, scaleTracker); // Invokes once to sync with the actual zoom value scaleTracker.invoke(null, null); zoomCombo.addActionListener(new ActionListener() { /** * */ public void actionPerformed(ActionEvent e) { mxGraphComponent graphComponent = editor.getGraphComponent(); // Zoomcombo is changed when the scale is changed in the diagram // but the change is ignored here if (!ignoreZoomChange) { String zoom = zoomCombo.getSelectedItem().toString(); if (zoom.equals(mxResources.get("page"))) { graphComponent.setPageVisible(true); graphComponent .setZoomPolicy(mxGraphComponent.ZOOM_POLICY_PAGE); } else if (zoom.equals(mxResources.get("width"))) { graphComponent.setPageVisible(true); graphComponent .setZoomPolicy(mxGraphComponent.ZOOM_POLICY_WIDTH); } else if (zoom.equals(mxResources.get("actualSize"))) { graphComponent.zoomActual(); } else { try { zoom = zoom.replace("%", ""); double scale = Math.min(16, Math.max(0.01, Double.parseDouble(zoom) / 100)); graphComponent.zoomTo(scale, graphComponent .isCenterZoom()); } catch (Exception ex) { JOptionPane.showMessageDialog(editor, ex .getMessage()); } } } } }); }
5