Create a relatively raw atari environment
482498
def env_maker(environment_id, seed, serial_id, monitor=False, allow_early_resets=False, normalize_observations=False,
              normalize_returns=False, normalize_gamma=0.99):
    
    env = gym.make(environment_id)
    env.seed(seed + serial_id)

    # Monitoring the env
    if monitor:
        logdir = logger.get_dir() and os.path.join(logger.get_dir(), str(serial_id))
    else:
        logdir = None

    env = Monitor(env, logdir, allow_early_resets=allow_early_resets)

    if normalize_observations or normalize_returns:
        env = EnvNormalize(
            env,
            normalize_observations=normalize_observations,
            normalize_returns=normalize_returns,
            gamma=normalize_gamma
        )

    return env
584886
def from_(self, win_pts):
        """"""
        # make relative to center pixel to convert from window
        # graphics space to standard X/Y coordinate space
        win_pts = np.asarray(win_pts, dtype=np.float)
        has_z = (win_pts.shape[-1] > 2)

        ctr_pt = list(self.viewer.get_center())
        if has_z:
            ctr_pt.append(0.0)

        mpy_pt = [1.0, -1.0]
        if has_z:
            mpy_pt.append(1.0)

        # off_x = win_x - ctr_x
        #       = win_x + -ctr_x
        # off_y = ctr_y - win_y
        #       = -win_y + ctr_y
        ctr_pt[0] = -ctr_pt[0]
        off_pts = np.add(np.multiply(win_pts, mpy_pt), ctr_pt)

        return off_pts
436256
def raw(self, output):
        """"""
        if isinstance(output, (list, tuple)):
            output = '\n'.join(map(str, output))
        self.outfile.write(str(output))
649568
def main():
    """"""
    WIDTH, HEIGHT = 120, 60
    TITLE = None

    with tcod.console_init_root(WIDTH, HEIGHT, TITLE, order="F",
                                renderer=tcod.RENDERER_SDL) as console:
        tcod.sys_set_fps(24)
        while True:
            tcod.console_flush()
            for event in tcod.event.wait():
                print(event)
                if event.type == "QUIT":
                    raise SystemExit()
                elif event.type == "MOUSEMOTION":
                    console.ch[:, -1] = 0
                    console.print_(0, HEIGHT - 1, str(event))
                else:
                    console.blit(console, 0, 0, 0, 1, WIDTH, HEIGHT - 2)
                    console.ch[:, -3] = 0
                    console.print_(0, HEIGHT - 3, str(event))
796898
def run():
    """"""
    import optparse

    parser = optparse.OptionParser(usage=r"%prog [<options>] [file ...]")
    parser.add_option(
        "-p", "--spread", type="float", default=3.0, help="Rainbow spread"
    )
    parser.add_option(
        "-F", "--freq", type="float", default=0.1, help="Rainbow frequency"
    )
    parser.add_option("-S", "--seed", type="int", default=0, help="Rainbow seed")
    parser.add_option(
        "-a",
        "--animate",
        action="store_true",
        default=False,
        help="Enable psychedelics",
    )
    parser.add_option(
        "-d", "--duration", type="int", default=12, help="Animation duration"
    )
    parser.add_option(
        "-s", "--speed", type="float", default=20.0, help="Animation speed"
    )
    parser.add_option(
        "-f",
        "--force",
        action="store_true",
        default=False,
        help="Force colour even when stdout is not a tty",
    )

    parser.add_option(
        "-3", action="store_const", dest="mode", const=8, help="Force 3 bit colour mode"
    )
    parser.add_option(
        "-4",
        action="store_const",
        dest="mode",
        const=16,
        help="Force 4 bit colour mode",
    )
    parser.add_option(
        "-8",
        action="store_const",
        dest="mode",
        const=256,
        help="Force 8 bit colour mode",
    )

    parser.add_option(
        "-c",
        "--charset-py2",
        default="utf-8",
        help="Manually set a charset to convert from, for python 2.7",
    )

    options, args = parser.parse_args()
    options.os = random.randint(0, 256) if options.seed == 0 else options.seed
    options.mode = options.mode or detect_mode()

    lolcat = LolCat(mode=options.mode)

    if not args:
        args = ["-"]

    for filename in args:
        if filename == "-":
            lolcat.cat(sys.stdin, options)
        else:
            try:
                with open(filename, "r") as handle:
                    lolcat.cat(handle, options)
            except IOError as error:
                sys.stderr.write(str(error) + "\n")
273507
def generate(env):
    """"""
    SCons.Tool.createStaticLibBuilder(env)

    # Set-up ms tools paths
    msvc_setup_env_once(env)

    env['AR']          = 'lib'
    env['ARFLAGS']     = SCons.Util.CLVar('/nologo')
    env['ARCOM']       = "${TEMPFILE('$AR $ARFLAGS /OUT:$TARGET $SOURCES','$ARCOMSTR')}"
    env['LIBPREFIX']   = ''
    env['LIBSUFFIX']   = '.lib'
868671
function createUniformWrapper(gl, program, uniforms, locations) {

  function makeGetter(index) {
    var proc = new Function('gl', 'prog', 'locations', 
      'return function(){return gl.getUniform(prog,locations[' + index + '])}') 
    return proc(gl, program, locations)
  }

  function makePropSetter(path, index, type) {
    switch(type) {
      case 'bool':
      case 'int':
      case 'sampler2D':
      case 'samplerCube':
        return 'gl.uniform1i(locations[' + index + '],obj' + path + ')'
      case 'float':
        return 'gl.uniform1f(locations[' + index + '],obj' + path + ')'
      default:
        var vidx = type.indexOf('vec')
        if(0 <= vidx && vidx <= 1 && type.length === 4 + vidx) {
          var d = type.charCodeAt(type.length-1) - 48
          if(d < 2 || d > 4) {
            throw new Error('gl-shader: Invalid data type')
          }
          switch(type.charAt(0)) {
            case 'b':
            case 'i':
              return 'gl.uniform' + d + 'iv(locations[' + index + '],obj' + path + ')'
            case 'v':
              return 'gl.uniform' + d + 'fv(locations[' + index + '],obj' + path + ')'
            default:
              throw new Error('gl-shader: Unrecognized data type for vector ' + name + ': ' + type)
          }
        } else if(type.indexOf('mat') === 0 && type.length === 4) {
          var d = type.charCodeAt(type.length-1) - 48
          if(d < 2 || d > 4) {
            throw new Error('gl-shader: Invalid uniform dimension type for matrix ' + name + ': ' + type)
          }
          return 'gl.uniformMatrix' + d + 'fv(locations[' + index + '],false,obj' + path + ')'
        } else {
          throw new Error('gl-shader: Unknown uniform data type for ' + name + ': ' + type)
        }
      break
    }
  }

  function enumerateIndices(prefix, type) {
    if(typeof type !== 'object') {
      return [ [prefix, type] ]
    }
    var indices = []
    for(var id in type) {
      var prop = type[id]
      var tprefix = prefix
      if(parseInt(id) + '' === id) {
        tprefix += '[' + id + ']'
      } else {
        tprefix += '.' + id
      }
      if(typeof prop === 'object') {
        indices.push.apply(indices, enumerateIndices(tprefix, prop))
      } else {
        indices.push([tprefix, prop])
      }
    }
    return indices
  }

  function makeSetter(type) {
    var code = [ 'return function updateProperty(obj){' ]
    var indices = enumerateIndices('', type)
    for(var i=0; i<indices.length; ++i) {
      var item = indices[i]
      var path = item[0]
      var idx  = item[1]
      if(locations[idx]) {
        code.push(makePropSetter(path, idx, uniforms[idx].type))
      }
    }
    code.push('return obj}')
    var proc = new Function('gl', 'prog', 'locations', code.join('\n'))
    return proc(gl, program, locations)
  }

  function defaultValue(type) {
    switch(type) {
      case 'bool':
        return false
      case 'int':
      case 'sampler2D':
      case 'samplerCube':
        return 0
      case 'float':
        return 0.0
      default:
        var vidx = type.indexOf('vec')
        if(0 <= vidx && vidx <= 1 && type.length === 4 + vidx) {
          var d = type.charCodeAt(type.length-1) - 48
          if(d < 2 || d > 4) {
            throw new Error('gl-shader: Invalid data type')
          }
          if(type.charAt(0) === 'b') {
            return dup(d, false)
          }
          return dup(d)
        } else if(type.indexOf('mat') === 0 && type.length === 4) {
          var d = type.charCodeAt(type.length-1) - 48
          if(d < 2 || d > 4) {
            throw new Error('gl-shader: Invalid uniform dimension type for matrix ' + name + ': ' + type)
          }
          return dup([d,d])
        } else {
          throw new Error('gl-shader: Unknown uniform data type for ' + name + ': ' + type)
        }
      break
    }
  }

  function storeProperty(obj, prop, type) {
    if(typeof type === 'object') {
      var child = processObject(type)
      Object.defineProperty(obj, prop, {
        get: identity(child),
        set: makeSetter(type),
        enumerable: true,
        configurable: false
      })
    } else {
      if(locations[type]) {
        Object.defineProperty(obj, prop, {
          get: makeGetter(type),
          set: makeSetter(type),
          enumerable: true,
          configurable: false
        })
      } else {
        obj[prop] = defaultValue(uniforms[type].type)
      }
    }
  }

  function processObject(obj) {
    var result
    if(Array.isArray(obj)) {
      result = new Array(obj.length)
      for(var i=0; i<obj.length; ++i) {
        storeProperty(result, i, obj[i])
      }
    } else {
      result = {}
      for(var id in obj) {
        storeProperty(result, id, obj[id])
      }
    }
    return result
  }

  //Return data
  var coallesced = coallesceUniforms(uniforms, true)
  return {
    get: identity(processObject(coallesced)),
    set: makeSetter(coallesced),
    enumerable: true,
    configurable: true
  }
}
1243084
def animate_2Dscatter(x, y, NumAnimatedPoints=50, NTrailPoints=20, 
    xlabel="", ylabel="",
    xlims=None, ylims=None, filename="testAnim.mp4", 
    bitrate=1e5, dpi=5e2, fps=30, figsize = [6, 6]):
    
    fig, ax = _plt.subplots(figsize = figsize)

    alphas = _np.linspace(0.1, 1, NTrailPoints)
    rgba_colors = _np.zeros((NTrailPoints,4))
    # for red the first column needs to be one
    rgba_colors[:,0] = 1.0
    # the fourth column needs to be your alphas
    rgba_colors[:, 3] = alphas


    scatter = ax.scatter(x[0:NTrailPoints], y[0:NTrailPoints], color=rgba_colors)

    if xlims == None:
        xlims = (min(x), max(x))
    if ylims == None:
        ylims = (min(y), max(y))

    ax.set_xlim(xlims)
    ax.set_ylim(ylims)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)

    def animate(i, scatter):
        scatter.axes.clear() # clear old scatter object
        scatter = ax.scatter(x[i:i+NTrailPoints], y[i:i+NTrailPoints], color=rgba_colors, animated=True) 
        # create new scatter with updated data
        ax.set_xlim(xlims)
        ax.set_ylim(ylims)
        ax.set_xlabel(xlabel)
        ax.set_ylabel(ylabel)
        return scatter,


    ani = _animation.FuncAnimation(fig, animate, _np.arange(1, NumAnimatedPoints),
                                  interval=25, blit=True, fargs=[scatter])
    ani.save(filename, bitrate=bitrate, dpi=dpi, fps=fps)
    return None
479791
def create_rectangle(proto_bits, pulse_len=100):
        
        ones = np.ones(pulse_len, dtype=np.float32) * 1
        zeros = np.ones(pulse_len, dtype=np.float32) * -1
        n = 0
        y = []
        for msg in proto_bits:
            for bit in msg:
                n += pulse_len
                if bit == "0":
                    y.extend(zeros)
                else:
                    y.extend(ones)
        x = np.arange(0, n).astype(np.int64)
        scene = ZoomableScene()
        scene.setSceneRect(0, -1, n, 2)
        scene.setBackgroundBrush(constants.BGCOLOR)
        scene.addLine(0, 0, n, 0, QPen(constants.AXISCOLOR, 0))
        if len(y) > 0:
            y = np.array(y)
        else:
            y = np.array(y).astype(np.float32)
        path = path_creator.array_to_QPath(x, y)
        scene.addPath(path, QPen(constants.LINECOLOR, 0))
        return scene, n
107637
def make_tb2rad_lut(self, filepath, normalized=True):
        """"""
        tb_ = np.arange(TB_MIN, TB_MAX, self.tb_resolution)
        retv = self.tb2radiance(tb_, normalized=normalized)
        rad = retv['radiance']
        np.savez(filepath, tb=tb_, radiance=rad)
290275
def extract_ar (archive, compression, cmd, verbosity, interactive, outdir):
    """"""
    opts = 'x'
    if verbosity > 1:
        opts += 'v'
    cmdlist = [cmd, opts, os.path.abspath(archive)]
    return (cmdlist, {'cwd': outdir})
667336
def _rgbtomask(self, obj):
        """"""
        dat = obj.get_image().get_data()  # RGB arrays
        return dat.sum(axis=2).astype(np.bool)
105637
function(env, op, other) {
        var result = [],
            rgb2;

        if (other instanceof tree.Color) {
            rgb2 = chroma(other.toString()).rgb();
        }
        else if (_.isArray(other)) {
            rgb2 = _.slice(other, 0, Math.max(other.length, 3));
        }
        else if (_.isObject(other)) {
            if (_.has(other, 'value')) {
                rgb2 = [other.value, other.value, other.value];
            }
            else {
                return;
            }
        }
        else {
            rgb2 = [other, other, other];
        }

        var rgb1 = chroma(this.toString()).rgb();

        for (var c = 0; c < 3; c++) {
            result[c] = tree.operate(op, rgb1[c] , rgb2[c]);
        }

        if (this.perceptual) {
            var normalize = function (x) {
                return x / 255;
            };
            result = hsluv.rgbToHsluv(_.map(result, normalize));
            result[1] = result[1] / 100;
            result[2] = result[2] / 100;
        }
        else {
            result = chroma(result).hsl();
        }

        return new tree.Color(result, this.alpha, this.perceptual);
    }
861738
def _from_p(self, mode):
        

        self._check_modes(("P", "PA"))

        if self.mode.endswith("A"):
            alpha = self.channels[-1]
        else:
            alpha = None

        chans = []
        cdfs = []

        color_chan = self.channels[0]

        for i in range(len(self.palette[0])):
            cdfs.append(np.zeros(len(self.palette)))
            for j in range(len(self.palette)):
                cdfs[i][j] = self.palette[j][i]
            new_chn = np.ma.array(np.interp(color_chan,
                                            np.arange(len(self.palette)),
                                            cdfs[i]),
                                  mask=color_chan.mask)
            chans.append(new_chn)

        if self.fill_value is not None:
            if alpha is not None:
                fill_alpha = self.fill_value[-1]
                self.fill_value = list(self.palette[int(self.fill_value[0])])
                self.fill_value += [fill_alpha]
            else:
                self.fill_value = list(self.palette[int(self.fill_value[0])])

        self.mode = self._secondary_mode
        self.channels = chans
        if alpha is not None:
            self.channels.append(alpha)
            self.mode = self.mode + "A"

        self.convert(mode)
198328
def save_raw(self):
        
        length = ctypes.c_ulong()
        cptr = ctypes.POINTER(ctypes.c_char)()
        _check_call(_LIB.XGBoosterGetModelRaw(self.handle,
                                              ctypes.byref(length),
                                              ctypes.byref(cptr)))
        return ctypes2buffer(cptr, length.value)
206493
def render_image(self, rgbobj, dst_x, dst_y):
        
        self.logger.debug("redraw surface")
        if self.surface is None:
            return

        # Prepare array for Cairo rendering
        # TODO: is there some high-bit depth option for Cairo?
        arr = rgbobj.get_array(self.rgb_order, dtype=np.uint8)

        daht, dawd, depth = arr.shape
        self.logger.debug("arr shape is %dx%dx%d" % (dawd, daht, depth))

        cr = cairo.Context(self.surface)
        # TODO: is it really necessary to hang on to this context?
        self.cr = cr

        # fill surface with background color
        imgwin_wd, imgwin_ht = self.viewer.get_window_size()
        cr.rectangle(0, 0, imgwin_wd, imgwin_ht)
        r, g, b = self.viewer.get_bg()
        cr.set_source_rgba(r, g, b)
        cr.fill()

        stride = cairo.ImageSurface.format_stride_for_width(cairo.FORMAT_ARGB32,
                                                            dawd)
        img_surface = cairo.ImageSurface.create_for_data(arr,
                                                         cairo.FORMAT_ARGB32,
                                                         dawd, daht, stride)

        cr.set_source_surface(img_surface, dst_x, dst_y)
        cr.set_operator(cairo.OPERATOR_SOURCE)

        cr.mask_surface(img_surface, dst_x, dst_y)
        cr.fill()
1169349
def frame_from_raw(raw):
    """"""
    command, payload = extract_from_frame(raw)
    frame = create_frame(command)
    if frame is None:
        PYVLXLOG.warning("Command %s not implemented, raw: %s", command, ":".join("{:02x}".format(c) for c in raw))
        return None
    frame.validate_payload_len(payload)
    frame.from_payload(payload)
    return frame