python类Iterable()的实例源码

image.py 文件源码 项目:brainiak 作者: brainiak 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def multimask_images(images: Iterable[SpatialImage],
                     masks: Sequence[np.ndarray], image_type: type = None
                     ) -> Iterable[Sequence[np.ndarray]]:
    """Mask images with multiple masks.

    Parameters
    ----------
    images:
        Images to mask.
    masks:
        Masks to apply.
    image_type:
        Type to cast images to.

    Yields
    ------
    Sequence[np.ndarray]
        For each mask, a masked image.
    """
    for image in images:
        yield [mask_image(image, mask, image_type) for mask in masks]
image.py 文件源码 项目:brainiak 作者: brainiak 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def mask_images(images: Iterable[SpatialImage], mask: np.ndarray,
                image_type: type = None) -> Iterable[np.ndarray]:
    """Mask images.

    Parameters
    ----------
    images:
        Images to mask.
    mask:
        Mask to apply.
    image_type:
        Type to cast images to.

    Yields
    ------
    np.ndarray
        Masked image.
    """
    for images in multimask_images(images, (mask,), image_type):
        yield images[0]
kmeans.py 文件源码 项目:modernpython 作者: rhettinger 项目源码 文件源码 阅读 37 收藏 0 点赞 0 评论 0
def mean(data: Iterable[float]) -> float:
    'Accurate arithmetic mean'
    data = list(data)
    return fsum(data) / len(data)
kmeans.py 文件源码 项目:modernpython 作者: rhettinger 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def transpose(matrix: Iterable[Iterable]) -> Iterable[tuple]:
    'Swap rows with columns for a 2-D array'
    return zip(*matrix)
kmeans.py 文件源码 项目:modernpython 作者: rhettinger 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def assign_data(centroids: Sequence[Centroid], data: Iterable[Point]) -> Dict[Centroid, Sequence[Point]]:
    'Assign data the closest centroid'
    d : DefaultDict[Point, List[Point]] = defaultdict(list)
    for point in data:
        centroid: Point = min(centroids, key=partial(dist, point))
        d[centroid].append(point)
    return dict(d)
kmeans.py 文件源码 项目:modernpython 作者: rhettinger 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def compute_centroids(groups: Iterable[Sequence[Point]]) -> List[Centroid]:
    'Compute the centroid of each group'
    return [tuple(map(mean, transpose(group))) for group in groups]
kmeans.py 文件源码 项目:modernpython 作者: rhettinger 项目源码 文件源码 阅读 39 收藏 0 点赞 0 评论 0
def k_means(data: Iterable[Point], k:int=2, iterations:int=10) -> List[Point]:
    'Return k-centroids for the data'
    data = list(data)
    centroids = sample(data, k)
    for i in range(iterations):
        labeled = assign_data(centroids, data)
        centroids = compute_centroids(labeled.values())
    return centroids
book.py 文件源码 项目:goodreads-api-client-python 作者: mdzhang 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def id_to_work_id(self, ids: Iterable[str]):
        id_csv = ','.join(ids)
        endpoint = 'book/id_to_work_id/{}'.format(id_csv)
        res = self._transport.req(endpoint=endpoint)
        return res['work-ids']
book.py 文件源码 项目:goodreads-api-client-python 作者: mdzhang 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def isbn_to_id(self, isbns: Iterable[str]):
        raise NotImplementedError('API always 404s on this endpoint')
book.py 文件源码 项目:goodreads-api-client-python 作者: mdzhang 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def review_counts(self, isbns: Iterable[str]):
        # This endpoint 406s on non-json content type
        endpoint = 'book/review_counts.json'
        params = {
            'isbns': ','.join(set(isbns)),
        }
        res = self._transport.req(endpoint=endpoint, params=params,
                                  transform='json')
        return res['books']
helpers.py 文件源码 项目:pylongecity 作者: cyrbon 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def render(posts: Iterable[Post], output_filepath: Optional[str] = None):
    ''' Puts html from posts into output_filepath (.html) and opens that in a specified browser '''
    posts = list(posts)
    if posts:
        write_and_open_in_browser(render_to_html(posts), output_filepath)
    else: print('Nothing found')
helpers.py 文件源码 项目:pylongecity 作者: cyrbon 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def has_links(posts: List[Post], *patterns, **kwargs) -> Iterable[Post]:
    '''
    Returns all posts which have matching links in them.
    Args:
        post (List[Post]): Posts to filter
        *patterns (List[str]): Patterns which links should match
        not (List[str]) : Patterns which links should not match. E.g., not=['google', 'longecity', 'amazon']

    '''
    return filter(lambda p: (len(match_links(p, *patterns, **kwargs)) > 0), posts)
whatstyle.py 文件源码 项目:whatstyle 作者: mikr 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def grouper(n, iterable, padvalue=None):
    # type: (int, Iterable[Any], Any) -> Iterable[Iterable[Any]]
    """grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')"""
    return izip_longest(*[iter(iterable)] * n, fillvalue=padvalue)

# ----------------------------------------------------------------------
# Functions to find an executable in the PATH, from:
# http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python
whatstyle.py 文件源码 项目:whatstyle 作者: mikr 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def option_make(optionname,      # type: AnyStr
                optiontype,      # type: AnyStr
                configs,         # type: Iterable[OptionValue]
                nestedopts=None  # type: Optional[StyleDef]
                ):
    # type: (...) -> Tuple[str, str, List[OptionValue], Optional[StyleDef]]
    configs = [typeconv(c) for c in configs]
    return unistr(optionname), unistr(optiontype), configs, nestedopts
whatstyle.py 文件源码 项目:whatstyle 作者: mikr 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def styledef_make(options=None):
    # type: (Union[dict, Iterable[Option], None]) -> StyleDef
    if isinstance(options, dict):
        s = styledef_make()
        for _, option in sorted(options.items()):
            if isinstance(option, dict):
                option = styledef_make(option)
            styledef_add_option(option, s)
        return s
    if options is None:
        options = []
    return StyleDef((option_name(o), o) for o in options)
whatstyle.py 文件源码 项目:whatstyle 作者: mikr 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def inclusiverange(start, stop):
    # type: (int, int) -> Iterable[int]
    return range(start, stop + 1)
whatstyle.py 文件源码 项目:whatstyle 作者: mikr 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def stylevariants(optionname, values):
    # type: (str, Iterable[OptionValue]) -> List[Style]
    return [stylevariant(optionname, v) for v in values]
whatstyle.py 文件源码 项目:whatstyle 作者: mikr 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def variants_for(self, option):
        # type: (Option) -> List[Style]

        def kvpairs(vs):
            # type: (Iterable[OptionValue]) -> List[Style]
            return stylevariants(stylename, vs)

        stylename = option_name(option)
        styletype = option_type(option)
        configs = option_configs(option)

        if configs:
            return kvpairs(configs)
        if styletype == 'bool':
            return kvpairs([True, False])
        if styletype == 'int':
            if stylename == 'column_limit':
                # Here we can get weird results, for example
                # in bottle_sqlalchemy.py is a constructor with
                # 8 arguments which are already split between two lines.
                # We find an optimum column limit of 126 because this
                # has less diff lines than putting each argument on a new
                # line. Maybe we should use a different diff metric.
                return kvpairs(self.column_limit_candidates)
            elif stylename == 'indent_width':
                return kvpairs([2, 4, 8])
            elif stylename == 'spaces_before_comment':
                return kvpairs(inclusiverange(1, 4))
            elif stylename.startswith('split_penalty'):
                # We avoid changing large integers whose purpose
                # is not exactly clear for the moment.
                pass
        return []

# ----------------------------------------------------------------------
whatstyle.py 文件源码 项目:whatstyle 作者: mikr 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def variants_for(self, option):
        # type: (Option) -> List[Style]

        stylename = option_name(option)
        styletype = option_type(option)
        configs = option_configs(option)

        def kvpairs(vs):
            # type: (Iterable[OptionValue]) -> List[Style]
            return stylevariants(stylename, vs)

        if configs:
            return kvpairs(configs)

        if stylename == 'indent':
            return kvpairs(['yes'])

        if stylename == 'wrap':
            return kvpairs([0])

        if stylename == 'indent-spaces':
            return kvpairs(inclusiverange(0, 8))

        if styletype == 'AutoBool':
            return kvpairs(['yes', 'no', 'auto'])

        if styletype == 'Boolean':
            return kvpairs(['yes', 'no'])
        return []
whatstyle.py 文件源码 项目:whatstyle 作者: mikr 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def variants_for(self, option):
        # type: (Option) -> List[Style]

        def kvpairs(vs):
            # type: (Iterable[OptionValue]) -> List[Style]
            return stylevariants(stylename, vs)

        def numreplace(configs, numvalues):
            # type: (List[OptionValue], Iterable[int]) -> List[OptionValue]
            extconfigs = []  # type: List[OptionValue]
            for c in configs:
                if isinstance(c, text_type) and '#' in c:
                    for n in numvalues:
                        num = str(n)
                        nc = c.replace('#', num)
                        extconfigs.append(nc)
                else:
                    extconfigs.append(c)
            return extconfigs

        stylename = option_name(option)
        configs = option_configs(option)

        if stylename == self.columnlimitname:
            candidates = self.column_limit_candidates
            candidates = [c for c in candidates if 50 <= c <= 200]
            return kvpairs(candidates)
        if stylename == 'indent':
            return kvpairs(numreplace(configs, [2, 4, 8]))
        if stylename == 'min-conditional-indent':
            return kvpairs(numreplace(configs, [0, 1, 2, 3]))
        if stylename == 'max-instatement-indent':
            return kvpairs(numreplace(configs, inclusiverange(40, 120)))
        if stylename == 'mode':
            return []
        if configs:
            return kvpairs(numreplace(configs, [1, 2, 4, 8]))
        return []


问题


面经


文章

微信
公众号

扫码关注公众号