@ExposedNew public static PyObject float_new( PyNewWrapper new_, boolean init, PyType subtype, PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("float", args, keywords, new String[] {"x"}, 0); PyObject x = ap.getPyObject(0, null); if (x == null) { if (new_.for_type == subtype) { return new PyFloat(0.0); } else { return new PyFloatDerived(subtype, 0.0); } } else { PyFloat floatObject = null; try { floatObject = x.__float__(); } catch (PyException e) { if (e.match(Py.AttributeError)) { // Translate AttributeError to TypeError // XXX: We are using the same message as CPython, even if // it is not strictly correct (instances of types // that implement the __float__ method are also // valid arguments) throw Py.TypeError("float() argument must be a string or a number"); } throw e; } if (new_.for_type == subtype) { return floatObject; } else { return new PyFloatDerived(subtype, floatObject.getValue()); } } }
public void dispatch(String[] args, FTPSession ftp) { CommandLine line = ArgParser.parse(args); if (args.length <= 0 || line == null || line.hasOption('h') || line.hasOption("help")) { // determine whether or not to print usage/help HelpFormatter help = new HelpFormatter(); help.printHelp("FTPClient", ArgParser.options()); } else { // otherwise handle all other options if (line.hasOption('C') || line.hasOption("connect")) { // handle server connection option commands.connect(ftp, line.getOptionValue('C')); } if (line.hasOption("l") || line.hasOption("list")) { if (line.hasOption("L") || line.hasOption("local")) { // handle option to list local files commands.listLocalWorkingDir(ftp); } else { // handle option to list remote files commands.listRemoteWorkingDir(ftp); } } if (line.hasOption('g') || line.hasOption("get")) { // handle getting a file on remote commands.getRemoteFile(ftp, line.getOptionValue('g')); } if (line.hasOption('p') || line.hasOption("put")) { // handle putting a file on remote commands.putRemoteFile(ftp, line.getOptionValues('p')); } if (line.hasOption('i') || line.hasOption("dir")) { // create directory on the ftp server commands.createRemoteDirectory(ftp, line.getOptionValue('i')); } if (line.hasOption('m') || line.hasOption("modify")) { // modify remote file permissions commands.changeRemotePermissions(ftp, line.getOptionValues('m')); } if (line.hasOption('d') || line.hasOption("delete")) { if (line.hasOption('R') || line.hasOption("recursive")) { // TODO: handle delete remote directory } else { // delete file on remote server commands.deleteRemoteFile(ftp, line.getOptionValue('d')); } } commands.exit(ftp); } }
/** * Sort the items of the list in place. Items is compared with the normal relative comparison * operators. */ @ExposedMethod(doc = BuiltinDocs.list_sort_doc) final synchronized void list_sort(PyObject[] args, String[] kwds) { ArgParser ap = new ArgParser("list", args, kwds, new String[] {"cmp", "key", "reverse"}, 0); PyObject cmp = ap.getPyObject(0, Py.None); PyObject key = ap.getPyObject(1, Py.None); PyObject reverse = ap.getPyObject(2, Py.False); sort(cmp, key, reverse); }
final void file_init(PyObject[] args, String[] kwds) { ArgParser ap = new ArgParser("file", args, kwds, new String[] {"name", "mode", "bufsize"}, 1); String nameArg = ap.getString(0, null); String modeArg = ap.getString(1, "r"); int buffArg = ap.getInt(2, 0); file_init(_setup(nameArg, modeArg, buffArg), nameArg, modeArg); }
public static void UnicodeTranslateError__init__( PyObject self, PyObject[] args, String[] kwargs) { PyBaseException.TYPE.invoke("__init__", self, args, kwargs); ArgParser ap = new ArgParser( "__init__", args, kwargs, new String[] {"object", "start", "end", "reason"}, 4); self.__setattr__("object", ap.getPyObjectByType(0, PyUnicode.TYPE)); self.__setattr__("start", ap.getPyObjectByType(1, PyInteger.TYPE)); self.__setattr__("end", ap.getPyObjectByType(2, PyInteger.TYPE)); self.__setattr__("reason", ap.getPyObjectByType(3, PyString.TYPE)); }
@ExposedNew @ExposedMethod(doc = BuiltinDocs.list___init___doc) final void list___init__(PyObject[] args, String[] kwds) { ArgParser ap = new ArgParser("list", args, kwds, new String[] {"sequence"}, 0); PyObject seq = ap.getPyObject(0, null); clear(); if (seq == null) { return; } if (seq instanceof PyList) { list.addAll(((PyList) seq).list); // don't convert } else if (seq instanceof PyTuple) { list.addAll(((PyTuple) seq).getList()); } else { for (PyObject item : seq.asIterable()) { append(item); } } }
private double doFunction(int beg, int end) { int argbeg; for (argbeg = beg; argbeg <= end && expression.charAt(argbeg) != '('; argbeg++) {; } String fncnam = expression.substring(beg, argbeg).trim(); ArgParser fncargs = new ArgParser(argbeg, end); FunctionHandler fnchdl = null; try { if ((fnchdl = pureFunctions.get(fncnam)) != null) { return fnchdl.evaluateFunction(fncnam, fncargs); } else if ((fnchdl = impureFunctions.get(fncnam)) != null) { isConstant = false; // impure functions cannot be guaranteed to be constant return fnchdl.evaluateFunction(fncnam, fncargs); } fncargs = null; // suppress check for too many fncargs } catch (ArithmeticException thr) { fncargs = null; throw thr; } catch (NoSuchMethodError thr) { fncargs = null; throw exception(beg, "Function not supported in this JVM: \"" + fncnam + "\""); } catch (UnsupportedOperationException thr) { fncargs = null; throw exception(beg, thr.getMessage()); } catch (Throwable thr) { fncargs = null; throw exception(beg, "Unexpected exception parsing function arguments", thr); } finally { if (fncargs != null) { if (fncargs.hasNext()) { throw exception(fncargs.getIndex(), "Function has too many arguments"); } offset = fncargs.getIndex(); } } throw exception(beg, "Function \"" + fncnam + "\" not recognized"); }
public static void UnicodeError__init__( PyObject self, PyObject[] args, String[] kwargs, PyType objectType) { ArgParser ap = new ArgParser( "__init__", args, kwargs, new String[] {"encoding", "object", "start", "end", "reason"}, 5); self.__setattr__("encoding", ap.getPyObjectByType(0, PyString.TYPE)); self.__setattr__("object", ap.getPyObjectByType(1, objectType)); self.__setattr__("start", ap.getPyObjectByType(2, PyInteger.TYPE)); self.__setattr__("end", ap.getPyObjectByType(3, PyInteger.TYPE)); self.__setattr__("reason", ap.getPyObjectByType(4, PyString.TYPE)); }
@ExposedNew static final PyObject function___new__( PyNewWrapper new_, boolean init, PyType subtype, PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser( "function", args, keywords, new String[] {"code", "globals", "name", "argdefs", "closure"}, 0); PyObject code = ap.getPyObject(0); PyObject globals = ap.getPyObject(1); PyObject name = ap.getPyObject(2, Py.None); PyObject defaults = ap.getPyObject(3, Py.None); PyObject closure = ap.getPyObject(4, Py.None); if (!(code instanceof PyBaseCode)) { throw Py.TypeError("function() argument 1 must be code, not " + code.getType().fastGetName()); } if (name != Py.None && !Py.isInstance(name, PyString.TYPE)) { throw Py.TypeError("arg 3 (name) must be None or string"); } if (defaults != Py.None && !(defaults instanceof PyTuple)) { throw Py.TypeError("arg 4 (defaults) must be None or tuple"); } PyBaseCode tcode = (PyBaseCode) code; int nfree = tcode.co_freevars == null ? 0 : tcode.co_freevars.length; if (!(closure instanceof PyTuple)) { if (nfree > 0 && closure == Py.None) { throw Py.TypeError("arg 5 (closure) must be tuple"); } else if (closure != Py.None) { throw Py.TypeError("arg 5 (closure) must be None or tuple"); } } int nclosure = closure == Py.None ? 0 : closure.__len__(); if (nfree != nclosure) { throw Py.ValueError( String.format( "%s requires closure of length %d, not %d", tcode.co_name, nfree, nclosure)); } if (nclosure > 0) { for (PyObject o : ((PyTuple) closure).asIterable()) { if (!(o instanceof PyCell)) { throw Py.TypeError( String.format("arg 5 (closure) expected cell, found %s", o.getType().fastGetName())); } } } PyFunction function = new PyFunction( globals, defaults == Py.None ? null : ((PyTuple) defaults).getArray(), tcode, null, closure == Py.None ? null : ((PyTuple) closure).getArray()); if (name != Py.None) { function.__name__ = name.toString(); } return function; }
public void run(String[] args) throws Exception { // args = new String[]{"-L", "baseline", "-A", "data/iris.arff", "-E", "cross", "10", "-N"}; // Random rand = new Random(1234); // Use a seed for deterministic results (makes debugging // easier) Random rand = new Random(); // No seed for non-deterministic results // Parse the command line arguments ArgParser parser = new ArgParser(args); String fileName = parser.getARFF(); // File specified by the user String learnerName = parser.getLearner(); // Learning algorithm specified by the user String evalMethod = parser.getEvaluation(); // Evaluation method specified by the user String evalParameter = parser.getEvalParameter(); // Evaluation parameters specified by the user boolean printConfusionMatrix = parser.getVerbose(); boolean normalize = parser.getNormalize(); // Load the model SupervisedLearner learner = getLearner(learnerName, rand); // Load the ARFF file Matrix data = new Matrix(); data.loadArff(fileName); double[] max = new double[data.cols()]; double[] min = new double[data.cols()]; for (int col = 0; col < max.length; col++) { max[col] = data.columnMax(col); min[col] = data.columnMin(col); } if (normalize) { System.out.println("Using normalized data\n"); data.normalize(); } // Print some stats System.out.println(); System.out.println("Dataset name: " + fileName); System.out.println("Number of instances: " + data.rows()); System.out.println("Number of attributes: " + data.cols()); System.out.println("Learning algorithm: " + learnerName); System.out.println("Evaluation method: " + evalMethod); System.out.println(); if (evalMethod.equals("training")) { System.out.println("Calculating accuracy on training set..."); System.out.println("# cols: " + data.cols()); Matrix features = new Matrix(data, 0, 0, data.rows(), data.cols() - 1); Matrix labels = new Matrix(data, 0, data.cols() - 1, data.rows(), 1); Matrix confusion = new Matrix(); double startTime = System.currentTimeMillis(); learner.train(features, labels); double elapsedTime = System.currentTimeMillis() - startTime; System.out.println("Time to train (in seconds): " + elapsedTime / 1000.0); double accuracy = learner.measureAccuracy(features, labels, confusion); System.out.println("Training set accuracy: " + accuracy); if (printConfusionMatrix) { System.out.println("\nConfusion matrix: (Row=target value, Col=predicted value)"); confusion.print(); System.out.println("\n"); } } else if (evalMethod.equals("static")) { Matrix testData = new Matrix(); testData.loadArff(evalParameter); if (normalize) testData .normalize(); // BUG! This may normalize differently from the training data. It should // use the same ranges for normalization! System.out.println("Calculating accuracy on separate test set..."); System.out.println("Test set name: " + evalParameter); System.out.println("Number of test instances: " + testData.rows()); Matrix features = new Matrix(data, 0, 0, data.rows(), data.cols() - 1); Matrix labels = new Matrix(data, 0, data.cols() - 1, data.rows(), 1); double startTime = System.currentTimeMillis(); learner.train(features, labels); double elapsedTime = System.currentTimeMillis() - startTime; System.out.println("Time to train (in seconds): " + elapsedTime / 1000.0); double trainAccuracy = learner.measureAccuracy(features, labels, null); System.out.println("Training set accuracy: " + trainAccuracy); Matrix testFeatures = new Matrix(testData, 0, 0, testData.rows(), testData.cols() - 1); Matrix testLabels = new Matrix(testData, 0, testData.cols() - 1, testData.rows(), 1); Matrix confusion = new Matrix(); double testAccuracy = learner.measureAccuracy(testFeatures, testLabels, confusion); System.out.println("Test set accuracy: " + testAccuracy); if (printConfusionMatrix) { System.out.println("\nConfusion matrix: (Row=target value, Col=predicted value)"); confusion.print(); System.out.println("\n"); } } else if (evalMethod.equals("random")) { System.out.println("Calculating accuracy on a random hold-out set..."); double trainPercent = 1 - Double.parseDouble(evalParameter); if (trainPercent < 0 || trainPercent > 1) throw new Exception("Percentage for random evaluation must be between 0 and 1"); System.out.println("Percentage used for training: " + trainPercent); System.out.println("Percentage used for testing: " + Double.parseDouble(evalParameter)); data.shuffle(rand); int trainSize = (int) (trainPercent * data.rows()); Matrix trainFeatures = new Matrix(data, 0, 0, trainSize, data.cols() - 1); Matrix trainLabels = new Matrix(data, 0, data.cols() - 1, trainSize, 1); Matrix testFeatures = new Matrix(data, trainSize, 0, data.rows() - trainSize, data.cols() - 1); Matrix testLabels = new Matrix(data, trainSize, data.cols() - 1, data.rows() - trainSize, 1); double startTime = System.currentTimeMillis(); learner.train(trainFeatures, trainLabels); double elapsedTime = System.currentTimeMillis() - startTime; System.out.println("Time to train (in seconds): " + elapsedTime / 1000.0); double trainAccuracy = learner.measureAccuracy(trainFeatures, trainLabels, null); System.out.println("Training set accuracy: " + trainAccuracy); Matrix confusion = new Matrix(); double testAccuracy = learner.measureAccuracy(testFeatures, testLabels, confusion); System.out.println("Test set accuracy: " + testAccuracy); if (printConfusionMatrix) { System.out.println("\nConfusion matrix: (Row=target value, Col=predicted value)"); confusion.print(); System.out.println("\n"); } } else if (evalMethod.equals("cross")) { System.out.println("Calculating accuracy using cross-validation..."); int folds = Integer.parseInt(evalParameter); if (folds <= 0) throw new Exception("Number of folds must be greater than 0"); System.out.println("Number of folds: " + folds); int reps = 1; double sumAccuracy = 0.0; double elapsedTime = 0.0; for (int j = 0; j < reps; j++) { data.shuffle(rand); for (int i = 0; i < folds; i++) { int begin = i * data.rows() / folds; int end = (i + 1) * data.rows() / folds; Matrix trainFeatures = new Matrix(data, 0, 0, begin, data.cols() - 1); Matrix trainLabels = new Matrix(data, 0, data.cols() - 1, begin, 1); Matrix testFeatures = new Matrix(data, begin, 0, end - begin, data.cols() - 1); Matrix testLabels = new Matrix(data, begin, data.cols() - 1, end - begin, 1); trainFeatures.add(data, end, 0, data.rows() - end); trainLabels.add(data, end, data.cols() - 1, data.rows() - end); double startTime = System.currentTimeMillis(); learner.train(trainFeatures, trainLabels); elapsedTime += System.currentTimeMillis() - startTime; double accuracy = learner.measureAccuracy(testFeatures, testLabels, null); sumAccuracy += accuracy; System.out.println("Rep=" + j + ", Fold=" + i + ", Accuracy=" + accuracy); } } elapsedTime /= (reps * folds); System.out.println("Average time to train (in seconds): " + elapsedTime / 1000.0); System.out.println("Mean accuracy=" + (sumAccuracy / (reps * folds))); } }
@ExposedNew public static PyObject complex_new( PyNewWrapper new_, boolean init, PyType subtype, PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("complex", args, keywords, "real", "imag"); PyObject real = ap.getPyObject(0, Py.Zero); PyObject imag = ap.getPyObject(1, null); // Special-case for single argument that is already complex if (real.getType() == TYPE && new_.for_type == subtype && imag == null) { return real; } if (real instanceof PyString) { if (imag != null) { throw Py.TypeError("complex() can't take second arg if first is a string"); } return real.__complex__(); } if (imag != null && imag instanceof PyString) { throw Py.TypeError("complex() second arg can't be a string"); } try { real = real.__complex__(); } catch (PyException pye) { if (!Py.matchException(pye, Py.AttributeError)) { // __complex__ not supported throw pye; } // otherwise try other means } PyComplex complexReal; PyComplex complexImag; PyFloat toFloat = null; if (real instanceof PyComplex) { complexReal = (PyComplex) real; } else { try { toFloat = real.__float__(); } catch (PyException pye) { if (Py.matchException(pye, Py.AttributeError)) { // __float__ not supported throw Py.TypeError("complex() argument must be a string or a number"); } throw pye; } complexReal = new PyComplex(toFloat.getValue()); } if (imag == null) { complexImag = new PyComplex(0.0); } else if (imag instanceof PyComplex) { complexImag = (PyComplex) imag; } else { toFloat = null; try { toFloat = imag.__float__(); } catch (PyException pye) { if (Py.matchException(pye, Py.AttributeError)) { // __float__ not supported throw Py.TypeError("complex() argument must be a string or a number"); } throw pye; } complexImag = new PyComplex(toFloat.getValue()); } complexReal.real -= complexImag.imag; complexReal.imag += complexImag.real; if (new_.for_type != subtype) { complexReal = new PyComplexDerived(subtype, complexReal.real, complexReal.imag); } return complexReal; }
/** * Starts the program * * @param args the standard arguments. If "competition" is one of them, then the SmartDashboard * will be in competition mode * @see main#inCompetition() inCompetition() */ public static void main(final String[] args) { // Present a loading bar (it will only show up if this is going slowly) final ProgressMonitor monitor = new ProgressMonitor( null, "Loading SmartDashboard", "Initializing internal code...", 0, 1000); // Search the filesystem for extensions (49%) FileSniffer.findExtensions(monitor, 0, 490); ArgParser argParser = new ArgParser(args, true, true, new String[] {"ip"}); inCompetition = argParser.hasFlag("competition"); boolean customIP = false; if (argParser.hasValue("ip")) { Robot.setHost(argParser.getValue("ip")); customIP = true; } final boolean useTeamNumber = !customIP; try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { try { monitor.setProgress(500); monitor.setNote("Setting Theme"); try { for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { UIManager.setLookAndFeel(info.getClassName()); } } } catch (Exception e) { } // Initialize GUI DashboardFrame frame = new DashboardFrame(inCompetition); monitor.setProgress(600); monitor.setNote("Getting Team Number"); IntegerProperty team = frame.getPrefs().team; while (team.getValue() <= 0) { team.setValue(JOptionPane.showInputDialog("Input Team Number")); } if (useTeamNumber) { Robot.setTeam(frame.getPrefs().team.getValue()); } frame.pack(); frame.setVisible(true); monitor.setProgress(750); monitor.setNote("Loading From Save"); // Load File file = new File(frame.getPrefs().saveFile.getValue()); if (file.exists()) { frame.load(file.getPath()); } monitor.setProgress(1000); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }); } catch (Exception ex) { ex.printStackTrace(); System.exit(2); } }
// To add/remove functions change evaluateOperator() and registration public double evaluateFunction(String fncnam, ArgParser fncargs) throws ArithmeticException { switch (Character.toLowerCase(fncnam.charAt(0))) { case 'a': { if (fncnam.equalsIgnoreCase("abs")) { return Math.abs(fncargs.next()); } if (fncnam.equalsIgnoreCase("acos")) { return Math.acos(fncargs.next()); } if (fncnam.equalsIgnoreCase("asin")) { return Math.asin(fncargs.next()); } if (fncnam.equalsIgnoreCase("atan")) { return Math.atan(fncargs.next()); } } break; case 'c': { if (fncnam.equalsIgnoreCase("cbrt")) { return Math.cbrt(fncargs.next()); } if (fncnam.equalsIgnoreCase("ceil")) { return Math.ceil(fncargs.next()); } if (fncnam.equalsIgnoreCase("cos")) { return Math.cos(fncargs.next()); } if (fncnam.equalsIgnoreCase("cosh")) { return Math.cosh(fncargs.next()); } } break; case 'e': { if (fncnam.equalsIgnoreCase("exp")) { return Math.exp(fncargs.next()); } if (fncnam.equalsIgnoreCase("expm1")) { return Math.expm1(fncargs.next()); } } break; case 'f': { if (fncnam.equalsIgnoreCase("floor")) { return Math.floor(fncargs.next()); } } break; case 'g': { // if(fncnam.equalsIgnoreCase("getExponent" )) { return // Math.getExponent(fncargs.next()); } needs Java 6 } break; case 'l': { if (fncnam.equalsIgnoreCase("log")) { return Math.log(fncargs.next()); } if (fncnam.equalsIgnoreCase("log10")) { return Math.log10(fncargs.next()); } if (fncnam.equalsIgnoreCase("log1p")) { return Math.log1p(fncargs.next()); } } break; case 'm': { if (fncnam.equalsIgnoreCase("max")) { return Math.max(fncargs.next(), fncargs.next()); } if (fncnam.equalsIgnoreCase("min")) { return Math.min(fncargs.next(), fncargs.next()); } } break; case 'n': { // if(fncnam.equalsIgnoreCase("nextUp" )) { return Math.nextUp // (fncargs.next()); } needs Java 6 } break; case 'r': { if (fncnam.equalsIgnoreCase("random")) { return Math.random(); } // impure if (fncnam.equalsIgnoreCase("round")) { return Math.round(fncargs.next()); } if (fncnam.equalsIgnoreCase("roundHE")) { return Math.rint(fncargs.next()); } // round half-even } break; case 's': { if (fncnam.equalsIgnoreCase("signum")) { return Math.signum(fncargs.next()); } if (fncnam.equalsIgnoreCase("sin")) { return Math.sin(fncargs.next()); } if (fncnam.equalsIgnoreCase("sinh")) { return Math.sinh(fncargs.next()); } if (fncnam.equalsIgnoreCase("sqrt")) { return Math.sqrt(fncargs.next()); } } break; case 't': { if (fncnam.equalsIgnoreCase("tan")) { return Math.tan(fncargs.next()); } if (fncnam.equalsIgnoreCase("tanh")) { return Math.tanh(fncargs.next()); } if (fncnam.equalsIgnoreCase("toDegrees")) { return Math.toDegrees(fncargs.next()); } if (fncnam.equalsIgnoreCase("toRadians")) { return Math.toRadians(fncargs.next()); } } break; case 'u': { if (fncnam.equalsIgnoreCase("ulp")) { return Math.ulp(fncargs.next()); } } break; // no default } throw new UnsupportedOperationException( "MathEval internal function setup is incorrect - internal function \"" + fncnam + "\" not handled"); }