Runs pygal programs and returns image data
779511
def run_pygal(data, options=[], format='svg'):
    
    import pygal

    chart_title = data.get('title', None)
    chart_type = data.get('type', '').lower()
    # Config options are pretty much proxied straight through from the JSON dict into the object
    config = pygal.Config()
    config_dict = data.get('config', {})
    for key in config_dict.keys():
        setattr(config, key, config_dict[key])

    if chart_type == 'bar':
        chart = pygal.HorizontalBar(config) if data.get('horizontal', False) else pygal.Bar(config)
    elif chart_type == 'line':
        chart = pygal.Line(config)
    elif chart_type == 'pie':
        ir=data.get('inner_radius', 0.0)
        hp=data.get('half_pie', False)
        chart = pygal.Pie(config, inner_radius=ir, half_pie=hp)
    else:
        print('undefined or unknown chart type')

    if chart is not None:
        chart.title = data.get('title', None)
        # Do labels (if present)
        label_data = data.get('x-labels', None)
        if isinstance(label_data, list):
            # use list
            chart.x_labels = label_data
        elif isinstance(label_data, dict):
            # use a range
            range_from = label_data.get('from', 0)
            range_to = label_data.get('to', 0)
            chart.x_labels = map(str, range(range_from, range_to))
        # insert data
        for data_set in data.get('data', []):
            title = data_set.get('title', None)
            values = data_set.get('values', None)
            chart.add(title, values)
        # now render
        result = chart.render_data_uri()
    else:
        result = None
    return result
364587
def load_image_from_disk(img_spec):
    """"""

    if isinstance(img_spec, str):
        if pexists(realpath(img_spec)):
            hdr = nib.load(img_spec)
            # trying to stick to an orientation
            hdr = nib.as_closest_canonical(hdr)
            img = hdr.get_data()
        else:
            raise IOError('Given path to image does not exist!')
    elif isinstance(img_spec, np.ndarray):
        img = img_spec
    else:
        raise ValueError('Invalid input specified! '
                         'Input either a path to image data, or provide 3d Matrix directly.')

    return img
32095
def pull_stream(image):
    
    return (json.loads(s) for s in _get_docker().pull(image, stream=True))
150234
def get_images(config, name=None, quiet=False, all=True, *args, **kwargs):
    '''
    
    '''
    err = "Unknown"
    client = _get_client(config)
    try:
        infos = client.images(name=name, quiet=quiet, all=all)
        for i in range(len(infos)):
            inf = _set_id(infos[i])
            try:
                inf['Human_Size'] = _sizeof_fmt(int(inf['Size']))
            except ValueError:
                pass
            try:
                ts = int(inf['Created'])
                dts = datetime.datetime.fromtimestamp(ts)
                inf['Human_IsoCreated'] = dts.isoformat()
                inf['Human_Created'] = dts.strftime(
                    '%Y-%m-%d %H:%M:%S')
            except Exception:
                pass
            try:
                inf['Human_VirtualSize'] = (
                    _sizeof_fmt(int(inf['VirtualSize'])))
            except ValueError:
                pass
        return infos
    except Exception as e:
        err = e
    utils.error("Unable to list Docker images: %s"%err)
    return None
155439
def vgadata():
    """"""
    if os.path.isfile('/sbin/lspci'):
        lspci = '/sbin/lspci'
    else:
        lspci = '/usr/bin/lspci'
    f = os.popen (lspci + ' -m')
    pdata = {}
    for line in f.readlines():
        p = line.split("\"")
        name = p[1].strip()
        if (name == "VGA compatible controller"):
            pdata["Graphics"] = p[3] + " " + p[5]
    f.close()
    return pdata
407467
def run(args):
    

    with warnings.catch_warnings():
        warnings.simplefilter('ignore')

        query = prepareQuery(args.query_file.read())
        ds = Dataset()

        res_indices_prev = set()  # de-duplication
        res_indices = set()

        # create sub graphs
        for f in args.graphs:
            g = Graph(identifier=os.path.basename(f.name))
            g.parse(data=f.read(), format='n3')
            ds.add_graph(g)

        # create and query data graph
        for data in read_by_chunk(args.input_file, int(args.chunk_size)):
            g = Graph(identifier='data')
            g.parse(data=data, format=args.input_type)
            ds.add_graph(g)
            res = ds.query(query)

            dedup_res_graph = Graph()
            if len(res) != 0:
                for r in res:
                    tid = generate_index(r)
                    res_indices.add(tid)
                    if tid in res_indices_prev:  # duplicated
                        continue
                    dedup_res_graph.add(r)

                if len(dedup_res_graph) > 0:
                    ret = dedup_res_graph.serialize(format=args.output_type, encoding='utf-8')
                    args.output_file.write(ret)

            ds.remove_graph(g)
            res_indices_prev = res_indices
            res_indices = set()
406761
def run_type(self):
        

        METAGGA_TYPES = {"TPSS", "RTPSS", "M06L", "MBJL", "SCAN", "MS0", "MS1", "MS2"}

        if self.parameters.get("LHFCALC", False):
            rt = "HF"
        elif self.parameters.get("METAGGA", "").strip().upper() in METAGGA_TYPES:
            rt = self.parameters["METAGGA"].strip().upper()
        elif self.parameters.get("LUSE_VDW", False):
            vdw_gga = {"RE": "DF", "OR": "optPBE", "BO": "optB88",
                       "MK": "optB86b", "ML": "DF2"}
            gga = self.parameters.get("GGA").upper()
            rt = "vdW-" + vdw_gga[gga]
        elif self.potcar_symbols[0].split()[0] == 'PAW':
            rt = "LDA"
        else:
            rt = "GGA"
        if self.is_hubbard:
            rt += "+U"
        return rt
808222
def _load_data(path, labels_number=1):
  """"""
  with tf.io.gfile.GFile(path, "rb") as f:
    data = f.read()
  offset = 0
  max_offset = len(data) - 1
  while offset < max_offset:
    labels = np.frombuffer(data, dtype=np.uint8, count=labels_number,
                           offset=offset).reshape((labels_number,))
    # 1 byte per label, 1024 * 3 = 3072 bytes for the image.
    offset += labels_number
    img = (np.frombuffer(data, dtype=np.uint8, count=3072, offset=offset)
           .reshape((3, _CIFAR_IMAGE_SIZE, _CIFAR_IMAGE_SIZE))
           .transpose((1, 2, 0))
          )
    offset += 3072
    yield labels, img
137770
def main():
    """"""
    if (sys.version_info < (2, 7)):
        sys.exit("This program requires python version 2.7 or later")

    # Options and arguments
    p = optparse.OptionParser(description='IIIF Image API static file generator',
                              usage='usage: %prog [options] file [[file2..]] (-h for help)',
                              version='%prog ' + __version__)

    p.add_option('--dst', '-d', action='store', default='/tmp',
                 help="Destination directory for images [default '%default']")
    p.add_option('--tilesize', '-t', action='store', type='int', default=512,
                 help="Tilesize in pixels [default %default]")
    p.add_option('--api-version', '--api', '-a', action='store', default='2.1',
                 help="API version, may be 1.1, 2.0 or 2.1 [default %default]")
    p.add_option('--prefix', '-p', action='store', default=None,
                 help="URI prefix for where the images will be served from (default '%default'). "
                      "An empty prefix may be OK if the HTML page including the image shares the "
                      "the same root on the same server as the images, otherwise a full URL should "
                      "be specified. This is used to construct the @id in the info.json")
    p.add_option('--identifier', '-i', action='store', default=None,
                 help="Identifier for the image that will be used in place of the filename "
                      "(minus extension). Notes that this option cannot be used if more than "
                      "one image file is to be processed")
    p.add_option('--extra', '-e', action='append', default=[],
                 help="Extra request parameters to be used to generate static files, may be "
                      "repeated (e.g. '/full/90,/0/default.jpg' for a 90 wide thumnail)")
    p.add_option('--write-html', action='store', default=None,
                 help="Write HTML page to the specified directory using the 'identifier.html' "
                      "as the filename. HTML will launch OpenSeadragon for this image and to "
                      "display some of information about info.json and tile locations. HTML will "
                      "assume OpenSeadragon at relative path openseadragonVVV/openseadragon.min.js "
                      "and user-interface icons in openseadragonVVV/images, where VVV are the "
                      "three parts of the version number. The --include-osd flag is also specified "
                      "then OpenSeadragon will be copied to these locations")
    p.add_option('--include-osd', action='store_true',
                 help="Include OpenSeadragon files with --write-html flag")
    p.add_option('--osd-version', action='store', default='2.0.0',
                 help="Generate static images for older versions of OpenSeadragon. Use of versions "
                      "prior to 1.2.1 will force use of /w,h/ for size parameter instead of /w,/. "
                      "Likely useful only in combination with --api-version=1.1 "
                      "[default %default]")
    p.add_option('--osd-width', action='store', type='int', default='500',
                 help="Width of OpenSeadragon pane in pixels. Applies only with "
                      "--write-html [default %default]")
    p.add_option('--osd-height', action='store', type='int', default='500',
                 help="Height of OpenSeadragon pane in pixels. Applies only with "
                      "--write-html [default %default]")
    p.add_option('--generator', action='store_true', default=False,
                 help="Use named generator modules in iiif.generators package instead "
                      "of a starting image [default %default]")
    p.add_option('--max-image-pixels', action='store', type='int', default=0,
                 help="Set the maximum number of pixels in an image. A non-zero value "
                      "will set a hard limit on the image size. If left unset then the "
                      "default configuration of the Python Image Libary (PIL) will give "
                      "a DecompressionBombWarning if the image size exceeds a default "
                      "maximum, but otherwise continue as normal")
    p.add_option('--dryrun', '-n', action='store_true',
                 help="Do not write anything, say what would be done")
    p.add_option('--quiet', '-q', action='store_true',
                 help="Quite (no output unless there is a warning/error)")
    p.add_option('--verbose', '-v', action='store_true',
                 help="Verbose")

    (opt, sources) = p.parse_args()

    level = logging.DEBUG if (opt.verbose) else \
        logging.WARNING if (opt.quiet) else logging.INFO
    logging.basicConfig(format='%(name)s: %(message)s',
                        level=level)
    logger = logging.getLogger(os.path.basename(__file__))

    if (not opt.write_html and opt.include_osd):
        logger.warn(
            "--include-osd has no effect without --write-html, ignoring")
    if (len(sources) == 0):
        logger.warn("No sources specified, nothing to do, bye! (-h for help)")
    elif (len(sources) > 1 and opt.identifier):
        logger.error(
            "Cannot use --identifier/-i option with multiple sources, aborting.")
    else:
        try:
            sg = IIIFStatic(dst=opt.dst, tilesize=opt.tilesize,
                            api_version=opt.api_version, dryrun=opt.dryrun,
                            prefix=opt.prefix, osd_version=opt.osd_version,
                            generator=opt.generator,
                            max_image_pixels=opt.max_image_pixels,
                            extras=opt.extra)
            for source in sources:
                # File or directory (or neither)?
                if (os.path.isfile(source) or opt.generator):
                    logger.info("source file: %s" % (source))
                    sg.generate(source, identifier=opt.identifier)
                    if (opt.write_html):
                        sg.write_html(html_dir=opt.write_html, include_osd=opt.include_osd,
                                      osd_width=opt.osd_width, osd_height=opt.osd_height)
                elif (os.path.isdir(source)):
                    logger.warn(
                        "Ignoring source '%s': directory coversion not supported" % (source))
                else:
                    logger.warn(
                        "Ignoring source '%s': neither file nor path" % (source))
        except (IIIFStaticError, IIIFError) as e:
            # catch known errors and report nicely...
            logger.error("Error: " + str(e))
1187975
def main():
    """"""
    parser = argparse.ArgumentParser()
    parser.add_argument('input',
                        metavar='INPUT',
                        help='Input directory with PNG files')
    parser.add_argument('output', nargs='?',
                        metavar='OUTPUT',
                        help='Output directory')
    parser.add_argument('--apikey',
                        metavar='APIKEY',
                        default=find_apikey(),
                        help='TinyPNG API Key')

    args = parser.parse_args()
    _main(args)
243340
def run():
    
    data_items = [
        [u"mushroom", u"fungus"],
        [u"tomato", u"fruit"],
        [u"topaz", u"mineral"],
        [u"iron", u"metal"],
        [u"dróżką", u"utf-8 sample"],
        [u"apple", u"fruit"],
        [u"cheese", u"dairy"],
        [u"peach", u"fruit"],
        [u"celery", u"vegetable"],
        [u"pear", u"fruit"],
        [u"ruby", u"mineral"],
        [u"titanium", u"metal"],
        [u"cat", u"animal"],
        [u"orange", u"fruit"],
        [u"WĄŻ", u"utf-8 sample"],
    ]

    results = certain_kind_tap(data_items)

    fruits, metals = results

    print("=== fruits ===")
    for fruit in fruits:
        print(fruit)

    print("=== metals ===")
    for metal in metals:
        print(metal)
1125839
def from_images(cls, images, weights=None, filter=None, wrap=None,
		aspect_adjust_width=False, aspect_adjust_height=False):
		
		import pyglet
		atlas, textures = _atlas_from_images(images)
		texturizer = cls(
			atlas.texture.id, [tex.tex_coords for tex in textures],
			weights, filter or pyglet.gl.GL_LINEAR, wrap or pyglet.gl.GL_CLAMP,
			aspect_adjust_width, aspect_adjust_height)
		texturizer.atlas = atlas
		texturizer.textures = textures
		return texturizer
351423
def get_raw_data(self):
        
        arguments = self.request.argv[1:]
        if not arguments[0].startswith('--'):
            # first argument is the program name
            arguments = arguments[1:]
        return parse_kwargs(arguments)
818036
def run_inference_on_image(image):
  
  if not tf.gfile.Exists(image):
    tf.logging.fatal('File does not exist %s', image)
  image_data = tf.gfile.FastGFile(image, 'rb').read()

  # Creates graph from saved GraphDef.
  create_graph()

  with tf.Session() as sess:
    # Some useful tensors:
    # 'softmax:0': A tensor containing the normalized prediction across
    #   1000 labels.
    # 'pool_3:0': A tensor containing the next-to-last layer containing 2048
    #   float description of the image.
    # 'DecodeJpeg/contents:0': A tensor containing a string providing JPEG
    #   encoding of the image.
    # Runs the softmax tensor by feeding the image_data as input to the graph.
    softmax_tensor = sess.graph.get_tensor_by_name('softmax:0')
    predictions = sess.run(softmax_tensor,
                           {'DecodeJpeg/contents:0': image_data})
    predictions = np.squeeze(predictions)

    # Creates node ID --> English string lookup.
    node_lookup = NodeLookup()

    top_k = predictions.argsort()[-FLAGS.num_top_predictions:][::-1]
    for node_id in top_k:
      human_string = node_lookup.id_to_string(node_id)
      score = predictions[node_id]
      print('%s (score = %.5f)' % (human_string, score))
27904
def main():
    

    parser = argparse.ArgumentParser(description='Run SSOIS and return the available images in a particular filter.')

    parser.add_argument("--filter",
                        action="store",
                        default='r',
                        dest="filter",
                        choices=['r', 'u'],
                        help="Passband: default is r.")
    parser.add_argument("--family", '-f',
                        action="store",
                        default=None,
                        help='List of objects to query.')
    parser.add_argument("--member", '-m',
                        action="store",
                        default=None,
                        help='Member object of family to query.')

    args = parser.parse_args()

    if args.family != None and args.member == None:
        get_family_info(str(args.family), args.filter)
    elif args.family == None and args.member != None:
        get_member_info(str(args.member), args.filter)
    else:
        print "Please input either a family or single member name"
351999
def gpp(argv=None):
    """"""
    if argv is None:
        argv = sys.argv[1:]
    argv.insert(0, 'preview')
    return main(argv)
1165471
def main(_):
  """"""
  eps = FLAGS.max_epsilon / 255.0
  batch_shape = [FLAGS.batch_size, FLAGS.image_height, FLAGS.image_width, 3]

  with tf.Graph().as_default():
    x_input = tf.placeholder(tf.float32, shape=batch_shape)
    noisy_images = x_input + eps * tf.sign(tf.random_normal(batch_shape))
    x_output = tf.clip_by_value(noisy_images, 0.0, 1.0)

    with tf.Session(FLAGS.master) as sess:
      for filenames, images in load_images(FLAGS.input_dir, batch_shape):
        out_images = sess.run(x_output, feed_dict={x_input: images})
        save_images(out_images, filenames, FLAGS.output_dir)