Provide the entry point to the subreddit_stats command.
427656
def main():
    """"""
    parser = arg_parser(usage='usage: %prog [options] SUBREDDIT VIEW')
    parser.add_option('-c', '--commenters', type='int', default=10,
                      help='Number of top commenters to display '
                      '[default %default]')
    parser.add_option('-d', '--distinguished', action='store_true',
                      help=('Include distinguished subissions and '
                            'comments (default: False). Note that regular '
                            'comments of distinguished submissions will still '
                            'be included.'))
    parser.add_option('-s', '--submitters', type='int', default=10,
                      help='Number of top submitters to display '
                      '[default %default]')

    options, args = parser.parse_args()

    if options.verbose == 1:
        logger.setLevel(logging.INFO)
    elif options.verbose > 1:
        logger.setLevel(logging.DEBUG)
    else:
        logger.setLevel(logging.NOTSET)
    logger.addHandler(logging.StreamHandler())

    if len(args) != 2:
        parser.error('SUBREDDIT and VIEW must be provided')
    subreddit, view = args
    check_for_updates(options)
    srs = SubredditStats(subreddit, options.site, options.distinguished)
    result = srs.run(view, options.submitters, options.commenters)
    if result:
        print(result.permalink)
    return 0
1293508
def main(news_dir=None):
    """"""
    if news_dir is None:
        from generate_news import news_dir
    news_dir = os.path.abspath(news_dir)

    # assume the name of the remote alias is just 'origin'
    remote_alias = 'origin'

    # figure out what the 'default branch' for the origin is
    origin_stats = subprocess.check_output(
        ['git', 'remote', 'show', remote_alias],
        cwd=news_dir
    ).decode()

    # the output of the git command looks like:
    # '  HEAD branch: master'
    origin_branch = 'master'  # unless we prove otherwise
    for line in origin_stats.splitlines():
        if 'head branch:' in line.lower():
            origin_branch = line.split(':', 1)[-1].strip()
            break

    origin = '%s/%s' % (remote_alias, origin_branch)

    # figure out the current branch
    current_branch = subprocess.check_output(
        ['git', 'rev-parse', '--abbrev-ref', 'HEAD'],
        cwd=news_dir
    ).decode().strip()

    print(':: Finding news in `%s` to add to remote `%s`' % (current_branch, origin))
    diff_command = ['git', 'diff', '%s...%s' % (origin, current_branch), '--name-status', news_dir]
    file_diff = subprocess.check_output(
        diff_command,
        cwd=news_dir
    ).decode()

    # the output of the git command looks like:
    # 'A       docs/news/789.feature'

    # [optional] ensure we have an addition, rather than just modify/delete
    added_news = [line for line in file_diff.splitlines() if line.lower().strip().startswith('a')]

    # pass or fail
    if not added_news:
        print(
            '! Error: Uh-oh, did not find any news files!\n'
            '! Please add a news file to `%s`\n'
            '+ File diff:\n%s\n'
            '{} Git diff command:\n`%s`\n' % (
                news_dir,
                file_diff.strip(),
                subprocess.list2cmdline(diff_command)
            )
        )
        exit(1)  # exit with an error status, no need for a traceback
    print(':: %s new files in `%s`' % (len(added_news), news_dir))
1247029
def initStats(self):
        """"""
        url = "%s://%s:%d/%s" % (self._proto, self._host, self._port, 
                                 self._statuspath)
        response = util.get_url(url, self._user, self._password)
        self._statusDict = {}
        for line in response.splitlines():
            mobj = re.match('\s*(\d+)\s+(\d+)\s+(\d+)\s*$', line)
            if mobj:
                idx = 0
                for key in ('accepts','handled','requests'):
                    idx += 1
                    self._statusDict[key] = util.parse_value(mobj.group(idx))
            else:
                for (key,val) in re.findall('(\w+):\s*(\d+)', line):
                    self._statusDict[key.lower()] = util.parse_value(val)
1180772
def stats(contents={}, &callback)
      send_request Request::Stats.new(contents) do |result|
        callback.call result

        if result[:status] == Errors::NO_ERROR && result[:key] != ''
          :proceed
        end
      end
    end
564877
def from_api_response(cls, reddit_session, json_dict):
        """"""
        # The Multireddit response contains the Subreddits attribute as a list
        # of dicts of the form {'name': 'subredditname'}.
        # We must convert each of these into a Subreddit object.
        json_dict['subreddits'] = [Subreddit(reddit_session, item['name'])
                                   for item in json_dict['subreddits']]
        return cls(reddit_session, None, None, json_dict)
798369
def init(self):
        """"""
        if not self.export_enable:
            return None
        # Build the RESTful URL where the stats will be posted
        url = '{}://{}:{}{}'.format(self.protocol,
                                    self.host,
                                    self.port,
                                    self.path)
        logger.info(
            "Stats will be exported to the RESTful endpoint {}".format(url))
        return url
585061
def cli(obj):
    """"""
    client = obj['client']
    metrics = client.mgmt_status()['metrics']
    headers = {'title': 'METRIC', 'type': 'TYPE', 'name': 'NAME', 'value': 'VALUE', 'average': 'AVERAGE'}
    click.echo(tabulate([{
        'title': m['title'],
        'type': m['type'],
        'name': '{}.{}'.format(m['group'], m['name']),
        'value': m.get('value', None) or m.get('count', 0),
        'average': int(m['totalTime']) * 1.0 / int(m['count']) if m['type'] == 'timer' else None
    } for m in metrics], headers=headers, tablefmt=obj['output']))
852917
def get_popular_subreddits(self, *args, **kwargs):
        
        url = self.config['popular_subreddits']
        return self.get_content(url, *args, **kwargs)
712521
def main(args=None):
    """"""
    if args is None:
        args = sys.argv[1:]

    parser = argparse.ArgumentParser(
        description='Makes UCL PHAS results better')
    parser.add_argument('--input', '-i',
                        type=str, help="csv file to import")
    parser.add_argument('--format', '-f', type=str,
                        help="reformats results by module and exports it to file specified")
    parser.add_argument('--plot', '-p', action='store_true',
                        help="plot the module results")
    parser.add_argument('--exportplots', '-ep', type=str,
                        help="export all plots to /path/you/want/")
    parser.add_argument('--showplots', '-sp',
                        action='store_true', help="show all plots")
    parser.add_argument(
        '--my', '-m', action="store_true", help="returns your weighted average for the year")
    parser.add_argument('--year', '-y', help="specify your year")
    parser.add_argument('--rank', '-r', action='store_true',
                        help="returns your rank in the year")
    parser.add_argument('--candidate', '-c',
                        help="specify your candidate number")
    args = parser.parse_args()

    #########################
    #                       #
    #         end           #
    #       argparse        #
    #                       #
    #                       #
    #########################
    resultr.main(args)
1123314
def load_subcommand(subparsers):
    
    parser_analyze = subparsers.add_parser('analyze', help='Analyze uwsgi log to get report')
    parser_analyze.add_argument('-f', '--filepath', type=argparse.FileType('r'), dest='filepath',
                                help='Path of uwsgi log file', required=True)
    parser_analyze.add_argument('--output', dest="output", type=argparse.FileType('w'), default=sys.stdout, 
                                help='HTML report file path')
    parser_analyze.add_argument('--min-msecs', dest="min_msecs", type=int, default=200,
                                help='Request serve time lower than this value will not be counted, default: 200')
    parser_analyze.add_argument('--domain', dest="domain", type=str, required=False,
                                help='Make url in report become a hyper-link by settings a domain')
    parser_analyze.add_argument('--url-file', dest="url_file", type=argparse.FileType('r'), required=False, 
                                help='Customized url rules in regular expression')
    parser_analyze.add_argument('--limit-url-groups', dest="limit_url_groups", type=int, required=False, 
                                default=LIMIT_URL_GROUPS, help='Number of url groups considered, default: 200')
    parser_analyze.add_argument('--limit-per-url-group', dest="limit_per_url_group", type=int,
                                required=False, default=LIMIT_PER_URL_GROUP,
                                help='Number of urls per group considered, default: 20')
    parser_analyze.set_defaults(func=analyze)
858386
def cmd(send, msg, args):
    
    if msg and not check_exists(msg):
        send("Non-existant subreddit.")
        return
    subreddit = msg if msg else None
    send(random_post(subreddit, args['config']['api']['bitlykey']))
319162
def main(**kwargs):
    
    draw_lines()
    draw_histogram()
    draw_bar_chart()
    destination = "-r /report"
    if use_html:
        generate_html()
        command = "dx-build-report-html {h} {d}".format(h=html_filename, d=destination)
    else:
        command = "dx-build-report-html {l} {b} {h} {d}".format(l=lines_filename, b=bars_filename, h=histogram_filename, d=destination)
    sub_output = json.loads(subprocess.check_output(command, shell=True))
    output = {}
    output["report"] = dxpy.dxlink(sub_output["recordId"])
    return output
615208
def main(argv=None):
    """"""

    # If we're invoked directly (runwith ...), we'll get None here.
    if argv is None:
        argv = sys.argv[1:]

    # Parse command-line arguments.
    argv = cli.parse_args(argv)

    # Translate CLI arguments to Popen options.
    options = {}
    for k in ('stdin', 'stdout', 'stderr', 'cwd'):
        v = getattr(argv, k, None)
        if v:
            options[k] = v

    # Start the child process.
    try:
        process = subprocess.Popen(
            argv.command, **options
        )
    except OSError:
        print('Invalid command %r.' % argv.command)
        sys.exit(2)

    # Wait for the child process to complete.
    thread = threading.Thread(target=process.wait)
    thread.start()
    if argv.time_limit is None:
        thread.join()
    else:
        thread.join(argv.time_limit.total_seconds())
    if thread.is_alive() and argv.grace_time:
        process.send_signal(SIGKILL)
        thread.join(argv.grace_time.total_seconds())
    if thread.is_alive():
        process.terminate()
        thread.join()
    status = process.returncode
    assert status is not None

    # Forward exit code.
    return status
1252210
def load_subcommand(subparsers):
    """"""
    parser_analyze = subparsers.add_parser('echo_conf', help='Echo sample configuration file')
    parser_analyze.set_defaults(func=echo_conf)
1142749
def main():
    
    parser = getBasicOptionParser()
    initializeOptions(parser)
    options = parseBasicOptions(parser)
    checkOptions(options, parser)
    config = Config()
    config.setOptions(options)
    jobStore = Toil.resumeJobStore(config.jobStore)
    stats = getStats(jobStore)
    collatedStatsTag = processData(jobStore.config, stats)
    reportData(collatedStatsTag, options)
166162
def display(self, stats, cs_status=None):
        
        # Init the internal line/column for Glances Curses
        self.init_line_column()

        # Get the current screen size
        screen_x = self.screen.getmaxyx()[1]
        screen_y = self.screen.getmaxyx()[0]
        stats_max = screen_y - 3
        stats_len = len(stats)

        self._page_max_lines = stats_max
        self._page_max = int(math.ceil(stats_len / stats_max))
        # Init position
        x = 0
        y = 0

        # Display top header
        if stats_len == 0:
            if self.first_scan and not self.args.disable_autodiscover:
                msg = 'Glances is scanning your network. Please wait...'
                self.first_scan = False
            else:
                msg = 'No Glances server available'
        elif len(stats) == 1:
            msg = 'One Glances server available'
        else:
            msg = '{} Glances servers available'.format(stats_len)
        if self.args.disable_autodiscover:
            msg += ' (auto discover is disabled)'
        if screen_y > 1:
            self.term_window.addnstr(y, x,
                                     msg,
                                     screen_x - x,
                                     self.colors_list['TITLE'])

            msg = '{}'.format(self._get_status_count(stats))
            self.term_window.addnstr(y + 1, x,
                                     msg,
                                     screen_x - x)

        if stats_len > stats_max and screen_y > 2:
            msg = '{} servers displayed.({}/{}) {}'.format(self.get_pagelines(stats),
                                                            self._current_page + 1, 
                                                            self._page_max, 
                                                            self._get_status_count(stats))
            self.term_window.addnstr(y + 1, x,
                                     msg,
                                     screen_x - x)
        
        if stats_len == 0:
            return False

        # Display the Glances server list
        # ================================

        # Table of table
        # Item description: [stats_id, column name, column size]
        column_def = [
            ['name', 'Name', 16],
            ['alias', None, None],
            ['load_min5', 'LOAD', 6],
            ['cpu_percent', 'CPU%', 5],
            ['mem_percent', 'MEM%', 5],
            ['status', 'STATUS', 9],
            ['ip', 'IP', 15],
            # ['port', 'PORT', 5],
            ['hr_name', 'OS', 16],
        ]
        y = 2

        # Display table header
        xc = x + 2
        for cpt, c in enumerate(column_def):
            if xc < screen_x and y < screen_y and c[1] is not None:
                self.term_window.addnstr(y, xc,
                                         c[1],
                                         screen_x - x,
                                         self.colors_list['BOLD'])
                xc += c[2] + self.space_between_column
        y += 1

        # If a servers has been deleted from the list...
        # ... and if the cursor is in the latest position
        if self.cursor > len(stats) - 1:
            # Set the cursor position to the latest item
            self.cursor = len(stats) - 1

        stats_list = self._get_stats(stats)
        start_line = self._page_max_lines * self._current_page 
        end_line = start_line + self.get_pagelines(stats_list)
        current_page = stats_list[start_line:end_line]
        
        # Display table
        line = 0
        for v in current_page:
            # Limit the number of displayed server (see issue #1256)
            if line >= stats_max:
                continue
            # Get server stats
            server_stat = {}
            for c in column_def:
                try:
                    server_stat[c[0]] = v[c[0]]
                except KeyError as e:
                    logger.debug(
                        "Cannot grab stats {} from server (KeyError: {})".format(c[0], e))
                    server_stat[c[0]] = '?'
                # Display alias instead of name
                try:
                    if c[0] == 'alias' and v[c[0]] is not None:
                        server_stat['name'] = v[c[0]]
                except KeyError:
                    pass

            # Display line for server stats
            cpt = 0
            xc = x

            # Is the line selected ?
            if line == self.cursor:
                # Display cursor
                self.term_window.addnstr(
                    y, xc, ">", screen_x - xc, self.colors_list['BOLD'])

            # Display the line
            xc += 2
            for c in column_def:
                if xc < screen_x and y < screen_y and c[1] is not None:
                    # Display server stats
                    self.term_window.addnstr(
                        y, xc, format(server_stat[c[0]]), c[2], self.colors_list[v['status']])
                    xc += c[2] + self.space_between_column
                cpt += 1
            # Next line, next server...
            y += 1
            line += 1

        return True
1138417
def main(command_line_arguments=None):
  """"""

  args = command_line_options(command_line_arguments)

  # get some colors for plotting
  cmap = mpl.cm.get_cmap(name='hsv')
  count = len(args.files) + (len(args.baselines) if args.baselines else 0)
  colors = [cmap(i) for i in numpy.linspace(0, 1.0, count+1)]

  # First, read the score files
  logger.info("Loading %d score files" % len(args.files))

  scores = [read_score_file(os.path.join(args.directory, f)) for f in args.files]

  false_alarms = []
  detection_rate = []
  logger.info("Computing FROC curves")
  for score in scores:
    # compute some thresholds
    tmin = min(score[2])
    tmax = max(score[2])
    count = 100
    thresholds = [tmin + float(x)/count * (tmax - tmin) for x in range(count+2)]
    false_alarms.append([])
    detection_rate.append([])
    for threshold in thresholds:
      detection_rate[-1].append(numpy.count_nonzero(numpy.array(score[1]) >= threshold) / float(score[0]))
      false_alarms[-1].append(numpy.count_nonzero(numpy.array(score[2]) >= threshold))
    # to display 0 in a semilogx plot, we have to add a little
#    false_alarms[-1][-1] += 1e-8

  # also read baselines
  if args.baselines is not None:
    for baseline in args.baselines:
      dr = []
      fa = []
      with open(os.path.join(args.baseline_directory, baseline)) as f:
        for line in f:
          splits = line.rstrip().split()
          dr.append(float(splits[0]))
          fa.append(int(splits[1]))
      false_alarms.append(fa)
      detection_rate.append(dr)

  logger.info("Plotting FROC curves to file '%s'", args.output)
  # create a multi-page PDF for the ROC curve
  pdf = PdfPages(args.output)
  figure = _plot_froc(false_alarms, detection_rate, colors, args.legends, args.title, args.max)
  mpl.xlabel('False Alarm (of %d pruned)' % len(scores[0][2]))
  mpl.ylabel('Detection Rate in \%% (total %d faces)' % scores[0][0])
  pdf.savefig(figure)
  pdf.close()

  if args.count_detections:
    for i, f in enumerate(args.files):
      det, all = count_detections(f)
      print("The number of detected faces for %s is %d out of %d" % (args.legends[i], det, all))