当前位置: 首页>>代码示例>>Python>>正文


Python utils.parse函数代码示例

本文整理汇总了Python中utils.parse函数的典型用法代码示例。如果您正苦于以下问题:Python parse函数的具体用法?Python parse怎么用?Python parse使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了parse函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: cutActivity

def cutActivity(row):
    fromdate = utils.parse(row[2])
    todate = utils.parse(row[3])
    # print fromdate, todate
    if (todate.date() - fromdate.date()).days != 1:
        print "error cutting activity: wrong date range"
        return [0, 0]
    else:
        middate = copy.deepcopy(todate).replace(hour=0, minute=0, second=0)
        firsthalf = [row[0], utils.deltatohours(middate - fromdate), fromdate.isoformat(' '), middate.isoformat(' ')]
        secondhalf = [row[0], utils.deltatohours(todate - middate), middate.isoformat(' '), todate.isoformat(' ')]
        # print firsthalf, secondhalf
        return [firsthalf, secondhalf]
开发者ID:ilcn,项目名称:time_analysis,代码行数:13,代码来源:analyze.py

示例2: join

 def join(self, layer_attr, data_table, data_attr, prefix=''):
     """
     Joins a data table to this feature collection.
     """
     # Build first a dictionary for the layer attribute
     idx = {}
     for feat in self.features:
         idx[parse(feat['properties'][layer_attr])] = feat
     # Now go through the data table and retrieve all data one by one
     for d in data_table:
         feat = idx.get(parse(d[data_attr]), None)
         if feat is None: continue
         for k in d:
             feat['properties'][prefix+k] = parse(d[k])
开发者ID:christiankaiser,项目名称:themavis,代码行数:14,代码来源:layer.py

示例3: rewriteQuestion

	def rewriteQuestion(inputSentence, addWHword = False):
		utils = RewriterUtils()
		utils.parse(inputSentence)
		vbzIndex = QuestionRewriter.getTheIndexOfVBZ(utils.wordList, utils.posMap)
		if vbzIndex == -1:
			raise Exception("No VBZ found!")

		rewrittenQuestion = [] 
		for i in xrange(vbzIndex + 1, len(utils.wordList)):
			rewriteQuestion.append(util.wordList[i])
		if addWHword:
			rewrittenQuestion.append(utils.wordList[vbzIndex])
		for i in xrange(0, vbzIndex):
			rewrittenQuestion.append(utils.wordList[i])
		return rewrittenQuestion
开发者ID:cuijiaxing,项目名称:nlp,代码行数:15,代码来源:question_rewriter.py

示例4: main

def main():
    usage = "usage: follow.py <search>"
    opts = utils.parse(sys.argv[1:], {}, ".splunkrc", usage=usage)

    if len(opts.args) != 1:
        utils.error("Search expression required", 2)
    search = opts.args[0]

    service = client.connect(**opts.kwargs)

    job = service.jobs.create(search, earliest_time="rt", latest_time="rt", search_mode="realtime")

    # Wait for the job to transition out of QUEUED and PARSING so that
    # we can if its a transforming search, or not.
    while True:
        job.refresh()
        if job["dispatchState"] not in ["QUEUED", "PARSING"]:
            break
        time.sleep(2)  # Wait

    if job["reportSearch"] is not None:  # Is it a transforming search?
        count = lambda: int(job["numPreviews"])
        items = lambda _: job.preview()
    else:
        count = lambda: int(job["eventCount"])
        items = lambda offset: job.events(offset=offset)

    try:
        follow(job, count, items)
    except KeyboardInterrupt:
        print "\nInterrupted."
    finally:
        job.cancel()
开发者ID:rsommer,项目名称:splunk-sdk-python,代码行数:33,代码来源:follow.py

示例5: main

def main(argv):
    weeks = []
    sessions = []

    with open('weeks.csv', newline='') as csvfile:
        weeksreader = reader(csvfile, quotechar='"')
        weeks = make_weeks(weeksreader)

    with open('tt.csv', newline='') as csvfile:
        ttreader = reader(csvfile, quotechar='"')
        errors = []
        sessions = parse(ttreader, config.MODULES, weeks, errors)
        for i, error in enumerate(errors):
            if i == len(error) - 1:
                print(error[0] + '\n' + error[1])
            else:
                print(error[0] + '\n' + error[1] + '\n')

    calendar = []
    calendar.append(['Subject', 'Start Date', 'End Date',
                    'Start Time', 'End Time', 'Location'])
    for session in sessions:
        calendar.append([
            session.title + '-' + session.kind,
            session.start.strftime('%Y/%m/%d'),
            session.end.strftime('%Y/%m/%d'),
            session.start.strftime('%H:%M'),
            session.end.strftime('%H:%M'),
            session.location
        ])

    with open('parsed.csv', 'w', newline='') as csvfile:
        csvwriter = writer(csvfile, delimiter=',', quotechar='"',
                           quoting=QUOTE_MINIMAL)
        csvwriter.writerows(calendar)
开发者ID:maxf130,项目名称:timetable_parser,代码行数:35,代码来源:tt-parse.py

示例6: main

def main():
    """ main entry """
    options = parse(sys.argv[1:], CLIRULES, ".splunkrc")

    if options.kwargs['omode'] not in OUTPUT_MODES:
        print "output mode must be one of %s, found %s" % (OUTPUT_MODES,
              options.kwargs['omode'])
        sys.exit(1)

    service = connect(**options.kwargs)

    if path.exists(options.kwargs['output']):
        if options.kwargs['recover'] == False:
            error("Export file exists, and recover option nor specified")
        else:
            options.kwargs['end'] = recover(options)
            options.kwargs['fixtail'] = True
            openmode = "a"
    else:
        openmode = "w"
        options.kwargs['fixtail'] = False
        
    try:
        options.kwargs['fd'] = open(options.kwargs['output'], openmode)
    except IOError:
        print "Failed to open output file %s w/ mode %s" % \
                             (options.kwargs['output'], openmode)
        sys.exit(1)

    export(options, service)
开发者ID:chiehwen,项目名称:splunk-sdk-python,代码行数:30,代码来源:export.py

示例7: main

def main():
    usage = "usage: %prog <search>"
    opts = utils.parse(sys.argv[:], {}, ".splunkrc", usage=usage)
    
    service = connect(**opts.kwargs)

    try:
        result = service.get(
            "search/jobs/export",
            search="search instantaneous_eps",
            index="_internal",
            earliest_time="rt", 
            latest_time="rt", 
            search_mode="realtime")

        for result in ResultsReader(result.body):
            
            if result is not None:
                if isinstance(result, dict):
        
                        # extract only the event contents
                        event=result.items()[2][1]
                        # strip out the leading timestamp files, they don't read well
                        shorte=event[61:]
                        # send the shortened event contents to the speech synth
                        subprocess.call(["/usr/bin/say", shorte])
                        
    except KeyboardInterrupt:
        print "\nInterrupted."
开发者ID:DoubleDensity,项目名称:splunk-speak,代码行数:29,代码来源:epsmon.py

示例8: test_sample_1

    def test_sample_1(self):
        graph = parse('sample-1.txt')

        result = karger(graph)
        ans = 2

        self.assertEqual(ans, result)
开发者ID:SHLo,项目名称:algorithms,代码行数:7,代码来源:test.py

示例9: main

def main(argv):
    usage = "usage: %prog [options]"

    redirect_port_args = {
        "redirectport": {
            "flags": ["--redirectport"],
            "default": PORT,
            "help": "Port to use for redirect server (default: %s)" % PORT,
        },
    }

    opts = utils.parse(argv, redirect_port_args, ".splunkrc", usage=usage)

    args = [("scheme", opts.kwargs["scheme"]),
            ("host", opts.kwargs["host"]),
            ("port", opts.kwargs["port"]),
            ("redirecthost", "localhost"),
            ("redirectport", opts.kwargs["redirectport"]),
            ("username", opts.kwargs["username"]),
            ("password", opts.kwargs["password"])]
    if 'app' in opts.kwargs.keys():
        args.append(('app', opts.kwargs['app']))
    if 'owner' in opts.kwargs.keys():
        args.append(('owner', opts.kwargs['owner']))

    # Encode these arguments
    args = urllib.urlencode(args)

    # Launch the browser
    webbrowser.open("file://%s" % os.path.join(os.getcwd(), "explorer.html?%s" % args))

    # And server the files
    server.serve(opts.kwargs["redirectport"])
开发者ID:Anlim,项目名称:splunk-sdk-python,代码行数:33,代码来源:explorer.py

示例10: main

def main():
    usage = ""

    argv = sys.argv[1:]

    splunk_opts = utils.parse(argv, {}, ".splunkrc", usage=usage)
    tracker = AnalyticsTracker("cli_app", splunk_opts.kwargs)
开发者ID:Anlim,项目名称:splunk-sdk-python,代码行数:7,代码来源:input.py

示例11: test_10

    def test_10(self):
        ans = -8448

        nums = parse('test10.txt')
        result = median_maintenance(nums)

        self.assertEqual(ans, result)
开发者ID:SHLo,项目名称:algorithms,代码行数:7,代码来源:test.py

示例12: main

def main(argv):
    usage = "usage: %prog [options]"
    opts = parse(argv, {}, ".splunkrc", usage=usage)
    service = client.connect(**opts.kwargs)

    for logger in service.loggers:
        print "%s (%s)" % (logger.name, logger['level'])
开发者ID:archankr,项目名称:splunk-sdk-python,代码行数:7,代码来源:loggers.py

示例13: main

def main():
    """Main program."""

    usage = "usage: %prog [options] <command> [<args>]"

    argv = sys.argv[1:]

    command = None
    commands = ['create', 'delete', 'list']

    # parse args, connect and setup 
    opts = parse(argv, {}, ".splunkrc", usage=usage)
    service = connect(**opts.kwargs)
    program = Program(service)

    if len(opts.args) == 0:
        # no args means list
        command = "list"
    elif opts.args[0] in commands:
        # args and the first in our list of commands, extract 
        # command and remove from regular args
        command = opts.args[0]
        opts.args.remove(command)
    else:
        # first one not in our list, default to list
        command = "list"

    program.run(command, opts)
开发者ID:apanda,项目名称:splunk-sdk-python,代码行数:28,代码来源:conf.py

示例14: setUpClass

    def setUpClass(cls):
        cls.opts = parse([], {}, ".splunkrc")

        # Before we start, make sure splunk doesn't need a restart.
        service = client.connect(**cls.opts.kwargs)
        if service.restart_required:
            service.restart(timeout=120)
开发者ID:Jaykul,项目名称:splunk-sdk-python,代码行数:7,代码来源:testlib.py

示例15: main

def main():
    usage = ""

    argv = sys.argv[1:]

    opts = utils.parse(argv, {}, ".splunkrc", usage=usage)
    retriever = AnalyticsRetriever(opts.args[0], opts.kwargs)    
开发者ID:larrys,项目名称:splunk-sdk-python,代码行数:7,代码来源:output.py


注:本文中的utils.parse函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。