initial script processing
498157
function process (ev) {
				ev = ev || global.event;
				// detect when it's done loading
				// ev.type == 'load' is for all browsers except IE6-9
				// IE6-9 need to use onreadystatechange and look for
				// el.readyState in {loaded, complete} (yes, we need both)
				if (ev.type == 'load' || readyStates[el.readyState]) {
					delete activeScripts[def.id];
					// release event listeners
					el.onload = el.onreadystatechange = el.onerror = ''; // ie cries if we use undefined
					success();
				}
			}
919456
private void startScript(String line, DispatchCallback callback) {
    OutputFile outFile = sqlLine.getScriptOutputFile();
    if (outFile != null) {
      callback.setToFailure();
      sqlLine.error(sqlLine.loc("script-already-running", outFile));
      return;
    }

    String filename;
    if (line.length() == "script".length()
        || (filename =
            sqlLine.dequote(line.substring("script".length() + 1))) == null) {
      sqlLine.error("Usage: script <file name>");
      callback.setToFailure();
      return;
    }

    try {
      outFile = new OutputFile(expand(filename));
      sqlLine.setScriptOutputFile(outFile);
      sqlLine.output(sqlLine.loc("script-started", outFile));
      callback.setToSuccess();
    } catch (Exception e) {
      callback.setToFailure();
      sqlLine.error(e);
    }
  }
935034
private void processOnce() throws CompilationFailedException, IOException, URISyntaxException {
        GroovyShell groovy = new GroovyShell(conf);
        setupContextClassLoader(groovy);
        groovy.run(getScriptSource(isScriptFile, script), args);
    }
267522
def _generate_main_scripts(self):
        

        head = self.parser.find('head').first_result()
        if head is not None:
            common_functions_script = self.parser.find(
                '#'
                + AccessibleEventImplementation.ID_SCRIPT_COMMON_FUNCTIONS
            ).first_result()
            if common_functions_script is None:
                common_functions_file = open(
                    os.path.join(
                        os.path.dirname(os.path.dirname(os.path.dirname(
                            os.path.realpath(__file__)
                        ))),
                        'js',
                        'common.js'
                    ),
                    'r'
                )
                common_functions_content = common_functions_file.read()
                common_functions_file.close()

                common_functions_script = self.parser.create_element('script')
                common_functions_script.set_attribute(
                    'id',
                    AccessibleEventImplementation.ID_SCRIPT_COMMON_FUNCTIONS
                )
                common_functions_script.set_attribute(
                    'type',
                    'text/javascript'
                )
                common_functions_script.append_text(common_functions_content)
                head.prepend_element(common_functions_script)
            if (
                self.parser.find(
                    '#'
                    + AccessibleEventImplementation.ID_SCRIPT_EVENT_LISTENER
                ).first_result() is None
            ):
                event_listener_file = open(
                    os.path.join(
                        os.path.dirname(os.path.dirname(os.path.dirname(
                            os.path.realpath(__file__)
                        ))),
                        'js',
                        'eventlistener.js'
                    ),
                    'r'
                )
                event_listener_script_content = event_listener_file.read()
                event_listener_file.close()

                script = self.parser.create_element('script')
                script.set_attribute(
                    'id',
                    AccessibleEventImplementation.ID_SCRIPT_EVENT_LISTENER
                )
                script.set_attribute('type', 'text/javascript')
                script.append_text(event_listener_script_content)
                common_functions_script.insert_after(script)
        local = self.parser.find('body').first_result()
        if local is not None:
            self.script_list = self.parser.find(
                '#'
                + AccessibleEventImplementation.ID_LIST_IDS_SCRIPT
            ).first_result()
            if self.script_list is None:
                self.script_list = self.parser.create_element('script')
                self.script_list.set_attribute(
                    'id',
                    AccessibleEventImplementation.ID_LIST_IDS_SCRIPT
                )
                self.script_list.set_attribute('type', 'text/javascript')
                self.script_list.append_text('var activeElements = [];')
                self.script_list.append_text('var hoverElements = [];')
                self.script_list.append_text('var dragElements = [];')
                self.script_list.append_text('var dropElements = [];')
                local.append_element(self.script_list)
            if self.parser.find(
                    '#'
                    + AccessibleEventImplementation.ID_FUNCTION_SCRIPT_FIX
            ).first_result() is None:
                include_file = open(
                    os.path.join(
                        os.path.dirname(os.path.dirname(os.path.dirname(
                            os.path.realpath(__file__)
                        ))),
                        'js',
                        'include.js'
                    ),
                    'r'
                )
                local_include_script_content = include_file.read()
                include_file.close()

                script_function = self.parser.create_element('script')
                script_function.set_attribute(
                    'id',
                    AccessibleEventImplementation.ID_FUNCTION_SCRIPT_FIX
                )
                script_function.set_attribute('type', 'text/javascript')
                script_function.append_text(local_include_script_content)
                local.append_element(script_function)
        self.main_script_added = True
1071696
def initialize():
    
    try:
        import multiprocessing
        ncpus = '{0}'.format(multiprocessing.cpu_count())
    except (ImportError, NotImplementedError):
        ncpus = '0'

    # Setup the command-line options and parse them.
    parser = argparse.ArgumentParser(description="Document a program or library written in modern Fortran. Any command-line options over-ride those specified in the project file.")
    parser.add_argument("project_file",help="file containing the description and settings for the project",
                        type=argparse.FileType('r'))
    parser.add_argument("-d","--src_dir",action="append",help='directories containing all source files for the project')
    parser.add_argument("-p","--page_dir",help="directory containing the optional page tree describing the project")
    parser.add_argument("-o","--output_dir",help="directory in which to place output files")
    parser.add_argument("-s","--css",help="custom style-sheet for the output")
    parser.add_argument("-r","--revision",dest="revision",help="Source code revision the project to document")
    parser.add_argument("--exclude",action="append",help="any files which should not be included in the documentation")
    parser.add_argument("--exclude_dir",action="append",help="any directories whose contents should not be included in the documentation")
    parser.add_argument("-e","--extensions",action="append",help="extensions which should be scanned for documentation (default: f90, f95, f03, f08)")
    parser.add_argument("-m","--macro",action="append",help="preprocessor macro (and, optionally, its value) to be applied to files in need of preprocessing.")
    parser.add_argument("-w","--warn",dest='warn',action='store_true',
                        help="display warnings for undocumented items")
    parser.add_argument("--no-search",dest='search',action='store_false',
                        help="don't process documentation to produce a search feature")
    parser.add_argument("-q","--quiet",dest='quiet',action='store_true',
                        help="do not print any description of progress")
    parser.add_argument("-V", "--version", action="version",
                        version="{}, version {}".format(__appname__,__version__))
    parser.add_argument("--debug",dest="dbg",action="store_true",
                        help="display traceback if fatal exception occurs")
    parser.add_argument("-I","--include",action="append",
                        help="any directories which should be searched for include files")
    # Get options from command-line
    args = parser.parse_args()
    # Set up Markdown reader
    md_ext = ['markdown.extensions.meta','markdown.extensions.codehilite',
              'markdown.extensions.extra',MathExtension(),'md_environ.environ']
    md = markdown.Markdown(extensions=md_ext, output_format="html5",
    extension_configs={})
    # Read in the project-file. This will contain global documentation (which
    # will appear on the homepage) as well as any information about the project
    # and settings for generating the documentation.
    proj_docs = args.project_file.read()
    md.convert(proj_docs)
    # Remake the Markdown object with settings parsed from the project_file
    if 'md_base_dir' in md.Meta: md_base = md.Meta['md_base_dir'][0] 
    else: md_base = os.path.dirname(args.project_file.name)
    md_ext.append('markdown_include.include')
    if 'md_extensions' in md.Meta: md_ext.extend(md.Meta['md_extensions'])
    md = markdown.Markdown(extensions=md_ext, output_format="html5",
            extension_configs={'markdown_include.include': {'base_path': md_base}})
    md.reset()
    # Re-read the project file
    proj_docs = md.convert(proj_docs)
    proj_data = md.Meta
    md.reset()
    # Get the default options, and any over-rides, straightened out
    options = ['src_dir','extensions','fpp_extensions','fixed_extensions',
               'output_dir','css','exclude',
               'project','author','author_description','author_pic',
               'summary','github','bitbucket','facebook','twitter',
               'google_plus','linkedin','email','website','project_github',
               'project_bitbucket','project_website','project_download',
               'project_sourceforge','project_url','display','hide_undoc','version',
               'year','docmark','predocmark','docmark_alt','predocmark_alt',
               'media_dir','favicon','warn','extra_vartypes','page_dir',
               'incl_src',
               'source','exclude_dir','macro','include','preprocess','quiet',
               'search','lower','sort','extra_mods','dbg','graph',
               'graph_maxdepth', 'graph_maxnodes',
               'license','extra_filetypes','preprocessor','creation_date',
               'print_creation_date','proc_internals','coloured_edges',
               'graph_dir','gitter_sidecar','mathjax_config','parallel',
               'revision', 'fixed_length_limit']
    defaults = {'src_dir':             ['./src'],
                'extensions':          ['f90','f95','f03','f08','f15'],
                'fpp_extensions':      ['F90','F95','F03','F08','F15','F','FOR'],
                'fixed_extensions':    ['f','for','F','FOR'],
                'output_dir':          './doc',
                'project':             'Fortran Program',
                'project_url':         '',
                'display':             ['public','protected'],
                'hide_undoc':          'false',
                'year':                date.today().year,
                'exclude':             [],
                'exclude_dir':         [],
                'docmark':             '!',
                'docmark_alt':         '*',
                'predocmark':          '>',
                'predocmark_alt':      '|',
                'favicon':             'default-icon',
                'extra_vartypes':      [],
                'incl_src':            'true',
                'source':              'false',
                'macro':               [],
                'include':             [],
                'preprocess':          'true',
                'preprocessor':        '',
                'proc_internals':      'false',
                'warn':                'false',
                'quiet':               'false',
                'search':              'true',
                'lower':               'false',
                'sort':                'src',
                'extra_mods':          [],
                'dbg':                 True,
                'graph':               'false',
                'graph_maxdepth':      '10000',
                'graph_maxnodes':      '1000000000',
                'license':             '',
                'extra_filetypes':     [],
                'creation_date':       '%Y-%m-%dT%H:%M:%S.%f%z',
                'print_creation_date': False,
                'coloured_edges':      'false',
                'parallel':            ncpus,
                'fixed_length_limit':  'true',
               }
    listopts = ['extensions','fpp_extensions','fixed_extensions','display',
                'extra_vartypes','src_dir','exclude','exclude_dir',
                'macro','include','extra_mods','extra_filetypes']
    # Evaluate paths relative to project file location
    if args.warn:
        args.warn = 'true'
    else:
        del args.warn
    if args.quiet:
        args.quiet = 'true'
    else:
        del args.quiet
    if not args.search:
        args.search = 'false'
    else:
        del args.search
    for option in options:
        if hasattr(args,option) and getattr(args,option):
            proj_data[option] = getattr(args,option)
        elif option in proj_data:
            # Think if there is a safe  way to evaluate any expressions found in this list
            #proj_data[option] = proj_data[option]
            if option not in listopts:
                proj_data[option] = '\n'.join(proj_data[option])
        elif option in defaults:
           proj_data[option] = defaults[option]
    base_dir = os.path.abspath(os.path.dirname(args.project_file.name))
    proj_data['base_dir'] = base_dir
    for var in ['src_dir','exclude_dir','include']:
        if var in proj_data:
            proj_data[var] = [os.path.normpath(os.path.join(base_dir,os.path.expanduser(os.path.expandvars(p)))) for p in proj_data[var]]
    for var in ['page_dir','output_dir','graph_dir','media_dir','css','mathjax_config']:
        if var in proj_data:
            proj_data[var] = os.path.normpath(os.path.join(base_dir,os.path.expanduser(os.path.expandvars(proj_data[var]))))
    if proj_data['favicon'].strip() != defaults['favicon']:
        proj_data['favicon'] = os.path.normpath(os.path.join(base_dir,os.path.expanduser(os.path.expandvars(proj_data['favicon']))))
    proj_data['display'] = [ item.lower() for item in proj_data['display'] ]
    proj_data['incl_src'] = proj_data['incl_src'].lower()
    proj_data['creation_date'] = datetime.now().strftime(proj_data['creation_date'])
    relative = (proj_data['project_url'] == '')
    proj_data['relative'] = relative
    proj_data['extensions'] += [ext for ext in proj_data['fpp_extensions'] if ext not in proj_data['extensions']]
    # Parse file extensions and comment characters for extra filetypes
    extdict = {}
    for ext in proj_data['extra_filetypes']:
        sp = ext.split()
        if len(sp) < 2: continue
        if (len(sp)==2):
            extdict[sp[0]] = (sp[1])        # (comment_char) only
        else:
            extdict[sp[0]] = (sp[1],sp[2])  # (comment_char and lexer_str)
    proj_data['extra_filetypes'] = extdict
    # Make sure no src_dir is contained within output_dir
    for projdir in proj_data['src_dir']:
        proj_path = ford.utils.split_path(projdir)
        out_path  = ford.utils.split_path(proj_data['output_dir'])
        for directory in out_path:
            if len(proj_path) == 0:
                break
            if directory == proj_path[0]:
                proj_path.remove(directory)
            else:
                break
        else:
            print('Error: directory containing source-code {} a subdirectory of output directory {}.'.format(proj_data['output_dir'],projdir))
            sys.exit(1)
    # Check that none of the docmarks are the same
    if proj_data['docmark'] == proj_data['predocmark'] != '':
        print('Error: docmark and predocmark are the same.')
        sys.exit(1)
    if proj_data['docmark'] == proj_data['docmark_alt'] != '':
        print('Error: docmark and docmark_alt are the same.')
        sys.exit(1)
    if proj_data['docmark'] == proj_data['predocmark_alt'] != '':
        print('Error: docmark and predocmark_alt are the same.')
        sys.exit(1)
    if proj_data['docmark_alt'] == proj_data['predocmark'] != '':
        print('Error: docmark_alt and predocmark are the same.')
        sys.exit(1)
    if proj_data['docmark_alt'] == proj_data['predocmark_alt'] != '':
        print('Error: docmark_alt and predocmark_alt are the same.')
        sys.exit(1)
    if proj_data['predocmark'] == proj_data['predocmark_alt'] != '':
        print('Error: predocmark and predocmark_alt are the same.')
        sys.exit(1)
    # Add gitter sidecar if specified in metadata
    if 'gitter_sidecar' in proj_data:
        proj_docs += '''
        <script>
            ((window.gitter = {{}}).chat = {{}}).options = {{
            room: '{}'
            }};
        </script>
        <script src="https://sidecar.gitter.im/dist/sidecar.v1.js" async defer></script>
        '''.format(proj_data['gitter_sidecar'].strip())
    # Handle preprocessor:
    if proj_data['preprocess'].lower() == 'true':
        if proj_data['preprocessor']:
            preprocessor = proj_data['preprocessor'].split()
        else:
            preprocessor = ['cpp','-traditional-cpp','-E', '-D__GFORTRAN__']

        # Check whether preprocessor works (reading nothing from stdin)
        try:
            devnull = open(os.devnull)
            subprocess.Popen(preprocessor, stdin=devnull, stdout=devnull,
                             stderr=devnull).communicate()
        except OSError as ex:
            print('Warning: Testing preprocessor failed')
            print('  Preprocessor command: {}'.format(preprocessor))
            print('  Exception: {}'.format(ex))
            print('  -> Preprocessing turned off')
            proj_data['preprocess'] = 'false'
        else:
            proj_data['preprocess'] = 'true'
            proj_data['preprocessor'] = preprocessor
    
    # Get correct license
    try:
        proj_data['license'] = LICENSES[proj_data['license'].lower()]
    except KeyError:
        print('Warning: license "{}" not recognized.'.format(proj_data['license']))
        proj_data['license'] = ''
    # Return project data, docs, and the Markdown reader
    md.reset()
    md.Meta = {}
    return (proj_data, proj_docs, md)
838395
function startClassInit(noDelay) {

			var script = scriptArr.pop(), data;

			var temp = getBaseDir(script.packageName);

			if (typeof loadedScript[temp  + script.Class] == 'object') {
				data = loadedScript[temp  + script.Class];
			}
			loadedScript[temp  + script.Class] = true;
			var temp;
			if(noDelay) {
				compiling_classes = compiling_classes || [];
				compiling_classes.push({script:script, data:data});
			}
			while(temp = compiling_classes.shift()){
				(function(temp){
					fileLoadeManager.onAllFileLoad(temp.script.includes, function(){
						classManager.init(temp.script, temp.data);
					});
				})(temp)
			}
			if(noDelay) {
				return;
			}
			compiling_classes = [];
			compiling_classes.push({script:script, data:data});
			setTimeout(function( ) {
				// Calling classManager after a short delay so that file get
				// completely ready.
				var temp;
				while(temp = compiling_classes.shift()){
					(function(temp){
						fileLoadeManager.onAllFileLoad(temp.script.includes, function(){
							classManager.init(temp.script, temp.data);
						});
					})(temp)
				}
				// fm.holdReady(false);
			}, 0);

		}
583556
function ScriptManager() {

  // child process
  this.ps = null;

  // script execution limit in milliseconds
  this._limit = 5000;

  // flag determining if a script is busy executing
  this._busy = false;

  // flag determining if script execution issued
  // any write commands
  this._written = false;

  // currently executing script name
  this._script = null;

  // injected reference to the command handlers
  this._commands = {};

  // script limit timeout listener
  this.onTimeout = this.onTimeout.bind(this);
}
154016
def editStartScript(self, index):
        """"""
        f = str(self.fileName(index))
        if f.endswith('.%s' % self.file_type):
            zipname = str(self.filePath(index))
            with ZipFile(zipname, 'a') as myzip:
                # extract+save script in tmp-dir:
                myzip.extract('__main__.py', self._tmp_dir_work)
                tempfilename = f[:-4]
                tempfilepath = os.path.join(self._tmp_dir_work, tempfilename)
                os.rename(
                    os.path.join(
                        self._tmp_dir_work,
                        '__main__.py'),
                    tempfilepath)
                self.openTxt(tempfilepath)
                self._editedSessions[index] = (
                    zipname, self._tmp_dir_work, tempfilename)
859728
private void executeScript() throws IOException, InterruptedException {

        File script = new File(m_scriptPath);
        List<String> params = new LinkedList<String>();
        params.add(script.getAbsolutePath());
        params.addAll(m_writtenFiles);
        ProcessBuilder pb = new ProcessBuilder(params.toArray(new String[params.size()]));
        pb.directory(new File(script.getParent()));
        Process pr = pb.start();
        pr.waitFor();
        BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
        while (buf.ready()) {
            String line = buf.readLine();
            if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(line)) {
                getReport().println(
                    Messages.get().container(Messages.RPT_OUTPUT_WEBSERVER_1, buf.readLine()),
                    I_CmsReport.FORMAT_OK);
            }
        }
    }
446392
def main():
    
    parser = optparse.OptionParser(usage="""usage: %prog [options] <package path> [exclude paths, ...]

Note: By default this script will not overwrite already created files.""")
    parser.add_option("-n", "--doc-header", action="store", dest="header", help="Documentation Header (default=Project)", default="Project")
    parser.add_option("-d", "--dest-dir", action="store", dest="destdir", help="Output destination directory", default="")
    parser.add_option("-s", "--suffix", action="store", dest="suffix", help="module suffix (default=txt)", default="txt")
    parser.add_option("-m", "--maxdepth", action="store", dest="maxdepth", help="Maximum depth of submodules to show in the TOC (default=4)", type="int", default=4)
    parser.add_option("-r", "--dry-run", action="store_true", dest="dryrun", help="Run the script without creating the files")
    parser.add_option("-f", "--force", action="store_true", dest="force", help="Overwrite all the files")
    parser.add_option("-t", "--no-toc", action="store_true", dest="notoc", help="Don't create the table of content file")
    (opts, args) = parser.parse_args()
    if not args:
        parser.error("package path is required.")
    else:
        rootpath, excludes = args[0], args[1:]
        if os.path.isdir(rootpath):
            # check if the output destination is a valid directory
            if opts.destdir and os.path.isdir(opts.destdir):
                excludes = normalize_excludes(rootpath, excludes)
                recurse_tree(rootpath, excludes, opts)
            else:
                print '%s is not a valid output destination directory.' % opts.destdir
        else:
            print '%s is not a valid directory.' % rootpath
518874
function initialize() {
    /**
     * Get custom settings from the query string
     */
    var scripts = document.getElementsByTagName('script');
    var src = (scripts[scripts.length - 1] || {}).src || '';
    var arg = src.indexOf('?') !== -1 ? src.split('?').pop() : '';
    arg.replace(/(\w+)(?:=([^&]*))?/g, function(a, key, value) {
      settings[key] = (value || '').replace(/^(0|false)$/, '');
    });

    /**
     * hang up the event handler to listen to the events hashchange
     */
    addEvent(eventNamePrefix + 'hashchange', onHashChange, false);

    // a list of objects with pairs of descriptors/object
    var data = [locationDescriptors, locationObject, eventsDescriptors, global, historyDescriptors, historyObject];

    // if browser support object 'state' in interface 'History'
    if (isSupportStateObjectInHistory) {
      // remove state property from descriptor
      delete historyDescriptors['state'];
    }

    // initializing descriptors
    for(var i = 0; i < data.length; i += 2) {
      for(var prop in data[i]) {
        if (data[i].hasOwnProperty(prop)) {
          if (typeof data[i][prop] !== 'object') {
            // If the descriptor is a simple function, simply just assign it an object
            data[i + 1][prop] = data[i][prop];
          } else {
            // prepare the descriptor the required format
            var descriptor = prepareDescriptorsForObject(data[i], prop, data[i][prop]);
            // try to set the descriptor object
            if (!redefineProperty(data[i + 1], prop, descriptor, function(n, o) {
              // is satisfied if the failed override property
              if (o === historyObject) {
                // the problem occurs in Safari on the Mac
                global.history = historyObject = data[i + 1] = n;
              }
            })) {
              // if there is no possibility override.
              // This browser does not support descriptors, such as IE7

              // remove previously hung event handlers
              removeEvent(eventNamePrefix + 'hashchange', onHashChange, false);

              // fail to initialize :(
              return false;
            }

            // create a repository for custom handlers onpopstate/onhashchange
            if (data[i + 1] === global) {
              eventsList[prop] = eventsList[prop.substr(2)] = [];
            }
          }
        }
      }
    }

    // check settings
    historyObject['setup']();

    // redirect if necessary
    if (settings['redirect']) {
      historyObject['redirect']();
    }

    // initialize
    if (settings["init"]) {
      // You agree that you will use window.history.location instead window.location
      isUsedHistoryLocationFlag = 1;
    }

    // If browser does not support object 'state' in interface 'History'
    if (!isSupportStateObjectInHistory && JSON) {
      storageInitialize();
    }

    // track clicks on anchors
    if (!isSupportHistoryAPI) {
      document[addEventListenerName](eventNamePrefix + "click", onAnchorClick, false);
    }

    if (document.readyState === 'complete') {
      onLoad(true);
    } else {
      if (!isSupportHistoryAPI && parseURL()._relative !== settings["basepath"]) {
        isFireInitialState = true;
      }
      /**
       * Need to avoid triggering events popstate the initial page load.
       * Hang handler popstate as will be fully loaded document that
       * would prevent triggering event onpopstate
       */
      addEvent(eventNamePrefix + 'load', onLoad, false);
    }

    // everything went well
    return true;
  }
811170
def _attrs_to_init_script(
    attrs, frozen, slots, post_init, cache_hash, base_attr_map, is_exc
):
    
    lines = []
    any_slot_ancestors = any(
        _is_slot_attr(a.name, base_attr_map) for a in attrs
    )
    if frozen is True:
        if slots is True:
            lines.append(
                # Circumvent the __setattr__ descriptor to save one lookup per
                # assignment.
                # Note _setattr will be used again below if cache_hash is True
                "_setattr = _cached_setattr.__get__(self, self.__class__)"
            )

            def fmt_setter(attr_name, value_var):
                return "_setattr('%(attr_name)s', %(value_var)s)" % {
                    "attr_name": attr_name,
                    "value_var": value_var,
                }

            def fmt_setter_with_converter(attr_name, value_var):
                conv_name = _init_converter_pat.format(attr_name)
                return "_setattr('%(attr_name)s', %(conv)s(%(value_var)s))" % {
                    "attr_name": attr_name,
                    "value_var": value_var,
                    "conv": conv_name,
                }

        else:
            # Dict frozen classes assign directly to __dict__.
            # But only if the attribute doesn't come from an ancestor slot
            # class.
            # Note _inst_dict will be used again below if cache_hash is True
            lines.append("_inst_dict = self.__dict__")
            if any_slot_ancestors:
                lines.append(
                    # Circumvent the __setattr__ descriptor to save one lookup
                    # per assignment.
                    "_setattr = _cached_setattr.__get__(self, self.__class__)"
                )

            def fmt_setter(attr_name, value_var):
                if _is_slot_attr(attr_name, base_attr_map):
                    res = "_setattr('%(attr_name)s', %(value_var)s)" % {
                        "attr_name": attr_name,
                        "value_var": value_var,
                    }
                else:
                    res = "_inst_dict['%(attr_name)s'] = %(value_var)s" % {
                        "attr_name": attr_name,
                        "value_var": value_var,
                    }
                return res

            def fmt_setter_with_converter(attr_name, value_var):
                conv_name = _init_converter_pat.format(attr_name)
                if _is_slot_attr(attr_name, base_attr_map):
                    tmpl = "_setattr('%(attr_name)s', %(c)s(%(value_var)s))"
                else:
                    tmpl = "_inst_dict['%(attr_name)s'] = %(c)s(%(value_var)s)"
                return tmpl % {
                    "attr_name": attr_name,
                    "value_var": value_var,
                    "c": conv_name,
                }

    else:
        # Not frozen.
        def fmt_setter(attr_name, value):
            return "self.%(attr_name)s = %(value)s" % {
                "attr_name": attr_name,
                "value": value,
            }

        def fmt_setter_with_converter(attr_name, value_var):
            conv_name = _init_converter_pat.format(attr_name)
            return "self.%(attr_name)s = %(conv)s(%(value_var)s)" % {
                "attr_name": attr_name,
                "value_var": value_var,
                "conv": conv_name,
            }

    args = []
    kw_only_args = []
    attrs_to_validate = []

    # This is a dictionary of names to validator and converter callables.
    # Injecting this into __init__ globals lets us avoid lookups.
    names_for_globals = {}
    annotations = {"return": None}

    for a in attrs:
        if a.validator:
            attrs_to_validate.append(a)
        attr_name = a.name
        arg_name = a.name.lstrip("_")
        has_factory = isinstance(a.default, Factory)
        if has_factory and a.default.takes_self:
            maybe_self = "self"
        else:
            maybe_self = ""
        if a.init is False:
            if has_factory:
                init_factory_name = _init_factory_pat.format(a.name)
                if a.converter is not None:
                    lines.append(
                        fmt_setter_with_converter(
                            attr_name,
                            init_factory_name + "({0})".format(maybe_self),
                        )
                    )
                    conv_name = _init_converter_pat.format(a.name)
                    names_for_globals[conv_name] = a.converter
                else:
                    lines.append(
                        fmt_setter(
                            attr_name,
                            init_factory_name + "({0})".format(maybe_self),
                        )
                    )
                names_for_globals[init_factory_name] = a.default.factory
            else:
                if a.converter is not None:
                    lines.append(
                        fmt_setter_with_converter(
                            attr_name,
                            "attr_dict['{attr_name}'].default".format(
                                attr_name=attr_name
                            ),
                        )
                    )
                    conv_name = _init_converter_pat.format(a.name)
                    names_for_globals[conv_name] = a.converter
                else:
                    lines.append(
                        fmt_setter(
                            attr_name,
                            "attr_dict['{attr_name}'].default".format(
                                attr_name=attr_name
                            ),
                        )
                    )
        elif a.default is not NOTHING and not has_factory:
            arg = "{arg_name}=attr_dict['{attr_name}'].default".format(
                arg_name=arg_name, attr_name=attr_name
            )
            if a.kw_only:
                kw_only_args.append(arg)
            else:
                args.append(arg)
            if a.converter is not None:
                lines.append(fmt_setter_with_converter(attr_name, arg_name))
                names_for_globals[
                    _init_converter_pat.format(a.name)
                ] = a.converter
            else:
                lines.append(fmt_setter(attr_name, arg_name))
        elif has_factory:
            arg = "{arg_name}=NOTHING".format(arg_name=arg_name)
            if a.kw_only:
                kw_only_args.append(arg)
            else:
                args.append(arg)
            lines.append(
                "if {arg_name} is not NOTHING:".format(arg_name=arg_name)
            )
            init_factory_name = _init_factory_pat.format(a.name)
            if a.converter is not None:
                lines.append(
                    "    " + fmt_setter_with_converter(attr_name, arg_name)
                )
                lines.append("else:")
                lines.append(
                    "    "
                    + fmt_setter_with_converter(
                        attr_name,
                        init_factory_name + "({0})".format(maybe_self),
                    )
                )
                names_for_globals[
                    _init_converter_pat.format(a.name)
                ] = a.converter
            else:
                lines.append("    " + fmt_setter(attr_name, arg_name))
                lines.append("else:")
                lines.append(
                    "    "
                    + fmt_setter(
                        attr_name,
                        init_factory_name + "({0})".format(maybe_self),
                    )
                )
            names_for_globals[init_factory_name] = a.default.factory
        else:
            if a.kw_only:
                kw_only_args.append(arg_name)
            else:
                args.append(arg_name)
            if a.converter is not None:
                lines.append(fmt_setter_with_converter(attr_name, arg_name))
                names_for_globals[
                    _init_converter_pat.format(a.name)
                ] = a.converter
            else:
                lines.append(fmt_setter(attr_name, arg_name))

        if a.init is True and a.converter is None and a.type is not None:
            annotations[arg_name] = a.type

    if attrs_to_validate:  # we can skip this if there are no validators.
        names_for_globals["_config"] = _config
        lines.append("if _config._run_validators is True:")
        for a in attrs_to_validate:
            val_name = "__attr_validator_{}".format(a.name)
            attr_name = "__attr_{}".format(a.name)
            lines.append(
                "    {}(self, {}, self.{})".format(val_name, attr_name, a.name)
            )
            names_for_globals[val_name] = a.validator
            names_for_globals[attr_name] = a
    if post_init:
        lines.append("self.__attrs_post_init__()")

    # because this is set only after __attrs_post_init is called, a crash
    # will result if post-init tries to access the hash code.  This seemed
    # preferable to setting this beforehand, in which case alteration to
    # field values during post-init combined with post-init accessing the
    # hash code would result in silent bugs.
    if cache_hash:
        if frozen:
            if slots:
                # if frozen and slots, then _setattr defined above
                init_hash_cache = "_setattr('%s', %s)"
            else:
                # if frozen and not slots, then _inst_dict defined above
                init_hash_cache = "_inst_dict['%s'] = %s"
        else:
            init_hash_cache = "self.%s = %s"
        lines.append(init_hash_cache % (_hash_cache_field, "None"))

    # For exceptions we rely on BaseException.__init__ for proper
    # initialization.
    if is_exc:
        vals = ",".join("self." + a.name for a in attrs if a.init)

        lines.append("BaseException.__init__(self, %s)" % (vals,))

    args = ", ".join(args)
    if kw_only_args:
        if PY2:
            raise PythonTooOldError(
                "Keyword-only arguments only work on Python 3 and later."
            )

        args += "{leading_comma}*, {kw_only_args}".format(
            leading_comma=", " if args else "",
            kw_only_args=", ".join(kw_only_args),
        )
    return (
        """\
def __init__(self, {args}):
    {lines}
""".format(
            args=args, lines="\n    ".join(lines) if lines else "pass"
        ),
        names_for_globals,
        annotations,
    )
1268634
def main():
    """"""

    parser = argparse.ArgumentParser()
    parser.add_argument('-o', '--outfile', metavar='output_file_path',
                        help="Save calltree stats to <outfile>")
    parser.add_argument('-i', '--infile', metavar='input_file_path',
                        help="Read Python stats from <infile>")
    parser.add_argument('-k', '--kcachegrind',
                        help="Run the kcachegrind tool on the converted data",
                        action="store_true")
    parser.add_argument('-r', '--run-script',
                        nargs=argparse.REMAINDER,
                        metavar=('scriptfile', 'args'),
                        dest='script',
                        help="Name of the Python script to run to collect"
                        " profiling data")
    args = parser.parse_args()

    outfile = args.outfile

    if args.script is not None:
        # collect profiling data by running the given script
        if not args.outfile:
            outfile = '%s.log' % os.path.basename(args.script[0])

        fd, tmp_path = tempfile.mkstemp(suffix='.prof', prefix='pyprof2calltree')
        os.close(fd)
        try:
            cmd = [
                sys.executable,
                '-m', 'cProfile',
                '-o', tmp_path,
            ]
            cmd.extend(args.script)
            subprocess.check_call(cmd)

            kg = CalltreeConverter(tmp_path)
        finally:
            os.remove(tmp_path)

    elif args.infile is not None:
        # use the profiling data from some input file
        if not args.outfile:
            outfile = '%s.log' % os.path.basename(args.infile)

        if args.infile == outfile:
            # prevent name collisions by appending another extension
            outfile += ".log"

        kg = CalltreeConverter(pstats.Stats(args.infile))

    else:
        # at least an input file or a script to run is required
        parser.print_usage()
        sys.exit(2)

    if args.outfile is not None or not args.kcachegrind:
        # user either explicitly required output file or requested by not
        # explicitly asking to launch kcachegrind
        sys.stderr.write("writing converted data to: %s\n" % outfile)
        with open(outfile, 'w') as f:
            kg.output(f)

    if args.kcachegrind:
        sys.stderr.write("launching kcachegrind\n")
        kg.visualize()
565462
function initScriptMode () {
		//buffer source node
		let bufferNode = context.createBufferSource()
		bufferNode.loop = true
		bufferNode.buffer = new AudioBuffer(context, {length: samplesPerFrame, numberOfChannels: channels})

		node = context.createScriptProcessor(samplesPerFrame)
		node.addEventListener('audioprocess', function tick (e) {
			if (isStopped) return

			let buf = fetch(e.inputBuffer.length)

			util.copy(buf, e.outputBuffer)

			//measure the moment when we have fed all the data for the last cb
			//and trigger according callbacks
			consume(buf.length)
		})

		//start should be done after the connection, or there is a chance it won’t
		bufferNode.connect(node)
		bufferNode.start()

		return node;
	}
688818
def main():
    """"""

    parser = argparse.ArgumentParser()
    parser.add_argument("--input_dir", help="The Input file directory", default="doc_templates/")
    parser.add_argument("--output_dir", help="Where to store the processed files", default="current_docs/")
    parser.add_argument("--java_src_dir", help="Where Java snippet source files are located",
                        default="src/test/java/io/improbable/snippet/")
    parser.add_argument("--python_src_dir", help="Where Python snippet source files are located",
                        default="src/test/python/")
    parser.add_argument("--debug", action='store_true', help="Turn on script debugging")

    args = parser.parse_args()
    if args.debug:
        logging.basicConfig(level=logging.DEBUG)

    snippet_store = {}
    for_all_files_in_dir(args.java_src_dir, lambda x: read_file_snippets(args.java_src_dir + x, snippet_store))
    for_all_files_in_dir(args.python_src_dir, lambda x: read_file_snippets(args.python_src_dir + x, snippet_store))
    stripped_snippet_store = {k: strip_block_whitespace(v) for k, v in snippet_store.items()}
    printd(str(stripped_snippet_store))
    check_output_dir_exists(args.output_dir)
    for_all_in_subdirs(args.input_dir, lambda x: do_rewrites(x,
                                                             args.input_dir,
                                                             args.output_dir,
                                                             stripped_snippet_store))
276246
def process(input_dir, output_dir, function):
        
        if not os.path.exists(output_dir):
            os.makedirs(output_dir)
        logger = log.get_global_console_logger()
        logger.info("Processing files in {}.".format(input_dir))
        input_file_names = os.listdir(input_dir)
        for input_file_name in input_file_names:
            logger.info("Processing {}.".format(input_file_name))
            input_file = os.path.join(input_dir, input_file_name)
            with codecs.open(input_file, "r", encoding="UTF-8") as f:
                input_string = f.read()
            output_string = function(input_string)
            output_file = os.path.join(output_dir, input_file_name)
            with codecs.open(output_file, "w", encoding="UTF-8") as f:
                f.write(output_string)
        logger.info("Saved processed files to {}.".format(output_dir))
1123239
def __finish_initializing(self):
        

        if self.args.debug or self.args.trace:
            # Set the console (StreamHandler) to allow debug statements.

            if self.args.debug:
                self.console.setLevel(logging.DEBUG)

            self.console.setFormatter(logging.Formatter('[%(levelname)s] %(asctime)s %(name)s - %(message)s'))

            # Set the global level to debug.
            if self.args.debug:
                self.log.setLevel(logging.DEBUG)

        if self.args.log or self.log_file:

            # Allow the user to override the default log file handler.
            try:
                self.log_file_handler = sys.modules['__main__'].log_file_handler(self.args.log or self.log_file)
            except Exception:
                self.log_file_handler = logging.FileHandler(self.args.log or self.log_file)

            self.log_file_handler.setFormatter(logging.Formatter('[%(levelname)s] %(asctime)s %(name)s - %(message)s'))
            self.log_file_handler.setLevel(logging.DEBUG)

            self.log.addHandler(self.log_file_handler)

        # Allow cli.log, args & self to be accessed from __main__
        if not hasattr(sys.modules['__main__'], 'log'):
            sys.modules['__main__'].log = self.log

        if not hasattr(sys.modules['__main__'], 'cli'):
            sys.modules['__main__'].cli = self

        if not hasattr(sys.modules['__main__'], 'args'):
            sys.modules['__main__'].args = self.args