Starts a server to render the specified file or directory containing a README.
517968
def watch(directory=None, auto_clear=False, extensions=[]):
    """"""
    if directory and not os.path.isdir(directory):
        raise ValueError('Directory not found: ' + directory)
    directory = os.path.abspath(directory)

    # Initial run
    event_handler = ChangeHandler(directory, auto_clear, extensions)
    event_handler.run()

    # Setup watchdog
    observer = Observer()
    observer.schedule(event_handler, path=directory, recursive=True)
    observer.start()

    # Watch and run tests until interrupted by user
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()
573976
function start(data, json) {
  if (typeof data == "string")
    data = [data];

  data = data.map(function(item) {
    var _relative = path.dirname(path.relative(json.dataDir, item));
    var _output = path.basename(item, ".md") + ".html";
    return {
      directory: _relative,
      data: item,
      output: _output,
      dataPath: path.resolve(json.dataDir, _relative, item),
      outputPath: path.resolve(json.outputDir, _relative, _output)
    };
  });

  function logError(err) {
    util.error("  %s❌ %s%s", c.bldred, c.txtrst, err);
  }

  data.forEach(function(item) {

    // Get the content from each data file.
    util.readfile(item.dataPath)
      .then(function(content) {
        util.info("- Parsing: %s%s%s", c.bldpur, item.dataPath, c.txtrst);
        return render(content);
      })
      .then(function(markFile) {
        return q.fcall(function () {
          // Change output location if specified in data file
          if (markFile.normal.meta && markFile.normal.meta.output) {
            item.output = markFile.normal.meta.output;
            item.outputPath = path.resolve(json.outputDir, item.directory, markFile.normal.meta.output);
            console.log(item.output, item.outputPath);
          }

          var template = item.template = determineTemplate(item, markFile, json);
          util.info("  Using template: %s", template);

          // Determine and compile the template
          try {
            var pugFn = pug.compileFile(template);

            // Render to HTML.
            return pugFn({
              $: markFile.normal.meta,
              html: markFile.normal.html,
              blocks: markFile,
              $$: markFile,
              markade: json
            });
          } catch(err) {
            if (err.code === "ENOENT") {
              throw new Error("There is no defined pug file for this markdown document");
            } else {
              throw err; // rethrow
            }
          }
        });
      })
      .then(function(html) {
        // Write the HTML file.
        return util.writefile(item.outputPath, html);
      })
      .then(function() {
        util.log("  %s✔ Compiled %s%s + %s = %s", c.bldgrn, c.txtrst, item.data, item.template, item.output);
      })
      .then(null, logError);
  });
}
930013
public void start() {
        stop(); // <-- If server is not running nothing happens.

        if (!isInitialized()) {
            onInit();
            server = __buildServer();
        }

        try {
            server.start();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
676731
void startFile(String src, PermissionStatus permissions,
                 String holder, String clientMachine,
                 boolean overwrite, boolean createParent, short replication, long blockSize
  ) throws IOException {
    INodeFileUnderConstruction file =
      startFileInternal(src, permissions, holder, clientMachine, overwrite, false,
      createParent, replication, blockSize);
    getEditLog().logSync(false);
    if (auditLog.isInfoEnabled()) {
      logAuditEvent(getCurrentUGI(),
        Server.getRemoteIp(),
        "create", src, null, file);
    }
  }
1004585
async function host(filename, options) {
    let files = [path.join(__dirname, "html")];
    if (options.assets) {
        files = [options.assets, ...files];
    }
    const server = new WebSocketHost({assets: files, port: options.port});
    let file;
    if (filename) {
        file = fs.readFileSync(filename).toString();
    } else {
        file = await read_stdin();
    }
    server.host_table("data_source_one", table(file));
    if (options.open) {
        open_browser(options.port);
    }
}
600095
def render_files(self, root=None):
        
        if root is None:
            tmp =  os.environ.get('TMP')
            root = sys.path[1 if tmp and tmp in sys.path else 0]
        items = []
        for filename in os.listdir(root):
            # for subdirname in dirnames:
            #     path = os.path.join(dirname, subdirname)
            #     items.append(FOLDER_TMPL.format(
            #         name=subdirname,
            #         id=path,
            #         items=self.render_files(path)
            #     ))
            #for filename in filenames:
            f,ext = os.path.splitext(filename)
            if ext in ['.py', '.enaml']:
                items.append(FILE_TMPL.format(
                    name=filename,
                    id=filename
                ))

        return "".join(items)
941852
def main(argv):
  """"""

  if flags.FLAGS.version:
    print("GRR server {}".format(config_server.VERSION["packageversion"]))
    return

  # We use .startswith so that multiple copies of services can easily be
  # created using systemd as worker1 worker2 ... worker25 etc.

  if not flags.FLAGS.component:
    raise ValueError("Need to specify which component to start.")

  # Start as a worker.
  if flags.FLAGS.component.startswith("worker"):
    worker.main([argv])

  # Start as a frontend that clients communicate with.
  elif flags.FLAGS.component.startswith("frontend"):
    frontend.main([argv])

  # Start as an AdminUI.
  elif flags.FLAGS.component.startswith("admin_ui"):
    admin_ui.main([argv])

  # Raise on invalid component.
  else:
    raise ValueError("No valid component specified. Got: "
                     "%s." % flags.FLAGS.component)
263726
def main():
    
    try:
        # Get the `src` directory's absolute path
        src_path = os.path.dirname(
            # `aoiklivereload` directory's absolute path
            os.path.dirname(
                # `demo` directory's absolute path
                os.path.dirname(
                    # This file's absolute path
                    os.path.abspath(__file__)
                )
            )
        )

        # If the `src` directory path is not in `sys.path`
        if src_path not in sys.path:
            # Add to `sys.path`.
            #
            # This aims to save user setting PYTHONPATH when running this demo.
            #
            sys.path.append(src_path)

        # Import reloader class
        from aoiklivereload import LiveReloader

        # Create reloader
        reloader = LiveReloader()

        # Start watcher thread
        reloader.start_watcher_thread()

        # Server host
        server_host = '0.0.0.0'

        # Server port
        server_port = 8000

        # Get message
        msg = '# ----- Run server -----\nHost: {}\nPort: {}'.format(
            server_host, server_port
        )

        # Print message
        print(msg)

        # Create Flask app
        flask_app = flask.Flask(__name__)

        # Create request handler
        @flask_app.route('/')
        def hello_handler():  # pylint: disable=unused-variable
            """
            Request handler.

            :return:
                Response body.
            """
            # Return response body
            return 'hello'

        # Run server
        flask_app.run(
            host=server_host,
            port=server_port,
            # Disable Flask's reloader
            debug=False,
        )

    # If have `KeyboardInterrupt`
    except KeyboardInterrupt:
        # Not treat as error
        pass
1060845
def _start(self):
        """"""
        assert self._tempdir is not None
        assert self._process is None
        self._process = subprocess.Popen(
            [
                self.paths.slapd,
                '-f', self._slapd_conf,
                '-h', self.uri,
                '-d', str(self.slapd_debug),
            ],
            stdout=sys.stdout,
            stderr=sys.stderr,
        )
        self._poll_slapd(timeout=self.max_server_startup_delay)
1369411
def render(template, dest, **kwargs):
    '''
    '''

    dest_dir = dirname(dest)
    if dest_dir and not exists(dest_dir):
        makedirs(dest_dir)

    template = environment.get_template(template)
    text = template.render(**kwargs)

    f = open(dest, 'wb')
    f.write(text.encode('utf-8'))
    f.close()
1231428
function start(object, filename) {
  var port = process.env.PORT || argv.port
  var hostname = argv.host === '0.0.0.0' ? 'localhost' : argv.host

  for (var prop in object) {
    console.log(chalk.gray('  http://' + hostname +  ':' + port + '/') + chalk.cyan(prop))
  }

  console.log(
    '\nYou can now go to ' + chalk.gray('http://' + hostname + ':' + port + '/\n')
  )

  console.log(
    'Enter ' + chalk.cyan('`s`') + ' at any time to create a snapshot of the db\n'
  )

  process.stdin.resume()
  process.stdin.setEncoding('utf8')
  process.stdin.on('data', function (chunk) {
    if (chunk.trim().toLowerCase() === 's') {
      var file = 'db-' + Date.now() + '.json'
      _db.save(object, file)
      console.log('\nSaved snapshot to ' + chalk.cyan(file) + '\n')
    }
  })

  if (filename) {
    var router = jsonServer.router(filename)
  } else {
    var router = jsonServer.router(object)
  }

  var server = jsonServer.create()
  server.use(jsonServer.defaults)
  server.use(router)
  server.listen(port, argv.host)
}
1189959
def render_requests_data_to_html(self, data, file_name, context={}):
        """"""
        file_path = os.path.join(self.html_dir, file_name)
        logger.info('Rendering HTML file %s...' % file_path)
        data = format_data(data)
        data.update(context)
        data.update(domain=self.domain)
        with open(file_path, 'w') as fp:
            fp.write(render_template('realtime.html', data))
157070
def render_text(path, cp):
    

    # define filename and slug from path
    filename = os.path.basename(path)
    slug = filename.replace('.', '_')

    # initializations
    content = None

    # read file as a string
    with codecs.open(path, 'r', encoding='utf-8', errors='replace') as fp:
        content = fp.read()

    # replace all the escaped characters
    content = unescape(content, unescape_table)

    # render template
    template_dir = pycbc.results.__path__[0] + '/templates/files'
    env = Environment(loader=FileSystemLoader(template_dir))
    env.globals.update(abs=abs)
    env.globals.update(path_exists=os.path.exists)
    template = env.get_template('file_pre.html')
    context = {'filename' : filename,
               'slug'     : slug,
               'cp'       : cp,
               'content'  : content}
    output = template.render(context)

    return output
1370090
public void run(String path, String port) {
        Server server = new Server();
        ServerConnector connector = new ServerConnector(server);
        connector.setHost("localhost");
        connector.setPort(Integer.parseInt(port));
        server.addConnector(connector);

        ResourceHandler resource_handler = new ResourceHandler();
        resource_handler.setDirectoriesListed(true);
        resource_handler.setWelcomeFiles(new String[]{"index.html"});

        resource_handler.setResourceBase(path);

        HandlerList handlers = new HandlerList();
        handlers.setHandlers(new Handler[]{resource_handler, new DefaultHandler()});
        server.setHandler(handlers);

        LOGGER.info("Serving out contents of: [{}] on http://localhost:{}/", path, port);
        LOGGER.info("(To stop server hit CTRL-C)");

        try {
            server.start();
            server.join();
        } catch (Exception e) {
            LOGGER.error("unable to start server", e);
        }
    }
811764
def _start_server(bindaddr, port, hostname, folder):
    """"""
    import asyncio
    from .httpserver import HttpProtocol
    loop = asyncio.get_event_loop()
    coroutine = loop.create_server(lambda: HttpProtocol(hostname, folder),
                                   bindaddr,
                                   port)
    server = loop.run_until_complete(coroutine)

    print('Starting server on {}'.format(server.sockets[0].getsockname()))
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass
601126
def render_file(self, filename):
        
        dirname, basename = split(filename)
        with changedir(dirname):
            infile = abspath(basename)
            outfile = abspath('.%s.html' % basename)
            self.docutils.publish_file(infile, outfile, self.styles)
            return outfile
185159
def render(file):
    """"""
    with file.open() as fp:
        encoding = detect_encoding(fp, default='utf-8')
        file_content = fp.read().decode(encoding)
        json_data = json.loads(file_content, object_pairs_hook=OrderedDict)
        return json.dumps(json_data, indent=4, separators=(',', ': '))