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


Python Helper类代码示例

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


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

示例1: calculate

def calculate(grid, maxdepth, is_it_max):
    if maxdepth == 0:
        return Helper.heuristic(grid)
    if not Helper.canMove(grid):
        return Helper.heuristic(grid)
    if is_it_max:
        v = -np.inf
        [children, moving] = Helper.getAvailableChildren(grid)
        for child in children:
            v = max(v,calculate(child,maxdepth-1,False))
        return v
    else:
        cells = [i for i, x in enumerate(grid) if x == 0]
        children = []
        v = np.inf
        for c in cells:
            gridcopy = list(grid)
            gridcopy[c]=2
            children.append(gridcopy)
            gridcopy = list(grid)
            gridcopy[c]=4
            children.append(gridcopy)
        for child in children:
            v = min(v,calculate(child,maxdepth-1,True))
        return v
开发者ID:ss4936,项目名称:2048,代码行数:25,代码来源:Minimax.py

示例2: classify

def classify(img, featureRepresentation='image', model_file=CLASSIFIER_FILE, shouldSaveResult=False):
    '''
    Classifies a sub-image or list of sub-images as grain (1) or not grain (0).

    Args:
        img: Input sub-image or list of input sub-images.

        featureRepresentation: Type of features to be used in classification.
            Can ake of one of the values 'image', 'pca' or 'glcm'. Note that the
            classifier must have also been built using the same
            feature representation.

        model_file: filepath of serialized classifier to be used.

        shouldSaveResult: If this boolean flag is set to true, this function
            will save the sub-images and their classifictions to the "Results"
            folder after classification.

    Return:
        scalar or list of 1 if grain and 0 otherwise.
    '''
    if(isinstance(img, np.ndarray)):
        img_features = None
        if(featureRepresentation == 'image'):
            img_features = img.flatten()
        elif(featureRepresentation == 'pca'):
            img_features = decomposition.PCA(n_components=8).fit_transform(img.flatten())
        elif(featureRepresentation == 'glcm'):
            img_features = Helper.get_textural_features(img, 1, True)
        clf = get_model(model_file)
        return clf.predict(img_features.reshape(1,-1))
    elif(isinstance(img, list)):
        if(featureRepresentation == 'glcm'):
            sample_size = 16
        else:
            sample_size = 20*20

        test_data = np.zeros((len(img), sample_size))
        i = 0
        for image in img:
            if(featureRepresentation == 'image'):
                test_data[i] = image.flatten()
            elif(featureRepresentation == 'pca'):
                test_data[i] = decomposition.PCA(n_components=8).fit_transform(image.flatten())
            elif(featureRepresentation == 'glcm'):
                test_data[i] = Helper.get_textural_features(image, 1, True)
            i = i+1

        clf = get_model(model_file)
        result = clf.predict(test_data)

        if(shouldSaveResult == True):
            # Save image with result in filename
            if os.path.exists("Results"):
                shutil.rmtree("Results")
            os.makedirs("Results")
            for i in xrange(0,len(img)):
                io.imsave("Results/{}_{}.png".format(Helper.generate_random_id(8), result[i]), img[i])
    else:
        return None
开发者ID:oduwa,项目名称:Wheat-Count,代码行数:60,代码来源:CNN.py

示例3: get_usercommand

 def get_usercommand(self):
     self.last_at_time = self.get_last_at_time()
     log("LAST_AT_TIME:%s" % self.last_at_time)
     self.last_at_time = Helper.str2date(self.last_at_time)
     try:
         list = self.api.mentions(5) #TODO: 5不靠谱.
         for listat in list:
             if listat.created_at>self.last_at_time:
                 if "[email protected]".decode("utf-8") in listat.text:
                     log("ReceiveCommand %s From %s!" % \
                         (listat.user.name, "zf"))
                     Helper.add_command_log(listat.user.name, "zf", listat.text, str(listat.created_at))
                     try:
                         retid = listat.retweeted_status.id
                     except:
                         retid = listat.id
                     self.repost_message(retid)
                 else:
                     log("ReceiveUnknownCommand.Text:%s" % listat.text)
             else:
                 log("Break Loop at %s" % str(listat.created_at))
                 break
     except:
         log("Get User Command Except Exception!")
         raise
     Helper.refresh_at_time()
开发者ID:HIT-Coder,项目名称:SmartWall,代码行数:26,代码来源:Poster.py

示例4: get_conversations

    def get_conversations(self, html):
        status = 0
        conversations = re.findall("<div class=\"c\">(.*?)</div>(?=<div class=\"(?:[cs])\"\>)", html)
        conversations = conversations[1:-2]
        parser = HTMLParser.HTMLParser()
        ret = []
        for conversation in conversations:
            item = {}
            tokens = re.findall(r'(.*?)<span class="ct">', conversation)[0]
            tokens = re.sub(r'<(?:.*?)>', '', tokens) # 去除html标记
            tokens = re.sub(r'\[(在线|忙碌|离开)\]', '', tokens) # 去除在线标记
            tokens = re.sub(r'\[\d+条新\]', '', tokens)
            tokens = re.split(r'&nbsp;', tokens)
            latest = tokens[3]
            latest = re.split(r':', latest, 1)[1]
            time = re.findall(r'<span class="ct">(.*?)</span>', conversation)[0]
            time = Helper.datetime_formater(time)
            cnt_datetime = Helper.str2date(time)
            if not cnt_datetime>self.last_time:
                status = 1
                return ret,status
            detail = re.findall(r'语音通话(?:.*?)<a href="(.*?)" class="cc">(?:.*?)</a>', conversation)[0]
            detail = parser.unescape(detail)+"&type=record"
            count = re.findall(r'共(\d+)条对话', conversation)[0]
            item.update(dict(p1=tokens[0],p2=tokens[2],latest=latest,time=time,detail=detail,count=count))
            ret.append(item)

        return ret,status
开发者ID:HIT-Coder,项目名称:SmartWall,代码行数:28,代码来源:Spider.py

示例5: summary

def summary(state):
    """
    Provides a summary of selected player

    :param state: current state of variables
    :return: prints a summary of the player
    """

    # Initialize variables
    stat_rankings = defaultdict(lambda: (defaultdict(float)))
    for player in state.normalized_player_statistics[state.iteration]:
        for statistic_name in state.normalized_player_statistics[state.iteration][player]:
            stat_rankings[statistic_name][player] = \
                state.normalized_player_statistics[state.iteration][player][statistic_name]

    # Decide which player to view the stats of
    while state.player_to_obtain is None:
        desired_player = raw_input("Enter a player name: ").lower()

        # If the input is valid, remove player from draft and add them to a team
        if desired_player in state.cumulative_player_statistics[state.iteration]:
            state.update_player_to_obtain(desired_player)

        # Suggests player names if input is incorrect
        else:
            Helper.check_incorrect_input(desired_player, state.normalized_player_statistics[state.iteration].keys())

    return Helper.calculate_player_summary(stat_rankings, state.player_to_obtain)
开发者ID:crsabbagh,项目名称:fantasy-bball,代码行数:28,代码来源:Services_old.py

示例6: run

    def run(self):
        message_url = "http://weibo.cn/msg/chat/list?tf=5_010&vt=4&gsid=%s" % self.gsid
        message_page = self._request(message_url).read()
        #TODO:
        try:
            total_page_count = int(re.findall(r'<input type="submit" value="跳页" />(?:.*?)/((?:\d)+)(?:.*?)</div>', message_page)[0])
        except:
            raise Exception("got an error!")
        log("TOTAL_PAGE_COUNT: %s" % total_page_count)
        page_index = 1
        conversations = self.get_conversations(message_page)

        while page_index<total_page_count:
            page_index += 1
            conversations.extend(self.fetch_conversations(page_index))
        log("Total %d Conversations!" % len(conversations))

        messages = []
        for conversation in conversations:
            peoples = [conversation["p1"],conversation["p2"]]
            detail = conversation["detail"]
            message_page = self._request(BASE_URL+detail).read()
            messages.extend(self.get_messages(message_page, peoples))
        log("Messages Total %d Counts!" % len(messages))
        Helper.save_2_sqlite(messages)
开发者ID:Sudy,项目名称:SmartWall,代码行数:25,代码来源:Spider.py

示例7: get_messages

 def get_messages(self, html, peoples):
     status = 0
     conversations = re.findall("<div class=\"c\">(.*?)</div>", html)
     conversations = conversations[2:-3]
     ret = []
     for conversation in conversations:
         msg = {}
         tokens = re.findall(r'(.*?)<span', conversation)[0]
         tokens = re.sub(r'<(?:.*?)>', '', tokens) # 去除html标记
         tokens = re.sub(r'\[(在线|忙碌|离开)\]', '', tokens) # 去除在线标记
         tokens = re.sub(r'\[\d+条新\]', '', tokens)
         tokens = re.split(r':', tokens, 1)
         people = tokens[0]
         message = tokens[1]
         time = re.findall(r'<span class="ct">(.*?)</span>', conversation)[0]
         time = Helper.datetime_formater(time)
         cnt_datetime = Helper.str2date(time)
         if not cnt_datetime>self.last_time:
             status = 1
             return ret,status
         if people == peoples[0]:
             msg["dst"] = peoples[1]
         else:
             msg["dst"] = peoples[0]
         msg["src"] = people
         msg["message"] = Helper.sql_escape(message)
         msg["time"] = time
         ret.append(msg)
     return ret, status
开发者ID:HIT-Coder,项目名称:SmartWall,代码行数:29,代码来源:Spider.py

示例8: resultfiletopairs

def resultfiletopairs(filename, outname):   
    print "init gene level proteins ..."    
    proteinsA, proteinsB, orthologs = GeneLevelProtein.initGeneLevelProteins(filename, None, None, False)

    print "pairwise orthology mappings ..."
    pairwise = Helper.pairwiseOrthologs(orthologs, proteinsA, proteinsB)      
    
    Helper.printPairsToFile(pairwise, outname)
开发者ID:expectopatronum,项目名称:orth-scripts,代码行数:8,代码来源:resultFileToPairs.py

示例9: _process

def _process(process):
    ''' Generate the code for a complete process (AST Top level) '''
    # In case model has nested states, flatten everything
    Helper.flatten(process)

    # Make an maping {input: {state: transition...}} in order to easily
    # generate the lookup tables for the state machine runtime
    mapping = Helper.map_input_state(process)
开发者ID:Kampbell,项目名称:opengeode,代码行数:8,代码来源:GenericBackend.py

示例10: info_online

 def info_online(self):
     """
     First good use of HELP_URL in addonpy template
     :return: Opens the Help URL in default browser
     """
     url = self.get_help_url()
     print("Opening URL '{0}'".format(url))
     Helper.open_url(url)
开发者ID:ninadmhatre,项目名称:pylrn,代码行数:8,代码来源:BucketSortAddon.py

示例11: get_model

def get_model(filename=MLP_FILE):
    ''' Fetch MLP classifier object from file'''
    classifier = Helper.unserialize(filename)

    if(classifier == None):
        classifier = build_model('glcm', dataset_file='../Datasets/old_data.data', iters=2)
        Helper.serialize(filename, classifier)

    return classifier
开发者ID:oduwa,项目名称:Wheat-Count,代码行数:9,代码来源:MLP.py

示例12: _process

def _process(process):
    ''' Generate LLVM IR code (incomplete) '''
    process_name = process.processName
    LOG.info('Generating LLVM IR code for process ' + str(process_name))

    # In case model has nested states, flatten everything
    Helper.flatten(process)

    # Make an maping {input: {state: transition...}} in order to easily
    # generate the lookup tables for the state machine runtime
    mapping = Helper.map_input_state(process)

    # Initialise LLVM global structure
    LLVM['module'] = core.Module.new(str(process_name))
    LLVM['pass_manager'] = passes.FunctionPassManager.new(LLVM['module'])
    LLVM['executor'] = ee.ExecutionEngine.new(LLVM['module'])
    # Set up the optimizer pipeline.
    # Start with registering info about how the
    # target lays out data structures.
#   LLVM['pass_manager'].add(LLVM['executor'].target_data)
#   # Do simple "peephole" optimizations and bit-twiddling optzns.
#   LLVM['pass_manager'].add(passes.PASS_INSTRUCTION_COMBINING)
#   # Reassociate expressions.
#   LLVM['pass_manager'].add(passes.PASS_REASSOCIATE)
#   # Eliminate Common SubExpressions.
#   LLVM['pass_manager'].add(passes.PASS_GVN)
#   # Simplify the control flow graph (deleting unreachable blocks, etc).
#   LLVM['pass_manager'].add(passes.PASS_CFG_SIMPLIFICATION)
#   LLVM['pass_manager'].initialize()

    # Create the runTransition function
    run_funct_name = 'run_transition'
    run_funct_type = core.Type.function(core.Type.void(), [
        core.Type.int()])
    run_funct = core.Function.new(
            LLVM['module'], run_funct_type, run_funct_name)
    # Generate the code of the start transition:
    # Clear scope
    LLVM['named_values'].clear()
    # Create the function name and type
    funct_name = str(process_name) + '_startup' 
    funct_type = core.Type.function(core.Type.void(), [])
    # Create a function object
    function = core.Function.new(LLVM['module'], funct_type, funct_name)
    # Create a new basic block to start insertion into.
    block = function.append_basic_block('entry')
    builder = core.Builder.new(block)
    # Add the body of the function
    builder.call(run_funct, (core.Constant.int(
                                     core.Type.int(), 0),))
    # Add terminator (mandatory)
    builder.ret_void()
    # Validate the generated code, checking for consistency.
    function.verify()
    # Optimize the function (not yet).
    # LLVM['pass_manager'].run(function)
    print function
开发者ID:meyerlaurent,项目名称:opengeode,代码行数:57,代码来源:LlvmGenerator.py

示例13: setUp

 def setUp(self):
     self._logger.info("_______________UI TestCase setUp_______________")
     '''
     Unlock the device
     '''
     self.phone._viewclient.dump()
     if(self.phone.getConfigItem('needunlock') =='1'):
         Helper.unlockDevice(self.phone)
         self.phone.sleep(2)
开发者ID:slimsymphony,项目名称:nst,代码行数:9,代码来源:uitestcase.py

示例14: processQueue

def processQueue(currentTracks, indicesToDownload):
	print('')
	print(indicesToDownload)
	filesSkipped = False
	disconnectionError = False

	numberOfSongsToDownload = len(indicesToDownload)

	for downloadNumber in range(numberOfSongsToDownload):
		try:
			songIndex = indicesToDownload[downloadNumber]
			currentSong = currentTracks[songIndex]
			currentDownload = Download.Download(currentSong, downloadNumber,
									numberOfSongsToDownload, downloadFolder)
		except Exception, e:
			print(str(e))
			print('Other library disconnected')
			disconnectionError = True
			break

		currentDownload.printSongInfo()
		updateFlashWithDownloadInfo(downloadNumber, numberOfSongsToDownload)

		currentDownload.artist = Helper.fixFileName(currentDownload.artist)
		currentDownload.album = Helper.fixFileName(currentDownload.album)
		currentDownload.title = Helper.fixFileName(currentDownload.title)

		if(currentDownload.isAlreadyExists()):
			print('Already downloaded, skipping!\n')
			continue

		if(currentDownload.isWrongType()):
			print('Song is protected or is non-audio, skipping!\n')
			filesSkipped = True
			continue

		# reset internal iTunes counter
		currentSong.Play()
		iTunes.Stop()

		# begin waiting
		capture = CapturePacket.CapturePacket(iTunesSock)
		capture.start()

		# bait it out...
		try:
			currentSong.Play()
		except Exception, e:
			print(str(e))
			print('File missing!\n')
			# flip killswitch for thread
			capture.kill()
			# tell flash something's up
			filesSkipped = True
			continue
开发者ID:gitter-badger,项目名称:aethyr,代码行数:55,代码来源:AethyrHelper.py

示例15: filetodb

def filetodb(c, filehandle, tax):
    fileAsList = []
    accessions = []
    for line in filehandle.readlines():
        if not line.startswith("#") and not line.startswith("<"):  # header usually starts with <
            split = line.split("\n")[0].split()
            if len(split) == 0:
                continue
            acc = Helper.retrieveAccessionNumber(split[0])
            fileAsList.append(
                [
                    acc,
                    split[1],
                    split[2],
                    split[3],
                    split[4],
                    split[5],
                    split[6],
                    split[7],
                    split[8],
                    split[9],
                    split[10],
                    split[11],
                    split[12],
                    split[14],
                ]
            )
            accessions.append(acc)

    lengths = Helper.getSequenceLengthsForAccessionsIds(accessions)
    i = c.execute("select count(*) from tsv_storage").fetchone()[0]
    for split in fileAsList:
        writetodb(
            c,
            i,
            split[0],
            tax,
            split[1],
            split[2],
            split[3],
            split[4],
            split[5],
            split[6],
            split[7],
            split[8],
            split[9],
            split[10],
            split[11],
            split[12],
            split[13],
            int(lengths[split[0]]),
        )
        i = i + 1
开发者ID:expectopatronum,项目名称:orth-scripts,代码行数:53,代码来源:addTsvToDb.py


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