text
stringlengths
14
410k
label
int32
0
9
public String readFileAsString(String filename) throws Exception { StringBuilder source = new StringBuilder(); InputStream in = this.getClass().getResourceAsStream(filename); Exception exception = null; BufferedReader reader; try { reader = new BufferedReader(new InputStreamReader(in, "UTF-8")); Exc...
9
private QCell getStateFromAction(QCell currentState, Action ac) { int endI = currentState.row; int endJ = currentState.col; if (ac == Action.LEFT) { endJ--; } if (ac == Action.RIGHT) { endJ++; } if (ac == Action.DOWN) { endI++; } if (ac == Action.UP) { endI--; } if (endI < 0 || endI...
9
public void setParticipantOffline(String id) { if(participants.containsKey(id)) { participants.get(id).setOffline(); } setChanged(); notifyObservers(ModelNotification.LIST_OF_PARTICIPANTS_CHANGED); }
1
public void setFloatArray(float[] floatArray){ this.floatArray = floatArray; }
0
public static Color weightToColor(double weight) { if (weight < 1e10) return Color.GREEN; if (weight < 1e12) return Color.CYAN; if (weight < 1e14) return Color.MAGENTA; if (weight < 1e16) return Color.BLUE; if (weight < 1e18) return Color.GRAY; if (weight < 1e20) return C...
9
public void DDSSpecial() { if(IsAttackingNPC && playerEquipment[playerWeapon] == 5698) { setAnimation(0x426); actionTimer = 4; SpecDamgNPC(31); DDS2Damg = true; DDStimer = 1; resetAnimation(); teleportToX = absX; teleportToY ...
4
private DataInstance getInputs(){ DataInstance data = new DataInstance(net_layers[0]); //Rack int[] cur_rack = rack.getCards(); data.addFeature(cur_rack, game.card_count); //Probabilities if (USE_PROB){ double[] pHigh = new double[game.rack_size], pLow = new double[game.rack_size]; for (int i=0; ...
2
protected void jump(String url, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestDispatcher rd = getServletContext().getRequestDispatcher(url); rd.forward(request, response); // request.getRequestDispatcher(url).include(request, response); ?????? }
0
@Override public String toString() { String result = "\n- Cuenta: " + this.cuenta + ", Cliente: " + this.nombre + ", Saldo: " + this.saldo+"\n"; // result += "\n MOVIMIENTOS: \n" + this.movimientos.toString(); return result; }
0
public boolean Grand (String ip) { String command = "sudo /bin/bash /portal/rules.sh grand " +ip; try { Process process; process = Runtime.getRuntime().exec(command); String line; BufferedReader is = new BufferedReader(new InputStreamReader(process.getInputStream())); w...
3
@Override public void execute(CommandExecutor player, String[] args) { if (args.length == 0) { help(player); return; } Command cmd = player.getServer().getCommandHandler().find(args[0]); if (cmd == null) { player.sendMessage("The specified command wasn't found!"); return; } cmd.help(player...
2
public int callCommand(PreparedStatement _sqlCommand, Connection _con) { int returnVal = 0; //Benchmark time start ThreadMXBean threadmxbean = ManagementFactory.getThreadMXBean(); long startTime; long finishTime; if (_enableSqlMonitor) startTime = threa...
4
public void setTitle(String title) { this.title = title; }
0
@Test public void testWinnerRatio() throws IllegalAccessException, InstantiationException { Class[] creatureClasses = new Class[] { Mouse.class, Rat.class, BigMouse.class, BigRat.class }; for (Class classCreature1 : creatureCla...
4
public void send(Envelope envelope) throws IOException { /* Send all the necessary commands to send a message. Call sendCommand() to do the dirty work. Do _not_ catch the exception thrown from sendCommand(). */ String mailFrom = "MAIL FROM: " + envelope.Sender + CRLF; sendCommand...
5
public void move(int x, int y, Entity entity) { /* * At some point we have to lock on the entity in order to give it an * update as to its current location (and direction). If a collision is * going to occur at this point, we can't have our cake and eat it too: * it won't be possible to getLocation() of ...
9
public String printResults(boolean all) { StringBuffer sb = new StringBuffer(100); double singleMultiRatio = 0.0; sb.append("Scale factor: " + parameterPool.getScalefactor() + "\n"); sb.append("Number of warmup runs: " + warmups + "\n"); if (multithreading) sb.append("Number of clients: ...
8
public void setMissingDataOption(int option){ if(option<1 || option>5)throw new IllegalArgumentException("The missing response option entered is " + option + "; the option must be 1, 2, 3, 4 or 5"); this.replacementOption = option; this.replacementOptionSet = true; if(this.personDeletion...
5
public Button(int i) { super(currentfloorplan.getItem(i / N, i % N)); this.setOpaque(true); this.setBorderPainted(true); this.setBackground(Color.white); this.x = i / N; this.y = i % N; switch(currentf...
9
public static String getDescriptiveType(Object value) { if (value == null) { return null; } Class<?> clazz = value.getClass(); if (Proxy.isProxyClass(clazz)) { StringBuilder result = new StringBuilder(clazz.getName()); result.append(" implementing "); Class<?>[] ifcs = clazz.getInterfaces(); for ...
7
@Override public void run() { int whatdo = Random.nextInt(0, 10); switch (whatdo) { case 0: case 1: case 2: case 3: int currentX = Mouse.getX(); int currentY = Mouse.getY(); Mouse.move(Random.nextInt(0, 20) + currentX, Random.nextInt(16, 39) + currentY); break; case 5: case 4: ...
8
private LinkedList<Theater> loadTheatersFromDisk(File name){ FileInputStream fis; ObjectInputStream ois; Theater theater = null; LinkedList<Theater> result = new LinkedList<Theater>(); try { fis = new FileInputStream(name); ois = new ObjectInputStream(fis); do{ try{ theater = (Theater) oi...
5
public static void asm_xorwf(Integer akt_Befehl, Prozessor cpu) { // Decode Integer adresse = getOpcodeFromToBit(akt_Befehl, 0, 6); Integer d = getOpcodeFromToBit(akt_Befehl, 7, 7); // Fetch Integer f = cpu.getSpeicherzellenWert(adresse); Integer w = cpu.getW(); // EXEC: XOR Integer result = new Inte...
1
public static void main(String[] args) { int len = 10; Random rand = new Random(); int val; int max = 20; Map<Holder<Integer>, Integer> m = new HashMap<Holder<Integer>, Integer>(len); for (int i = 0; i < len; ++i) { val = rand.nextInt(max) + 1; m.p...
2
private void serverNameChanged() { if (client.getCommunicator() != null) { popUpWindow dialog = new popUpWindow(this, "Wollen Sie sich wirklich vom Server abmelden ?"); if (dialog.getResult()) { client.disconnect(); } } if (client.getCommunicator() == null) { isServerOk = (...
6
public static void main(String... args) throws Exception { TTransport transport = new TFramedTransport(new TSocket("localhost", 10000)); transport.open(); TProtocol protocol = new TBinaryProtocol(transport); BookService.Client client = new BookService.Client(protocol); long l = S...
1
public void writeObjectFeatureStart(String name) { switch (AObjectEnum.valueOf(name.toUpperCase())) { case NAME: System.out.print("Name: "); break; case MASS: System.out.print("Mass: "); break; case TEMPERATURE: ...
7
@Override public int read() { // test if the available input has reached its end // and the EOS should be returned if (str != null && pos == str.length()) { str = null; // this is supposed to return -1 on "end of stream" // but I'm having a hard time locating the constant return java.io.StreamTokeniz...
5
protected void repaint(){ if( site != null ){ site.repaint(); } }
1
public void playRound(Player player){ boolean cont = true; Scanner in = new Scanner( System.in ); int roundNumber = 0; while(!player.getHand(1).isBust() && cont){ roundNumber++; //check for split.... //options hit, stand or double if(roundNumber > 1){ System.out.println("Would you like to hi...
7
protected int[] clusterIter(int iterNum) { Smatrix = getSimilarMatrix(oriDatas); int diffCount = 0;//中心点不变化的次数 for (int i = 0; i < iterNum; i++) { int diffNum = 0;//在一次迭代中中心点变化的个数 // System.out.println("正在进行第" + i + "次迭代"); //注意,先更新R再更新A //TODO 更新时是...
5
@Override public void train(List<Instance> instances) { // calculate the Gram Matrix. // java List maintains iterator order. this.instances = instances; int index1 = 0; int index2 = 0; labels = new double[instances.size()]; dualParam = new double[instances.size()]; gramMatrix = new double[instances.si...
6
private int[][] createPattern() { List<Integer> positionNumbers = Arrays.asList(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15); //indices of the 16 places where a dot COULD be placed Collections.shuffle(positionNumbers); //randomize their order List<Integer> dotPositions = positionNumbers.subList(0, 4); //get the first...
4
@Override public void actionPerformed(ActionEvent ev) { switch(getVector()) { case UP: moveUp(); break; case DOWN: moveDown(); break; case LEFT: moveLeft(); break; ...
4
public void move() { Random generator = new Random(); int num1 = generator.nextInt(4); if (num1 == 0) { x -= 5; y -= 5; } else if (num1 == 1) { x -= 5; y += 5; } else if (num1 == 2) { x += 5; y -= 5; ...
7
private Response putAndGetResponse(Behavior target, String client_id) throws IOException { Response res; String baseDir = baseFilePath + File.separator + client_id + File.separator + "Target"; // System.out.println(baseDir + File.separator + "Target.xml"); File targetXmlFile = new File(baseDir + File.se...
2
public Dimension getMinimumSize() { int height = 0; int width = 0; // // Use the size set by the application // if (isPreferredSizeSet()) return super.getPreferredSize(); // // Leave room for the component border // Border bor...
5
public void showDebugGrid(boolean draw) { if(draw == true) { DRAW_DEBUG_GRID = true; } else { DRAW_DEBUG_GRID = false; } }
1
public void setFlowSensitiveAliasing(boolean flowSensitiveAliasing) { this.flowSensitiveAliasing = flowSensitiveAliasing; }
0
public void valueChanged(ListSelectionEvent e) { if (refreshing > 0) return; // If cell selection is enabled, both row and column change events are fired if (e.getSource() == table.getSelectionModel() && table.getRowSelectionAllowed() && !e.getValueIsAdj...
4
public static void main(String[] args) throws ClassNotFoundException, IOException { /*ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("test.txt"))); out.writeObject(new Theater(1, "NAME", "THEATER", 1)); out.writeObject(new Theater(2, "NAME2", "THEATER2", 2)); o...
3
public void start() throws IOException{ distributedService = new DistributedService(); distributedService.registerListener(new LockEventListener(this)); distributedService.init(); String msg = "Joined_by: " + ":" + memberid; //To notify all nodes of the network, that a new member just joined the family. not...
0
@Override public void focusLost(FocusEvent event) { if(event.getSource() == carbohydratePercentageTextField) { try { carbohydratePercentageSlider.setValue(Integer.valueOf(carbohydratePercentageTextField.getText())); } catch(NumberFormatException nfe) { carbohydratePercentageTextField.setText(String.val...
6
public static void main(String[] args) { DataSet data = new DataSet("Creatieve industrie"); Category cat; String catagoryName = "Creatieve industrie"; GeoCoder geo = new GeoCoder(); SBICode sbiCode = new SBICode(); Rijksdriehoeksmeting rdCalc = new Rijksdriehoeksmeting(); int teller = 0; Scanner ...
7
public JSONArray toJSONArray(JSONArray names) throws JSONException { if (names == null || names.length() == 0) { return null; } JSONArray ja = new JSONArray(); for (int i = 0; i < names.length(); i += 1) { ja.put(this.opt(names.getString(i))); } re...
3
public static File getLibraryPath(File root) { String path = INSTANCE.versionData.getStringValue("install", "forge"); String[] split = Iterables.toArray(Splitter.on(':').omitEmptyStrings().split(path), String.class); File dest = root; Iterable<String> subSplit = Splitter.on('.').omitEmpt...
1
public static void main(String args[]) { CheckersSetup setup = new CheckersSetup(); UtilityKingWantsCenter test = new UtilityKingWantsCenter(); if(test.getEstimatedUtilityForDarkPlayer(setup, false) != 0) { System.out.println("Test1 failed!"); } int array[][] = setup.getPiecesOnBoard(); array[3][3] = ...
9
public void run(){ //Read input and process here mainServer.log("Client connecting from " + address); //DataOutputStream out = null; try { in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true...
9
public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n; boolean[] prime = new boolean[1000001]; for (int i = 2; i < 1000000; i++) { if (!prime[i]) { for (int j = i + i; j < 1000000; j += i) { prime[j] = true; ...
8
public static LinkedListNode findKth(LinkedListNode n, int k) { if(k<1) return null; LinkedListNode quick, slow; quick = slow = n; int i; for(i = 1; i<=k && quick != null; i++ ) quick = quick.next; if(i != k+1 ) return null; while(quick!= null) { quick = quick.next; slow = slow.next; ...
5
public void p_Nickname_abusive_Playforfun( LinkedHashMap<String, LinkedHashMap<String, String>> credentials) { autoutil.openBrowser(dataSheet(credentials,"url","url")); autoutil.waitTime(8000); autoutil.clickButton(dataSheet(credentials,"button","sign"),propFile("link")); autoutil.waitTime(3000); fo...
8
public SpeakerListResponse(final Boolean success, final String errorMessage, final List<Speaker> speakerList) { super(success, errorMessage); this.speakerList = speakerList; }
0
@Override public void run() { ParticleUtil.display(WrapperPlayServerWorldParticles.ParticleEffect.CLOUD, new Vector(0.1 * count.get(), 0.15 * count.get(), 0.10 * count.get()), 0, 4 * count.get(), player.getLocation()); if(count.get() < 12) { player.setVelocity(new Vecto...
3
public static void stringToArgs(Vector<String> vec, String s, boolean allowQuotedStrings) throws StringScanException { StringScanner scanner = new StringScanner(s); scanner.skipWhiteSpace(); while (!scanner.atEnd()) { if (allowQuotedStrings) { vec.add(scanner.scanString()); } else { ...
2
public static final String getCommonRoot(String fullPathOne, String fullPathTwo) { int i; int len1; int len2; int max; if (fullPathOne == null) { len1 = 0; } else { fullPathOne = fullPathOne.replace('\\', '/'); len1 = fullPathOne.length(); } if (fullPathTwo == null) { len2 = 0; } else { ...
9
public void hardShot() throws IOException { if (0 == stackSize) { target = new Point(rand(), rand()); numAttempts = 0; while (!testChoice(target, 1)) { target = new Point(rand(), rand()); } if (board.fire(target.x, targe...
6
public int agregarCliente(String name, String surname1, String surname2, String mail, String DNI, String telefono, String contact_date, String transaccion) { boolean Nocaracter = validarFormato(name); boolean Nocaracter2 = validarFormato(surname1); int condicion = 0; //...
6
@AfterClass public static void tearDownClass() { }
0
void enq(query q) { if (q.getCnode()==null) { common.out("Enq query is null"); Thread.dumpStack(); System.exit(0); } if (parentq==null) q.pqid=q.qid; else q.pqid=parentq.qid; query tq; for (int i=0;i<qbuf.size();i++) { tq=qbuf.get(i); if (tq.getCnode().getId()==q.getCnode().getId() && ...
7
public void intialize(){ try{ //store local machines IP and name InetAddress addr = InetAddress.getLocalHost(); PeerInfo.local.IP = addr.getHostAddress(); PeerInfo.local.name = addr.getHostName(); PeerInfo.local.ID = "rmi://" + PeerInfo.local.IP + ":" + PeerInfo.rmi.port + "/share"; System.out.print...
9
public int getImgIndexedColors() { return imgIndexedColors; }
0
static LinkedListNode partition(LinkedListNode n, int p) { LinkedListNode beforeHead = null; LinkedListNode beforeTail = null; LinkedListNode afterHead = null; LinkedListNode afterTail = null; while (n != null) { if (n.getValue() < p) { if (beforeHead...
5
@Override public void put( ByteBuffer out, boolean[] v ) { if (v == null) { out.put( Compress.NULL ); } else { Compress.putIntUnsignedNullable( out, v.length ); byte[] bytes = new byte[toBytes( v.length )]; for (int i = 0; ...
3
public void update(final Observable obj, final Object arg) { final String line = (String) arg; final String thisLine = line.substring(line.indexOf("Text [") + "Text [".length(), line.indexOf("]", line.indexOf("Text ["))); if (thisLine.indexOf(CLUSTER_RADIO_SEND) < 0) { return; ...
8
public boolean insertAfter(int key, int value) { NodeDLL current = first; while(current.data!= key) { current = current.next; if (current == null) return false; } NodeDLL newNodeDLL = new NodeDLL(value); if(current == last) { newNodeDLL.next = null; last = newNodeDLL; } else { ne...
3
public String getURL(String address){ String URL = address; if(!URL.startsWith("http://")){ URL = "http://" + address; } String domain = URL; if(!URL.endsWith("/") && !URL.endsWith(".html") && !URL.endsWith(".shtml") && !URL.endsWith(".htm") && !URL.endsWith(".aspx") ...
8
@Override public void actionPerformed(ActionEvent e) { if(e.getSource() == startStop){ if(recording){ Recorder stopper = (Recorder) theRecorder; stopper.getLine().close(); recording = false; startStop.setText("Start Recording"); backButton.setEnabled(true); } else if(!recordi...
4
@Override public String getSVG( HashMap<String, Double> chartMetrics, HashMap<String, Object> axisMetrics, ChartSeries s ) { double w = chartMetrics.get( "w" ); double h = chartMetrics.get( "h" ); double max = chartMetrics.get( "max" ); double min = chartMetrics.get( "min" ); Object[] categories = s.getCate...
9
private void combinationUtil(int arr[], int data[], int start, int end, int index, int r) { if (index == r) { int sum = 0; for (int j = 0; j < r - 1; j++) { for(int k=j+1;k<r;k++){ sum+=compatibilityArr[data[j]][data[k]]; } } // System.out.println("sum = "+sum); if (sum > maxTeamComp...
6
private void changeResolution(int res) { if (resolution == resolutionSelections.length-1) { increase.setEnabled(false); decrease.setEnabled(true); answer = true; } else if (resolution == 0) { decrease.setEnabled(false); increase.setEnabled(true); answer = false; } else { increase.setEnabled(t...
4
@Test public void testSaleAll() throws Exception { TestTicketPool pool = this.createTicketPool(); int stopCount = pool.getRoute().getStops().size(); TicketPoolQueryArgs query = new TicketPoolQueryArgs(); query.setCount(1); query.setSeatType(~0); ArrayList<TicketPoolTicket> soldTickets = ...
5
public void bfs(UndirectedNode root) { Queue<UndirectedNode> queue = new LinkedList<UndirectedNode>(); queue.add(root); root.visited = true; while (!queue.isEmpty()) { UndirectedNode curNode = queue.poll(); System.out.println(curNode.data + " "); for (...
3
public void testGet_DateTimeFieldType() { LocalDateTime test = new LocalDateTime(1970, 6, 9, 10, 20, 30, 40); assertEquals(1970, test.get(DateTimeFieldType.year())); assertEquals(6, test.get(DateTimeFieldType.monthOfYear())); assertEquals(9, test.get(DateTimeFieldType.dayOfMonth())); ...
1
@Override public void subscribeSource(ClientSenderInterface sender, ResultData initialData) throws OneSubscriptionPerSendData { DataDescription dataDescription = initialData.getDataDescription(); if((sender == null)) throw new IllegalArgumentException("Parameter 'sender' ist null"); if((dataDescription == null)...
9
public void nextPermutation(int[] num) { // error checking if (num == null || num.length <= 1) { return; } // find the rightmost i-1/ith pair s.t num[i-1]<num[i] int r = num.length, l = num.length; for (int i = num.length - 1; i >= 1; i--) { if (num[i] > num[i - 1]) { r = i; l = i - 1; bre...
9
@Override public void paintComponent(final Graphics g) { // Check if we have a running game super.paintComponent(g); g.setColor(this.getBackground()); g.fillRect(0, 0, getWidth(), getHeight()); if (this.model != null) { // Draw all tiles by going over them x-wise and y-wise. for (int i = 0; i < this....
3
protected Object buildXPath(final String query, final boolean moreNodes) { try { XPathExecutable x = xPathCompiler.compile(query); XPathSelector selector = x.load(); selector.setContextItem(this.contextItem); XdmValue value = selector.evaluate(); if (moreNodes) { String[] list...
3
public static String replaceWithUsrProps(String src,Properties props){ Pattern pattern = Pattern.compile("\\$\\{([^\\?}]+)(\\?([^}\\?]+))?\\}"); Matcher matcher=pattern.matcher(src); while(matcher.find()){ String key = matcher.group(1); String methodName = matcher.group(3...
3
private void updateImportEnablement() { boolean isEnabled = prefLoadButton.getSelection(); prefPathTable.setEnabled(isEnabled); prefFileAddButton.setEnabled(isEnabled); boolean isConfig = isEnabled; boolean isSelOne = isEnabled; boolean canMoveUp = false; boolean canMoveDown = false; if (isSelOne)...
8
public void exportAsImage() { final JDialog dlog = new JDialog(); dlog.setTitle("Select Output Image Format"); dlog.getContentPane().setLayout(new BorderLayout()); dlog.setModal(true); JPanel ctrlPanel = new JPanel(); ctrlPanel.add(new JLabel("Format:")); String ...
6
public boolean authenticate() throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader( socket.getInputStream())); String user = in.readLine(); String pass = in.readLine(); BufferedReader br = new BufferedReader(new FileReader( "C:\\Users\\aawor_000\\workspace\\TCPServer\\src\...
1
public void add(Admin admin) throws DAOPoikkeus, InvalidAdminPoikkeus{ Connection connection = avaaYhteys(); //Katsotaan, että löytyykö samalla käyttäjänimellä käyttäjä, jos löytyy, niin lähetetään virhe PreparedStatement usernameLookup; try { usernameLookup = connection.prepareStatement("select username ...
2
public String nextCDATA() throws JSONException { char c; int i; StringBuffer sb = new StringBuffer(); for(;;) { c = next(); if(end()) { throw syntaxError("Unclosed CDATA"); } sb.append(c); i = sb.length() - 3; if(i >= 0 && sb.charAt(i) == ']' && sb.charAt(i + 1) == ']' && sb.charAt(i ...
6
public void registerWidgetClass(final Class<? extends FormWidget> widget) { try { final Constructor<? extends FormWidget> c = widget .getConstructor(String.class); final FormWidget fw = c.newInstance(widget.getSimpleName()); this.addWidget(fw); } catch (final SecurityException e) { // TODO Auto-gen...
8
static void rewriteResponseHeaders(URLConnection conn, HttpServletResponse resp) { Map<String, List<String>> map = conn.getHeaderFields(); if (map != null) { for (Map.Entry<String, List<String>> header : map.entrySet()) { if (header.getKey().equals("content-length")) { continue; } if (header....
9
public static boolean password(String pass){ if(pass.matches("(\\w){8,30}")) return true; return false; }
1
private void check(final String txtToParse, final char delim, final char qualifier, final String[] expected) { final List splitLineResults = ParserUtils.splitLine(txtToParse, delim, qualifier, 10, false, false); assertEquals("Did Not Get Amount Of Elements Expected (d = " + delim + " q = " + qualifier ...
1
private boolean updateBufferedOperation(int index, Operation op ) { if(bufferedOperation.containsKey(index) ) { Operation alreadyWaitOp = bufferedOperation.get(index); if(transactions.get(alreadyWaitOp.getRWinfo().get(0)).isOlder(transactions.get(op.getRWinfo().get(0)))) { // transaction waiting for the var...
2
public Set keySet() { return this.map.keySet(); }
0
public void handleEvents(List<PrioritizableStageDriver> drivers, List<StageProcessTimingEvent> events) { if (events.isEmpty()) { return; } Map<Stage, Tuple> timings = new HashMap<Stage, Tuple>(); long total = 0; for (StageProcessTimingEvent ev : events) { ...
9
public String toStringAsciiArt(int maxLen) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < maxLen; i++) { if ((i >= start) && (i <= end)) sb.append('-'); else sb.append(' '); } return sb.toString(); }
3
public static Map<String, Object> getHasMany(Object obj) throws Exception { Map<String, Object> attrs = new HashMap<String, Object>(); for (Field field : obj.getClass().getDeclaredFields()) { Class<?> fieldType = field.getType(); String fieldName = field.getName(); Annotation[] annotations = field.getDecla...
4
public boolean isValidSudoku(char[][] board) { for (int i = 0; i < 9; i++) { boolean[] pos1 = new boolean[board.length]; boolean[] pos2 = new boolean[board.length]; for (int j = 0; j < 9; j++) { char c1 = board[i][j]; char c2 = board[j][i]; ...
9
@SuppressWarnings("unchecked") public static <T extends Number> T getNeutralMulElem(Class<T> type) { switch (type.getSimpleName()) { case "Double": return (T) (new Double(1.0)); case "Float": return (T) (new Float(1.0)); case "Byte": return (T) (new Byte((byte) 1)); case "Short": return...
6
public void testPresent6() { try { TreeNode tree = new TreeNode("root", 2); tree.branch[0] = mkChain(new String[]{ "label1", "label2" }); tree.branch[1] = mkChain(new String[]{ "label3", "label4" }); TreeNode result = contains(tree, new TreeNode("label4")); ...
7
public void stateChanged(ChangeEvent e) { if(imageMat != null){ int oldIdx = viewTabs.getSelectedIndex(); viewTabs.removeAll(); viewTabs.addTab("Output", null, outputViewPanel, null); viewTabs.addTab("Overlay", null, overlayViewPanel, null); Mat localMat = imageMat.clone(); Mat overlayMat = new Mat...
5
private static ByteBuf toByteBuf(String wiresharkCopy) { ByteBuf bb = Unpooled.buffer(); char[] charArray = wiresharkCopy.toCharArray(); for (int i = 0; i < charArray.length; i += 2) { char one = charArray[i]; char two = charArray[i + 1]; bb.writeByte(Byte.parseByte("" + one + two, 16)); } return b...
1
public String readThing() { // skip whitespace // System.out.println("PAParser: whitespace: \""); while (PDFFile.isWhiteSpace(data[loc])) { // System.out.print (new String(data, loc, 1)); loc++; } // System.out.print("\": thing: ")...
3
static void assignBands(float rnd, int[][] pal, int split, int cur) { float hue, sat; int place = (256 / split) * cur; for (int i = 0; i < 256; i += split) { if (i <= 60) { hue = (float) (i) / 420.0f; sat = (i / 60.0f) * 0.2f + 0.8f; } else if (i > 60 && i <= 120) { hue = (float) (i) / 500.0f; ...
7
private void indent(Node node, StringBuffer buf) { for (int i = 0, limit = node.getDepth(); i < limit; i++) { buf.append("\t"); } }
1