Esempio n. 1
0
 Object unpack(ByteStream buf) {
   int bits = BEreadInt(buf);
   float v = Float.intBitsToFloat(bits);
   if (PyFloat.float_format == PyFloat.Format.UNKNOWN
       && (Float.isInfinite(v) || Float.isNaN(v))) {
     throw Py.ValueError("can't unpack IEEE 754 special value on non-IEEE platform");
   }
   return Py.newFloat(v);
 }
Esempio n. 2
0
 Object unpack(ByteStream buf) {
   long bits = (((long) BEreadInt(buf)) << 32) + (BEreadInt(buf) & 0xFFFFFFFFL);
   double v = Double.longBitsToDouble(bits);
   if (PyFloat.double_format == PyFloat.Format.UNKNOWN
       && (Double.isInfinite(v) || Double.isNaN(v))) {
     throw Py.ValueError("can't unpack IEEE 754 special value on non-IEEE platform");
   }
   return Py.newFloat(v);
 }
Esempio n. 3
0
 private PyObject checkCircularReference(PyObject obj) {
   PyObject ident = null;
   if (markers != null) {
     ident = Py.newInteger(Py.id(obj));
     if (markers.__contains__(ident)) {
       throw Py.ValueError("Circular reference detected");
     }
     markers.__setitem__(ident, obj);
   }
   return ident;
 }
Esempio n. 4
0
  /**
   * Creates an iterator that returns selected values from an iterable.
   *
   * @param startObj the index of where in the iterable to start returning values
   * @param stopObj the index of where in the iterable to stop returning values
   * @param stepObj the number of steps to take beween each call to <code>next()</code>
   */
  public static PyIterator islice(
      final PyObject iterable, PyObject startObj, PyObject stopObj, PyObject stepObj) {
    final int stop = py2int(stopObj, 0, "Stop argument must be a non-negative integer or None");
    final int start = py2int(startObj, 0, "Start argument must be a non-negative integer or None");
    final int step = py2int(stepObj, 1, "Step argument must be a non-negative integer or None");
    final boolean stopNone = stopObj instanceof PyNone;

    if (start < 0 || step < 0 || stop < 0) {
      throw Py.ValueError("Indices for islice() must be non-negative integers");
    }

    if (step == 0) {
      throw Py.ValueError("Step must be one or larger for islice()");
    }

    return new ItertoolsIterator() {
      int counter = start;

      int lastCount = 0;

      PyObject iter = iterable.__iter__();

      public PyObject __iternext__() {
        PyObject result = null;

        if (counter >= stop && !stopNone) {
          return null;
        }

        while (lastCount <= counter) {
          result = nextElement(iter);
          lastCount++;
        }
        counter += step;
        return result;
      }
    };
  }
Esempio n. 5
0
  public PyObject __call__(PyObject[] args, String[] keywords) {

    BCP bcp = (BCP) __self__;

    switch (index) {
      case 0:

        /*
         * B.bcp(table, [where=None, params=None, include=None, exclude=None, toTable=None, bindings=None])
         */
        String where = null;
        PyObject params = Py.None;
        PyArgParser parser = new PyArgParser(args, keywords);
        String table = (String) parser.arg(0, Py.None).__tojava__(String.class);

        if (table == null) {
          throw Py.ValueError(zxJDBC.getString("invalidTableName"));
        }

        // 'where' can be the second argument or a keyword
        if (parser.numArg() >= 2) {
          where = (String) parser.arg(1, Py.None).__tojava__(String.class);
        }

        if (where == null) {
          where = (String) parser.kw("where", Py.None).__tojava__(String.class);
        }

        // 'params' can be the third argument or a keyword
        if (parser.numArg() >= 3) {
          params = parser.arg(2, Py.None);
        }

        if (params == Py.None) {
          params = parser.kw("params", Py.None);
        }

        String toTable = (String) parser.kw("toTable", Py.None).__tojava__(String.class);
        PyObject include = parser.kw("include", Py.None);
        PyObject exclude = parser.kw("exclude", Py.None);
        PyObject bindings = parser.kw("bindings", Py.None);
        PyObject count = bcp.bcp(table, where, params, include, exclude, toTable, bindings);

        return count;

      default:
        throw info.unexpectedCall(3, false);
    }
  }
Esempio n. 6
0
 private static int py2int(PyObject obj, int defaultValue, String msg) {
   if (obj instanceof PyNone) {
     return defaultValue;
   } else {
     int value = defaultValue;
     try {
       value = Py.py2int(obj);
     } catch (PyException pyEx) {
       if (pyEx.match(Py.TypeError)) {
         throw Py.ValueError(msg);
       } else {
         throw pyEx;
       }
     }
     return value;
   }
 }
Esempio n. 7
0
 private PyString encode_float(PyObject obj) {
   /* Return the JSON representation of a PyFloat */
   double i = obj.asDouble();
   if (Double.isInfinite(i) || Double.isNaN(i)) {
     if (!allow_nan) {
       throw Py.ValueError("Out of range float values are not JSON compliant");
     }
     if (i == Double.POSITIVE_INFINITY) {
       return new PyString("Infinity");
     } else if (i == Double.NEGATIVE_INFINITY) {
       return new PyString("-Infinity");
     } else {
       return new PyString("NaN");
     }
   }
   /* Use a better float format here? */
   return obj.__repr__();
 }
Esempio n. 8
0
  /**
   * Method __call__
   *
   * @param arg
   * @return PyObject
   */
  public PyObject __call__(PyObject arg) {

    BCP bcp = (BCP) __self__;

    switch (index) {
      case 0:
        String table = (String) arg.__tojava__(String.class);

        if (table == null) {
          throw Py.ValueError(zxJDBC.getString("invalidTableName"));
        }

        PyObject count = bcp.bcp(table, null, Py.None, Py.None, Py.None, null, Py.None);

        return count;

      default:
        throw info.unexpectedCall(1, false);
    }
  }
Esempio n. 9
0
  /**
   * Open file and return a stream. Raise IOError upon failure. This is a port to Java of the
   * CPython _io.open (Modules/_io/_iomodule.c) following the same logic, but expressed with the
   * benefits of Java syntax.
   *
   * @param args array of arguments from Python call via Jython framework
   * @param kwds array of keywords from Python call via Jython framework
   * @return the stream object
   */
  public static PyObject open(PyObject[] args, String[] kwds) {

    // Get the arguments to variables
    ArgParser ap = new ArgParser("open", args, kwds, openKwds, 1);
    PyObject file = ap.getPyObject(0);
    String m = ap.getString(1, "r");
    int buffering = ap.getInt(2, -1);
    final String encoding = ap.getString(3, null);
    final String errors = ap.getString(4, null);
    final String newline = ap.getString(5, null);
    boolean closefd = Py.py2boolean(ap.getPyObject(6, Py.True));

    // Decode the mode string
    OpenMode mode =
        new OpenMode(m) {

          @Override
          public void validate() {
            super.validate();
            validate(encoding, errors, newline);
          }
        };

    mode.checkValid();

    /*
     * Create the Raw file stream. Let the constructor deal with the variants and argument
     * checking.
     */
    PyFileIO raw = new PyFileIO(file, mode, closefd);

    /*
     * From the Python documentation for io.open() buffering = 0 to switch buffering off (only
     * allowed in binary mode), 1 to select line buffering (only usable in text mode), and an
     * integer > 1 to indicate the size of a fixed-size buffer.
     *
     * When no buffering argument is given, the default buffering policy works as follows:
     * Binary files are buffered in fixed-size chunks; "Interactive" text files (files for which
     * isatty() returns True) use line buffering. Other text files use the policy described
     * above for binary files.
     *
     * In Java, it seems a stream never is *known* to be interactive, but we ask anyway, and
     * maybe one day we shall know.
     */
    boolean line_buffering = false;

    if (buffering == 0) {
      if (!mode.binary) {
        throw Py.ValueError("can't have unbuffered text I/O");
      }
      return raw;

    } else if (buffering == 1) {
      // The stream is to be read line-by-line.
      line_buffering = true;
      // Force default size for actual buffer
      buffering = -1;

    } else if (buffering < 0 && raw.isatty()) {
      // No buffering argument given but stream is inteeractive.
      line_buffering = true;
    }

    if (buffering < 0) {
      /*
       * We are still being asked for the default buffer size. CPython establishes the default
       * buffer size using fstat(fd), but Java appears to give no clue. A useful study of
       * buffer sizes in NIO is http://www.evanjones.ca/software/java-bytebuffers.html . This
       * leads us to the fixed choice of _DEFAULT_BUFFER_SIZE (=8KB).
       */
      buffering = _DEFAULT_BUFFER_SIZE;
    }

    /*
     * We now know just what particular class of file we are opening, and therefore what stack
     * (buffering and text encoding) we should build.
     */
    if (buffering == 0) {
      // Not buffering, return the raw file object
      return raw;

    } else {
      // We are buffering, so wrap raw into a buffered file
      PyObject bufferType = null;
      PyObject io = imp.load("io");

      if (mode.updating) {
        bufferType = io.__getattr__("BufferedRandom");
      } else if (mode.writing || mode.appending) {
        bufferType = io.__getattr__("BufferedWriter");
      } else { // = reading
        bufferType = io.__getattr__("BufferedReader");
      }

      PyInteger pyBuffering = new PyInteger(buffering);
      PyObject buffer = bufferType.__call__(raw, pyBuffering);

      if (mode.binary) {
        // If binary, return the just the buffered file
        return buffer;

      } else {
        // We are opening in text mode, so wrap buffered file in a TextIOWrapper.
        PyObject textType = io.__getattr__("TextIOWrapper");
        PyObject[] textArgs = {
          buffer,
          ap.getPyObject(3, Py.None),
          ap.getPyObject(4, Py.None),
          ap.getPyObject(5, Py.None),
          Py.newBoolean(line_buffering)
        };
        PyObject wrapper = textType.__call__(textArgs);
        wrapper.__setattr__("mode", new PyString(m));
        return wrapper;
      }
    }
  }