run the named generator and monitor the input and generator folder
555204
def _script_reload(script, input, output):
    """"""
    input = [Path(entry).expand().abspath() for entry in input]
    output = Path(output).expand().abspath()
    cmd = 'python3 {0} {1} {2}'.format(script, ' '.join(input), output)
    event_handler = RunScriptChangeHandler(cmd)
    event_handler.run()  # run always once
    observer = Observer()
    path = script.dirname().expand().abspath()
    click.secho('watch: {0}'.format(path), fg='blue')
    observer.schedule(event_handler, path, recursive=True)
    for entry in input:
        entry = entry.dirname().expand().abspath()
        click.secho('watch: {0}'.format(entry), fg='blue')
        observer.schedule(event_handler, entry, recursive=True)
    path = Path(__file__).parent / 'qface'
    click.secho('watch: {0}'.format(path), fg='blue')
    observer.schedule(event_handler, path, recursive=True)
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()
66446
def run_recursively_and_collect_multiple_changes(monitor, times, directory, *flags, &block)
      watch_and_run(monitor, times, true, directory, *flags, &block)
    end
73753
def run(self):
        

        #######################################################################
        # Config
        #######################################################################
        self.config = load_config(self.configfile)

        collectors = load_collectors(self.config['server']['collectors_path'])
        metric_queue_size = int(self.config['server'].get('metric_queue_size',
                                                          16384))
        self.metric_queue = self.manager.Queue(maxsize=metric_queue_size)
        self.log.debug('metric_queue_size: %d', metric_queue_size)

        #######################################################################
        # Handlers
        #
        # TODO: Eventually move each handler to it's own process space?
        #######################################################################

        if 'handlers_path' in self.config['server']:
            handlers_path = self.config['server']['handlers_path']

            # Make an list if not one
            if isinstance(handlers_path, basestring):
                handlers_path = handlers_path.split(',')
                handlers_path = map(str.strip, handlers_path)
                self.config['server']['handlers_path'] = handlers_path

            load_include_path(handlers_path)

        if 'handlers' not in self.config['server']:
            self.log.critical('handlers missing from server section in config')
            sys.exit(1)

        handlers = self.config['server'].get('handlers')
        if isinstance(handlers, basestring):
            handlers = [handlers]

        # Prevent the Queue Handler from being a normal handler
        if 'diamond.handler.queue.QueueHandler' in handlers:
            handlers.remove('diamond.handler.queue.QueueHandler')

        self.handlers = load_handlers(self.config, handlers)

        QueueHandler = load_dynamic_class(
            'diamond.handler.queue.QueueHandler',
            Handler
        )

        self.handler_queue = QueueHandler(
            config=self.config, queue=self.metric_queue, log=self.log)

        handlers_process = multiprocessing.Process(
            name="Handlers",
            target=handler_process,
            args=(self.handlers, self.metric_queue, self.log),
        )

        handlers_process.daemon = True
        handlers_process.start()

        #######################################################################
        # Signals
        #######################################################################

        if hasattr(signal, 'SIGHUP'):
            signal.signal(signal.SIGHUP, signal_to_exception)

        #######################################################################

        while True:
            try:
                active_children = multiprocessing.active_children()
                running_processes = []
                for process in active_children:
                    running_processes.append(process.name)
                running_processes = set(running_processes)

                ##############################################################
                # Collectors
                ##############################################################

                running_collectors = []
                for collector, config in self.config['collectors'].iteritems():
                    if config.get('enabled', False) is not True:
                        continue
                    running_collectors.append(collector)
                running_collectors = set(running_collectors)

                # Collectors that are running but shouldn't be
                for process_name in running_processes - running_collectors:
                    if 'Collector' not in process_name:
                        continue
                    for process in active_children:
                        if process.name == process_name:
                            process.terminate()

                collector_classes = dict(
                    (cls.__name__.split('.')[-1], cls)
                    for cls in collectors.values()
                )

                load_delay = self.config['server'].get('collectors_load_delay',
                                                       1.0)
                for process_name in running_collectors - running_processes:
                    # To handle running multiple collectors concurrently, we
                    # split on white space and use the first word as the
                    # collector name to spin
                    collector_name = process_name.split()[0]

                    if 'Collector' not in collector_name:
                        continue

                    if collector_name not in collector_classes:
                        self.log.error('Can not find collector %s',
                                       collector_name)
                        continue

                    collector = initialize_collector(
                        collector_classes[collector_name],
                        name=process_name,
                        configfile=self.configfile,
                        handlers=[self.handler_queue])

                    if collector is None:
                        self.log.error('Failed to load collector %s',
                                       process_name)
                        continue

                    # Splay the loads
                    time.sleep(float(load_delay))

                    process = multiprocessing.Process(
                        name=process_name,
                        target=collector_process,
                        args=(collector, self.metric_queue, self.log)
                    )
                    process.daemon = True
                    process.start()

                if not handlers_process.is_alive():
                    self.log.error('Handlers process exited')
                    if (str_to_bool(self.config['server'].get(
                            'abort_on_handlers_process_exit', 'False'))):
                        raise Exception('Handlers process exited')

                ##############################################################

                time.sleep(1)

            except SIGHUPException:
                # ignore further SIGHUPs for now
                original_sighup_handler = signal.getsignal(signal.SIGHUP)
                signal.signal(signal.SIGHUP, signal.SIG_IGN)

                self.log.info('Reloading state due to HUP')
                self.config = load_config(self.configfile)
                collectors = load_collectors(
                    self.config['server']['collectors_path'])
                # restore SIGHUP handler
                signal.signal(signal.SIGHUP, original_sighup_handler)
877006
def generate(self, cache_root):
        
        generator_cwd = os.path.join(cache_root, 'generated', self.vlnv.sanitized_name)
        generator_input_file  = os.path.join(generator_cwd, self.name+'_input.yml')

        logger.info('Generating ' + str(self.vlnv))
        if not os.path.exists(generator_cwd):
            os.makedirs(generator_cwd)
        with open(generator_input_file, 'w') as f:
            f.write(yaml.dump(self.generator_input))

        args = [os.path.join(os.path.abspath(self.generator.root), self.generator.command),
                generator_input_file]

        if self.generator.interpreter:
            args[0:0] = [self.generator.interpreter]

        Launcher(args[0], args[1:],
                 cwd=generator_cwd).run()

        cores = []
        logger.debug("Looking for generated cores in " + generator_cwd)
        for root, dirs, files in os.walk(generator_cwd):
            for f in files:
                if f.endswith('.core'):
                    try:
                        cores.append(Core(os.path.join(root, f)))
                    except SyntaxError as e:
                        w = "Failed to parse generated core file " + f + ": " + e.msg
                        raise RuntimeError(w)
        logger.debug("Found " + ', '.join(str(c.name) for c in cores))
        return cores
570500
def main():
    cmd = sys.argv
    cmd.pop(0)
    
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '-s',
        '--src',
        help='source folder to watch',
        default='.',
        dest='src',
        metavar='folder'
    )
    parser.add_argument(
        '-d',
        '--dest',
        help='source folder to watch',
        default=None,
        dest='dest',
        metavar='folder'
    )
    args = parser.parse_args()
    print 'Initializing...'
    config.source_dir = os.path.abspath(args.src)
    if args.dest != None:
        config.dest_dir = os.path.abspath(args.dest)
    init_sources(config.source_dir)
    if cmd:
        c = cmd[0]
        commands = globals()
        if c in commands:
            commands[c]()
1243759
def run_command(self, args=None, node_paths=None):
    """"""
    return command_gen(
      self.tool_installations,
      self.name,
      args=args,
      node_paths=node_paths
    )
902232
def run():
    """"""
    
    # Grab server args
    args = client_helper.grab_server_args()

    # Start up workbench connection
    workbench = zerorpc.Client(timeout=300, heartbeat=60)
    workbench.connect('tcp://'+args['server']+':'+args['port'])
    
    # Grab all the filenames from the data directory
    data_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)),'../data')
    file_list = all_files_in_directory(data_dir)

    # Upload the files into workbench
    md5_list = []
    for path in file_list:

        # Skip OS generated files
        if '.DS_Store' in path: 
            continue

        with open(path,'rb') as f:
            filename = os.path.basename(path)

            # Here we're going to save network traffic by asking
            # Workbench if it already has this md5
            raw_bytes = f.read()
            md5 = hashlib.md5(raw_bytes).hexdigest()
            md5_list.append(md5)
            if workbench.has_sample(md5):
                print 'Workbench already has this sample %s' % md5
            else:
                # Store the sample into workbench
                md5 = workbench.store_sample(raw_bytes, filename, 'unknown')
                print 'Filename %s uploaded: type_tag %s, md5 %s' % (filename, 'unknown', md5)

    # Okay now explode any container types
    zip_files = workbench.generate_sample_set('zip')
    _foo = workbench.set_work_request('unzip', zip_files); list(_foo) # See Issue #306
    pcap_files = workbench.generate_sample_set('pcap')
    _foo = workbench.set_work_request('pcap_bro', pcap_files); list(_foo) # See Issue #306
    mem_files = workbench.generate_sample_set('mem')
    _foo = workbench.set_work_request('mem_procdump', mem_files); list(_foo) # See Issue #306


    # Make sure all files are properly identified
    print 'Info: Ensuring File Identifications...'
    type_tag_set = set()
    all_files = workbench.generate_sample_set()
    meta_all = workbench.set_work_request('meta', all_files)
    for meta in meta_all:
        type_tag_set.add(meta['type_tag'])
        if meta['type_tag'] in ['unknown', 'own']:
            print meta
    pprint.pprint(type_tag_set)
40211
private void startFolderMonitor() {
    if (serverConfiguration.getAppFolderToMonitor() != null) {
      try {
        folderMonitor = new FolderMonitor(this, serverConfiguration);
        folderMonitor.start();
      } catch (IOException e) {
        log.warning("Could not monitor the given folder: "
            + serverConfiguration.getAppFolderToMonitor());
      }
    }
  }
1007835
def run(self):
        

        init_folder = os.getcwd()
        os.chdir(self.folder)

        with zopen(self.log_file, 'w') as fout:
            subprocess.call([self._NWCHEM2FIESTA_cmd, self._nwcheminput_fn,
                             self._nwchemoutput_fn, self._nwchemmovecs_fn],
                            stdout=fout)

        os.chdir(init_folder)
1257933
def run(self):
        """"""
        while True:
            data = self.queue.get()
            if data is None:
                Logger.get_logger(__name__).info("Stopping collector process ...")
                break

            # updating the report data
            self.store.update(data)
            # writing the report
            generate(self.store, 'html', os.getcwd())
608938
def watch_and_run(monitor, times, recursively, directory, *flags)
      result = OpenStruct.new(directory: directory, changes: [])
      i = 0
      result.changes[i] = OpenStruct.new(called: false)
      can_return = false
      callback = Proc.new do |change|
        next if can_return

        result.changes[i].called = true;
        result.changes[i].change = change

        i += 1

        if i < times
          result.changes[i] = OpenStruct.new(called: false)
        else
          can_return = true
        end
      end

      if recursively
        monitor.watch_recursively(directory, *flags, &callback)
      else
        monitor.watch(directory, *flags, &callback)
      end

      thread = Thread.new(monitor) { |m| m.run! }
      sleep(0.2) # give time for the monitor to bootup

      yield # So much boilerplate code to get here :S

      sleep(0.2) # allow the monitor to run the callbacks

      # Nothing can change after the callback if there is only one of them,
      # so never wait for one callback
      if times > 1
        until can_return
          sleep(0.1)
        end
      end

      return result
    ensure
      monitor.stop
      thread.join if thread
    end
369508
def run(self):
        
        run_command = (
            settings.project_customization.runfile.read_text().split()
        )
        chmod_string = (
            "chmod +x "
            + settings.project_customization.runfile.absolute().as_posix()
        )
        subprocess.run(chmod_string.split())
        subprocess.run(
            run_command, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr
        )
178058
def run_main(args: argparse.Namespace, do_exit=True) -> None:
    
    if args.init:
        generate()
        return None  # exit after generate instead of starting to lint

    handler = CheckHandler(
        file=args.config_file, out_json=args.json, files=args.files)

    for style in get_stylers():
        handler.run_linter(style())

    for linter in get_linters():
        handler.run_linter(linter())

    for security in get_security():
        handler.run_linter(security())

    for tool in get_tools():
        tool = tool()

        # Only run pypi if everything else passed
        if tool.name == "pypi" and handler.status_code != 0:
            continue

        handler.run_linter(tool)

    if do_exit:
        handler.exit()
    return handler.status_code
342783
public static void main(String args[])
   {
      try
      {
      // Create the monitor
      
      //FileMonitor fm = FileMonitor.createFileMonitor(args);
         FileMonitor.createFileMonitor(args);
      }
      catch(Exception e)
      {
         System.err.println("Unable monitor specified input error="+e);
         System.exit(-1);
      }
      // Avoid program exit
      while (!false)
      {
         try
         {
            Thread.sleep(1000);
         }
         catch(Exception e){e.printStackTrace();}
      }

   }
790871
def setup_run(self):
        
        self.state_execution_status = StateExecutionStatus.ACTIVE
        self.preempted = False
        if not isinstance(self.input_data, dict):
            raise TypeError("input_data must be of type dict")
        if not isinstance(self.output_data, dict):
            raise TypeError("output_data must be of type dict")
        self.check_input_data_type()
1054617
def run():
    """"""
    _parser_options()
    set_verbose(args["verbose"])
    
    if _check_global_settings():
        _load_db()
    else:
        exit(-1)

    #Check the server configuration against the script arguments passed in.
    _setup_server()

    if args["rollback"]:
        _server_rollback()
        okay("The server rollback appears to have been successful.")
        exit(0)

    _server_enable()    
    _list_repos()
    _handle_install()
    
    #This is the workhorse once a successful installation has happened.
    _do_cron()
522379
def main():
    """"""
    desc = 'Benchmark the files generated by generate.py'
    parser = argparse.ArgumentParser(description=desc)
    parser.add_argument(
        '--src',
        dest='src_dir',
        default='generated',
        help='The directory containing the sources to benchmark'
    )
    parser.add_argument(
        '--out',
        dest='out_dir',
        default='../../doc',
        help='The output directory'
    )
    parser.add_argument(
        '--include',
        dest='include',
        default='include',
        help='The directory containing the headeres for the benchmark'
    )
    parser.add_argument(
        '--boost_headers',
        dest='boost_headers',
        default='../../../..',
        help='The directory containing the Boost headers (the boost directory)'
    )
    parser.add_argument(
        '--compiler',
        dest='compiler',
        default='g++',
        help='The compiler to do the benchmark with'
    )
    parser.add_argument(
        '--repeat_count',
        dest='repeat_count',
        type=int,
        default=5,
        help='How many times a measurement should be repeated.'
    )

    args = parser.parse_args()

    compiler = compiler_info(args.compiler)
    results = benchmark(
        args.src_dir,
        args.compiler,
        [args.include, args.boost_headers],
        args.repeat_count
    )

    plot_diagrams(results, configs_in(args.src_dir), compiler, args.out_dir)