Generage API documentation
550001
def run_apidoc(_):
    """"""
    import better_apidoc
    better_apidoc.main([
        'better-apidoc',
        '-t',
        os.path.join('.', '_templates'),
        '--force',
        '--no-toc',
        '--separate',
        '-o',
        os.path.join('.', 'API'),
        os.path.join('..', 'src', 'qnet'),
    ])
1105753
function doc(pkgName, pkgVersion) {
    const typedoc = require("typedoc");
    const typescriptOptions = require(path.resolve("./build/tsconfig.es5-commonjs.json")).compilerOptions;
    const typedocOptions = require(path.resolve("./build/typedoc.js"));

    // Add version number to header of generated HTML documentation
    typedocOptions.name = pkgName + " v" + pkgVersion;

    const app = new typedoc.Application(Object.assign(typedocOptions, typescriptOptions));

    // A path to source files can only be specified on the command line, 
    // in the API we have to specify individual source files.
    // Note that the "exclude" option pattern is also not considered in API code.
    const srcFiles = [];
    getTypedocModuleSources(path.resolve(typedocOptions.src), srcFiles);
    getTypedocModuleSources(path.resolve(typedocOptions.src, "db/adapters/"), srcFiles);

    rimraf.sync(path.resolve("./" + typedocOptions.out));

    logInfo("Generate HTML documentation from source code...");
    const success = app.generateDocs(srcFiles, typedocOptions.out);
    if (!success) {
        logError("Failed to generate HTML documentation");
    }

    function getTypedocModuleSources(srcPath, srcFiles) {
        fse.readdirSync(srcPath).forEach((file, index) => {
            let filePath = path.join(srcPath, file);
            if (!fse.lstatSync(filePath).isDirectory()) {
                if (path.extname(filePath) === ".ts") {
                    srcFiles.push(filePath);
                }
            }
        });
    }
}
343688
function genTaskOptions(env) {
	var mp = env.pluginName + ': ';
	return {
		name : '<%= commit.versionTag %>',
		pkgCurrVerBumpMsg : mp
				+ 'Updating <%= env.pkgPath %> version to match release version <%= commit.version %> <%= commit.skipTaskGen(options.releaseSkipTasks) %>',
		pkgNextVerBumpMsg : mp
				+ 'Bumping <%= env.pkgPath %> version to <%= commit.next.version %> <%= commit.skipTaskGen(options.releaseSkipTasks) %>',
		distBranchPubMsg : mp + 'Publishing <%= commit.version %> <%= commit.skipTaskGen(options.releaseSkipTasks) %>',
		pkgJsonReplacer : null,
		pkgJsonSpace : 2,
		gitHostname : github.hostname,
		repoName : 'origin',
		repoUser : env.pluginName,
		repoEmail : env.pluginName + '@' + (process.env.TRAVIS_BUILD_NUMBER ? 'travis-ci.org' : 'example.org'),
		chgLog : 'HISTORY.md',
		authors : 'AUTHORS.md',
		chgLogLineFormat : '  * %s',
		chgLogRequired : true,
		chgLogSkipRegExps : [ mp ],
		authorsRequired : false,
		authorsSkipLineRegExp : null,
		distBranch : 'gh-pages',
		distDir : 'dist',
		distBranchCreateRegExp : /Couldn't find remote ref/i,
		distExcludeDirRegExp : /.?node_modules.?/gmi,
		distExcludeFileRegExp : /.?\.zip|tar.?/gmi,
		distAssetCompressRatio : 9,
		distAssetDir : '..',
		distAssetUpdateFunction : null,
		distAssetUpdateFiles : [],
		distBranchUpdateFunction : null,
		distBranchUpdateFiles : [],
		rollbackStrategy : 'queue',
		rollbackAsyncTimeout : 60000,
		asyncTimeout : 60000,
		releaseSkipTasks : [ 'ci' ],
		npmTag : '',
		npmRegistryURL : 'https://registry.npmjs.org'
	};
}
519209
function generateFormatterExamples(formatterInfo, prereleaseVersion) {
    const output = ejs.render(cat("./templates/formatter-examples.md.ejs"), formatterInfo);
    let filename = "../eslint.github.io/docs/user-guide/formatters/index.md",
        htmlFilename = "../eslint.github.io/docs/user-guide/formatters/html-formatter-example.html";

    if (prereleaseVersion) {
        filename = filename.replace("/docs", `/docs/${prereleaseVersion}`);
        htmlFilename = htmlFilename.replace("/docs", `/docs/${prereleaseVersion}`);
        if (!test("-d", path.dirname(filename))) {
            mkdir(path.dirname(filename));
        }
    }

    output.to(filename);
    formatterInfo.formatterResults.html.result.to(htmlFilename);
}
819821
def _gen_doc(cls, summary, full_name, identifier, example_call, doc_str,
                 show_examples):
        """"""
        ret = docstrings.dedents("""
            %s

            This plotting method adds data arrays and plots them via
            :class:`%s` plotters

            To plot data from a netCDF file type::

                >>> psy.plot.%s(%s)

            %s""" % (summary, full_name, identifier, example_call, doc_str))

        if show_examples:
            ret += '\n\n' + cls._gen_examples(identifier)
        return ret
742350
def gendocs(ctx,
            source=None,
            outputpath="",
            extra=False,
            lib=False,
            type="",
            title="",
            theme="",
            showthemes=False,
            showtypes=False):
    
    verbose = ctx.obj['VERBOSE']
    sTime = ctx.obj['STIME']
    print_opts = {
        'labels': verbose,
    }

    from .ontodocs.builder import show_themes, random_theme, show_types

    try:
        # check that we have the required dependencies
        import django
    except:
        click.secho(
            "WARNING: this functionality requires the Django package and other extra dependecies.",
            fg="red")
        click.secho("Install with `pip install ontospy[HTML] -U`")
        sys.exit(0)

    if not source and not showthemes and not showtypes and not lib:
        click.echo(ctx.get_help())
        return

    if showthemes:
        show_themes()
        sys.exit(0)

    if showtypes:
        show_types()
        sys.exit(0)

    if theme and theme == "random":
        theme = random_theme()

    if outputpath:
        if not (os.path.exists(outputpath)) or not (os.path.isdir(outputpath)):
            click.secho(
                "WARNING: the -o option must include a valid directory path.",
                fg="red")
            sys.exit(0)

    if source and len(source) > 1:
        click.secho(
            'Note: currently only one argument can be passed', fg='red')

    if lib:
        click.secho("Local library => '%s'" % get_home_location(), fg='white')
        ontouri = action_listlocal(all_details=False)
        if ontouri:
            source = [os.path.join(get_home_location(), ontouri)]
        else:
            raise SystemExit(1)

    # note: the local ontospy library gets displayed via this method too
    url = action_visualize(
        source,
        fromshell=False,
        path=outputpath,
        title=title,
        viztype=type,
        theme=theme,
        verbose=verbose)

    if url:  # open browser
        import webbrowser
        webbrowser.open(url)

    eTime = time.time()
    tTime = eTime - sTime
    printDebug("\n-----------\n" + "Time:	   %0.2fs" % tTime, "comment")
974843
def generate_docs(app):
    
    # Figure out the correct directories to use
    config = app.config
    config_dir = app.env.srcdir
    javascript_root = os.path.join(config_dir, config.jsdoc_source_root)
    if javascript_root[-1] != os.path.sep:
        javascript_root += os.path.sep
    if not javascript_root:
        return
    output_root = os.path.join(config_dir, config.jsdoc_output_root)
    execution_dir = os.path.join(config_dir, '..')
    exclude = config.jsdoc_exclude

    # Remove any files generated by earlier builds
    cleanup(output_root)

    # Generate the actual reST files
    jsdoc_toolkit_dir = os.path.join(SOURCE_PATH, 'jsdoc-toolkit')
    jsdoc_rst_dir = os.path.join(SOURCE_PATH, 'jsdoc-toolkit-rst-template')
    build_xml_path = os.path.join(jsdoc_rst_dir, 'build.xml')
    command = ['ant', '-f', build_xml_path,
               '-Djsdoc-toolkit.dir=%s' % jsdoc_toolkit_dir,
               '-Djs.src.dir=%s' % javascript_root,
               '-Djs.rst.dir=%s' % output_root]
    if exclude:
        exclude_args = ['--exclude=\\"%s\\"' % path for path in exclude]
        command.append('-Djs.exclude="%s"' % ' '.join(exclude_args))
    try:
        process = Popen(command, cwd=execution_dir)
        process.wait()
    except OSError:
        raise JSDocError('Error running ant; is it installed?')

    # Convert the absolute paths in the file listing to relative ones
    path = os.path.join(output_root, 'files.rst')
    with open(path, 'r') as f:
        content = f.read()
    content = content.replace(javascript_root, '')
    with open(path, 'w') as f:
        f.write(content)
696203
def _get_generator(parser, extract, keep, check_maf):
    """"""
    if extract is not None:
        parser = Extractor(parser, names=extract)

    for data in parser.iter_genotypes():
        data.genotypes = data.genotypes[keep]

        # Checking the MAF, if required
        if check_maf:
            data.code_minor()

        yield data
752529
def get_generation_code(self, **gencode):
        
        channels, verts = self.coordinates
        channels = ', '.join(["'{}'".format(ch) for ch in channels])

        verts = list(verts)

        ## Formatting the vertexes
        # List level (must be first), used for gates that may have multiple vertexes like a polygon
        if len(verts) == 1:
            verts = verts[0]

            # Tuple level (must be second), used for catching the number of dimensions
            # on which a vertex is defined
            if len(verts) == 1:
                verts = verts[0]

        # Format vertices to include less sigfigs
        verts = apply_format(verts, '{:.3e}')

        gencode.setdefault('name', self.name)
        gencode.setdefault('region', self.region)
        gencode.setdefault('gate_type', self._gencode_gate_class)
        gencode.setdefault('verts', verts)
        gencode.setdefault('channels', channels)
        format_string = "{name} = {gate_type}({verts}, ({channels}), region='{region}', name='{name}')"
        return format_string.format(**gencode)
1172006
def _write_gen_model_stats(self, iteration:int)->None:
        ""
        generator = self.learn.gan_trainer.generator
        self.stats_writer.write(model=generator, iteration=iteration, tbwriter=self.tbwriter, name='gen_model_stats')
        self.gen_stats_updated = True
277322
function () {
        var generator = this.generator;

        if (!generator || !generator.x || !generator.y || !generator.z) {
            throw new Error('Invalid generator');
        }
        var xFunc = generator.x;
        var yFunc = generator.y;
        var zFunc = generator.z;
        var uRange = generator.u || [0, 1, 0.05];
        var vRange = generator.v || [0, 1, 0.05];

        var uNum = Math.floor((uRange[1] - uRange[0] + uRange[2]) / uRange[2]);
        var vNum = Math.floor((vRange[1] - vRange[0] + vRange[2]) / vRange[2]);

        if (!isFinite(uNum) || !isFinite(vNum)) {
            throw new Error('Infinite generator');
        }

        var vertexNum = uNum * vNum;
        this.attributes.position.init(vertexNum);
        this.attributes.texcoord0.init(vertexNum);

        var pos = [];
        var texcoord = [];
        var nVertex = 0;
        for (var j = 0; j < vNum; j++) {
            for (var i = 0; i < uNum; i++) {
                var u = i * uRange[2] + uRange[0];
                var v = j * vRange[2] + vRange[0];
                pos[0] = xFunc(u, v);
                pos[1] = yFunc(u, v);
                pos[2] = zFunc(u, v);

                texcoord[0] = i / (uNum - 1);
                texcoord[1] = j / (vNum - 1);

                this.attributes.position.set(nVertex, pos);
                this.attributes.texcoord0.set(nVertex, texcoord);
                nVertex++;
            }
        }

        var IndicesCtor = vertexNum > 0xffff ? Uint32Array : Uint16Array;
        var nIndices = (uNum - 1) * (vNum - 1) * 6;
        var indices = this.indices = new IndicesCtor(nIndices);

        var n = 0;
        for (var j = 0; j < vNum - 1; j++) {
            for (var i = 0; i < uNum - 1; i++) {
                var i2 = j * uNum + i;
                var i1 = (j * uNum + i + 1);
                var i4 = (j + 1) * uNum + i + 1;
                var i3 = (j + 1) * uNum + i;

                indices[n++] = i1;
                indices[n++] = i2;
                indices[n++] = i4;

                indices[n++] = i2;
                indices[n++] = i3;
                indices[n++] = i4;
            }
        }

        this.generateVertexNormals();
        this.updateBoundingBox();
    }
522113
def generate_cxx(module_name, code, specs=None, optimizations=None,
                 module_dir=None):
    '''

    '''

    pm, ir, renamings, docstrings = front_middle_end(module_name, code,
                                                     optimizations, module_dir)

    # back-end
    content = pm.dump(Cxx, ir)

    # instantiate the meta program
    if specs is None:

        class Generable(object):
            def __init__(self, content):
                self.content = content

            def __str__(self):
                return str(self.content)

            generate = __str__

        mod = Generable(content)

        def error_checker():
            tog.typecheck(ir)

    else:

        # uniform typing
        if isinstance(specs, dict):
            specs = Spec(specs, {})

        def error_checker():
            types = tog.typecheck(ir)
            check_specs(specs, renamings, types)

        specs.to_docstrings(docstrings)
        check_exports(ir, specs, renamings)

        if isinstance(code, bytes):
            code_bytes = code
        else:
            code_bytes = code.encode('ascii', 'ignore')
        metainfo = {'hash': hashlib.sha256(code_bytes).hexdigest(),
                    'version': __version__,
                    'date': datetime.now()}

        mod = PythonModule(module_name, docstrings, metainfo)
        mod.add_to_includes(
            Include("pythonic/core.hpp"),
            Include("pythonic/python/core.hpp"),
            # FIXME: only include these when needed
            Include("pythonic/types/bool.hpp"),
            Include("pythonic/types/int.hpp"),
            Line("#ifdef _OPENMP\n#include <omp.h>\n#endif")
        )
        mod.add_to_includes(*[Include(inc) for inc in
                              _extract_specs_dependencies(specs)])
        mod.add_to_includes(*content.body)
        mod.add_to_includes(
            Include("pythonic/python/exception_handler.hpp"),
        )

        def warded(module_name, internal_name):
            return pythran_ward + '{0}::{1}'.format(module_name, internal_name)

        for function_name, signatures in specs.functions.items():
            internal_func_name = renamings.get(function_name,
                                               function_name)
            # global variables are functions with no signatures :-)
            if not signatures:
                mod.add_global_var(function_name,
                                   "{}()()".format(warded(module_name,
                                                          internal_func_name)))

            for sigid, signature in enumerate(signatures):
                numbered_function_name = "{0}{1}".format(internal_func_name,
                                                         sigid)
                arguments_types = [pytype_to_ctype(t) for t in signature]
                arguments_names = HasArgument(internal_func_name).visit(ir)
                arguments = [n for n, _ in
                             zip(arguments_names, arguments_types)]
                name_fmt = pythran_ward + "{0}::{1}::type{2}"
                args_list = ", ".join(arguments_types)
                specialized_fname = name_fmt.format(module_name,
                                                    internal_func_name,
                                                    "<{0}>".format(args_list)
                                                    if arguments_names else "")
                result_type = "typename %s::result_type" % specialized_fname
                mod.add_pyfunction(
                    FunctionBody(
                        FunctionDeclaration(
                            Value(
                                result_type,
                                numbered_function_name),
                            [Value(t + '&&', a)
                             for t, a in zip(arguments_types, arguments)]),
                        Block([Statement("""
                            PyThreadState *_save = PyEval_SaveThread();
                            try {{
                                auto res = {0}()({1});
                                PyEval_RestoreThread(_save);
                                return res;
                            }}
                            catch(...) {{
                                PyEval_RestoreThread(_save);
                                throw;
                            }}
                            """.format(warded(module_name,
                                              internal_func_name),
                                       ', '.join(arguments)))])
                    ),
                    function_name,
                    arguments_types,
                    signature
                )

        for function_name, signature in specs.capsules.items():
            internal_func_name = renamings.get(function_name,
                                               function_name)

            arguments_types = [pytype_to_ctype(t) for t in signature]
            arguments_names = HasArgument(internal_func_name).visit(ir)
            arguments = [n for n, _ in
                         zip(arguments_names, arguments_types)]
            name_fmt = pythran_ward + "{0}::{1}::type{2}"
            args_list = ", ".join(arguments_types)
            specialized_fname = name_fmt.format(module_name,
                                                internal_func_name,
                                                "<{0}>".format(args_list)
                                                if arguments_names else "")
            result_type = "typename %s::result_type" % specialized_fname
            docstring = spec_to_string(function_name, signature)
            mod.add_capsule(
                FunctionBody(
                    FunctionDeclaration(
                        Value(result_type, function_name),
                        [Value(t, a)
                         for t, a in zip(arguments_types, arguments)]),
                    Block([ReturnStatement("{0}()({1})".format(
                        warded(module_name, internal_func_name),
                        ', '.join(arguments)))])
                ),
                function_name,
                docstring
            )

    return mod, error_checker
599467
def _gen_doc(cls, summary, full_name, identifier, example_call, doc_str,
                 show_examples):
        """"""
        # leave out the first argument
        example_call = ', '.join(map(str.strip, example_call.split(',')[1:]))
        ret = docstrings.dedents("""
            %s

            This plotting method adds data arrays and plots them via
            :class:`%s` plotters

            To plot a variable in this dataset, type::

                >>> ds.psy.plot.%s(%s)

            %s""" % (summary, full_name, identifier, example_call, doc_str))

        if show_examples:
            ret += '\n\n' + cls._gen_examples(identifier)
        return ret
996554
def _find_field_generator_templates(self):
        
        field_gen_templates = {}

        # Extract field generators from class dict
        for name, g in self.__class__.__dict__.items():
            if isinstance(g, TohuBaseGenerator):
                field_gen_templates[name] = g.set_tohu_name(f'{name} (TPL)')

        # Extract field generators from instance dict
        for name, g in self.__dict__.items():
            if isinstance(g, TohuBaseGenerator):
                field_gen_templates[name] = g.set_tohu_name(f'{name} (TPL)')

        return field_gen_templates
99927
function genCap(point, ux, uy, v1i, v2i, pushVert, pushIndices) {
    if (!point.cap) {
        genRoundedCap(point, ux, uy, v1i, v2i, pushVert, pushIndices);
    } else {
        switch (point.cap.type) {
            case LineCaps.LINECAP_TYPE_ARROW:
                genArrowCap(point, ux, uy, v1i, v2i, pushVert, pushIndices);
                break;

            case LineCaps.LINECAP_TYPE_ROUNDED:
                genRoundedCap(point, ux, uy, v1i, v2i, pushVert, pushIndices);
                break;

            case LineCaps.LINECAP_TYPE_HALF_ARROW_A:
                genHalfArrowACap(point, ux, uy, v1i, v2i, pushVert, pushIndices);
                break;

            default:
                // default to no cap
                break;
        }
    }
}
76879
function genWeexHandler (params, handlerCode) {
  var innerHandlerCode = handlerCode;
  var exps = params.filter(function (exp) { return simplePathRE.test(exp) && exp !== '$event'; });
  var bindings = exps.map(function (exp) { return ({ '@binding': exp }); });
  var args = exps.map(function (exp, i) {
    var key = "$_" + (i + 1);
    innerHandlerCode = innerHandlerCode.replace(exp, key);
    return key
  });
  args.push('$event');
  return '{\n' +
    "handler:function(" + (args.join(',')) + "){" + innerHandlerCode + "},\n" +
    "params:" + (JSON.stringify(bindings)) + "\n" +
    '}'
}
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))