repo
stringlengths
1
29
path
stringlengths
24
332
code
stringlengths
39
579k
gbp-0.9.19
gbp-0.9.19//gbp/deb/changelog.pyclass:ChangeLogSection/parse
@classmethod def parse(cls, section): """ Parse one changelog section @param section: a changelog section @type section: C{str} @returns: the parse changelog section @rtype: L{ChangeLogSection} """ header = section.split('\n')[0] package = header.split()[0] version = header.split()[1][1:-1] return cls(package, version)
eli5
eli5//utils.pyfile:/utils.py:function:max_or_0/max_or_0
def max_or_0(it): """ >>> max_or_0([]) 0 >>> max_or_0(iter([])) 0 >>> max_or_0(iter([-10, -2, -11])) -2 """ lst = list(it) return max(lst) if lst else 0
pymoso
pymoso//chnutils.pyfile:/chnutils.py:function:do_work/do_work
def do_work(func, args, kwargs=None): """ Wrap a function with arguments and return the result for multiprocessing routines. Parameters ---------- func Function to be called in multiprocessing args : tuple Positional arguments to 'func' kwargs : dict Keyword arguments to 'func' Returns ------- result Output of 'func(args, kwargs)' """ if kwargs: result = func(*args, **kwargs) else: result = func(*args) return result
pyang
pyang//xpath_parser.pyfile:/xpath_parser.py:function:p_or_expr_1/p_or_expr_1
def p_or_expr_1(p): """OrExpr : AndExpr""" p[0] = p[1]
dolmen.collection-0.3
dolmen.collection-0.3//src/dolmen/collection/interfaces.pyclass:ICollection/clear
def clear(): """Empty the collection: remove all components from it. """
honeybee-core-1.28.3
honeybee-core-1.28.3//honeybee/orientation.pyfile:/honeybee/orientation.py:function:angles_from_num_orient/angles_from_num_orient
def angles_from_num_orient(num_subdivisions=4): """Get a list of angles based on the number of compass subdividsions. Args: num_subdivisions: An integer for the number of times that the compass should be subdivided. Default: 4, which will yield angles for North, East South, and West. Returns: A list of angles in degrees with a length of the num_subdivisions, which denote the boundaries of each orientation category. """ step = 360.0 / num_subdivisions start = step / 2.0 angles = [] while start < 360: angles.append(start) start += step return angles
tsnet
tsnet//utils/calc_parabola_vertex.pyfile:/utils/calc_parabola_vertex.py:function:calc_parabola_vertex/calc_parabola_vertex
def calc_parabola_vertex(points): """Adapted and modifed to get the unknowns for defining a parabola Parameters ---------- points : list Three points on the pump characteristics curve. """ [(x1, y1), (x2, y2), (x3, y3)] = points denom = (x1 - x2) * (x1 - x3) * (x2 - x3) A = (x3 * (y2 - y1) + x2 * (y1 - y3) + x1 * (y3 - y2)) / denom B = (x3 * x3 * (y1 - y2) + x2 * x2 * (y3 - y1) + x1 * x1 * (y2 - y3) ) / denom C = (x2 * x3 * (x2 - x3) * y1 + x3 * x1 * (x3 - x1) * y2 + x1 * x2 * ( x1 - x2) * y3) / denom return A, B, C
numba
numba//core/funcdesc.pyclass:PythonFunctionDescriptor/from_specialized_function
@classmethod def from_specialized_function(cls, func_ir, typemap, restype, calltypes, mangler, inline, noalias): """ Build a FunctionDescriptor for a given specialization of a Python function (in nopython mode). """ return cls._from_python_function(func_ir, typemap, restype, calltypes, native=True, mangler=mangler, inline=inline, noalias=noalias)
data_prc
data_prc//departements.pyfile:/departements.py:function:_format_code/_format_code
def _format_code(code): """ Format departement code (Add a 0 at the end if the length < 0). :returns: formatted code :rtype: str """ if len(code) < 3: return code + '0' return code
dropbox-10.1.2
dropbox-10.1.2//dropbox/team.pyclass:UsersSelectorArg/team_member_ids
@classmethod def team_member_ids(cls, val): """ Create an instance of this class set to the ``team_member_ids`` tag with value ``val``. :param list of [str] val: :rtype: UsersSelectorArg """ return cls('team_member_ids', val)
dgl_cu102-0.4.3.post2.data
dgl_cu102-0.4.3.post2.data//purelib/dgl/backend/backend.pyfile:/purelib/dgl/backend/backend.py:function:min/min
def min(input, dim): """Reduce min the input tensor along the given dim. Parameters ---------- input : Tensor The input tensor. dim : int The reduce dim. Returns ------- Tensor A framework-specific tensor. """ pass
abics
abics//mc_mpi.pyclass:RXParams/from_toml
@classmethod def from_toml(cls, fname): """ Read information from toml file Parameters ---------- f: str The name of input toml File Returns ------- DFTParams: DFTParams object self """ import toml return cls.from_dict(toml.load(fname))
qalaboratory-0.2.0
qalaboratory-0.2.0//qalab/qaenv.pyfile:/qalab/qaenv.py:function:set_log_level_from_verbose/set_log_level_from_verbose
def set_log_level_from_verbose(console_handler, args, logger): """Set logging level handler for script""" if not args.verbose: console_handler.setLevel('INFO') elif args.verbose == 1: console_handler.setLevel('WARNING') elif args.verbose == 2: console_handler.setLevel('INFO') elif args.verbose >= 3: console_handler.setLevel('DEBUG') else: logger.critical("LOGGER level doesn't exist")
urbansim_templates
urbansim_templates//utils.pyfile:/utils.py:function:to_list/to_list
def to_list(items): """ In many places we accept either a single string or a list of strings. This function normalizes None -> [None], str -> [str], and leaves lists unchanged. Parameters ---------- items : str, list, or None Returns ------- list """ if not isinstance(items, list): items = [items] return items
sparc.cache-0.0.3
sparc.cache-0.0.3//sparc/cache/interfaces.pyclass:IAgeableCachedItem/expiration
def expiration(): """Python datetime of when cached item should be considered invalid"""
PyEIS
PyEIS//PyEIS_Lin_KK.pyfile:/PyEIS_Lin_KK.py:function:KK_RC59/KK_RC59
def KK_RC59(w, Rs, R_values, t_values): """ Kramers-Kronig Function: -RC- Kristian B. Knudsen ([email protected] / [email protected]) """ return Rs + R_values[0] / (1 + w * 1.0j * t_values[0]) + R_values[1] / ( 1 + w * 1.0j * t_values[1]) + R_values[2] / (1 + w * 1.0j * t_values[2] ) + R_values[3] / (1 + w * 1.0j * t_values[3]) + R_values[4] / (1 + w * 1.0j * t_values[4]) + R_values[5] / (1 + w * 1.0j * t_values[5] ) + R_values[6] / (1 + w * 1.0j * t_values[6]) + R_values[7] / (1 + w * 1.0j * t_values[7]) + R_values[8] / (1 + w * 1.0j * t_values[8] ) + R_values[9] / (1 + w * 1.0j * t_values[9]) + R_values[10] / (1 + w * 1.0j * t_values[10]) + R_values[11] / (1 + w * 1.0j * t_values[11] ) + R_values[12] / (1 + w * 1.0j * t_values[12]) + R_values[13] / ( 1 + w * 1.0j * t_values[13]) + R_values[14] / (1 + w * 1.0j * t_values[14]) + R_values[15] / (1 + w * 1.0j * t_values[15] ) + R_values[16] / (1 + w * 1.0j * t_values[16]) + R_values[17] / ( 1 + w * 1.0j * t_values[17]) + R_values[18] / (1 + w * 1.0j * t_values[18]) + R_values[19] / (1 + w * 1.0j * t_values[19] ) + R_values[20] / (1 + w * 1.0j * t_values[20]) + R_values[21] / ( 1 + w * 1.0j * t_values[21]) + R_values[22] / (1 + w * 1.0j * t_values[22]) + R_values[23] / (1 + w * 1.0j * t_values[23] ) + R_values[24] / (1 + w * 1.0j * t_values[24]) + R_values[25] / ( 1 + w * 1.0j * t_values[25]) + R_values[26] / (1 + w * 1.0j * t_values[26]) + R_values[27] / (1 + w * 1.0j * t_values[27] ) + R_values[28] / (1 + w * 1.0j * t_values[28]) + R_values[29] / ( 1 + w * 1.0j * t_values[29]) + R_values[30] / (1 + w * 1.0j * t_values[30]) + R_values[31] / (1 + w * 1.0j * t_values[31] ) + R_values[32] / (1 + w * 1.0j * t_values[32]) + R_values[33] / ( 1 + w * 1.0j * t_values[33]) + R_values[34] / (1 + w * 1.0j * t_values[34]) + R_values[35] / (1 + w * 1.0j * t_values[35] ) + R_values[36] / (1 + w * 1.0j * t_values[36]) + R_values[37] / ( 1 + w * 1.0j * t_values[37]) + R_values[38] / (1 + w * 1.0j * t_values[38]) + R_values[39] / (1 + w * 1.0j * t_values[39] ) + R_values[40] / (1 + w * 1.0j * t_values[40]) + R_values[41] / ( 1 + w * 1.0j * t_values[41]) + R_values[42] / (1 + w * 1.0j * t_values[42]) + R_values[43] / (1 + w * 1.0j * t_values[43] ) + R_values[44] / (1 + w * 1.0j * t_values[44]) + R_values[45] / ( 1 + w * 1.0j * t_values[45]) + R_values[46] / (1 + w * 1.0j * t_values[46]) + R_values[47] / (1 + w * 1.0j * t_values[47] ) + R_values[48] / (1 + w * 1.0j * t_values[48]) + R_values[49] / ( 1 + w * 1.0j * t_values[49]) + R_values[50] / (1 + w * 1.0j * t_values[50]) + R_values[51] / (1 + w * 1.0j * t_values[51] ) + R_values[52] / (1 + w * 1.0j * t_values[52]) + R_values[53] / ( 1 + w * 1.0j * t_values[53]) + R_values[54] / (1 + w * 1.0j * t_values[54]) + R_values[55] / (1 + w * 1.0j * t_values[55] ) + R_values[56] / (1 + w * 1.0j * t_values[56]) + R_values[57] / ( 1 + w * 1.0j * t_values[57]) + R_values[58] / (1 + w * 1.0j * t_values[58])
strakspycoin-0.80
strakspycoin-0.80//pycoin/tx/script/microcode.pyfile:/pycoin/tx/script/microcode.py:function:do_OP_2ROT/do_OP_2ROT
def do_OP_2ROT(stack): """ >>> s = [1, 2, 3, 4, 5, 6] >>> do_OP_2ROT(s) >>> print(s) [3, 4, 5, 6, 1, 2] """ stack.append(stack.pop(-6)) stack.append(stack.pop(-6))
news-please-1.5.3
news-please-1.5.3//newsplease/crawler/spiders/gdelt_crawler.pyclass:GdeltCrawler/supports_site
@staticmethod def supports_site(url): """ Rss Crawler is supported if the url is a valid rss feed Determines if this crawler works on the given url. :param str url: The url to test :return bool: Determines wether this crawler work on the given url """ return True
HdlLib
HdlLib//SysGen/HDLEditor.pyfile:/SysGen/HDLEditor.py:function:SyncCondition/SyncCondition
def SyncCondition(ClockName, EveryEdge=False, Rising=True): """ Return code for clock synchronous condition. """ if EveryEdge: return "{0}'event".format(ClockName) elif Rising: return 'rising_edge({0})'.format(ClockName) else: return 'falling_edge({0})'.format(ClockName)
sharedpy-0.0.106
sharedpy-0.0.106//sharedpy/text/utils.pyfile:/sharedpy/text/utils.py:function:contains/contains
def contains(value, allowed_chars): """ Returns True if every char in value is present in alllowed_chars, otherwise False Both arguments should be of type string """ for c in value: if not c in allowed_chars: return False return True
ibmsecurity
ibmsecurity//isam/base/sysaccount/groups.pyfile:/isam/base/sysaccount/groups.py:function:get/get
def get(isamAppliance, id, check_mode=False, force=False): """ Get information on particular group by id """ return isamAppliance.invoke_get('Retrieving group', '/sysaccount/groups/{0}/v1'.format(id))
RelStorage-3.0.1
RelStorage-3.0.1//src/relstorage/adapters/interfaces.pyclass:IManagedDBConnection/drop
def drop(): """ Unconditionally drop (close) the database connection. """
bpy
bpy//ops/pose.pyfile:/ops/pose.py:function:reveal/reveal
def reveal(select: bool=True): """Reveal all bones hidden in Pose Mode :param select: Select :type select: bool """ pass
matematik
matematik//formula/algebra1.pyfile:/formula/algebra1.py:function:slope_formula/slope_formula
def slope_formula(x1, x2, y1, y2): """ definition: func(x1, x2, y1, y2) {...} objective : returns the slope (m) from the slope formula m = y2 - y1 / x2 - x1 """ slope = (y2 - y1) / (x2 - x1) return slope
cis_interface-0.7.10
cis_interface-0.7.10//cis_interface/metaschema/datatypes/MetaschemaType.pyclass:MetaschemaType/issubtype
@classmethod def issubtype(cls, t): """Determine if this type is a subclass of the provided type. Args: t (str): Type name to check against. Returns: bool: True if this type is a subtype of the specified type t. """ return cls.name == t
htmlfun-0.1.0
htmlfun-0.1.0//htmlfun/core.pyfile:/htmlfun/core.py:function:void_el/void_el
def void_el(tag_type, *content): """Same as el but for void elements.""" result = [] try: if isinstance(content[0], dict): attrs_dict, content = content[0], content[1:] attrs_pairs = [] for key in attrs_dict: attrs_pairs.append('%s="%s"' % (key, attrs_dict[key])) attrs_string = ' '.join(attrs_pairs) open_tag = '<%s %s>' % (tag_type, attrs_string) else: open_tag = '<%s>' % tag_type except IndexError: open_tag = '<%s>' % tag_type result.append(open_tag) for item in content: result.append(item) return result
wrangle-0.6.7
wrangle-0.6.7//wrangle/utils/wrangler_utils.pyfile:/wrangle/utils/wrangler_utils.py:function:max_category/max_category
def max_category(data, max_categories): """Max Category Configuration WHAT: helper function for setting the max_categories parameter for wrangler() OPTIONS: integer value for max number of categories 'max' for allowing any number of categories 'auto' for allowing 1/50 of total values as max number of categories INPUT: a dataframe or an array/series/list and the option OUTPUT: an integer representing the maximum allowed number of categories. """ if max_categories == 'auto': max_categories = len(data) / 50 elif max_categories == 'max': max_categories = len(data) + 1 elif type(max_categories) == int: max_categories = max_categories elif max_categories is None: max_categories = len(data) + 1 return max_categories
hpimdm
hpimdm//igmp/nonquerier/NoMembersPresent.pyfile:/igmp/nonquerier/NoMembersPresent.py:function:group_membership_timeout/group_membership_timeout
def group_membership_timeout(group_state: 'GroupState'): """ timer associated with group GroupState object has expired """ group_state.group_state_logger.debug( 'NonQuerier NoMembersPresent: group_membership_timeout') return
idstring-1.0.3
idstring-1.0.3//idstring.pyclass:IDstring/thirty2
@classmethod def thirty2(cls, x): """idstring.thirty2(n: int) --> Thirty-two bit string # like hex(n) but 5 bits encoded, not four""" q, r = divmod(int(x), len(cls.ALPHABET)) digits = [cls.ALPHABET[r]] while q: q, r = divmod(q, len(cls.ALPHABET)) digits.append(cls.ALPHABET[r]) return ''.join(digits[::-1])
mercurial
mercurial//parser.pyclass:basealiasrules/expand
@classmethod def expand(cls, aliases, tree): """Expand aliases in tree, recursively. 'aliases' is a dictionary mapping user defined aliases to alias objects. """ return cls._expand(aliases, tree, [], {})
mxnet
mxnet//symbol/gen_sparse.pyfile:/symbol/gen_sparse.py:function:cos/cos
def cos(data=None, name=None, attr=None, out=None, **kwargs): """Computes the element-wise cosine of the input array. The input should be in radians (:math:`2\\pi` rad equals 360 degrees). .. math:: cos([0, \\pi/4, \\pi/2]) = [1, 0.707, 0] The storage type of ``cos`` output is always dense Defined in src/operator/tensor/elemwise_unary_op_trig.cc:L90 Parameters ---------- data : Symbol The input array. name : string, optional. Name of the resulting symbol. Returns ------- Symbol The result symbol. """ return 0,
livestock_linux
livestock_linux//air.pyfile:/air.py:function:stratification/stratification
def stratification(height, value_mean, height_top, value_top): """ Calculates the stratification of the temperature or relative humidity :param height: height at which the stratification value is wanted. in m. :param value_mean: mean value :param height_top: height at the top of the boundary. in m :param value_top: value at the top of the boundary :return: value at desired height. """ return value_mean - 2 * height * (value_mean - value_top) / height_top
phovea_server-5.0.1
phovea_server-5.0.1//phovea_server/launch.pyfile:/phovea_server/launch.py:function:create_embedded/create_embedded
def create_embedded(): """ Imports the phovea_server and creates an application """ from .server import create_application return create_application()
problog-2.1.0.40
problog-2.1.0.40//problog/util.pyfile:/problog/util.py:function:format_value/format_value
def format_value(data, precision=8): """Pretty print a given value. :param data: data to format :param precision: max. number of digits :type precision: int :return: pretty printed result :rtype: str """ if isinstance(data, float): data = ('%.' + str(precision) + 'g') % data else: data = str(data) return ('{:<' + str(precision + 2) + '}').format(data)
arvpyf-0.4.3
arvpyf-0.4.3//versioneer.pyfile:/versioneer.py:function:render_pep440_pre/render_pep440_pre
def render_pep440_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE """ if pieces['closest-tag']: rendered = pieces['closest-tag'] if pieces['distance']: rendered += '.post.dev%d' % pieces['distance'] else: rendered = '0.post.dev%d' % pieces['distance'] return rendered
simimg
simimg//utils/handyfunctions.pyfile:/utils/handyfunctions.py:function:mergeGroupDicts/mergeGroupDicts
def mergeGroupDicts(ListGDict): """ this routine takes a list of group dicts each element containing a dict of matching images returned by a condition modules. So if for example the date module returned: GL1 = { 1:{1,2,3}, 2:{2,3,6}, 5:{5,6} } and the hash module returned: GL2 = { 2:{2,3,4}, 5:{5,6}, 6:{6,7} } the ListGDict will be [G1, G2] This function should return the union of each by element: GL = { 1:{1,2,3}, 2:{2,3,4,6}, 5:{5,6}, 6:{6,7} } """ GDict = {} for d in ListGDict: for m, g in d.items(): previous = GDict[m] if m in GDict else set() GDict[m] = previous | g return GDict
uwsgiconf
uwsgiconf//uwsgi_stub.pyfile:/uwsgi_stub.py:function:cache_div/cache_div
def cache_div(key, value=2, expires=None, cache=None): """Divides the specified key value by the specified value. * http://uwsgi.readthedocs.io/en/latest/Changelog-1.9.9.html#math-for-cache :param str|unicode key: :param int value: :param int expires: Expire timeout (seconds). :param str|unicode cache: Cache name with optional address (if @-syntax is used). :rtype: bool """ return False
detext-1.0.12
detext-1.0.12//src/detext/utils/misc_utils.pyfile:/src/detext/utils/misc_utils.py:function:force_set_hparam/force_set_hparam
def force_set_hparam(hparams, name, value): """ Removes name from hparams and sets hparams.name == value. This function is introduced because hparams.set_hparam(name, value) requires value to be of the same type as the existing hparam.get(name) if name is already set in hparam """ hparams.del_hparam(name) hparams.add_hparam(name, value)
stldecomposemod
stldecomposemod//forecast_funcs.pyfile:/forecast_funcs.py:function:drift/drift
def drift(data, n=3, **kwargs): """The drift forecast for the next point is a linear extrapolation from the previous ``n`` points in the series. Args: data (np.array): Observed data, presumed to be ordered in time. n (int): period over which to calculate linear model for extrapolation Returns: float: a single-valued forecast for the next value in the series. """ yi = data[-n] yf = data[-1] slope = (yf - yi) / (n - 1) forecast = yf + slope return forecast
sylib
sylib//filenames.pyfile:/filenames.py:function:digits_required/digits_required
def digits_required(length): """ Returns the number of digits that would be needed to represent 'length' number of elements. """ digits = 0 while 10 ** digits <= length: digits += 1 return digits
riemann_keys
riemann_keys//base58.pyfile:/base58.py:function:to_long/to_long
def to_long(base, lookup_f, s): """ Convert an array to a (possibly bignum) integer, along with a prefix value of how many prefixed zeros there are. base: the source base lookup_f: a function to convert an element of s to a value between 0 and base-1. s: the value to convert """ prefix = 0 v = 0 for c in s: v *= base try: v += lookup_f(c) except Exception: raise ValueError('bad character %s in string %s' % (c, s)) if v == 0: prefix += 1 return v, prefix
dropbox
dropbox//team_log.pyclass:EventDetails/missing_details
@classmethod def missing_details(cls, val): """ Create an instance of this class set to the ``missing_details`` tag with value ``val``. :param MissingDetails val: :rtype: EventDetails """ return cls('missing_details', val)
tmep-2.0.1
tmep-2.0.1//tmep/functions.pyclass:Functions/tmpl_first
@staticmethod def tmpl_first(text, count=1, skip=0, sep=u'; ', join_str=u'; '): """ * synopsis: ``%first{text}`` or ``%first{text,count,skip}`` or ``%first{text,count,skip,sep,join}`` * description: Returns the first item, separated by ; . You can use %first{text,count,skip}, where count is the number of items (default 1) and skip is number to skip (default 0). You can also use %first{text,count,skip,sep,join} where sep is the separator, like ; or / and join is the text to concatenate the items. :param text: the string :param count: The number of items included :param skip: The number of items skipped :param sep: the separator. Usually is '; ' (default) or '/ ' :param join_str: the string which will join the items, default '; '. """ skip = int(skip) count = skip + int(count) return join_str.join(text.split(sep)[skip:count])
fake-blender-api-2.79-0.3.1
fake-blender-api-2.79-0.3.1//bpy/ops/armature.pyfile:/bpy/ops/armature.py:function:delete/delete
def delete(): """Remove selected bones from the armature """ pass
caps-ms-0.3
caps-ms-0.3//modellingService/Utils.pyfile:/modellingService/Utils.py:function:reshapeParams/reshapeParams
def reshapeParams(hyperparams, reshaper): """ A utility function that takes a dictionary of transformations for valid hyperparameters and filters out invalid params Testing the function: print reshapeParams({'regParam': 'invalid', 'elasticNetParam': 0.1, 'maxDepth': 0.1}, {'regParam': float, 'elasticNetParam': float, 'threshold': float}) # Expect: {'elasticNetParam': 0.1} :param hyperparams: the dirty dictionary :param reshaper: the transformations :return: the clean dictionary """ d = {} for k, v in hyperparams.items(): if reshaper.has_key(k): f = reshaper[k] if isinstance(v, str): if v.replace('.', '', 1).isdigit(): d[k] = f(v) else: continue elif isinstance(v, float): d[k] = f(v) elif isinstance(v, int): d[k] = f(v) else: continue else: continue return d
dqsegdb2
dqsegdb2//api.pyfile:/api.py:function:name_query_url/name_query_url
def name_query_url(host, ifo): """Returns the URL to use in querying for flag names Parameters ---------- host : `str` the URL of the target DQSEGDB2 host ifo : `str` the interferometer prefix Returns ------- url : `str` the full REST URL to query for information Examples -------- >>> from dqsegdb2.api import name_query_url >>> print(name_query_url('https://segments.ligo.org', 'G1')) 'https://segments.ligo.org/dq/G1' """ return '{host}/dq/{ifo}'.format(host=host, ifo=ifo)
tidings
tidings//events.pyclass:Event/_activation_url
@classmethod def _activation_url(cls, watch): """Return a URL pointing to a view which :meth:`activates <tidings.models.Watch.activate()>` a watch. TODO: provide generic implementation of this before liberating. Generic implementation could involve a setting to the default ``reverse()`` path, e.g. ``'tidings.activate_watch'``. """ raise NotImplementedError
requests
requests//cookies.pyfile:/cookies.py:function:remove_cookie_by_name/remove_cookie_by_name
def remove_cookie_by_name(cookiejar, name, domain=None, path=None): """Unsets a cookie by name, by default over all domains and paths. Wraps CookieJar.clear(), is O(n). """ clearables = [] for cookie in cookiejar: if cookie.name != name: continue if domain is not None and domain != cookie.domain: continue if path is not None and path != cookie.path: continue clearables.append((cookie.domain, cookie.path, cookie.name)) for domain, path, name in clearables: cookiejar.clear(domain, path, name)
gevent
gevent//util.pyclass:GreenletTree/current_tree
@classmethod def current_tree(cls): """ current_tree() -> GreenletTree Returns the `GreenletTree` for the current thread. """ return cls._forest()[1]
pyboto3-1.4.4
pyboto3-1.4.4//pyboto3/waf.pyfile:/pyboto3/waf.py:function:get_sql_injection_match_set/get_sql_injection_match_set
def get_sql_injection_match_set(SqlInjectionMatchSetId=None): """ Returns the SqlInjectionMatchSet that is specified by SqlInjectionMatchSetId . See also: AWS API Documentation Examples The following example returns the details of a SQL injection match set with the ID example1ds3t-46da-4fdb-b8d5-abc321j569j5. Expected Output: :example: response = client.get_sql_injection_match_set( SqlInjectionMatchSetId='string' ) :type SqlInjectionMatchSetId: string :param SqlInjectionMatchSetId: [REQUIRED] The SqlInjectionMatchSetId of the SqlInjectionMatchSet that you want to get. SqlInjectionMatchSetId is returned by CreateSqlInjectionMatchSet and by ListSqlInjectionMatchSets . :rtype: dict :return: { 'SqlInjectionMatchSet': { 'SqlInjectionMatchSetId': 'string', 'Name': 'string', 'SqlInjectionMatchTuples': [ { 'FieldToMatch': { 'Type': 'URI'|'QUERY_STRING'|'HEADER'|'METHOD'|'BODY', 'Data': 'string' }, 'TextTransformation': 'NONE'|'COMPRESS_WHITE_SPACE'|'HTML_ENTITY_DECODE'|'LOWERCASE'|'CMD_LINE'|'URL_DECODE' }, ] } } :returns: HEADER : A specified request header, for example, the value of the User-Agent or Referer header. If you choose HEADER for the type, specify the name of the header in Data . METHOD : The HTTP method, which indicated the type of operation that the request is asking the origin to perform. Amazon CloudFront supports the following methods: DELETE , GET , HEAD , OPTIONS , PATCH , POST , and PUT . QUERY_STRING : A query string, which is the part of a URL that appears after a ? character, if any. URI : The part of a web request that identifies a resource, for example, /images/daily-ad.jpg . BODY : The part of a request that contains any additional data that you want to send to your web server as the HTTP request body, such as data from a form. The request body immediately follows the request headers. Note that only the first 8192 bytes of the request body are forwarded to AWS WAF for inspection. To allow or block requests based on the length of the body, you can create a size constraint set. For more information, see CreateSizeConstraintSet . """ pass
ipyroute-0.0.38
ipyroute-0.0.38//ipyroute/base.pyclass:Base/_get
@classmethod def _get(cls, *args): """ The method determines what iproute2 command retrieves info, and how the output is fed back. """ raise NotImplementedError
mmtf
mmtf//codecs/encoders/encoders.pyfile:/codecs/encoders/encoders.py:function:run_length_encode/run_length_encode
def run_length_encode(in_array): """A function to run length decode an int array. :param in_array: the inptut array of integers :return the encoded integer array""" if len(in_array) == 0: return [] curr_ans = in_array[0] out_array = [curr_ans] counter = 1 for in_int in in_array[1:]: if in_int == curr_ans: counter += 1 else: out_array.append(counter) out_array.append(in_int) curr_ans = in_int counter = 1 out_array.append(counter) return out_array
dazl-6.7.6
dazl-6.7.6//dazl/plugins/capture/plugin_capture.pyclass:LedgerCapturePlugin/to_file
@classmethod def to_file(cls, path, **kwargs) ->'LedgerCapturePlugin': """ Return a :class:`LedgerCapturePlugin` that writes its output to a file. :param path: The file to write to. """ return cls(open(path, 'w'), True, **kwargs)
BranchBound-1.2.4
BranchBound-1.2.4//BranchBound/Heuristic.pyfile:/BranchBound/Heuristic.py:function:compute_recursive_heuristic/compute_recursive_heuristic
def compute_recursive_heuristic(init_heuristic_object): """ Does absolutely nothing """ return None
ssb_optimize
ssb_optimize//optimizer.pyfile:/optimizer.py:function:constraints_check/constraints_check
def constraints_check(constraints=None): """Check constraints list for consistency and return the list with basic problems corrected. A valid constraints list is a list of constraint dictionaries. --> [{const_dict}, ... ,{const_dict}] A constraint dictionary specifies individual constraint functions, arguments (args and kwargs), and constraint types. The value corresponding the 'func' key is a callable function which defines the constraint. Traditional functions ('def func(x): ...') and lambda functions ('func = lambda x: ...') both work. The function signature must be of the form 'func(x, *args, **kwargs)' where 'x' is a float or a list of floats representing a vector. The return value from 'func' must be a float. Values corresponding to the 'args' and 'kwargs' keys are any additional arguments to be passed to 'func' (both are optional). Positional arguments (args) are specified as a tuple and keyword arguments (kwargs) are specified as a dictionary. The 'type' key specifies the inequality that the value returned from 'func' must obey for the constraint to be satisfied. Values for the inequality specification may be '>0', '>=0', '<0', '<=0'. const_dict --> {'type': ineq_spec_string, 'func': callable_func, 'args': (args_tuple), 'kwargs': {kwargs_dict}} Args: constraints (list): List of constraint dictionaries. Returns: list: Validated list of constraint dictionaries. Raises: TypeError: constraints must be a list of dictionaries TypeError: constraint is not a dictionary TypeError: constraint dictionary does not have required "type" key ValueError: constraint["type"] must be >0, >=0, <0, or <=0 TypeError: constraint dictionary does not have required "func" key ValueError: constraint["func"] must be callable TypeError: constraint["args"] must be a tuple TypeError: constraint["kwargs"] must be a dictionary """ if constraints is not None: if not isinstance(constraints, list): raise TypeError('constraints must be a list of dictionaries') for i, const in enumerate(constraints): if not isinstance(const, dict): raise TypeError('constraint[%d] is not a dictionary' % i) if 'type' not in const.keys(): raise TypeError( 'constraint[%d] dictionary does not have required "type" key' % i) if const['type'] not in ['>0', '>=0', '<0', '<=0']: raise ValueError( 'constraint[%d]["type"] must be >0, >=0, <0, or <=0' % i) if 'func' not in const.keys(): raise TypeError( 'constraint[%d] dictionary does not have required "func" key' % i) if not callable(const['func']): raise TypeError('constraint[%d]["func"] must be callable' % i) if 'args' not in const.keys(): const['args'] = () if not isinstance(const['args'], tuple): raise TypeError('constraint[%d]["args"] must be a tuple' % i) if 'kwargs' not in const.keys(): const['kwargs'] = {} if not isinstance(const['kwargs'], dict): raise TypeError( 'constraint[%d]["kwargs"] must be a dictionary' % i) return constraints
igraph
igraph//drawing/baseclasses.pyclass:AbstractXMLRPCDrawer/_resolve_hostname
@staticmethod def _resolve_hostname(url): """Parses the given URL, resolves the hostname to an IP address and returns a new URL with the resolved IP address. This speeds up things big time on Mac OS X where an IP lookup would be performed for every XML-RPC call otherwise.""" from urllib.parse import urlparse, urlunparse import re url_parts = urlparse(url) hostname = url_parts.netloc if re.match('[0-9.:]+$', hostname): return url from socket import gethostbyname if ':' in hostname: hostname = hostname[0:hostname.index(':')] hostname = gethostbyname(hostname) if url_parts.port is not None: hostname = '%s:%d' % (hostname, url_parts.port) url_parts = list(url_parts) url_parts[1] = hostname return urlunparse(url_parts)
declxml-1.1.3
declxml-1.1.3//declxml.pyfile:/declxml.py:function:_is_valid_root_processor/_is_valid_root_processor
def _is_valid_root_processor(processor): """Return True if the given XML processor can be used as a root processor.""" return hasattr(processor, 'parse_at_root')
handygeometry-0.12
handygeometry-0.12//handygeometry/handygeometry.pyfile:/handygeometry/handygeometry.py:function:area_trapezoid/area_trapezoid
def area_trapezoid(a, b, height): """ Formula: (a + b) * h / 2 """ return (a + b) * height / 2
stoq-4.7.0.post1
stoq-4.7.0.post1//stoqlib/domain/station.pyclass:BranchStation/get_active_stations
@classmethod def get_active_stations(cls, store): """Returns the currently active branch stations. :param store: a store :returns: a sequence of currently active stations """ return store.find(cls, is_active=True).order_by(cls.name)
pacifica-metadata-0.12.4
pacifica-metadata-0.12.4//pacifica/metadata/orm/sync.pyclass:MetadataSystem/get_version
@classmethod def get_version(cls): """Get the current version as a tuple.""" return cls.get(part='major').value, cls.get(part='minor').value
zope.dublincore-4.2.0
zope.dublincore-4.2.0//src/zope/dublincore/interfaces.pyclass:ICMFDublinCore/Rights
def Rights(): """Return the resource rights. Return a string describing the intellectual property status, if any, of the resource. for the resource. The first unqualified Dublin Core `Rights` element value is returned as a unicode string if an unqualified element is defined, otherwise, an empty unicode string is returned. """
perceval
perceval//client.pyclass:HttpClient/sanitize_for_archive
@staticmethod def sanitize_for_archive(url, headers, payload): """Sanitize the URL, headers and payload of a HTTP request before storing/retrieving items. By default, this method does not modify url, headers and payload. The modifications take place within the specific backends that redefine the sanitize_for_archive. :param: url: HTTP url request :param: headers: HTTP headers request :param: payload: HTTP payload request :returns url, headers and payload sanitized """ return url, headers, payload
mercurial-5.4
mercurial-5.4//mercurial/thirdparty/zope/interface/common/idatetime.pyclass:IDateTimeClass/utcfromtimestamp
def utcfromtimestamp(timestamp): """Return the UTC datetime from the POSIX timestamp with tzinfo None. This may raise ValueError, if the timestamp is out of the range of values supported by the platform C gmtime() function. It's common for this to be restricted to years in 1970 through 2038. See also fromtimestamp(). """
dropbox-10.1.2
dropbox-10.1.2//dropbox/team_log.pyclass:EventType/member_change_status
@classmethod def member_change_status(cls, val): """ Create an instance of this class set to the ``member_change_status`` tag with value ``val``. :param MemberChangeStatusType val: :rtype: EventType """ return cls('member_change_status', val)
everest
everest//missions/kepler/kepler.pyfile:/missions/kepler/kepler.py:function:InjectionStatistics/InjectionStatistics
def InjectionStatistics(*args, **kwargs): """ Computes and plots the statistics for injection/recovery tests. """ raise NotImplementedError('This mission is not yet supported.')
pyboto3-1.4.4
pyboto3-1.4.4//pyboto3/cognitoidentityprovider.pyfile:/pyboto3/cognitoidentityprovider.py:function:get_csv_header/get_csv_header
def get_csv_header(UserPoolId=None): """ Gets the header information for the .csv file to be used as input for the user import job. See also: AWS API Documentation :example: response = client.get_csv_header( UserPoolId='string' ) :type UserPoolId: string :param UserPoolId: [REQUIRED] The user pool ID for the user pool that the users are to be imported into. :rtype: dict :return: { 'UserPoolId': 'string', 'CSVHeader': [ 'string', ] } """ pass
txkube
txkube//_interface.pyclass:IKubernetes/versioned_client
def versioned_client(): """ Create a client which will interact with the Kubernetes deployment represented by this object. Customize that client for the version of Kubernetes it will interact with. :return Deferred(IKubernetesClient): The client. """
neuprint-python-0.4.9
neuprint-python-0.4.9//versioneer.pyfile:/versioneer.py:function:render_pep440_pre/render_pep440_pre
def render_pep440_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE """ if pieces['closest-tag']: rendered = pieces['closest-tag'] if pieces['distance']: rendered += '.post.dev%d' % pieces['distance'] else: rendered = '0.post.dev%d' % pieces['distance'] return rendered
apologies-0.1.14
apologies-0.1.14//src/apologies/demo.pyfile:/src/apologies/demo.py:function:_draw/_draw
def _draw(stdscr, board, state, history): """Draw the static portions of the screen.""" stdscr.clear() stdscr.border() stdscr.refresh() board.border() board.refresh() state.border() state.refresh() history.border() history.refresh()
mail263
mail263//mail_utils.pyfile:/mail_utils.py:function:get_size_cond/get_size_cond
def get_size_cond(rule_dict): """ 如果 size 不存在,默认 >= :param rule_dict: :return: """ try: cond = rule_dict['size']['cond'] except KeyError: return 'g' return 'g' if cond == '>=' else 'l'
dgl-0.4.3.post2.data
dgl-0.4.3.post2.data//purelib/dgl/backend/backend.pyfile:/purelib/dgl/backend/backend.py:function:astype/astype
def astype(input, ty): """Convert the input tensor to the given data type. Parameters ---------- input : Tensor The input tensor. ty : data type It should be one of the values in the data type dict. Returns ------- Tensor A framework-specific tensor. """ pass
aws-ssm-tools-1.2.1
aws-ssm-tools-1.2.1//ssm_tools/common.pyfile:/ssm_tools/common.py:function:bytes_to_human/bytes_to_human
def bytes_to_human(size): """ Convert Bytes to more readable units """ units = ['B', 'kB', 'MB', 'GB', 'TB'] unit_idx = 0 while unit_idx < len(units) - 1: if size < 2048: break size /= 1024.0 unit_idx += 1 return size, units[unit_idx]
dials-0.0.1
dials-0.0.1//algorithms/integration/parallel_integrator.pyclass:MaskCalculatorFactory/create
@classmethod def create(cls, experiments, params=None): """ Select the mask calculator """ from dials.algorithms.profile_model.gaussian_rs.algorithm import GaussianRSMaskCalculatorFactory if params is None: from dials.command_line.integrate import phil_scope params = phil_scope.extract() selection = params.profile.algorithm if selection == 'gaussian_rs': algorithm = GaussianRSMaskCalculatorFactory.create(experiments) else: raise RuntimeError('Unknown profile model algorithm') return algorithm
bhmm-0.6.3
bhmm-0.6.3//bhmm/util/analysis.pyfile:/bhmm/util/analysis.py:function:beta_confidence_intervals/beta_confidence_intervals
def beta_confidence_intervals(ci_X, ntrials, ci=0.95): """ Compute confidence intervals of beta distributions. Parameters ---------- ci_X : numpy.array Computed confidence interval estimate from `ntrials` experiments ntrials : int The number of trials that were run. ci : float, optional, default=0.95 Confidence interval to report (e.g. 0.95 for 95% confidence interval) Returns ------- Plow : float The lower bound of the symmetric confidence interval. Phigh : float The upper bound of the symmetric confidence interval. Examples -------- >>> ci_X = np.random.rand(10,10) >>> ntrials = 100 >>> [Plow, Phigh] = beta_confidence_intervals(ci_X, ntrials) """ ci_low = 0.5 - ci / 2 ci_high = 0.5 + ci / 2 from scipy.stats import beta Plow = ci_X * 0.0 Phigh = ci_X * 0.0 for i in range(ci_X.shape[0]): for j in range(ci_X.shape[1]): Plow[i, j] = beta.ppf(ci_low, a=ci_X[i, j] * ntrials, b=(1 - ci_X[i, j]) * ntrials) Phigh[i, j] = beta.ppf(ci_high, a=ci_X[i, j] * ntrials, b=(1 - ci_X[i, j]) * ntrials) return [Plow, Phigh]
turbulenz_tools-1.0.7
turbulenz_tools-1.0.7//turbulenz_tools/utils/json_utils.pyfile:/turbulenz_tools/utils/json_utils.py:function:float_to_string/float_to_string
def float_to_string(f): """Unitiliy float encoding which clamps floats close to 0 and 1 and uses %g instead of repr().""" if abs(f) < 1e-06: return '0' elif abs(1 - f) < 1e-06: return '1' return '%g' % f
nexson-0.0.2
nexson-0.0.2//nexson/syntax/helper.pyfile:/nexson/syntax/helper.py:function:_cull_redundant_about/_cull_redundant_about
def _cull_redundant_about(obj): """Removes the @about key from the `obj` dict if that value refers to the dict's '@id' """ about_val = obj.get('@about') if about_val: id_val = obj.get('@id') if id_val and '#' + id_val == about_val: del obj['@about']
gemato-14.3
gemato-14.3//gemato/util.pyfile:/gemato/util.py:function:path_starts_with/path_starts_with
def path_starts_with(path, prefix): """ Returns True if the specified @path starts with the @prefix, performing component-wide comparison. Otherwise returns False. """ return prefix == '' or (path + '/').startswith(prefix.rstrip('/') + '/')
pegaflow
pegaflow//netlogger/util.pyfile:/netlogger/util.py:function:_find_space/_find_space
def _find_space(text, maxpos): """Find rightmost whitespace position, or -1 if none.""" p = -1 for ws in (' ', '-'): p = max(p, text.rfind(ws, 0, maxpos)) return p
configuration-registry-0.5.0
configuration-registry-0.5.0//registry.pyfile:/registry.py:function:valid/valid
def valid(options, templateopts): """Verify that all required options in the template are present""" required = templateopts['required'].keys() for k in required: if k not in options: return False return True
enablebanking
enablebanking//models/seb_sweden_connector_settings.pyclass:SEBSwedenConnectorSettings/__ne__
def __ne__(A, other): """Returns true if both objects are not equal""" return not A == other
girder-3.1.0
girder-3.1.0//plugins/oauth/girder_oauth/providers/base.pyclass:ProviderBase/addScopes
@classmethod def addScopes(cls, scopes): """ Plugins wishing to use additional provider features that require other auth scopes should use this method to add additional required scopes to the list. :param scopes: List of additional required scopes. :type scopes: list :returns: The new list of auth scopes. """ cls._AUTH_SCOPES.extend(scopes) return cls._AUTH_SCOPES
Products.listen-0.7.1
Products.listen-0.7.1//Products/listen/interfaces/mailinglist.pyclass:IPendingList/get_user_emails
def get_user_emails(): """ return the list of all pending emails """
pyjen
pyjen//plugins/parameterizedbuild.pyclass:ParameterizedBuild/get_jenkins_plugin_name
@staticmethod def get_jenkins_plugin_name(): """Gets the name of the Jenkins plugin associated with this PyJen plugin This static method is used by the PyJen plugin API to associate this class with a specific Jenkins plugin, as it is encoded in the config.xml :rtype: :class:`str` """ return 'hudson.model.ParametersDefinitionProperty'
ANBOT-3.1.0
ANBOT-3.1.0//ANBOT/utils/chat_formatting.pyfile:/ANBOT/utils/chat_formatting.py:function:escape/escape
def escape(text: str, *, mass_mentions: bool=False, formatting: bool=False ) ->str: """Get text with all mass mentions or markdown escaped. Parameters ---------- text : str The text to be escaped. mass_mentions : `bool`, optional Set to :code:`True` to escape mass mentions in the text. formatting : `bool`, optional Set to :code:`True` to escpae any markdown formatting in the text. Returns ------- str The escaped text. """ if mass_mentions: text = text.replace('@everyone', '@\u200beveryone') text = text.replace('@here', '@\u200bhere') if formatting: text = text.replace('`', '\\`').replace('*', '\\*').replace('_', '\\_' ).replace('~', '\\~') return text
dropbox
dropbox//files.pyclass:CreateFolderBatchResultEntry/failure
@classmethod def failure(cls, val): """ Create an instance of this class set to the ``failure`` tag with value ``val``. :param CreateFolderEntryError val: :rtype: CreateFolderBatchResultEntry """ return cls('failure', val)
netssh2
netssh2//session.pyclass:Session/_encode_to_bytes
@staticmethod def _encode_to_bytes(string): """ Tries to encode any string from bytes. Does not fail if gets already encoded string. :param string: string to encode :type string: basestring :return: encoded string :rtype: bytes """ return string if isinstance(string, bytes) else string.encode('ascii', 'ignore')
cis_interface
cis_interface//metaschema/datatypes/MetaschemaType.pyclass:MetaschemaType/encode_data_readable
@classmethod def encode_data_readable(cls, obj, typedef): """Encode an object's data in a readable format. Args: obj (object): Object to encode. typedef (dict): Type definition that should be used to encode the object. Returns: string: Encoded object. """ return cls.encode_data(obj, typedef)
Kivy-1.11.1
Kivy-1.11.1//kivy/tools/pep8checker/pep8.pyfile:/kivy/tools/pep8checker/pep8.py:function:mute_string/mute_string
def mute_string(text): """Replace contents with 'xxx' to prevent syntax matching. >>> mute_string('"abc"') '"xxx"' >>> mute_string("'''abc'''") "'''xxx'''" >>> mute_string("r'abc'") "r'xxx'" """ start = text.index(text[-1]) + 1 end = len(text) - 1 if text[-3:] in ('"""', "'''"): start += 2 end -= 2 return text[:start] + 'x' * (end - start) + text[end:]
grabseqslib
grabseqslib//imicrobe.pyfile:/imicrobe.py:function:_closest_below_index/_closest_below_index
def _closest_below_index(l, n): """ Helper function. Returns index of closest number in `l` to `n`, without going over. """ best = -1 best_i = -1 for i in range(len(l)): if l[i] < n: if n - l[i] < n - best: best_i = i best = l[i] return best_i
kemlglearn-0.3.15
kemlglearn-0.3.15//kemlglearn/metrics/cluster.pyfile:/kemlglearn/metrics/cluster.py:function:maplabels/maplabels
def maplabels(labels): """ Returns a dictionary mapping a set of labels to an index :param labels: :return: """ poslabels = {} for lab, p in zip(labels, range(len(labels))): poslabels[lab] = p return poslabels
ncsv-0.15.5
ncsv-0.15.5//ncsv/ncsv.pyfile:/ncsv/ncsv.py:function:pad/pad
def pad(s, max_length, right=True): """ Returns a padded string """ if right: return s[:max_length].ljust(max_length) else: return s[:max_length].rjust(max_length)
keystone-16.0.0
keystone-16.0.0//keystone/oauth1/backends/base.pyfile:/keystone/oauth1/backends/base.py:function:filter_token/filter_token
def filter_token(access_token_ref): """Filter out private items in an access token dict. 'access_secret' is never returned. :returns: access_token_ref """ if access_token_ref: access_token_ref = access_token_ref.copy() access_token_ref.pop('access_secret', None) return access_token_ref
guiqwt
guiqwt//styles.pyclass:ItemParameters/register_multiselection
@classmethod def register_multiselection(cls, klass, klass_ms): """Register a DataSet couple: (DataSet, DataSet_for_MultiSelection)""" cls.MULTISEL_DATASETS.insert(0, (klass, klass_ms))
skutil-0.0.16
skutil-0.0.16//versioneer.pyfile:/versioneer.py:function:plus_or_dot/plus_or_dot
def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if '+' in pieces.get('closest-tag', ''): return '.' return '+'
bpy
bpy//ops/object.pyfile:/ops/object.py:function:scale_clear/scale_clear
def scale_clear(clear_delta: bool=False): """Clear the object’s scale :param clear_delta: Clear Delta, Clear delta scale in addition to clearing the normal scale transform :type clear_delta: bool """ pass
mixer-6.1.3
mixer-6.1.3//mixer/backend/peewee.pyfile:/mixer/backend/peewee.py:function:get_blob/get_blob
def get_blob(**kwargs): """ Generate value for BlobField. """ raise NotImplementedError
mxnet
mxnet//symbol/gen_sparse.pyfile:/symbol/gen_sparse.py:function:cosh/cosh
def cosh(data=None, name=None, attr=None, out=None, **kwargs): """Returns the hyperbolic cosine of the input array, computed element-wise. .. math:: cosh(x) = 0.5\\times(exp(x) + exp(-x)) The storage type of ``cosh`` output is always dense Defined in src/operator/tensor/elemwise_unary_op_trig.cc:L351 Parameters ---------- data : Symbol The input array. name : string, optional. Name of the resulting symbol. Returns ------- Symbol The result symbol. """ return 0,
Junkyard-0.0.3a5
Junkyard-0.0.3a5//Junkyard/garbagebasket/FileHandler.pyfile:/Junkyard/garbagebasket/FileHandler.py:function:uniform_filename/uniform_filename
def uniform_filename(filename): """ function makes filename directory strings uniform to the "\\" backslash standard :param filename: file directory string you want to format to a "\\" standard :return: """ filters = ['/', '//', '\\\\'] for f in filters: if f in filename: filename = filename.replace(f, '\\') return filename
nipy-0.4.2
nipy-0.4.2//nipy/io/nibcompat.pyfile:/nipy/io/nibcompat.py:function:get_affine/get_affine
def get_affine(img): """ Return affine from nibabel image Parameters ---------- img : ``SpatialImage`` instance Instance of nibabel ``SpatialImage`` class Returns ------- affine : object affine object from `img` """ try: return img.affine except AttributeError: return img.get_affine()
bpy
bpy//app/timers.pyfile:/app/timers.py:function:unregister/unregister
def unregister(function): """Unregister timer. :param function: Function to unregister. """ pass