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


Python any函数代码示例

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


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

示例1: indent_code

    def indent_code(self, code):
        """Accepts a string of code or a list of code lines"""

        # code mostly copied from ccode
        if isinstance(code, string_types):
            code_lines = self.indent_code(code.splitlines(True))
            return "".join(code_lines)

        tab = "  "
        inc_regex = ("^function ", "^if ", "^elseif ", "^else$", "^for ")
        dec_regex = ("^end$", "^elseif ", "^else$")

        # pre-strip left-space from the code
        code = [line.lstrip(" \t") for line in code]

        increase = [int(any([search(re, line) for re in inc_regex])) for line in code]
        decrease = [int(any([search(re, line) for re in dec_regex])) for line in code]

        pretty = []
        level = 0
        for n, line in enumerate(code):
            if line == "" or line == "\n":
                pretty.append(line)
                continue
            level -= decrease[n]
            pretty.append("%s%s" % (tab * level, line))
            level += increase[n]
        return pretty
开发者ID:brajeshvit,项目名称:virtual,代码行数:28,代码来源:octave.py

示例2: generate_file_map

    def generate_file_map(self):
        # Read all the files in the given folder.
        # We gather them all and then send them up to GAE.
        # We do this rather than processing template locally. Because local processing
        file_map = dict()
        fdir = os.path.dirname(self.view.file_name()).replace(self.parent_path+'/', '')
        for root, dirs, files in os.walk(self.path):
            for filename in files:
                if any(filename.endswith(postfix) for postfix in ['.tracking', '.html', '.txt', '.yaml', '.js']):
                    contents = read_file(os.path.join(root, filename))
                    file_map['%s/%s' % (fdir, filename)] = contents
                    # file_map[filename] = contents
        for root, dirs, files in os.walk(self.image_path):
            for filename in files:
                image_path = os.path.abspath(os.path.join(root, filename))
                contents = encode_image(image_path)
                file_map[filename] = contents
        for root, dirs, files in os.walk(self.parent_path):
            for filename in files:
                if any(filename.endswith(postfix) for postfix in ['.tracking', '.html', '.txt', '.yaml', '.js']):
                    contents = read_file(os.path.join(root, filename))
                    file_map[filename] = contents
        print(file_map.keys())

        return file_map
开发者ID:TriggerMail,项目名称:triggermail_sublimetext_plugin,代码行数:25,代码来源:triggermail_templates.py

示例3: change_engine_state

 def change_engine_state(self,widget):
     checked = widget.get_active()
     name = widget.get_child().get_text()
     if checked:
         if not any(x in name for x in self.engines_list):
             print "activating %s engine" % name
             self.engines_list.append(name)
             self.gui.conf["engines"] = self.engines_list
             self.gui.conf.write()
             self.init_engine(name)
             try:
                 if getattr(self, '%s' % name).adult_content:
                     self.gui.engine_selector.append(name,True)
             except:
                 self.gui.engine_selector.append(name)
             self.gui.engine_selector.setIndexFromString(name)
     else:
         if any(x in name for x in self.engines_list):
             print "deactivating %s engine" % name
             self.engines_list.remove(name)
             self.gui.conf["engines"] = self.engines_list
             self.gui.conf.write()
             self.gui.engine_selector.setIndexFromString(name)
             self.gui.engine_selector.remove(self.gui.engine_selector.getSelectedIndex())
             self.gui.engine_selector.select(0)
开发者ID:smolleyes,项目名称:gmediafinder-gtk3,代码行数:25,代码来源:main.py

示例4: aggregate_scores

def aggregate_scores(scores, display_name="summary", location=None):
    """
    scores: A list of ScoreBase objects
    display_name: The display name for the score object
    location: The location under which all objects in scores are located
    returns: A tuple (all_total, graded_total).
        all_total: A ScoreBase representing the total score summed over all input scores
        graded_total: A ScoreBase representing the score summed over all graded input scores
    """
    total_correct_graded = float_sum(score.earned for score in scores if score.graded)
    total_possible_graded = float_sum(score.possible for score in scores if score.graded)
    any_attempted_graded = any(score.attempted for score in scores if score.graded)

    total_correct = float_sum(score.earned for score in scores)
    total_possible = float_sum(score.possible for score in scores)
    any_attempted = any(score.attempted for score in scores)

    # regardless of whether it is graded
    all_total = AggregatedScore(total_correct, total_possible, False, display_name, location, any_attempted)

    # selecting only graded things
    graded_total = AggregatedScore(
        total_correct_graded, total_possible_graded, True, display_name, location, any_attempted_graded,
    )

    return all_total, graded_total
开发者ID:CUCWD,项目名称:edx-platform,代码行数:26,代码来源:graders.py

示例5: checkRequirementsMatch

    def checkRequirementsMatch(self, subPanelName):
        # Read requirements for the specified subpanel form the XML config file
        xmlRequirement = "./Subpanels/Subpanel/[@Name='" + subPanelName +"']/Requirement"
        subPanelRequirements = xml.findall(xmlRequirement)
        
        panelRequirements = {}
        booleanOperation = {}      
        for requirements in subPanelRequirements:
            requirement = requirements.text.split(':')
            if requirement[0] == "All": # Need element 1 populated if "All" detected
                requirement.append("All")
            panelRequirements[requirement[0]] = requirement[1].strip()
            booleanOperation[requirement[0]] = requirements.get("type")

        # Go through each subpanel requirement and check against board configuration
        # If no boolean type defined, assume AND
        requirementType = panelRequirements.keys()
        # If no Requirement found, assume ALL
        try:
            if (requirementType[0] == "All"):
                check = True
            else:
                check = any(panelRequirements[requirementType[0]] in s for s in self.boardConfiguration.values())
                for testRequirement in requirementType[1:]:
                    if (booleanOperation[testRequirement] == "or") or (booleanOperation[testRequirement] == "OR"):
                        check = check or any(panelRequirements[testRequirement] in s for s in self.boardConfiguration.values())
                    else:
                        check = check and any(panelRequirements[testRequirement] in s for s in self.boardConfiguration.values())
        except:
            check = True
        return check
开发者ID:CNCBASHER,项目名称:AeroQuadConfiguratorPyQt,代码行数:31,代码来源:AeroQuadConfigurator.py

示例6: hisRead

    def hisRead(self,**kwargs):
        """
        This method returns a list of history records
        arguments are : 
        ids : a ID or a list of ID 
        AND_search : a list of keywords to look for in trend names
        OR_search : a list of keywords to look for in trend names
        rng : haystack range (today,yesterday, last24hours...
        start : string representation of start time ex. '2014-01-01T00:00' 
        end : string representation of end time ex. '2014-01-01T00:00'
        """
        self._filteredList = [] # Empty list to be returned
        # Keyword Arguments
        print(kwargs)
        ids = kwargs.pop('id','')
        AND_search = kwargs.pop('AND_search','')
        OR_search = kwargs.pop('OR_search','')
        rng = kwargs.pop('rng','')
        start = kwargs.pop('start','')
        end = kwargs.pop('end','')
        takeall = kwargs.pop('all','')
        # Remaining kwargs...
        if kwargs: raise TypeError('Unknown argument(s) : %s' % kwargs)
        
        # Build datetimeRange based on start and end
        if start and end:
            datetimeRange = start+','+end
        else:
            datetimeRange = rng
        
        
        # Find histories matching ALL keywords in AND_search
        for eachHistory in self.hisAll():
            takeit = False
            # Find histories matching ANY keywords in OR_search
            if (AND_search != '') and all([keywords in eachHistory['name'] for keywords in AND_search]):
                print('AND_search : Adding %s to recordList' % eachHistory['name'])               
                takeit = True
                
            # Find histories matching ANY ID in id list       
            elif (OR_search != '') and any([keywords in eachHistory['name'] for keywords in OR_search]):
                print('OR_search : Adding %s to recordList' % eachHistory['name'])                
                takeit = True
                
            elif (ids != '') and any([id in eachHistory['id'] for id in ids]):
                print('ID found : Adding %s to recordList' % eachHistory['name'])
                takeit = True
            
            elif takeall != '':
                print('Adding %s to recordList' % eachHistory['name'])
                takeit = True
                
            if takeit:
                self._filteredList.append(HisRecord(self,eachHistory['id'],datetimeRange))
            

        if self._filteredList == []:
            print('No trends found... sorry !')
        
        return self._filteredList
开发者ID:gitter-badger,项目名称:pyhaystack,代码行数:60,代码来源:HaystackClient.py

示例7: _rec

    def _rec(self, obj, state):
        """
        EXAMPLES::

            sage: from sage.combinat.sf.ns_macdonald import NonattackingBacktracker
            sage: n = NonattackingBacktracker(LatticeDiagram([0,1,2]))
            sage: len(list(n))
            12
            sage: obj = [ [], [None], [None, None]]
            sage: state = 2, 1
            sage: list(n._rec(obj, state))
            [([[], [1], [None, None]], (3, 1), False),
             ([[], [2], [None, None]], (3, 1), False)]
        """
        #We need to set the i,j^th entry.
        i, j = state

        #Get the next state
        new_state = self.get_next_pos(i, j)
        yld = True if new_state is None else False

        for k in range(1, len(self._shape)+1):
            #We check to make sure that k does not
            #violate any of the attacking conditions
            if j==1 and any( self.pi(x)==k for x in range(i+1, len(self._shape)+1)):
                continue
            if any( obj[ii-1][jj-1] == k for ii, jj in
                    self._shape.boxes_same_and_lower_right(i, j) if jj != 0):
                continue

            #Fill in the in the i,j box with k+1
            obj[i-1][j-1] = k

            #Yield the object
            yield copy.deepcopy(obj), new_state, yld
开发者ID:Etn40ff,项目名称:sage,代码行数:35,代码来源:ns_macdonald.py

示例8: _get_indicators

 def _get_indicators(self, prototype=None, unwrap=True):
     from abjad.tools import indicatortools
     prototype = prototype or (object,)
     if not isinstance(prototype, tuple):
         prototype = (prototype,)
     prototype_objects, prototype_classes = [], []
     for indicator_prototype in prototype:
         if isinstance(indicator_prototype, type):
             prototype_classes.append(indicator_prototype)
         else:
             prototype_objects.append(indicator_prototype)
     prototype_objects = tuple(prototype_objects)
     prototype_classes = tuple(prototype_classes)
     matching_indicators = []
     for indicator in self._indicator_expressions:
         if isinstance(indicator, prototype_classes):
             matching_indicators.append(indicator)
         elif any(indicator == x for x in prototype_objects):
             matching_indicators.append(indicator)
         elif isinstance(indicator, indicatortools.IndicatorExpression):
             if isinstance(indicator.indicator, prototype_classes):
                 matching_indicators.append(indicator)
             elif any(indicator.indicator == x for x in prototype_objects):
                 matching_indicators.append(indicator)
     if unwrap:
         matching_indicators = [x.indicator for x in matching_indicators]
     matching_indicators = tuple(matching_indicators)
     return matching_indicators
开发者ID:rulio,项目名称:abjad,代码行数:28,代码来源:Spanner.py

示例9: test_tcp

    def test_tcp(self):
        n = self.pathod("304")
        self._tcpproxy_on()
        i = self.pathod("305")
        i2 = self.pathod("306")
        self._tcpproxy_off()

        self.master.masterq.join()

        assert n.status_code == 304
        assert i.status_code == 305
        assert i2.status_code == 306
        assert any(f.response.status_code == 304 for f in self.master.state.flows)
        assert not any(f.response.status_code == 305 for f in self.master.state.flows)
        assert not any(f.response.status_code == 306 for f in self.master.state.flows)

        # Test that we get the original SSL cert
        if self.ssl:
            i_cert = SSLCert(i.sslinfo.certchain[0])
            i2_cert = SSLCert(i2.sslinfo.certchain[0])
            n_cert = SSLCert(n.sslinfo.certchain[0])

            assert i_cert == i2_cert == n_cert

        # Make sure that TCP messages are in the event log.
        assert any("305" in m for m in self.master.log)
        assert any("306" in m for m in self.master.log)
开发者ID:noscripter,项目名称:mitmproxy,代码行数:27,代码来源:test_server.py

示例10: test_ignore

    def test_ignore(self):
        n = self.pathod("304")
        self._ignore_on()
        i = self.pathod("305")
        i2 = self.pathod("306")
        self._ignore_off()

        self.master.masterq.join()

        assert n.status_code == 304
        assert i.status_code == 305
        assert i2.status_code == 306
        assert any(f.response.status_code == 304 for f in self.master.state.flows)
        assert not any(f.response.status_code == 305 for f in self.master.state.flows)
        assert not any(f.response.status_code == 306 for f in self.master.state.flows)

        # Test that we get the original SSL cert
        if self.ssl:
            i_cert = SSLCert(i.sslinfo.certchain[0])
            i2_cert = SSLCert(i2.sslinfo.certchain[0])
            n_cert = SSLCert(n.sslinfo.certchain[0])

            assert i_cert == i2_cert
            assert i_cert != n_cert

        # Test Non-HTTP traffic
        spec = "200:i0,@100:d0"  # this results in just 100 random bytes
        # mitmproxy responds with bad gateway
        assert self.pathod(spec).status_code == 502
        self._ignore_on()
        with raises(HttpException):
            self.pathod(spec)  # pathoc tries to parse answer as HTTP

        self._ignore_off()
开发者ID:noscripter,项目名称:mitmproxy,代码行数:34,代码来源:test_server.py

示例11: checkPlanetSplitter

def checkPlanetSplitter (city="nyc"):
    # Run planetsplitter if .mem files don't exist for city. Also unzips OSM
    # file if still in .bz2 format
    files = os.listdir (".") # from /src
    if city.lower ()[0] == "l":
        city = "london"
        prfx = "lo"
    else:
        city = "nyc"
        prfx = "ny"
    # First unzip
    datadir = "../data/"
    dfiles = os.listdir (datadir)
    fcheck = any (f.find (city) > -1 and f.endswith(".osm") for f in dfiles)
    if not any (f.find(city) > -1 and f.endswith (".osm") for f in dfiles):
        bf = [f for f in dfiles if f.find (city) > -1 and f.endswith (".bz2")]
        if not bf:
            print "ERROR: %s.bz2 file does not exist to unzip" % bf 
            # TODO: exception handler
        else:
            bf = datadir + bf [0]
            args = ["bunzip2", bf]
            print "Unzipping planet-%s.osm ... " % city
            subprocess.Popen (args)
    if not any (f.startswith(prfx) and f.endswith(".mem") for f in files):
        planetfile = datadir + "planet-" + city + ".osm"
        args = ["/Users/colinbroderick/Downloads/routino-2.7.2/src/planetsplitter", "--prefix=" + prfx,\
                "--tagging=/Users/colinbroderick/Downloads/routino-2.7.2/xml/routino-tagging.xml",\
                planetfile]
        print "planet-%s.osm not yet split. Running planetsplitter..." % city
        subprocess.Popen (args)
    else:
        print "%s already split" % city
开发者ID:dcorreab,项目名称:bike-correlations,代码行数:33,代码来源:router.py

示例12: filter_file

def filter_file(file_name):
    if any(file_name.startswith(ignored_file) for ignored_file in ignored_files):
        return False
    base_name = os.path.basename(file_name)
    if any(fnmatch.fnmatch(base_name, pattern) for pattern in file_patterns_to_ignore):
        return False
    return True
开发者ID:awestroke,项目名称:servo,代码行数:7,代码来源:tidy.py

示例13: googleplus

def googleplus(url):
    try:
        result = getUrl(url).result
        u = re.compile('"(http.+?videoplayback[?].+?)"').findall(result)
        if len(u) == 0:
            result = getUrl(url, mobile=True).result
            u = re.compile('"(http.+?videoplayback[?].+?)"').findall(result)

        u = [i.replace('\\u003d','=').replace('\\u0026','&') for i in u]

        d = []
        try: d += [[{'quality': '1080p', 'url': i} for i in u if any(x in i for x in ['&itag=37&', '&itag=137&', '&itag=299&', '&itag=96&', '&itag=248&', '&itag=303&', '&itag=46&'])][0]]
        except: pass
        try: d += [[{'quality': 'HD', 'url': i} for i in u if any(x in i for x in ['&itag=22&', '&itag=84&', '&itag=136&', '&itag=298&', '&itag=120&', '&itag=95&', '&itag=247&', '&itag=302&', '&itag=45&', '&itag=102&'])][0]]
        except: pass

        url = []
        for i in d:
            try: url.append({'quality': i['quality'], 'url': getUrl(i['url'], output='geturl').result})
            except: pass

        if url == []: return
        return url
    except:
        return
开发者ID:Dragonkids21,项目名称:MetalKettles-Addon-Repository,代码行数:25,代码来源:commonresolvers.py

示例14: get_squeeze_dims

def get_squeeze_dims(xarray_obj,
                     dim: Union[Hashable, Iterable[Hashable], None] = None,
                     axis: Union[int, Iterable[int], None] = None
                     ) -> List[Hashable]:
    """Get a list of dimensions to squeeze out.
    """
    if dim is not None and axis is not None:
        raise ValueError('cannot use both parameters `axis` and `dim`')
    if dim is None and axis is None:
        return [d for d, s in xarray_obj.sizes.items() if s == 1]

    if isinstance(dim, Iterable) and not isinstance(dim, str):
        dim = list(dim)
    elif dim is not None:
        dim = [dim]
    else:
        assert axis is not None
        if isinstance(axis, int):
            axis = [axis]
        axis = list(axis)
        if any(not isinstance(a, int) for a in axis):
            raise TypeError(
                'parameter `axis` must be int or iterable of int.')
        alldims = list(xarray_obj.sizes.keys())
        dim = [alldims[a] for a in axis]

    if any(xarray_obj.sizes[k] > 1 for k in dim):
        raise ValueError('cannot select a dimension to squeeze out '
                         'which has length greater than one')
    return dim
开发者ID:crusaderky,项目名称:xarray,代码行数:30,代码来源:common.py

示例15: apply_filter_include_exclude

def apply_filter_include_exclude(
        filename, include_filters, exclude_filters):
    """Apply inclusion/exclusion filters to filename

    The include_filters are tested against
    the given (relative) filename.
    The exclude_filters are tested against
    the stripped, given (relative), and absolute filenames.

    filename (str): the file path to match, should be relative
    include_filters (list of regex): ANY of these filters must match
    exclude_filters (list of regex): NONE of these filters must match

    returns: (filtered, exclude)
        filtered (bool): True when filename failed the include_filter
        excluded (bool): True when filename failed the exclude_filters
    """

    filtered = not any(f.match(filename) for f in include_filters)
    excluded = False

    if filtered:
        return filtered, excluded

    excluded = any(f.match(filename) for f in exclude_filters)

    return filtered, excluded
开发者ID:gcovr,项目名称:gcovr,代码行数:27,代码来源:gcov.py


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