repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
Erotemic/utool | utool/util_list.py | length_hint | def length_hint(obj, default=0):
"""
Return an estimate of the number of items in obj.
This is the PEP 424 implementation.
If the object supports len(), the result will be
exact. Otherwise, it may over- or under-estimate by an
arbitrary amount. The result will be an integer >= 0.
"""
tr... | python | def length_hint(obj, default=0):
"""
Return an estimate of the number of items in obj.
This is the PEP 424 implementation.
If the object supports len(), the result will be
exact. Otherwise, it may over- or under-estimate by an
arbitrary amount. The result will be an integer >= 0.
"""
tr... | [
"def",
"length_hint",
"(",
"obj",
",",
"default",
"=",
"0",
")",
":",
"try",
":",
"return",
"len",
"(",
"obj",
")",
"except",
"TypeError",
":",
"try",
":",
"get_hint",
"=",
"type",
"(",
"obj",
")",
".",
"__length_hint__",
"except",
"AttributeError",
":... | Return an estimate of the number of items in obj.
This is the PEP 424 implementation.
If the object supports len(), the result will be
exact. Otherwise, it may over- or under-estimate by an
arbitrary amount. The result will be an integer >= 0. | [
"Return",
"an",
"estimate",
"of",
"the",
"number",
"of",
"items",
"in",
"obj",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L3459-L3486 | train |
product-definition-center/pdc-client | pdc_client/plugin_helpers.py | add_parser_arguments | def add_parser_arguments(parser, args, group=None, prefix=DATA_PREFIX):
"""
Helper method that populates parser arguments. The argument values can
be later retrieved with `extract_arguments` method.
The `args` argument to this method should be a dict with strings as
keys and dicts as values. The ke... | python | def add_parser_arguments(parser, args, group=None, prefix=DATA_PREFIX):
"""
Helper method that populates parser arguments. The argument values can
be later retrieved with `extract_arguments` method.
The `args` argument to this method should be a dict with strings as
keys and dicts as values. The ke... | [
"def",
"add_parser_arguments",
"(",
"parser",
",",
"args",
",",
"group",
"=",
"None",
",",
"prefix",
"=",
"DATA_PREFIX",
")",
":",
"if",
"group",
":",
"parser",
"=",
"parser",
".",
"add_argument_group",
"(",
"group",
")",
"for",
"arg",
",",
"kwargs",
"in... | Helper method that populates parser arguments. The argument values can
be later retrieved with `extract_arguments` method.
The `args` argument to this method should be a dict with strings as
keys and dicts as values. The keys will be used as keys in returned
data. Their values will be passed as kwargs ... | [
"Helper",
"method",
"that",
"populates",
"parser",
"arguments",
".",
"The",
"argument",
"values",
"can",
"be",
"later",
"retrieved",
"with",
"extract_arguments",
"method",
"."
] | 7236fd8b72e675ebb321bbe337289d9fbeb6119f | https://github.com/product-definition-center/pdc-client/blob/7236fd8b72e675ebb321bbe337289d9fbeb6119f/pdc_client/plugin_helpers.py#L102-L125 | train |
product-definition-center/pdc-client | pdc_client/plugin_helpers.py | add_mutually_exclusive_args | def add_mutually_exclusive_args(parser, args, required=False, prefix=DATA_PREFIX):
"""
Helper method that populates mutually exclusive arguments. The argument values can
be later retrieved with `extract_arguments` method.
The `args` argument to this method should be a dict with strings as
keys and ... | python | def add_mutually_exclusive_args(parser, args, required=False, prefix=DATA_PREFIX):
"""
Helper method that populates mutually exclusive arguments. The argument values can
be later retrieved with `extract_arguments` method.
The `args` argument to this method should be a dict with strings as
keys and ... | [
"def",
"add_mutually_exclusive_args",
"(",
"parser",
",",
"args",
",",
"required",
"=",
"False",
",",
"prefix",
"=",
"DATA_PREFIX",
")",
":",
"parser",
"=",
"parser",
".",
"add_mutually_exclusive_group",
"(",
"required",
"=",
"required",
")",
"for",
"arg",
","... | Helper method that populates mutually exclusive arguments. The argument values can
be later retrieved with `extract_arguments` method.
The `args` argument to this method should be a dict with strings as
keys and dicts as values. The keys will be used as keys in returned
data. Their values will be passe... | [
"Helper",
"method",
"that",
"populates",
"mutually",
"exclusive",
"arguments",
".",
"The",
"argument",
"values",
"can",
"be",
"later",
"retrieved",
"with",
"extract_arguments",
"method",
"."
] | 7236fd8b72e675ebb321bbe337289d9fbeb6119f | https://github.com/product-definition-center/pdc-client/blob/7236fd8b72e675ebb321bbe337289d9fbeb6119f/pdc_client/plugin_helpers.py#L128-L147 | train |
product-definition-center/pdc-client | pdc_client/plugin_helpers.py | add_create_update_args | def add_create_update_args(parser, required_args, optional_args, create=False):
"""Wrapper around ``add_parser_arguments``.
If ``create`` is True, one argument group will be created for each of
``required_args`` and ``optional_args``. Each required argument will have
the ``required`` parameter set to T... | python | def add_create_update_args(parser, required_args, optional_args, create=False):
"""Wrapper around ``add_parser_arguments``.
If ``create`` is True, one argument group will be created for each of
``required_args`` and ``optional_args``. Each required argument will have
the ``required`` parameter set to T... | [
"def",
"add_create_update_args",
"(",
"parser",
",",
"required_args",
",",
"optional_args",
",",
"create",
"=",
"False",
")",
":",
"if",
"create",
":",
"for",
"key",
"in",
"required_args",
":",
"required_args",
"[",
"key",
"]",
"[",
"'required'",
"]",
"=",
... | Wrapper around ``add_parser_arguments``.
If ``create`` is True, one argument group will be created for each of
``required_args`` and ``optional_args``. Each required argument will have
the ``required`` parameter set to True automatically.
If ``create`` is False, only one group of optional arguments wi... | [
"Wrapper",
"around",
"add_parser_arguments",
"."
] | 7236fd8b72e675ebb321bbe337289d9fbeb6119f | https://github.com/product-definition-center/pdc-client/blob/7236fd8b72e675ebb321bbe337289d9fbeb6119f/pdc_client/plugin_helpers.py#L150-L169 | train |
product-definition-center/pdc-client | pdc_client/plugin_helpers.py | extract_arguments | def extract_arguments(args, prefix=DATA_PREFIX):
"""Return a dict of arguments created by `add_parser_arguments`.
If the key in `args` contains two underscores, a nested dictionary will be
created. Only keys starting with given prefix are examined. The prefix is
stripped away and does not appear in the... | python | def extract_arguments(args, prefix=DATA_PREFIX):
"""Return a dict of arguments created by `add_parser_arguments`.
If the key in `args` contains two underscores, a nested dictionary will be
created. Only keys starting with given prefix are examined. The prefix is
stripped away and does not appear in the... | [
"def",
"extract_arguments",
"(",
"args",
",",
"prefix",
"=",
"DATA_PREFIX",
")",
":",
"data",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"args",
".",
"__dict__",
")",
":",
"if",
"key",
".",
"startswith",
"(",
"prefix",
")",
"a... | Return a dict of arguments created by `add_parser_arguments`.
If the key in `args` contains two underscores, a nested dictionary will be
created. Only keys starting with given prefix are examined. The prefix is
stripped away and does not appear in the result. | [
"Return",
"a",
"dict",
"of",
"arguments",
"created",
"by",
"add_parser_arguments",
"."
] | 7236fd8b72e675ebb321bbe337289d9fbeb6119f | https://github.com/product-definition-center/pdc-client/blob/7236fd8b72e675ebb321bbe337289d9fbeb6119f/pdc_client/plugin_helpers.py#L172-L194 | train |
glormph/msstitch | src/app/actions/mslookup/searchspace.py | create_searchspace | def create_searchspace(lookup, fastafn, proline_cut=False,
reverse_seqs=True, do_trypsinize=True):
"""Given a FASTA database, proteins are trypsinized and resulting peptides
stored in a database or dict for lookups"""
allpeps = []
for record in SeqIO.parse(fastafn, 'fasta'):
... | python | def create_searchspace(lookup, fastafn, proline_cut=False,
reverse_seqs=True, do_trypsinize=True):
"""Given a FASTA database, proteins are trypsinized and resulting peptides
stored in a database or dict for lookups"""
allpeps = []
for record in SeqIO.parse(fastafn, 'fasta'):
... | [
"def",
"create_searchspace",
"(",
"lookup",
",",
"fastafn",
",",
"proline_cut",
"=",
"False",
",",
"reverse_seqs",
"=",
"True",
",",
"do_trypsinize",
"=",
"True",
")",
":",
"allpeps",
"=",
"[",
"]",
"for",
"record",
"in",
"SeqIO",
".",
"parse",
"(",
"fas... | Given a FASTA database, proteins are trypsinized and resulting peptides
stored in a database or dict for lookups | [
"Given",
"a",
"FASTA",
"database",
"proteins",
"are",
"trypsinized",
"and",
"resulting",
"peptides",
"stored",
"in",
"a",
"database",
"or",
"dict",
"for",
"lookups"
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/mslookup/searchspace.py#L24-L43 | train |
Erotemic/utool | utool/util_hash.py | hashid_arr | def hashid_arr(arr, label='arr', hashlen=16):
""" newer version of hashstr_arr2 """
hashstr = hash_data(arr)[0:hashlen]
if isinstance(arr, (list, tuple)):
shapestr = len(arr)
else:
shapestr = ','.join(list(map(str, arr.shape)))
hashid = '{}-{}-{}'.format(label, shapestr, hashstr)
... | python | def hashid_arr(arr, label='arr', hashlen=16):
""" newer version of hashstr_arr2 """
hashstr = hash_data(arr)[0:hashlen]
if isinstance(arr, (list, tuple)):
shapestr = len(arr)
else:
shapestr = ','.join(list(map(str, arr.shape)))
hashid = '{}-{}-{}'.format(label, shapestr, hashstr)
... | [
"def",
"hashid_arr",
"(",
"arr",
",",
"label",
"=",
"'arr'",
",",
"hashlen",
"=",
"16",
")",
":",
"hashstr",
"=",
"hash_data",
"(",
"arr",
")",
"[",
"0",
":",
"hashlen",
"]",
"if",
"isinstance",
"(",
"arr",
",",
"(",
"list",
",",
"tuple",
")",
")... | newer version of hashstr_arr2 | [
"newer",
"version",
"of",
"hashstr_arr2"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_hash.py#L163-L171 | train |
Erotemic/utool | utool/util_hash.py | _update_hasher | def _update_hasher(hasher, data):
"""
This is the clear winner over the generate version.
Used by hash_data
Ignore:
import utool
rng = np.random.RandomState(0)
# str1 = rng.rand(0).dumps()
str1 = b'SEP'
str2 = rng.rand(10000).dumps()
for timer in utool.Ti... | python | def _update_hasher(hasher, data):
"""
This is the clear winner over the generate version.
Used by hash_data
Ignore:
import utool
rng = np.random.RandomState(0)
# str1 = rng.rand(0).dumps()
str1 = b'SEP'
str2 = rng.rand(10000).dumps()
for timer in utool.Ti... | [
"def",
"_update_hasher",
"(",
"hasher",
",",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"(",
"tuple",
",",
"list",
",",
"zip",
")",
")",
":",
"needs_iteration",
"=",
"True",
"elif",
"(",
"util_type",
".",
"HAVE_NUMPY",
"and",
"isinstance",
... | This is the clear winner over the generate version.
Used by hash_data
Ignore:
import utool
rng = np.random.RandomState(0)
# str1 = rng.rand(0).dumps()
str1 = b'SEP'
str2 = rng.rand(10000).dumps()
for timer in utool.Timerit(100, label='twocall'):
hashe... | [
"This",
"is",
"the",
"clear",
"winner",
"over",
"the",
"generate",
"version",
".",
"Used",
"by",
"hash_data"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_hash.py#L241-L358 | train |
Erotemic/utool | utool/util_hash.py | combine_hashes | def combine_hashes(bytes_list, hasher=None):
"""
Only works on bytes
Example:
>>> # DISABLE_DOCTEST
>>> x = [b('1111'), b('2222')]
>>> y = [b('11'), b('11'), b('22'), b('22')]
>>> bytes_list = y
>>> out1 = ut.combine_hashes(x, hashlib.sha1())
>>> hasher = has... | python | def combine_hashes(bytes_list, hasher=None):
"""
Only works on bytes
Example:
>>> # DISABLE_DOCTEST
>>> x = [b('1111'), b('2222')]
>>> y = [b('11'), b('11'), b('22'), b('22')]
>>> bytes_list = y
>>> out1 = ut.combine_hashes(x, hashlib.sha1())
>>> hasher = has... | [
"def",
"combine_hashes",
"(",
"bytes_list",
",",
"hasher",
"=",
"None",
")",
":",
"if",
"hasher",
"is",
"None",
":",
"hasher",
"=",
"hashlib",
".",
"sha256",
"(",
")",
"for",
"b",
"in",
"bytes_list",
":",
"hasher",
".",
"update",
"(",
"b",
")",
"hash... | Only works on bytes
Example:
>>> # DISABLE_DOCTEST
>>> x = [b('1111'), b('2222')]
>>> y = [b('11'), b('11'), b('22'), b('22')]
>>> bytes_list = y
>>> out1 = ut.combine_hashes(x, hashlib.sha1())
>>> hasher = hashlib.sha1()
>>> out2 = ut.combine_hashes(y, hashe... | [
"Only",
"works",
"on",
"bytes"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_hash.py#L410-L434 | train |
Erotemic/utool | utool/util_hash.py | hash_data | def hash_data(data, hashlen=None, alphabet=None):
r"""
Get a unique hash depending on the state of the data.
Args:
data (object): any sort of loosely organized data
hashlen (None): (default = None)
alphabet (None): (default = None)
Returns:
str: text - hash string
... | python | def hash_data(data, hashlen=None, alphabet=None):
r"""
Get a unique hash depending on the state of the data.
Args:
data (object): any sort of loosely organized data
hashlen (None): (default = None)
alphabet (None): (default = None)
Returns:
str: text - hash string
... | [
"def",
"hash_data",
"(",
"data",
",",
"hashlen",
"=",
"None",
",",
"alphabet",
"=",
"None",
")",
":",
"r",
"if",
"alphabet",
"is",
"None",
":",
"alphabet",
"=",
"ALPHABET_27",
"if",
"hashlen",
"is",
"None",
":",
"hashlen",
"=",
"HASH_LEN2",
"if",
"isin... | r"""
Get a unique hash depending on the state of the data.
Args:
data (object): any sort of loosely organized data
hashlen (None): (default = None)
alphabet (None): (default = None)
Returns:
str: text - hash string
CommandLine:
python -m utool.util_hash hash_d... | [
"r",
"Get",
"a",
"unique",
"hash",
"depending",
"on",
"the",
"state",
"of",
"the",
"data",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_hash.py#L438-L498 | train |
Erotemic/utool | utool/util_hash.py | convert_hexstr_to_bigbase | def convert_hexstr_to_bigbase(hexstr, alphabet=ALPHABET, bigbase=BIGBASE):
r"""
Packs a long hexstr into a shorter length string with a larger base
Ignore:
# Determine the length savings with lossless conversion
import sympy as sy
consts = dict(hexbase=16, hexlen=256, bigbase=27)
... | python | def convert_hexstr_to_bigbase(hexstr, alphabet=ALPHABET, bigbase=BIGBASE):
r"""
Packs a long hexstr into a shorter length string with a larger base
Ignore:
# Determine the length savings with lossless conversion
import sympy as sy
consts = dict(hexbase=16, hexlen=256, bigbase=27)
... | [
"def",
"convert_hexstr_to_bigbase",
"(",
"hexstr",
",",
"alphabet",
"=",
"ALPHABET",
",",
"bigbase",
"=",
"BIGBASE",
")",
":",
"r",
"x",
"=",
"int",
"(",
"hexstr",
",",
"16",
")",
"if",
"x",
"==",
"0",
":",
"return",
"'0'",
"sign",
"=",
"1",
"if",
... | r"""
Packs a long hexstr into a shorter length string with a larger base
Ignore:
# Determine the length savings with lossless conversion
import sympy as sy
consts = dict(hexbase=16, hexlen=256, bigbase=27)
symbols = sy.symbols('hexbase, hexlen, bigbase, newlen')
haexbase... | [
"r",
"Packs",
"a",
"long",
"hexstr",
"into",
"a",
"shorter",
"length",
"string",
"with",
"a",
"larger",
"base"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_hash.py#L766-L806 | train |
Erotemic/utool | utool/util_hash.py | get_file_hash | def get_file_hash(fpath, blocksize=65536, hasher=None, stride=1,
hexdigest=False):
r"""
For better hashes use hasher=hashlib.sha256, and keep stride=1
Args:
fpath (str): file path string
blocksize (int): 2 ** 16. Affects speed of reading file
hasher (None): defau... | python | def get_file_hash(fpath, blocksize=65536, hasher=None, stride=1,
hexdigest=False):
r"""
For better hashes use hasher=hashlib.sha256, and keep stride=1
Args:
fpath (str): file path string
blocksize (int): 2 ** 16. Affects speed of reading file
hasher (None): defau... | [
"def",
"get_file_hash",
"(",
"fpath",
",",
"blocksize",
"=",
"65536",
",",
"hasher",
"=",
"None",
",",
"stride",
"=",
"1",
",",
"hexdigest",
"=",
"False",
")",
":",
"r",
"if",
"hasher",
"is",
"None",
":",
"hasher",
"=",
"hashlib",
".",
"sha1",
"(",
... | r"""
For better hashes use hasher=hashlib.sha256, and keep stride=1
Args:
fpath (str): file path string
blocksize (int): 2 ** 16. Affects speed of reading file
hasher (None): defaults to sha1 for fast (but insecure) hashing
stride (int): strides > 1 skip data to hash, useful f... | [
"r",
"For",
"better",
"hashes",
"use",
"hasher",
"=",
"hashlib",
".",
"sha256",
"and",
"keep",
"stride",
"=",
"1"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_hash.py#L829-L897 | train |
Erotemic/utool | utool/util_hash.py | get_file_uuid | def get_file_uuid(fpath, hasher=None, stride=1):
""" Creates a uuid from the hash of a file
"""
if hasher is None:
hasher = hashlib.sha1() # 20 bytes of output
#hasher = hashlib.sha256() # 32 bytes of output
# sha1 produces a 20 byte hash
hashbytes_20 = get_file_hash(fpath, hasher=... | python | def get_file_uuid(fpath, hasher=None, stride=1):
""" Creates a uuid from the hash of a file
"""
if hasher is None:
hasher = hashlib.sha1() # 20 bytes of output
#hasher = hashlib.sha256() # 32 bytes of output
# sha1 produces a 20 byte hash
hashbytes_20 = get_file_hash(fpath, hasher=... | [
"def",
"get_file_uuid",
"(",
"fpath",
",",
"hasher",
"=",
"None",
",",
"stride",
"=",
"1",
")",
":",
"if",
"hasher",
"is",
"None",
":",
"hasher",
"=",
"hashlib",
".",
"sha1",
"(",
")",
"hashbytes_20",
"=",
"get_file_hash",
"(",
"fpath",
",",
"hasher",
... | Creates a uuid from the hash of a file | [
"Creates",
"a",
"uuid",
"from",
"the",
"hash",
"of",
"a",
"file"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_hash.py#L968-L979 | train |
Erotemic/utool | utool/util_hash.py | combine_uuids | def combine_uuids(uuids, ordered=True, salt=''):
"""
Creates a uuid that specifies a group of UUIDS
Args:
uuids (list): list of uuid objects
ordered (bool): if False uuid order changes the resulting combined uuid
otherwise the uuids are considered an orderless set
salt (... | python | def combine_uuids(uuids, ordered=True, salt=''):
"""
Creates a uuid that specifies a group of UUIDS
Args:
uuids (list): list of uuid objects
ordered (bool): if False uuid order changes the resulting combined uuid
otherwise the uuids are considered an orderless set
salt (... | [
"def",
"combine_uuids",
"(",
"uuids",
",",
"ordered",
"=",
"True",
",",
"salt",
"=",
"''",
")",
":",
"if",
"len",
"(",
"uuids",
")",
"==",
"0",
":",
"return",
"get_zero_uuid",
"(",
")",
"elif",
"len",
"(",
"uuids",
")",
"==",
"1",
":",
"return",
... | Creates a uuid that specifies a group of UUIDS
Args:
uuids (list): list of uuid objects
ordered (bool): if False uuid order changes the resulting combined uuid
otherwise the uuids are considered an orderless set
salt (str): salts the resulting hash
Returns:
uuid.UUI... | [
"Creates",
"a",
"uuid",
"that",
"specifies",
"a",
"group",
"of",
"UUIDS"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_hash.py#L1028-L1087 | train |
dsoprea/NsqSpinner | nsq/master.py | Master.__start_connection | def __start_connection(self, context, node, ccallbacks=None):
"""Start a new connection, and manage it from a new greenlet."""
_logger.debug("Creating connection object: CONTEXT=[%s] NODE=[%s]",
context, node)
c = nsq.connection.Connection(
context,
... | python | def __start_connection(self, context, node, ccallbacks=None):
"""Start a new connection, and manage it from a new greenlet."""
_logger.debug("Creating connection object: CONTEXT=[%s] NODE=[%s]",
context, node)
c = nsq.connection.Connection(
context,
... | [
"def",
"__start_connection",
"(",
"self",
",",
"context",
",",
"node",
",",
"ccallbacks",
"=",
"None",
")",
":",
"_logger",
".",
"debug",
"(",
"\"Creating connection object: CONTEXT=[%s] NODE=[%s]\"",
",",
"context",
",",
"node",
")",
"c",
"=",
"nsq",
".",
"co... | Start a new connection, and manage it from a new greenlet. | [
"Start",
"a",
"new",
"connection",
"and",
"manage",
"it",
"from",
"a",
"new",
"greenlet",
"."
] | 972237b8ddce737983bfed001fde52e5236be695 | https://github.com/dsoprea/NsqSpinner/blob/972237b8ddce737983bfed001fde52e5236be695/nsq/master.py#L44-L76 | train |
dsoprea/NsqSpinner | nsq/master.py | Master.__audit_connections | def __audit_connections(self, ccallbacks):
"""Monitor state of all connections, and utility of all servers."""
while self.__quit_ev.is_set() is False:
# Remove any connections that are dead.
self.__connections = filter(
lambda (n, c, g): not g... | python | def __audit_connections(self, ccallbacks):
"""Monitor state of all connections, and utility of all servers."""
while self.__quit_ev.is_set() is False:
# Remove any connections that are dead.
self.__connections = filter(
lambda (n, c, g): not g... | [
"def",
"__audit_connections",
"(",
"self",
",",
"ccallbacks",
")",
":",
"while",
"self",
".",
"__quit_ev",
".",
"is_set",
"(",
")",
"is",
"False",
":",
"self",
".",
"__connections",
"=",
"filter",
"(",
"lambda",
"(",
"n",
",",
"c",
",",
"g",
")",
":"... | Monitor state of all connections, and utility of all servers. | [
"Monitor",
"state",
"of",
"all",
"connections",
"and",
"utility",
"of",
"all",
"servers",
"."
] | 972237b8ddce737983bfed001fde52e5236be695 | https://github.com/dsoprea/NsqSpinner/blob/972237b8ddce737983bfed001fde52e5236be695/nsq/master.py#L111-L170 | train |
dsoprea/NsqSpinner | nsq/master.py | Master.__join_connections | def __join_connections(self):
"""Wait for all connections to close. There are no side-effects here.
We just want to try and leave -after- everything has closed, in
general.
"""
interval_s = nsq.config.client.CONNECTION_CLOSE_AUDIT_WAIT_S
graceful_wait_s = nsq.config.cl... | python | def __join_connections(self):
"""Wait for all connections to close. There are no side-effects here.
We just want to try and leave -after- everything has closed, in
general.
"""
interval_s = nsq.config.client.CONNECTION_CLOSE_AUDIT_WAIT_S
graceful_wait_s = nsq.config.cl... | [
"def",
"__join_connections",
"(",
"self",
")",
":",
"interval_s",
"=",
"nsq",
".",
"config",
".",
"client",
".",
"CONNECTION_CLOSE_AUDIT_WAIT_S",
"graceful_wait_s",
"=",
"nsq",
".",
"config",
".",
"client",
".",
"CONNECTION_QUIT_CLOSE_TIMEOUT_S",
"graceful",
"=",
... | Wait for all connections to close. There are no side-effects here.
We just want to try and leave -after- everything has closed, in
general. | [
"Wait",
"for",
"all",
"connections",
"to",
"close",
".",
"There",
"are",
"no",
"side",
"-",
"effects",
"here",
".",
"We",
"just",
"want",
"to",
"try",
"and",
"leave",
"-",
"after",
"-",
"everything",
"has",
"closed",
"in",
"general",
"."
] | 972237b8ddce737983bfed001fde52e5236be695 | https://github.com/dsoprea/NsqSpinner/blob/972237b8ddce737983bfed001fde52e5236be695/nsq/master.py#L172-L200 | train |
dsoprea/NsqSpinner | nsq/master.py | Master.__manage_connections | def __manage_connections(self, ccallbacks=None):
"""This runs as the main connection management greenlet."""
_logger.info("Running client.")
# Create message-handler.
if self.__message_handler_cls is not None:
# TODO(dustin): Move this to another thread if we can mix multithreading wi... | python | def __manage_connections(self, ccallbacks=None):
"""This runs as the main connection management greenlet."""
_logger.info("Running client.")
# Create message-handler.
if self.__message_handler_cls is not None:
# TODO(dustin): Move this to another thread if we can mix multithreading wi... | [
"def",
"__manage_connections",
"(",
"self",
",",
"ccallbacks",
"=",
"None",
")",
":",
"_logger",
".",
"info",
"(",
"\"Running client.\"",
")",
"if",
"self",
".",
"__message_handler_cls",
"is",
"not",
"None",
":",
"self",
".",
"__message_handler",
"=",
"self",
... | This runs as the main connection management greenlet. | [
"This",
"runs",
"as",
"the",
"main",
"connection",
"management",
"greenlet",
"."
] | 972237b8ddce737983bfed001fde52e5236be695 | https://github.com/dsoprea/NsqSpinner/blob/972237b8ddce737983bfed001fde52e5236be695/nsq/master.py#L202-L237 | train |
dsoprea/NsqSpinner | nsq/master.py | Master.set_servers | def set_servers(self, node_couplets):
"""Set the current collection of servers. The entries are 2-tuples of
contexts and nodes.
"""
node_couplets_s = set(node_couplets)
if node_couplets_s != self.__node_couplets_s:
_logger.info("Servers have changed. NEW: %s REMOVE... | python | def set_servers(self, node_couplets):
"""Set the current collection of servers. The entries are 2-tuples of
contexts and nodes.
"""
node_couplets_s = set(node_couplets)
if node_couplets_s != self.__node_couplets_s:
_logger.info("Servers have changed. NEW: %s REMOVE... | [
"def",
"set_servers",
"(",
"self",
",",
"node_couplets",
")",
":",
"node_couplets_s",
"=",
"set",
"(",
"node_couplets",
")",
"if",
"node_couplets_s",
"!=",
"self",
".",
"__node_couplets_s",
":",
"_logger",
".",
"info",
"(",
"\"Servers have changed. NEW: %s REMOVED: ... | Set the current collection of servers. The entries are 2-tuples of
contexts and nodes. | [
"Set",
"the",
"current",
"collection",
"of",
"servers",
".",
"The",
"entries",
"are",
"2",
"-",
"tuples",
"of",
"contexts",
"and",
"nodes",
"."
] | 972237b8ddce737983bfed001fde52e5236be695 | https://github.com/dsoprea/NsqSpinner/blob/972237b8ddce737983bfed001fde52e5236be695/nsq/master.py#L239-L257 | train |
dsoprea/NsqSpinner | nsq/master.py | Master.start | def start(self, ccallbacks=None):
"""Establish and maintain connections."""
self.__manage_g = gevent.spawn(self.__manage_connections, ccallbacks)
self.__ready_ev.wait() | python | def start(self, ccallbacks=None):
"""Establish and maintain connections."""
self.__manage_g = gevent.spawn(self.__manage_connections, ccallbacks)
self.__ready_ev.wait() | [
"def",
"start",
"(",
"self",
",",
"ccallbacks",
"=",
"None",
")",
":",
"self",
".",
"__manage_g",
"=",
"gevent",
".",
"spawn",
"(",
"self",
".",
"__manage_connections",
",",
"ccallbacks",
")",
"self",
".",
"__ready_ev",
".",
"wait",
"(",
")"
] | Establish and maintain connections. | [
"Establish",
"and",
"maintain",
"connections",
"."
] | 972237b8ddce737983bfed001fde52e5236be695 | https://github.com/dsoprea/NsqSpinner/blob/972237b8ddce737983bfed001fde52e5236be695/nsq/master.py#L268-L272 | train |
dsoprea/NsqSpinner | nsq/master.py | Master.stop | def stop(self):
"""Stop all of the connections."""
_logger.debug("Emitting quit signal for connections.")
self.__quit_ev.set()
_logger.info("Waiting for connection manager to stop.")
self.__manage_g.join() | python | def stop(self):
"""Stop all of the connections."""
_logger.debug("Emitting quit signal for connections.")
self.__quit_ev.set()
_logger.info("Waiting for connection manager to stop.")
self.__manage_g.join() | [
"def",
"stop",
"(",
"self",
")",
":",
"_logger",
".",
"debug",
"(",
"\"Emitting quit signal for connections.\"",
")",
"self",
".",
"__quit_ev",
".",
"set",
"(",
")",
"_logger",
".",
"info",
"(",
"\"Waiting for connection manager to stop.\"",
")",
"self",
".",
"_... | Stop all of the connections. | [
"Stop",
"all",
"of",
"the",
"connections",
"."
] | 972237b8ddce737983bfed001fde52e5236be695 | https://github.com/dsoprea/NsqSpinner/blob/972237b8ddce737983bfed001fde52e5236be695/nsq/master.py#L274-L281 | train |
LEMS/pylems | lems/run.py | run | def run(file_path,include_dirs=[],dlems=False,nogui=False):
"""
Function for running from a script or shell.
"""
import argparse
args = argparse.Namespace()
args.lems_file = file_path
args.I = include_dirs
args.dlems = dlems
args.nogui = nogui
main(args=args) | python | def run(file_path,include_dirs=[],dlems=False,nogui=False):
"""
Function for running from a script or shell.
"""
import argparse
args = argparse.Namespace()
args.lems_file = file_path
args.I = include_dirs
args.dlems = dlems
args.nogui = nogui
main(args=args) | [
"def",
"run",
"(",
"file_path",
",",
"include_dirs",
"=",
"[",
"]",
",",
"dlems",
"=",
"False",
",",
"nogui",
"=",
"False",
")",
":",
"import",
"argparse",
"args",
"=",
"argparse",
".",
"Namespace",
"(",
")",
"args",
".",
"lems_file",
"=",
"file_path",... | Function for running from a script or shell. | [
"Function",
"for",
"running",
"from",
"a",
"script",
"or",
"shell",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/run.py#L44-L54 | train |
dsoprea/NsqSpinner | nsq/node.py | DiscoveredNode.connect | def connect(self, nice_quit_ev):
"""Connect the server. We expect this to implement backoff and all
connection logistics for servers that were discovered via a lookup
node.
"""
_logger.debug("Connecting to discovered node: [%s]", self.server_host)
stop_epoch = time.t... | python | def connect(self, nice_quit_ev):
"""Connect the server. We expect this to implement backoff and all
connection logistics for servers that were discovered via a lookup
node.
"""
_logger.debug("Connecting to discovered node: [%s]", self.server_host)
stop_epoch = time.t... | [
"def",
"connect",
"(",
"self",
",",
"nice_quit_ev",
")",
":",
"_logger",
".",
"debug",
"(",
"\"Connecting to discovered node: [%s]\"",
",",
"self",
".",
"server_host",
")",
"stop_epoch",
"=",
"time",
".",
"time",
"(",
")",
"+",
"nsq",
".",
"config",
".",
"... | Connect the server. We expect this to implement backoff and all
connection logistics for servers that were discovered via a lookup
node. | [
"Connect",
"the",
"server",
".",
"We",
"expect",
"this",
"to",
"implement",
"backoff",
"and",
"all",
"connection",
"logistics",
"for",
"servers",
"that",
"were",
"discovered",
"via",
"a",
"lookup",
"node",
"."
] | 972237b8ddce737983bfed001fde52e5236be695 | https://github.com/dsoprea/NsqSpinner/blob/972237b8ddce737983bfed001fde52e5236be695/nsq/node.py#L62-L98 | train |
dsoprea/NsqSpinner | nsq/node.py | ServerNode.connect | def connect(self, nice_quit_ev):
"""Connect the server. We expect this to implement connection logistics
for servers that were explicitly prescribed to us.
"""
_logger.debug("Connecting to explicit server node: [%s]",
self.server_host)
# According to th... | python | def connect(self, nice_quit_ev):
"""Connect the server. We expect this to implement connection logistics
for servers that were explicitly prescribed to us.
"""
_logger.debug("Connecting to explicit server node: [%s]",
self.server_host)
# According to th... | [
"def",
"connect",
"(",
"self",
",",
"nice_quit_ev",
")",
":",
"_logger",
".",
"debug",
"(",
"\"Connecting to explicit server node: [%s]\"",
",",
"self",
".",
"server_host",
")",
"try",
":",
"c",
"=",
"self",
".",
"primitive_connect",
"(",
")",
"except",
"geven... | Connect the server. We expect this to implement connection logistics
for servers that were explicitly prescribed to us. | [
"Connect",
"the",
"server",
".",
"We",
"expect",
"this",
"to",
"implement",
"connection",
"logistics",
"for",
"servers",
"that",
"were",
"explicitly",
"prescribed",
"to",
"us",
"."
] | 972237b8ddce737983bfed001fde52e5236be695 | https://github.com/dsoprea/NsqSpinner/blob/972237b8ddce737983bfed001fde52e5236be695/nsq/node.py#L107-L130 | train |
glormph/msstitch | src/app/drivers/prottable/fdr.py | ProttableFDRDriver.prepare | def prepare(self):
"""No percolator XML for protein tables"""
self.target = self.fn
self.targetheader = reader.get_tsv_header(self.target)
self.decoyheader = reader.get_tsv_header(self.decoyfn) | python | def prepare(self):
"""No percolator XML for protein tables"""
self.target = self.fn
self.targetheader = reader.get_tsv_header(self.target)
self.decoyheader = reader.get_tsv_header(self.decoyfn) | [
"def",
"prepare",
"(",
"self",
")",
":",
"self",
".",
"target",
"=",
"self",
".",
"fn",
"self",
".",
"targetheader",
"=",
"reader",
".",
"get_tsv_header",
"(",
"self",
".",
"target",
")",
"self",
".",
"decoyheader",
"=",
"reader",
".",
"get_tsv_header",
... | No percolator XML for protein tables | [
"No",
"percolator",
"XML",
"for",
"protein",
"tables"
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/drivers/prottable/fdr.py#L32-L36 | train |
product-definition-center/pdc-client | pdc_client/__init__.py | PDCClient.obtain_token | def obtain_token(self):
"""
Try to obtain token from all end-points that were ever used to serve the
token. If the request returns 404 NOT FOUND, retry with older version of
the URL.
"""
token_end_points = ('token/obtain',
'obtain-token',
... | python | def obtain_token(self):
"""
Try to obtain token from all end-points that were ever used to serve the
token. If the request returns 404 NOT FOUND, retry with older version of
the URL.
"""
token_end_points = ('token/obtain',
'obtain-token',
... | [
"def",
"obtain_token",
"(",
"self",
")",
":",
"token_end_points",
"=",
"(",
"'token/obtain'",
",",
"'obtain-token'",
",",
"'obtain_token'",
")",
"for",
"end_point",
"in",
"token_end_points",
":",
"try",
":",
"return",
"self",
".",
"auth",
"[",
"end_point",
"]"... | Try to obtain token from all end-points that were ever used to serve the
token. If the request returns 404 NOT FOUND, retry with older version of
the URL. | [
"Try",
"to",
"obtain",
"token",
"from",
"all",
"end",
"-",
"points",
"that",
"were",
"ever",
"used",
"to",
"serve",
"the",
"token",
".",
"If",
"the",
"request",
"returns",
"404",
"NOT",
"FOUND",
"retry",
"with",
"older",
"version",
"of",
"the",
"URL",
... | 7236fd8b72e675ebb321bbe337289d9fbeb6119f | https://github.com/product-definition-center/pdc-client/blob/7236fd8b72e675ebb321bbe337289d9fbeb6119f/pdc_client/__init__.py#L195-L210 | train |
product-definition-center/pdc-client | pdc_client/__init__.py | _BeanBagWrapper.results | def results(self, *args, **kwargs):
"""
Return an iterator with all pages of data.
Return NoResultsError with response if there is unexpected data.
"""
def worker():
kwargs['page'] = 1
while True:
response = self.client(*args, **kwarg... | python | def results(self, *args, **kwargs):
"""
Return an iterator with all pages of data.
Return NoResultsError with response if there is unexpected data.
"""
def worker():
kwargs['page'] = 1
while True:
response = self.client(*args, **kwarg... | [
"def",
"results",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"def",
"worker",
"(",
")",
":",
"kwargs",
"[",
"'page'",
"]",
"=",
"1",
"while",
"True",
":",
"response",
"=",
"self",
".",
"client",
"(",
"*",
"args",
",",
"**",
"... | Return an iterator with all pages of data.
Return NoResultsError with response if there is unexpected data. | [
"Return",
"an",
"iterator",
"with",
"all",
"pages",
"of",
"data",
".",
"Return",
"NoResultsError",
"with",
"response",
"if",
"there",
"is",
"unexpected",
"data",
"."
] | 7236fd8b72e675ebb321bbe337289d9fbeb6119f | https://github.com/product-definition-center/pdc-client/blob/7236fd8b72e675ebb321bbe337289d9fbeb6119f/pdc_client/__init__.py#L331-L352 | train |
glormph/msstitch | src/app/actions/headers/base.py | get_isoquant_fields | def get_isoquant_fields(pqdb=False, poolnames=False):
"""Returns a headerfield dict for isobaric quant channels. Channels are
taken from DB and there isn't a pool-independent version of this yet"""
# FIXME when is a None database passed?
if pqdb is None:
return {}
try:
channels_psms ... | python | def get_isoquant_fields(pqdb=False, poolnames=False):
"""Returns a headerfield dict for isobaric quant channels. Channels are
taken from DB and there isn't a pool-independent version of this yet"""
# FIXME when is a None database passed?
if pqdb is None:
return {}
try:
channels_psms ... | [
"def",
"get_isoquant_fields",
"(",
"pqdb",
"=",
"False",
",",
"poolnames",
"=",
"False",
")",
":",
"if",
"pqdb",
"is",
"None",
":",
"return",
"{",
"}",
"try",
":",
"channels_psms",
"=",
"pqdb",
".",
"get_isoquant_amountpsms_channels",
"(",
")",
"except",
"... | Returns a headerfield dict for isobaric quant channels. Channels are
taken from DB and there isn't a pool-independent version of this yet | [
"Returns",
"a",
"headerfield",
"dict",
"for",
"isobaric",
"quant",
"channels",
".",
"Channels",
"are",
"taken",
"from",
"DB",
"and",
"there",
"isn",
"t",
"a",
"pool",
"-",
"independent",
"version",
"of",
"this",
"yet"
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/headers/base.py#L83-L100 | train |
trendels/gevent_inotifyx | example.py | watch_for_events | def watch_for_events():
"""Wait for events and print them to stdout."""
fd = inotify.init()
try:
wd = inotify.add_watch(fd, '/tmp', inotify.IN_CLOSE_WRITE)
while True:
for event in inotify.get_events(fd):
print("event:", event.name, event.get_mask_description())
... | python | def watch_for_events():
"""Wait for events and print them to stdout."""
fd = inotify.init()
try:
wd = inotify.add_watch(fd, '/tmp', inotify.IN_CLOSE_WRITE)
while True:
for event in inotify.get_events(fd):
print("event:", event.name, event.get_mask_description())
... | [
"def",
"watch_for_events",
"(",
")",
":",
"fd",
"=",
"inotify",
".",
"init",
"(",
")",
"try",
":",
"wd",
"=",
"inotify",
".",
"add_watch",
"(",
"fd",
",",
"'/tmp'",
",",
"inotify",
".",
"IN_CLOSE_WRITE",
")",
"while",
"True",
":",
"for",
"event",
"in... | Wait for events and print them to stdout. | [
"Wait",
"for",
"events",
"and",
"print",
"them",
"to",
"stdout",
"."
] | b1e531616d150e86b13aeca450a61c66f9bbc855 | https://github.com/trendels/gevent_inotifyx/blob/b1e531616d150e86b13aeca450a61c66f9bbc855/example.py#L16-L25 | train |
ColinDuquesnoy/QCrash | qcrash/formatters/markdown.py | MardownFormatter.format_body | def format_body(self, description, sys_info=None, traceback=None):
"""
Formats the body using markdown.
:param description: Description of the issue, written by the user.
:param sys_info: Optional system information string
:param log: Optional application log
:param trac... | python | def format_body(self, description, sys_info=None, traceback=None):
"""
Formats the body using markdown.
:param description: Description of the issue, written by the user.
:param sys_info: Optional system information string
:param log: Optional application log
:param trac... | [
"def",
"format_body",
"(",
"self",
",",
"description",
",",
"sys_info",
"=",
"None",
",",
"traceback",
"=",
"None",
")",
":",
"body",
"=",
"BODY_ITEM_TEMPLATE",
"%",
"{",
"'name'",
":",
"'Description'",
",",
"'value'",
":",
"description",
"}",
"if",
"trace... | Formats the body using markdown.
:param description: Description of the issue, written by the user.
:param sys_info: Optional system information string
:param log: Optional application log
:param traceback: Optional traceback. | [
"Formats",
"the",
"body",
"using",
"markdown",
"."
] | 775e1b15764e2041a8f9a08bea938e4d6ce817c7 | https://github.com/ColinDuquesnoy/QCrash/blob/775e1b15764e2041a8f9a08bea938e4d6ce817c7/qcrash/formatters/markdown.py#L21-L43 | train |
garethr/cloth | src/cloth/tasks.py | list | def list():
"List EC2 name and public and private ip address"
for node in env.nodes:
print "%s (%s, %s)" % (node.tags["Name"], node.ip_address,
node.private_ip_address) | python | def list():
"List EC2 name and public and private ip address"
for node in env.nodes:
print "%s (%s, %s)" % (node.tags["Name"], node.ip_address,
node.private_ip_address) | [
"def",
"list",
"(",
")",
":",
"\"List EC2 name and public and private ip address\"",
"for",
"node",
"in",
"env",
".",
"nodes",
":",
"print",
"\"%s (%s, %s)\"",
"%",
"(",
"node",
".",
"tags",
"[",
"\"Name\"",
"]",
",",
"node",
".",
"ip_address",
",",
"node",
... | List EC2 name and public and private ip address | [
"List",
"EC2",
"name",
"and",
"public",
"and",
"private",
"ip",
"address"
] | b50c7cd6b03f49a931ee55ec94212760c50694a9 | https://github.com/garethr/cloth/blob/b50c7cd6b03f49a931ee55ec94212760c50694a9/src/cloth/tasks.py#L40-L44 | train |
steveYeah/PyBomb | pybomb/clients/games_client.py | GamesClient.quick_search | def quick_search(self, name, platform=None, sort_by=None, desc=True):
"""
Quick search method that allows you to search for a game using only the
title and the platform
:param name: string
:param platform: int
:param sort_by: string
:param desc: bool
:ret... | python | def quick_search(self, name, platform=None, sort_by=None, desc=True):
"""
Quick search method that allows you to search for a game using only the
title and the platform
:param name: string
:param platform: int
:param sort_by: string
:param desc: bool
:ret... | [
"def",
"quick_search",
"(",
"self",
",",
"name",
",",
"platform",
"=",
"None",
",",
"sort_by",
"=",
"None",
",",
"desc",
"=",
"True",
")",
":",
"if",
"platform",
"is",
"None",
":",
"query_filter",
"=",
"\"name:{0}\"",
".",
"format",
"(",
"name",
")",
... | Quick search method that allows you to search for a game using only the
title and the platform
:param name: string
:param platform: int
:param sort_by: string
:param desc: bool
:return: pybomb.clients.Response | [
"Quick",
"search",
"method",
"that",
"allows",
"you",
"to",
"search",
"for",
"a",
"game",
"using",
"only",
"the",
"title",
"and",
"the",
"platform"
] | 54045d74e642f8a1c4366c24bd6a330ae3da6257 | https://github.com/steveYeah/PyBomb/blob/54045d74e642f8a1c4366c24bd6a330ae3da6257/pybomb/clients/games_client.py#L88-L118 | train |
quikmile/trellio | trellio/pinger.py | Pinger.send_ping | def send_ping(self, payload=None):
"""
Sends the ping after the interval specified when initializing
"""
yield from asyncio.sleep(self._interval)
self._handler.send_ping(payload=payload)
self._start_timer(payload=payload) | python | def send_ping(self, payload=None):
"""
Sends the ping after the interval specified when initializing
"""
yield from asyncio.sleep(self._interval)
self._handler.send_ping(payload=payload)
self._start_timer(payload=payload) | [
"def",
"send_ping",
"(",
"self",
",",
"payload",
"=",
"None",
")",
":",
"yield",
"from",
"asyncio",
".",
"sleep",
"(",
"self",
".",
"_interval",
")",
"self",
".",
"_handler",
".",
"send_ping",
"(",
"payload",
"=",
"payload",
")",
"self",
".",
"_start_t... | Sends the ping after the interval specified when initializing | [
"Sends",
"the",
"ping",
"after",
"the",
"interval",
"specified",
"when",
"initializing"
] | e8b050077562acf32805fcbb9c0c162248a23c62 | https://github.com/quikmile/trellio/blob/e8b050077562acf32805fcbb9c0c162248a23c62/trellio/pinger.py#L38-L44 | train |
quikmile/trellio | trellio/pinger.py | Pinger.pong_received | def pong_received(self, payload=None):
"""
Called when a pong is received. So the timer is cancelled
"""
if self._timer is not None:
self._timer.cancel()
self._failures = 0
asyncio.async(self.send_ping(payload=payload)) | python | def pong_received(self, payload=None):
"""
Called when a pong is received. So the timer is cancelled
"""
if self._timer is not None:
self._timer.cancel()
self._failures = 0
asyncio.async(self.send_ping(payload=payload)) | [
"def",
"pong_received",
"(",
"self",
",",
"payload",
"=",
"None",
")",
":",
"if",
"self",
".",
"_timer",
"is",
"not",
"None",
":",
"self",
".",
"_timer",
".",
"cancel",
"(",
")",
"self",
".",
"_failures",
"=",
"0",
"asyncio",
".",
"async",
"(",
"se... | Called when a pong is received. So the timer is cancelled | [
"Called",
"when",
"a",
"pong",
"is",
"received",
".",
"So",
"the",
"timer",
"is",
"cancelled"
] | e8b050077562acf32805fcbb9c0c162248a23c62 | https://github.com/quikmile/trellio/blob/e8b050077562acf32805fcbb9c0c162248a23c62/trellio/pinger.py#L46-L53 | train |
Erotemic/utool | utool/util_type.py | is_comparable_type | def is_comparable_type(var, type_):
"""
Check to see if `var` is an instance of known compatible types for `type_`
Args:
var (?):
type_ (?):
Returns:
bool:
CommandLine:
python -m utool.util_type is_comparable_type --show
Example:
>>> # DISABLE_DOCTEST
... | python | def is_comparable_type(var, type_):
"""
Check to see if `var` is an instance of known compatible types for `type_`
Args:
var (?):
type_ (?):
Returns:
bool:
CommandLine:
python -m utool.util_type is_comparable_type --show
Example:
>>> # DISABLE_DOCTEST
... | [
"def",
"is_comparable_type",
"(",
"var",
",",
"type_",
")",
":",
"other_types",
"=",
"COMPARABLE_TYPES",
".",
"get",
"(",
"type_",
",",
"type_",
")",
"return",
"isinstance",
"(",
"var",
",",
"other_types",
")"
] | Check to see if `var` is an instance of known compatible types for `type_`
Args:
var (?):
type_ (?):
Returns:
bool:
CommandLine:
python -m utool.util_type is_comparable_type --show
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_type import * # NOQ... | [
"Check",
"to",
"see",
"if",
"var",
"is",
"an",
"instance",
"of",
"known",
"compatible",
"types",
"for",
"type_"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_type.py#L104-L133 | train |
Erotemic/utool | utool/util_type.py | smart_cast | def smart_cast(var, type_):
"""
casts var to type, and tries to be clever when var is a string
Args:
var (object): variable to cast
type_ (type or str): type to attempt to cast to
Returns:
object:
CommandLine:
python -m utool.util_type --exec-smart_cast
Exampl... | python | def smart_cast(var, type_):
"""
casts var to type, and tries to be clever when var is a string
Args:
var (object): variable to cast
type_ (type or str): type to attempt to cast to
Returns:
object:
CommandLine:
python -m utool.util_type --exec-smart_cast
Exampl... | [
"def",
"smart_cast",
"(",
"var",
",",
"type_",
")",
":",
"if",
"type_",
"is",
"None",
"or",
"var",
"is",
"None",
":",
"return",
"var",
"try",
":",
"if",
"issubclass",
"(",
"type_",
",",
"type",
"(",
"None",
")",
")",
":",
"return",
"var",
"except",... | casts var to type, and tries to be clever when var is a string
Args:
var (object): variable to cast
type_ (type or str): type to attempt to cast to
Returns:
object:
CommandLine:
python -m utool.util_type --exec-smart_cast
Example:
>>> # ENABLE_DOCTEST
... | [
"casts",
"var",
"to",
"type",
"and",
"tries",
"to",
"be",
"clever",
"when",
"var",
"is",
"a",
"string"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_type.py#L169-L260 | train |
Erotemic/utool | utool/util_type.py | fuzzy_subset | def fuzzy_subset(str_):
"""
converts a string into an argument to list_take
"""
if str_ is None:
return str_
if ':' in str_:
return smart_cast(str_, slice)
if str_.startswith('['):
return smart_cast(str_[1:-1], list)
else:
return smart_cast(str_, list) | python | def fuzzy_subset(str_):
"""
converts a string into an argument to list_take
"""
if str_ is None:
return str_
if ':' in str_:
return smart_cast(str_, slice)
if str_.startswith('['):
return smart_cast(str_[1:-1], list)
else:
return smart_cast(str_, list) | [
"def",
"fuzzy_subset",
"(",
"str_",
")",
":",
"if",
"str_",
"is",
"None",
":",
"return",
"str_",
"if",
"':'",
"in",
"str_",
":",
"return",
"smart_cast",
"(",
"str_",
",",
"slice",
")",
"if",
"str_",
".",
"startswith",
"(",
"'['",
")",
":",
"return",
... | converts a string into an argument to list_take | [
"converts",
"a",
"string",
"into",
"an",
"argument",
"to",
"list_take"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_type.py#L331-L342 | train |
Erotemic/utool | utool/util_type.py | fuzzy_int | def fuzzy_int(str_):
"""
lets some special strings be interpreted as ints
"""
try:
ret = int(str_)
return ret
except Exception:
# Parse comma separated values as ints
if re.match(r'\d*,\d*,?\d*', str_):
return tuple(map(int, str_.split(',')))
# Par... | python | def fuzzy_int(str_):
"""
lets some special strings be interpreted as ints
"""
try:
ret = int(str_)
return ret
except Exception:
# Parse comma separated values as ints
if re.match(r'\d*,\d*,?\d*', str_):
return tuple(map(int, str_.split(',')))
# Par... | [
"def",
"fuzzy_int",
"(",
"str_",
")",
":",
"try",
":",
"ret",
"=",
"int",
"(",
"str_",
")",
"return",
"ret",
"except",
"Exception",
":",
"if",
"re",
".",
"match",
"(",
"r'\\d*,\\d*,?\\d*'",
",",
"str_",
")",
":",
"return",
"tuple",
"(",
"map",
"(",
... | lets some special strings be interpreted as ints | [
"lets",
"some",
"special",
"strings",
"be",
"interpreted",
"as",
"ints"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_type.py#L345-L359 | train |
Erotemic/utool | utool/util_type.py | get_type | def get_type(var):
"""
Gets types accounting for numpy
Ignore:
import utool as ut
import pandas as pd
var = np.array(['a', 'b', 'c'])
ut.get_type(var)
var = pd.Index(['a', 'b', 'c'])
ut.get_type(var)
"""
if HAVE_NUMPY and isinstance(var, np.ndarray):
... | python | def get_type(var):
"""
Gets types accounting for numpy
Ignore:
import utool as ut
import pandas as pd
var = np.array(['a', 'b', 'c'])
ut.get_type(var)
var = pd.Index(['a', 'b', 'c'])
ut.get_type(var)
"""
if HAVE_NUMPY and isinstance(var, np.ndarray):
... | [
"def",
"get_type",
"(",
"var",
")",
":",
"if",
"HAVE_NUMPY",
"and",
"isinstance",
"(",
"var",
",",
"np",
".",
"ndarray",
")",
":",
"if",
"_WIN32",
":",
"type_",
"=",
"var",
".",
"dtype",
"else",
":",
"type_",
"=",
"var",
".",
"dtype",
".",
"type",
... | Gets types accounting for numpy
Ignore:
import utool as ut
import pandas as pd
var = np.array(['a', 'b', 'c'])
ut.get_type(var)
var = pd.Index(['a', 'b', 'c'])
ut.get_type(var) | [
"Gets",
"types",
"accounting",
"for",
"numpy"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_type.py#L377-L403 | train |
Erotemic/utool | utool/util_type.py | get_homogenous_list_type | def get_homogenous_list_type(list_):
"""
Returns the best matching python type even if it is an ndarray assumes all
items in the list are of the same type. does not check this
"""
# TODO Expand and make work correctly
if HAVE_NUMPY and isinstance(list_, np.ndarray):
item = list_
elif... | python | def get_homogenous_list_type(list_):
"""
Returns the best matching python type even if it is an ndarray assumes all
items in the list are of the same type. does not check this
"""
# TODO Expand and make work correctly
if HAVE_NUMPY and isinstance(list_, np.ndarray):
item = list_
elif... | [
"def",
"get_homogenous_list_type",
"(",
"list_",
")",
":",
"if",
"HAVE_NUMPY",
"and",
"isinstance",
"(",
"list_",
",",
"np",
".",
"ndarray",
")",
":",
"item",
"=",
"list_",
"elif",
"isinstance",
"(",
"list_",
",",
"list",
")",
"and",
"len",
"(",
"list_",... | Returns the best matching python type even if it is an ndarray assumes all
items in the list are of the same type. does not check this | [
"Returns",
"the",
"best",
"matching",
"python",
"type",
"even",
"if",
"it",
"is",
"an",
"ndarray",
"assumes",
"all",
"items",
"in",
"the",
"list",
"are",
"of",
"the",
"same",
"type",
".",
"does",
"not",
"check",
"this"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_type.py#L528-L553 | train |
LEMS/pylems | lems/base/stack.py | Stack.pop | def pop(self):
"""
Pops a value off the top of the stack.
@return: Value popped off the stack.
@rtype: *
@raise StackError: Raised when there is a stack underflow.
"""
if self.stack:
val = self.stack[0]
self.stack = self.stack[1:]
... | python | def pop(self):
"""
Pops a value off the top of the stack.
@return: Value popped off the stack.
@rtype: *
@raise StackError: Raised when there is a stack underflow.
"""
if self.stack:
val = self.stack[0]
self.stack = self.stack[1:]
... | [
"def",
"pop",
"(",
"self",
")",
":",
"if",
"self",
".",
"stack",
":",
"val",
"=",
"self",
".",
"stack",
"[",
"0",
"]",
"self",
".",
"stack",
"=",
"self",
".",
"stack",
"[",
"1",
":",
"]",
"return",
"val",
"else",
":",
"raise",
"StackError",
"("... | Pops a value off the top of the stack.
@return: Value popped off the stack.
@rtype: *
@raise StackError: Raised when there is a stack underflow. | [
"Pops",
"a",
"value",
"off",
"the",
"top",
"of",
"the",
"stack",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/base/stack.py#L36-L51 | train |
glormph/msstitch | src/app/actions/mslookup/spectra.py | create_spectra_lookup | def create_spectra_lookup(lookup, fn_spectra):
"""Stores all spectra rt, injection time, and scan nr in db"""
to_store = []
mzmlmap = lookup.get_mzmlfile_map()
for fn, spectrum in fn_spectra:
spec_id = '{}_{}'.format(mzmlmap[fn], spectrum['scan'])
mzml_rt = round(float(spectrum['rt']), 1... | python | def create_spectra_lookup(lookup, fn_spectra):
"""Stores all spectra rt, injection time, and scan nr in db"""
to_store = []
mzmlmap = lookup.get_mzmlfile_map()
for fn, spectrum in fn_spectra:
spec_id = '{}_{}'.format(mzmlmap[fn], spectrum['scan'])
mzml_rt = round(float(spectrum['rt']), 1... | [
"def",
"create_spectra_lookup",
"(",
"lookup",
",",
"fn_spectra",
")",
":",
"to_store",
"=",
"[",
"]",
"mzmlmap",
"=",
"lookup",
".",
"get_mzmlfile_map",
"(",
")",
"for",
"fn",
",",
"spectrum",
"in",
"fn_spectra",
":",
"spec_id",
"=",
"'{}_{}'",
".",
"form... | Stores all spectra rt, injection time, and scan nr in db | [
"Stores",
"all",
"spectra",
"rt",
"injection",
"time",
"and",
"scan",
"nr",
"in",
"db"
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/mslookup/spectra.py#L4-L19 | train |
Erotemic/utool | utool/util_assert.py | assert_raises | def assert_raises(ex_type, func, *args, **kwargs):
r"""
Checks that a function raises an error when given specific arguments.
Args:
ex_type (Exception): exception type
func (callable): live python function
CommandLine:
python -m utool.util_assert assert_raises --show
Examp... | python | def assert_raises(ex_type, func, *args, **kwargs):
r"""
Checks that a function raises an error when given specific arguments.
Args:
ex_type (Exception): exception type
func (callable): live python function
CommandLine:
python -m utool.util_assert assert_raises --show
Examp... | [
"def",
"assert_raises",
"(",
"ex_type",
",",
"func",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"r",
"try",
":",
"func",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"except",
"Exception",
"as",
"ex",
":",
"assert",
"isinstance",
"(",
"ex",
",... | r"""
Checks that a function raises an error when given specific arguments.
Args:
ex_type (Exception): exception type
func (callable): live python function
CommandLine:
python -m utool.util_assert assert_raises --show
Example:
>>> # ENABLE_DOCTEST
>>> from utool... | [
"r",
"Checks",
"that",
"a",
"function",
"raises",
"an",
"error",
"when",
"given",
"specific",
"arguments",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_assert.py#L26-L55 | train |
dsoprea/NsqSpinner | nsq/connection_election.py | ConnectionElection.command_for_all_connections | def command_for_all_connections(self, cb):
"""Invoke the callback with a command-object for each connection."""
for connection in self.__master.connections:
cb(connection.command) | python | def command_for_all_connections(self, cb):
"""Invoke the callback with a command-object for each connection."""
for connection in self.__master.connections:
cb(connection.command) | [
"def",
"command_for_all_connections",
"(",
"self",
",",
"cb",
")",
":",
"for",
"connection",
"in",
"self",
".",
"__master",
".",
"connections",
":",
"cb",
"(",
"connection",
".",
"command",
")"
] | Invoke the callback with a command-object for each connection. | [
"Invoke",
"the",
"callback",
"with",
"a",
"command",
"-",
"object",
"for",
"each",
"connection",
"."
] | 972237b8ddce737983bfed001fde52e5236be695 | https://github.com/dsoprea/NsqSpinner/blob/972237b8ddce737983bfed001fde52e5236be695/nsq/connection_election.py#L40-L44 | train |
Erotemic/utool | utool/util_autogen.py | dump_autogen_code | def dump_autogen_code(fpath, autogen_text, codetype='python', fullprint=None,
show_diff=None, dowrite=None):
"""
Helper that write a file if -w is given on command line, otherwise
it just prints it out. It has the opption of comparing a diff to the file.
"""
import utool as ut
... | python | def dump_autogen_code(fpath, autogen_text, codetype='python', fullprint=None,
show_diff=None, dowrite=None):
"""
Helper that write a file if -w is given on command line, otherwise
it just prints it out. It has the opption of comparing a diff to the file.
"""
import utool as ut
... | [
"def",
"dump_autogen_code",
"(",
"fpath",
",",
"autogen_text",
",",
"codetype",
"=",
"'python'",
",",
"fullprint",
"=",
"None",
",",
"show_diff",
"=",
"None",
",",
"dowrite",
"=",
"None",
")",
":",
"import",
"utool",
"as",
"ut",
"if",
"dowrite",
"is",
"N... | Helper that write a file if -w is given on command line, otherwise
it just prints it out. It has the opption of comparing a diff to the file. | [
"Helper",
"that",
"write",
"a",
"file",
"if",
"-",
"w",
"is",
"given",
"on",
"command",
"line",
"otherwise",
"it",
"just",
"prints",
"it",
"out",
".",
"It",
"has",
"the",
"opption",
"of",
"comparing",
"a",
"diff",
"to",
"the",
"file",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_autogen.py#L22-L69 | train |
Erotemic/utool | utool/util_autogen.py | autofix_codeblock | def autofix_codeblock(codeblock, max_line_len=80,
aggressive=False,
very_aggressive=False,
experimental=False):
r"""
Uses autopep8 to format a block of code
Example:
>>> # DISABLE_DOCTEST
>>> import utool as ut
>>> co... | python | def autofix_codeblock(codeblock, max_line_len=80,
aggressive=False,
very_aggressive=False,
experimental=False):
r"""
Uses autopep8 to format a block of code
Example:
>>> # DISABLE_DOCTEST
>>> import utool as ut
>>> co... | [
"def",
"autofix_codeblock",
"(",
"codeblock",
",",
"max_line_len",
"=",
"80",
",",
"aggressive",
"=",
"False",
",",
"very_aggressive",
"=",
"False",
",",
"experimental",
"=",
"False",
")",
":",
"r",
"import",
"autopep8",
"arglist",
"=",
"[",
"'--max-line-lengt... | r"""
Uses autopep8 to format a block of code
Example:
>>> # DISABLE_DOCTEST
>>> import utool as ut
>>> codeblock = ut.codeblock(
'''
def func( with , some = 'Problems' ):
syntax ='Ok'
but = 'Its very messy'
if None:
... | [
"r",
"Uses",
"autopep8",
"to",
"format",
"a",
"block",
"of",
"code"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_autogen.py#L186-L223 | train |
Erotemic/utool | utool/util_autogen.py | auto_docstr | def auto_docstr(modname, funcname, verbose=True, moddir=None, modpath=None, **kwargs):
r"""
called from vim. Uses strings of filename and modnames to build docstr
Args:
modname (str): name of a python module
funcname (str): name of a function in the module
Returns:
str: docstr
... | python | def auto_docstr(modname, funcname, verbose=True, moddir=None, modpath=None, **kwargs):
r"""
called from vim. Uses strings of filename and modnames to build docstr
Args:
modname (str): name of a python module
funcname (str): name of a function in the module
Returns:
str: docstr
... | [
"def",
"auto_docstr",
"(",
"modname",
",",
"funcname",
",",
"verbose",
"=",
"True",
",",
"moddir",
"=",
"None",
",",
"modpath",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"r",
"func",
",",
"module",
",",
"error_str",
"=",
"load_func_from_module",
"(",
... | r"""
called from vim. Uses strings of filename and modnames to build docstr
Args:
modname (str): name of a python module
funcname (str): name of a function in the module
Returns:
str: docstr
CommandLine:
python -m utool.util_autogen auto_docstr
python -m utool ... | [
"r",
"called",
"from",
"vim",
".",
"Uses",
"strings",
"of",
"filename",
"and",
"modnames",
"to",
"build",
"docstr"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_autogen.py#L396-L442 | train |
Erotemic/utool | utool/util_autogen.py | make_args_docstr | def make_args_docstr(argname_list, argtype_list, argdesc_list, ismethod,
va_name=None, kw_name=None, kw_keys=[]):
r"""
Builds the argument docstring
Args:
argname_list (list): names
argtype_list (list): types
argdesc_list (list): descriptions
ismethod (b... | python | def make_args_docstr(argname_list, argtype_list, argdesc_list, ismethod,
va_name=None, kw_name=None, kw_keys=[]):
r"""
Builds the argument docstring
Args:
argname_list (list): names
argtype_list (list): types
argdesc_list (list): descriptions
ismethod (b... | [
"def",
"make_args_docstr",
"(",
"argname_list",
",",
"argtype_list",
",",
"argdesc_list",
",",
"ismethod",
",",
"va_name",
"=",
"None",
",",
"kw_name",
"=",
"None",
",",
"kw_keys",
"=",
"[",
"]",
")",
":",
"r",
"import",
"utool",
"as",
"ut",
"if",
"ismet... | r"""
Builds the argument docstring
Args:
argname_list (list): names
argtype_list (list): types
argdesc_list (list): descriptions
ismethod (bool): if generating docs for a method
va_name (Optional[str]): varargs name
kw_name (Optional[str]): kwargs name
kw... | [
"r",
"Builds",
"the",
"argument",
"docstring"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_autogen.py#L457-L529 | train |
Erotemic/utool | utool/util_autogen.py | make_default_docstr | def make_default_docstr(func, with_args=True, with_ret=True,
with_commandline=True, with_example=True,
with_header=False, with_debug=False):
r"""
Tries to make a sensible default docstr so the user
can fill things in without typing too much
# TODO: Interl... | python | def make_default_docstr(func, with_args=True, with_ret=True,
with_commandline=True, with_example=True,
with_header=False, with_debug=False):
r"""
Tries to make a sensible default docstr so the user
can fill things in without typing too much
# TODO: Interl... | [
"def",
"make_default_docstr",
"(",
"func",
",",
"with_args",
"=",
"True",
",",
"with_ret",
"=",
"True",
",",
"with_commandline",
"=",
"True",
",",
"with_example",
"=",
"True",
",",
"with_header",
"=",
"False",
",",
"with_debug",
"=",
"False",
")",
":",
"r"... | r"""
Tries to make a sensible default docstr so the user
can fill things in without typing too much
# TODO: Interleave old documentation with new documentation
Args:
func (function): live python function
with_args (bool):
with_ret (bool): (Defaults to True)
with_command... | [
"r",
"Tries",
"to",
"make",
"a",
"sensible",
"default",
"docstr",
"so",
"the",
"user",
"can",
"fill",
"things",
"in",
"without",
"typing",
"too",
"much"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_autogen.py#L763-L894 | train |
Erotemic/utool | utool/util_autogen.py | remove_codeblock_syntax_sentinals | def remove_codeblock_syntax_sentinals(code_text):
r"""
Removes template comments and vim sentinals
Args:
code_text (str):
Returns:
str: code_text_
"""
flags = re.MULTILINE | re.DOTALL
code_text_ = code_text
code_text_ = re.sub(r'^ *# *REM [^\n]*$\n?', '', code_text_, fl... | python | def remove_codeblock_syntax_sentinals(code_text):
r"""
Removes template comments and vim sentinals
Args:
code_text (str):
Returns:
str: code_text_
"""
flags = re.MULTILINE | re.DOTALL
code_text_ = code_text
code_text_ = re.sub(r'^ *# *REM [^\n]*$\n?', '', code_text_, fl... | [
"def",
"remove_codeblock_syntax_sentinals",
"(",
"code_text",
")",
":",
"r",
"flags",
"=",
"re",
".",
"MULTILINE",
"|",
"re",
".",
"DOTALL",
"code_text_",
"=",
"code_text",
"code_text_",
"=",
"re",
".",
"sub",
"(",
"r'^ *# *REM [^\\n]*$\\n?'",
",",
"''",
",",
... | r"""
Removes template comments and vim sentinals
Args:
code_text (str):
Returns:
str: code_text_ | [
"r",
"Removes",
"template",
"comments",
"and",
"vim",
"sentinals"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_autogen.py#L897-L913 | train |
glormph/msstitch | src/app/actions/mzidtsv/proteingroup_sorters.py | sort_protein_group | def sort_protein_group(pgroup, sortfunctions, sortfunc_index):
"""Recursive function that sorts protein group by a number of sorting
functions."""
pgroup_out = []
subgroups = sortfunctions[sortfunc_index](pgroup)
sortfunc_index += 1
for subgroup in subgroups:
if len(subgroup) > 1 and sor... | python | def sort_protein_group(pgroup, sortfunctions, sortfunc_index):
"""Recursive function that sorts protein group by a number of sorting
functions."""
pgroup_out = []
subgroups = sortfunctions[sortfunc_index](pgroup)
sortfunc_index += 1
for subgroup in subgroups:
if len(subgroup) > 1 and sor... | [
"def",
"sort_protein_group",
"(",
"pgroup",
",",
"sortfunctions",
",",
"sortfunc_index",
")",
":",
"pgroup_out",
"=",
"[",
"]",
"subgroups",
"=",
"sortfunctions",
"[",
"sortfunc_index",
"]",
"(",
"pgroup",
")",
"sortfunc_index",
"+=",
"1",
"for",
"subgroup",
"... | Recursive function that sorts protein group by a number of sorting
functions. | [
"Recursive",
"function",
"that",
"sorts",
"protein",
"group",
"by",
"a",
"number",
"of",
"sorting",
"functions",
"."
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/mzidtsv/proteingroup_sorters.py#L35-L48 | train |
glormph/msstitch | src/app/actions/mzidtsv/proteingroup_sorters.py | sort_amounts | def sort_amounts(proteins, sort_index):
"""Generic function for sorting peptides and psms. Assumes a higher
number is better for what is passed at sort_index position in protein."""
amounts = {}
for protein in proteins:
amount_x_for_protein = protein[sort_index]
try:
amounts[... | python | def sort_amounts(proteins, sort_index):
"""Generic function for sorting peptides and psms. Assumes a higher
number is better for what is passed at sort_index position in protein."""
amounts = {}
for protein in proteins:
amount_x_for_protein = protein[sort_index]
try:
amounts[... | [
"def",
"sort_amounts",
"(",
"proteins",
",",
"sort_index",
")",
":",
"amounts",
"=",
"{",
"}",
"for",
"protein",
"in",
"proteins",
":",
"amount_x_for_protein",
"=",
"protein",
"[",
"sort_index",
"]",
"try",
":",
"amounts",
"[",
"amount_x_for_protein",
"]",
"... | Generic function for sorting peptides and psms. Assumes a higher
number is better for what is passed at sort_index position in protein. | [
"Generic",
"function",
"for",
"sorting",
"peptides",
"and",
"psms",
".",
"Assumes",
"a",
"higher",
"number",
"is",
"better",
"for",
"what",
"is",
"passed",
"at",
"sort_index",
"position",
"in",
"protein",
"."
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/mzidtsv/proteingroup_sorters.py#L51-L61 | train |
chriso/gauged | gauged/structures/sparse_map.py | SparseMap.free | def free(self):
"""Free the map"""
if self._ptr is None:
return
Gauged.map_free(self.ptr)
SparseMap.ALLOCATIONS -= 1
self._ptr = None | python | def free(self):
"""Free the map"""
if self._ptr is None:
return
Gauged.map_free(self.ptr)
SparseMap.ALLOCATIONS -= 1
self._ptr = None | [
"def",
"free",
"(",
"self",
")",
":",
"if",
"self",
".",
"_ptr",
"is",
"None",
":",
"return",
"Gauged",
".",
"map_free",
"(",
"self",
".",
"ptr",
")",
"SparseMap",
".",
"ALLOCATIONS",
"-=",
"1",
"self",
".",
"_ptr",
"=",
"None"
] | Free the map | [
"Free",
"the",
"map"
] | cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976 | https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/structures/sparse_map.py#L65-L71 | train |
chriso/gauged | gauged/structures/sparse_map.py | SparseMap.append | def append(self, position, array):
"""Append an array to the end of the map. The position
must be greater than any positions in the map"""
if not Gauged.map_append(self.ptr, position, array.ptr):
raise MemoryError | python | def append(self, position, array):
"""Append an array to the end of the map. The position
must be greater than any positions in the map"""
if not Gauged.map_append(self.ptr, position, array.ptr):
raise MemoryError | [
"def",
"append",
"(",
"self",
",",
"position",
",",
"array",
")",
":",
"if",
"not",
"Gauged",
".",
"map_append",
"(",
"self",
".",
"ptr",
",",
"position",
",",
"array",
".",
"ptr",
")",
":",
"raise",
"MemoryError"
] | Append an array to the end of the map. The position
must be greater than any positions in the map | [
"Append",
"an",
"array",
"to",
"the",
"end",
"of",
"the",
"map",
".",
"The",
"position",
"must",
"be",
"greater",
"than",
"any",
"positions",
"in",
"the",
"map"
] | cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976 | https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/structures/sparse_map.py#L73-L77 | train |
chriso/gauged | gauged/structures/sparse_map.py | SparseMap.slice | def slice(self, start=0, end=0):
"""Slice the map from [start, end)"""
tmp = Gauged.map_new()
if tmp is None:
raise MemoryError
if not Gauged.map_concat(tmp, self.ptr, start, end, 0):
Gauged.map_free(tmp) # pragma: no cover
raise MemoryError
r... | python | def slice(self, start=0, end=0):
"""Slice the map from [start, end)"""
tmp = Gauged.map_new()
if tmp is None:
raise MemoryError
if not Gauged.map_concat(tmp, self.ptr, start, end, 0):
Gauged.map_free(tmp) # pragma: no cover
raise MemoryError
r... | [
"def",
"slice",
"(",
"self",
",",
"start",
"=",
"0",
",",
"end",
"=",
"0",
")",
":",
"tmp",
"=",
"Gauged",
".",
"map_new",
"(",
")",
"if",
"tmp",
"is",
"None",
":",
"raise",
"MemoryError",
"if",
"not",
"Gauged",
".",
"map_concat",
"(",
"tmp",
","... | Slice the map from [start, end) | [
"Slice",
"the",
"map",
"from",
"[",
"start",
"end",
")"
] | cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976 | https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/structures/sparse_map.py#L79-L87 | train |
chriso/gauged | gauged/structures/sparse_map.py | SparseMap.concat | def concat(self, operand, start=0, end=0, offset=0):
"""Concat a map. You can also optionally slice the operand map
and apply an offset to each position before concatting"""
if not Gauged.map_concat(self.ptr, operand.ptr, start, end, offset):
raise MemoryError | python | def concat(self, operand, start=0, end=0, offset=0):
"""Concat a map. You can also optionally slice the operand map
and apply an offset to each position before concatting"""
if not Gauged.map_concat(self.ptr, operand.ptr, start, end, offset):
raise MemoryError | [
"def",
"concat",
"(",
"self",
",",
"operand",
",",
"start",
"=",
"0",
",",
"end",
"=",
"0",
",",
"offset",
"=",
"0",
")",
":",
"if",
"not",
"Gauged",
".",
"map_concat",
"(",
"self",
".",
"ptr",
",",
"operand",
".",
"ptr",
",",
"start",
",",
"en... | Concat a map. You can also optionally slice the operand map
and apply an offset to each position before concatting | [
"Concat",
"a",
"map",
".",
"You",
"can",
"also",
"optionally",
"slice",
"the",
"operand",
"map",
"and",
"apply",
"an",
"offset",
"to",
"each",
"position",
"before",
"concatting"
] | cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976 | https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/structures/sparse_map.py#L89-L93 | train |
chriso/gauged | gauged/structures/sparse_map.py | SparseMap.buffer | def buffer(self, byte_offset=0):
"""Get a copy of the map buffer"""
contents = self.ptr.contents
ptr = addressof(contents.buffer.contents) + byte_offset
length = contents.length * 4 - byte_offset
return buffer((c_char * length).from_address(ptr).raw) \
if length else ... | python | def buffer(self, byte_offset=0):
"""Get a copy of the map buffer"""
contents = self.ptr.contents
ptr = addressof(contents.buffer.contents) + byte_offset
length = contents.length * 4 - byte_offset
return buffer((c_char * length).from_address(ptr).raw) \
if length else ... | [
"def",
"buffer",
"(",
"self",
",",
"byte_offset",
"=",
"0",
")",
":",
"contents",
"=",
"self",
".",
"ptr",
".",
"contents",
"ptr",
"=",
"addressof",
"(",
"contents",
".",
"buffer",
".",
"contents",
")",
"+",
"byte_offset",
"length",
"=",
"contents",
".... | Get a copy of the map buffer | [
"Get",
"a",
"copy",
"of",
"the",
"map",
"buffer"
] | cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976 | https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/structures/sparse_map.py#L99-L105 | train |
timedata-org/loady | loady/whitelist.py | matches | def matches(target, entry):
"""Does the target match the whitelist entry?"""
# It must match all the non-empty entries.
for t, e in itertools.zip_longest(target, entry):
if e and t != e:
return False
# ...and the provider and user can't be empty.
return entry[0] and entry[1] | python | def matches(target, entry):
"""Does the target match the whitelist entry?"""
# It must match all the non-empty entries.
for t, e in itertools.zip_longest(target, entry):
if e and t != e:
return False
# ...and the provider and user can't be empty.
return entry[0] and entry[1] | [
"def",
"matches",
"(",
"target",
",",
"entry",
")",
":",
"for",
"t",
",",
"e",
"in",
"itertools",
".",
"zip_longest",
"(",
"target",
",",
"entry",
")",
":",
"if",
"e",
"and",
"t",
"!=",
"e",
":",
"return",
"False",
"return",
"entry",
"[",
"0",
"]... | Does the target match the whitelist entry? | [
"Does",
"the",
"target",
"match",
"the",
"whitelist",
"entry?"
] | 94ffcdb92f15a28f3c85f77bd293a9cb59de4cad | https://github.com/timedata-org/loady/blob/94ffcdb92f15a28f3c85f77bd293a9cb59de4cad/loady/whitelist.py#L29-L38 | train |
timedata-org/loady | loady/whitelist.py | check_entry | def check_entry(*entry):
"""Throws an exception if the entry isn't on the whitelist."""
whitelist = read_whitelist()
if not check_allow_prompt(entry, whitelist):
whitelist.append(entry)
write_whitelist(whitelist) | python | def check_entry(*entry):
"""Throws an exception if the entry isn't on the whitelist."""
whitelist = read_whitelist()
if not check_allow_prompt(entry, whitelist):
whitelist.append(entry)
write_whitelist(whitelist) | [
"def",
"check_entry",
"(",
"*",
"entry",
")",
":",
"whitelist",
"=",
"read_whitelist",
"(",
")",
"if",
"not",
"check_allow_prompt",
"(",
"entry",
",",
"whitelist",
")",
":",
"whitelist",
".",
"append",
"(",
"entry",
")",
"write_whitelist",
"(",
"whitelist",
... | Throws an exception if the entry isn't on the whitelist. | [
"Throws",
"an",
"exception",
"if",
"the",
"entry",
"isn",
"t",
"on",
"the",
"whitelist",
"."
] | 94ffcdb92f15a28f3c85f77bd293a9cb59de4cad | https://github.com/timedata-org/loady/blob/94ffcdb92f15a28f3c85f77bd293a9cb59de4cad/loady/whitelist.py#L64-L69 | train |
timedata-org/loady | loady/data.py | load_uncached | def load_uncached(location, use_json=None):
"""
Return data at either a file location or at the raw version of a
URL, or raise an exception.
A file location either contains no colons like /usr/tom/test.txt,
or a single character and a colon like C:/WINDOWS/STUFF.
A URL location is anything tha... | python | def load_uncached(location, use_json=None):
"""
Return data at either a file location or at the raw version of a
URL, or raise an exception.
A file location either contains no colons like /usr/tom/test.txt,
or a single character and a colon like C:/WINDOWS/STUFF.
A URL location is anything tha... | [
"def",
"load_uncached",
"(",
"location",
",",
"use_json",
"=",
"None",
")",
":",
"if",
"not",
"whitelist",
".",
"is_file",
"(",
"location",
")",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"raw",
".",
"raw",
"(",
"location",
")",
")",
"if",
"not",
... | Return data at either a file location or at the raw version of a
URL, or raise an exception.
A file location either contains no colons like /usr/tom/test.txt,
or a single character and a colon like C:/WINDOWS/STUFF.
A URL location is anything that's not a file location.
If the URL ends in .json, ... | [
"Return",
"data",
"at",
"either",
"a",
"file",
"location",
"or",
"at",
"the",
"raw",
"version",
"of",
"a",
"URL",
"or",
"raise",
"an",
"exception",
"."
] | 94ffcdb92f15a28f3c85f77bd293a9cb59de4cad | https://github.com/timedata-org/loady/blob/94ffcdb92f15a28f3c85f77bd293a9cb59de4cad/loady/data.py#L12-L50 | train |
Erotemic/utool | utool/util_alg.py | find_group_differences | def find_group_differences(groups1, groups2):
r"""
Returns a measure of how disimilar two groupings are
Args:
groups1 (list): true grouping of items
groups2 (list): predicted grouping of items
CommandLine:
python -m utool.util_alg find_group_differences
SeeAlso:
vt... | python | def find_group_differences(groups1, groups2):
r"""
Returns a measure of how disimilar two groupings are
Args:
groups1 (list): true grouping of items
groups2 (list): predicted grouping of items
CommandLine:
python -m utool.util_alg find_group_differences
SeeAlso:
vt... | [
"def",
"find_group_differences",
"(",
"groups1",
",",
"groups2",
")",
":",
"r",
"import",
"utool",
"as",
"ut",
"item_to_others1",
"=",
"{",
"item",
":",
"set",
"(",
"_group",
")",
"-",
"{",
"item",
"}",
"for",
"_group",
"in",
"groups1",
"for",
"item",
... | r"""
Returns a measure of how disimilar two groupings are
Args:
groups1 (list): true grouping of items
groups2 (list): predicted grouping of items
CommandLine:
python -m utool.util_alg find_group_differences
SeeAlso:
vtool.group_indicies
vtool.apply_grouping
... | [
"r",
"Returns",
"a",
"measure",
"of",
"how",
"disimilar",
"two",
"groupings",
"are"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L43-L120 | train |
Erotemic/utool | utool/util_alg.py | find_group_consistencies | def find_group_consistencies(groups1, groups2):
r"""
Returns a measure of group consistency
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> groups1 = [[1, 2, 3], [4], [5, 6]]
>>> groups2 = [[1, 2], [4], [5, 6]]
>>> common_groups = find_grou... | python | def find_group_consistencies(groups1, groups2):
r"""
Returns a measure of group consistency
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> groups1 = [[1, 2, 3], [4], [5, 6]]
>>> groups2 = [[1, 2], [4], [5, 6]]
>>> common_groups = find_grou... | [
"def",
"find_group_consistencies",
"(",
"groups1",
",",
"groups2",
")",
":",
"r",
"group1_list",
"=",
"{",
"tuple",
"(",
"sorted",
"(",
"_group",
")",
")",
"for",
"_group",
"in",
"groups1",
"}",
"group2_list",
"=",
"{",
"tuple",
"(",
"sorted",
"(",
"_gro... | r"""
Returns a measure of group consistency
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> groups1 = [[1, 2, 3], [4], [5, 6]]
>>> groups2 = [[1, 2], [4], [5, 6]]
>>> common_groups = find_group_consistencies(groups1, groups2)
>>> result... | [
"r",
"Returns",
"a",
"measure",
"of",
"group",
"consistency"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L123-L140 | train |
Erotemic/utool | utool/util_alg.py | compare_groups | def compare_groups(true_groups, pred_groups):
r"""
Finds how predictions need to be modified to match the true grouping.
Notes:
pred_merges - the merges needed that would need to be done for the
pred_groups to match true_groups.
pred_hybrid - the hybrid split/merges needed that ... | python | def compare_groups(true_groups, pred_groups):
r"""
Finds how predictions need to be modified to match the true grouping.
Notes:
pred_merges - the merges needed that would need to be done for the
pred_groups to match true_groups.
pred_hybrid - the hybrid split/merges needed that ... | [
"def",
"compare_groups",
"(",
"true_groups",
",",
"pred_groups",
")",
":",
"r",
"import",
"utool",
"as",
"ut",
"true",
"=",
"{",
"frozenset",
"(",
"_group",
")",
"for",
"_group",
"in",
"true_groups",
"}",
"pred",
"=",
"{",
"frozenset",
"(",
"_group",
")"... | r"""
Finds how predictions need to be modified to match the true grouping.
Notes:
pred_merges - the merges needed that would need to be done for the
pred_groups to match true_groups.
pred_hybrid - the hybrid split/merges needed that would need to be done
for the pred_gro... | [
"r",
"Finds",
"how",
"predictions",
"need",
"to",
"be",
"modified",
"to",
"match",
"the",
"true",
"grouping",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L143-L234 | train |
Erotemic/utool | utool/util_alg.py | grouping_delta_stats | def grouping_delta_stats(old, new):
"""
Returns statistics about grouping changes
Args:
old (set of frozenset): old grouping
new (set of frozenset): new grouping
Returns:
pd.DataFrame: df: data frame of size statistics
Example:
>>> # ENABLE_DOCTEST
>>> from... | python | def grouping_delta_stats(old, new):
"""
Returns statistics about grouping changes
Args:
old (set of frozenset): old grouping
new (set of frozenset): new grouping
Returns:
pd.DataFrame: df: data frame of size statistics
Example:
>>> # ENABLE_DOCTEST
>>> from... | [
"def",
"grouping_delta_stats",
"(",
"old",
",",
"new",
")",
":",
"import",
"pandas",
"as",
"pd",
"import",
"utool",
"as",
"ut",
"group_delta",
"=",
"ut",
".",
"grouping_delta",
"(",
"old",
",",
"new",
")",
"stats",
"=",
"ut",
".",
"odict",
"(",
")",
... | Returns statistics about grouping changes
Args:
old (set of frozenset): old grouping
new (set of frozenset): new grouping
Returns:
pd.DataFrame: df: data frame of size statistics
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> imp... | [
"Returns",
"statistics",
"about",
"grouping",
"changes"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L440-L484 | train |
Erotemic/utool | utool/util_alg.py | upper_diag_self_prodx | def upper_diag_self_prodx(list_):
"""
upper diagnoal of cartesian product of self and self.
Weird name. fixme
Args:
list_ (list):
Returns:
list:
CommandLine:
python -m utool.util_alg --exec-upper_diag_self_prodx
Example:
>>> # ENABLE_DOCTEST
>>> fr... | python | def upper_diag_self_prodx(list_):
"""
upper diagnoal of cartesian product of self and self.
Weird name. fixme
Args:
list_ (list):
Returns:
list:
CommandLine:
python -m utool.util_alg --exec-upper_diag_self_prodx
Example:
>>> # ENABLE_DOCTEST
>>> fr... | [
"def",
"upper_diag_self_prodx",
"(",
"list_",
")",
":",
"return",
"[",
"(",
"item1",
",",
"item2",
")",
"for",
"n1",
",",
"item1",
"in",
"enumerate",
"(",
"list_",
")",
"for",
"n2",
",",
"item2",
"in",
"enumerate",
"(",
"list_",
")",
"if",
"n1",
"<",... | upper diagnoal of cartesian product of self and self.
Weird name. fixme
Args:
list_ (list):
Returns:
list:
CommandLine:
python -m utool.util_alg --exec-upper_diag_self_prodx
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>>... | [
"upper",
"diagnoal",
"of",
"cartesian",
"product",
"of",
"self",
"and",
"self",
".",
"Weird",
"name",
".",
"fixme"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L487-L511 | train |
Erotemic/utool | utool/util_alg.py | colwise_diag_idxs | def colwise_diag_idxs(size, num=2):
r"""
dont trust this implementation or this function name
Args:
size (int):
Returns:
?: upper_diag_idxs
CommandLine:
python -m utool.util_alg --exec-colwise_diag_idxs --size=5 --num=2
python -m utool.util_alg --exec-colwise_diag_... | python | def colwise_diag_idxs(size, num=2):
r"""
dont trust this implementation or this function name
Args:
size (int):
Returns:
?: upper_diag_idxs
CommandLine:
python -m utool.util_alg --exec-colwise_diag_idxs --size=5 --num=2
python -m utool.util_alg --exec-colwise_diag_... | [
"def",
"colwise_diag_idxs",
"(",
"size",
",",
"num",
"=",
"2",
")",
":",
"r",
"import",
"utool",
"as",
"ut",
"diag_idxs",
"=",
"ut",
".",
"iprod",
"(",
"*",
"[",
"range",
"(",
"size",
")",
"for",
"_",
"in",
"range",
"(",
"num",
")",
"]",
")",
"... | r"""
dont trust this implementation or this function name
Args:
size (int):
Returns:
?: upper_diag_idxs
CommandLine:
python -m utool.util_alg --exec-colwise_diag_idxs --size=5 --num=2
python -m utool.util_alg --exec-colwise_diag_idxs --size=3 --num=3
Example:
... | [
"r",
"dont",
"trust",
"this",
"implementation",
"or",
"this",
"function",
"name"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L547-L591 | train |
Erotemic/utool | utool/util_alg.py | product_nonsame | def product_nonsame(list1, list2):
""" product of list1 and list2 where items are non equal """
for item1, item2 in itertools.product(list1, list2):
if item1 != item2:
yield (item1, item2) | python | def product_nonsame(list1, list2):
""" product of list1 and list2 where items are non equal """
for item1, item2 in itertools.product(list1, list2):
if item1 != item2:
yield (item1, item2) | [
"def",
"product_nonsame",
"(",
"list1",
",",
"list2",
")",
":",
"for",
"item1",
",",
"item2",
"in",
"itertools",
".",
"product",
"(",
"list1",
",",
"list2",
")",
":",
"if",
"item1",
"!=",
"item2",
":",
"yield",
"(",
"item1",
",",
"item2",
")"
] | product of list1 and list2 where items are non equal | [
"product",
"of",
"list1",
"and",
"list2",
"where",
"items",
"are",
"non",
"equal"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L600-L604 | train |
Erotemic/utool | utool/util_alg.py | greedy_max_inden_setcover | def greedy_max_inden_setcover(candidate_sets_dict, items, max_covers=None):
"""
greedy algorithm for maximum independent set cover
Covers items with sets from candidate sets. Could be made faster.
CommandLine:
python -m utool.util_alg --test-greedy_max_inden_setcover
Example0:
>>>... | python | def greedy_max_inden_setcover(candidate_sets_dict, items, max_covers=None):
"""
greedy algorithm for maximum independent set cover
Covers items with sets from candidate sets. Could be made faster.
CommandLine:
python -m utool.util_alg --test-greedy_max_inden_setcover
Example0:
>>>... | [
"def",
"greedy_max_inden_setcover",
"(",
"candidate_sets_dict",
",",
"items",
",",
"max_covers",
"=",
"None",
")",
":",
"uncovered_set",
"=",
"set",
"(",
"items",
")",
"rejected_keys",
"=",
"set",
"(",
")",
"accepted_keys",
"=",
"set",
"(",
")",
"covered_items... | greedy algorithm for maximum independent set cover
Covers items with sets from candidate sets. Could be made faster.
CommandLine:
python -m utool.util_alg --test-greedy_max_inden_setcover
Example0:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> import ut... | [
"greedy",
"algorithm",
"for",
"maximum",
"independent",
"set",
"cover"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L611-L681 | train |
Erotemic/utool | utool/util_alg.py | setcover_greedy | def setcover_greedy(candidate_sets_dict, items=None, set_weights=None, item_values=None, max_weight=None):
r"""
Greedy algorithm for various covering problems.
approximation gaurentees depending on specifications like set_weights and item values
Set Cover: log(len(items) + 1) approximation algorithm
... | python | def setcover_greedy(candidate_sets_dict, items=None, set_weights=None, item_values=None, max_weight=None):
r"""
Greedy algorithm for various covering problems.
approximation gaurentees depending on specifications like set_weights and item values
Set Cover: log(len(items) + 1) approximation algorithm
... | [
"def",
"setcover_greedy",
"(",
"candidate_sets_dict",
",",
"items",
"=",
"None",
",",
"set_weights",
"=",
"None",
",",
"item_values",
"=",
"None",
",",
"max_weight",
"=",
"None",
")",
":",
"r",
"import",
"utool",
"as",
"ut",
"solution_cover",
"=",
"{",
"}"... | r"""
Greedy algorithm for various covering problems.
approximation gaurentees depending on specifications like set_weights and item values
Set Cover: log(len(items) + 1) approximation algorithm
Weighted Maximum Cover: 1 - 1/e == .632 approximation algorithm
Generalized maximum coverage is not impl... | [
"r",
"Greedy",
"algorithm",
"for",
"various",
"covering",
"problems",
".",
"approximation",
"gaurentees",
"depending",
"on",
"specifications",
"like",
"set_weights",
"and",
"item",
"values"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L684-L752 | train |
Erotemic/utool | utool/util_alg.py | item_hist | def item_hist(list_):
""" counts the number of times each item appears in the dictionary """
dict_hist = {}
# Insert each item into the correct group
for item in list_:
if item not in dict_hist:
dict_hist[item] = 0
dict_hist[item] += 1
return dict_hist | python | def item_hist(list_):
""" counts the number of times each item appears in the dictionary """
dict_hist = {}
# Insert each item into the correct group
for item in list_:
if item not in dict_hist:
dict_hist[item] = 0
dict_hist[item] += 1
return dict_hist | [
"def",
"item_hist",
"(",
"list_",
")",
":",
"dict_hist",
"=",
"{",
"}",
"for",
"item",
"in",
"list_",
":",
"if",
"item",
"not",
"in",
"dict_hist",
":",
"dict_hist",
"[",
"item",
"]",
"=",
"0",
"dict_hist",
"[",
"item",
"]",
"+=",
"1",
"return",
"di... | counts the number of times each item appears in the dictionary | [
"counts",
"the",
"number",
"of",
"times",
"each",
"item",
"appears",
"in",
"the",
"dictionary"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L901-L909 | train |
Erotemic/utool | utool/util_alg.py | get_nth_prime | def get_nth_prime(n, max_prime=4100, safe=True):
""" hacky but still brute force algorithm for finding nth prime for small tests """
if n <= 100:
first_100_primes = (
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61,
67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 10... | python | def get_nth_prime(n, max_prime=4100, safe=True):
""" hacky but still brute force algorithm for finding nth prime for small tests """
if n <= 100:
first_100_primes = (
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61,
67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 10... | [
"def",
"get_nth_prime",
"(",
"n",
",",
"max_prime",
"=",
"4100",
",",
"safe",
"=",
"True",
")",
":",
"if",
"n",
"<=",
"100",
":",
"first_100_primes",
"=",
"(",
"2",
",",
"3",
",",
"5",
",",
"7",
",",
"11",
",",
"13",
",",
"17",
",",
"19",
","... | hacky but still brute force algorithm for finding nth prime for small tests | [
"hacky",
"but",
"still",
"brute",
"force",
"algorithm",
"for",
"finding",
"nth",
"prime",
"for",
"small",
"tests"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L1049-L1070 | train |
Erotemic/utool | utool/util_alg.py | knapsack | def knapsack(items, maxweight, method='recursive'):
r"""
Solve the knapsack problem by finding the most valuable subsequence of
`items` subject that weighs no more than `maxweight`.
Args:
items (tuple): is a sequence of tuples `(value, weight, id_)`, where
`value` is a number and `w... | python | def knapsack(items, maxweight, method='recursive'):
r"""
Solve the knapsack problem by finding the most valuable subsequence of
`items` subject that weighs no more than `maxweight`.
Args:
items (tuple): is a sequence of tuples `(value, weight, id_)`, where
`value` is a number and `w... | [
"def",
"knapsack",
"(",
"items",
",",
"maxweight",
",",
"method",
"=",
"'recursive'",
")",
":",
"r",
"if",
"method",
"==",
"'recursive'",
":",
"return",
"knapsack_recursive",
"(",
"items",
",",
"maxweight",
")",
"elif",
"method",
"==",
"'iterative'",
":",
... | r"""
Solve the knapsack problem by finding the most valuable subsequence of
`items` subject that weighs no more than `maxweight`.
Args:
items (tuple): is a sequence of tuples `(value, weight, id_)`, where
`value` is a number and `weight` is a non-negative integer, and
`id_` ... | [
"r",
"Solve",
"the",
"knapsack",
"problem",
"by",
"finding",
"the",
"most",
"valuable",
"subsequence",
"of",
"items",
"subject",
"that",
"weighs",
"no",
"more",
"than",
"maxweight",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L1134-L1282 | train |
Erotemic/utool | utool/util_alg.py | knapsack_ilp | def knapsack_ilp(items, maxweight, verbose=False):
"""
solves knapsack using an integer linear program
CommandLine:
python -m utool.util_alg knapsack_ilp
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> import utool as ut
>>> # Solve h... | python | def knapsack_ilp(items, maxweight, verbose=False):
"""
solves knapsack using an integer linear program
CommandLine:
python -m utool.util_alg knapsack_ilp
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> import utool as ut
>>> # Solve h... | [
"def",
"knapsack_ilp",
"(",
"items",
",",
"maxweight",
",",
"verbose",
"=",
"False",
")",
":",
"import",
"pulp",
"values",
"=",
"[",
"t",
"[",
"0",
"]",
"for",
"t",
"in",
"items",
"]",
"weights",
"=",
"[",
"t",
"[",
"1",
"]",
"for",
"t",
"in",
... | solves knapsack using an integer linear program
CommandLine:
python -m utool.util_alg knapsack_ilp
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> import utool as ut
>>> # Solve https://xkcd.com/287/
>>> weights = [2.15, 2.75, 3.35, 3... | [
"solves",
"knapsack",
"using",
"an",
"integer",
"linear",
"program"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L1286-L1337 | train |
Erotemic/utool | utool/util_alg.py | knapsack_iterative | def knapsack_iterative(items, maxweight):
# Knapsack requires integral weights
weights = [t[1] for t in items]
max_exp = max([number_of_decimals(w_) for w_ in weights])
coeff = 10 ** max_exp
# Adjust weights to be integral
int_maxweight = int(maxweight * coeff)
int_items = [(v, int(w * coeff... | python | def knapsack_iterative(items, maxweight):
# Knapsack requires integral weights
weights = [t[1] for t in items]
max_exp = max([number_of_decimals(w_) for w_ in weights])
coeff = 10 ** max_exp
# Adjust weights to be integral
int_maxweight = int(maxweight * coeff)
int_items = [(v, int(w * coeff... | [
"def",
"knapsack_iterative",
"(",
"items",
",",
"maxweight",
")",
":",
"weights",
"=",
"[",
"t",
"[",
"1",
"]",
"for",
"t",
"in",
"items",
"]",
"max_exp",
"=",
"max",
"(",
"[",
"number_of_decimals",
"(",
"w_",
")",
"for",
"w_",
"in",
"weights",
"]",
... | items = int_items
maxweight = int_maxweight | [
"items",
"=",
"int_items",
"maxweight",
"=",
"int_maxweight"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L1385-L1397 | train |
Erotemic/utool | utool/util_alg.py | knapsack_iterative_int | def knapsack_iterative_int(items, maxweight):
r"""
Iterative knapsack method
Math:
maximize \sum_{i \in T} v_i
subject to \sum_{i \in T} w_i \leq W
Notes:
dpmat is the dynamic programming memoization matrix.
dpmat[i, w] is the total value of the items with weight at mos... | python | def knapsack_iterative_int(items, maxweight):
r"""
Iterative knapsack method
Math:
maximize \sum_{i \in T} v_i
subject to \sum_{i \in T} w_i \leq W
Notes:
dpmat is the dynamic programming memoization matrix.
dpmat[i, w] is the total value of the items with weight at mos... | [
"def",
"knapsack_iterative_int",
"(",
"items",
",",
"maxweight",
")",
":",
"r",
"values",
"=",
"[",
"t",
"[",
"0",
"]",
"for",
"t",
"in",
"items",
"]",
"weights",
"=",
"[",
"t",
"[",
"1",
"]",
"for",
"t",
"in",
"items",
"]",
"maxsize",
"=",
"maxw... | r"""
Iterative knapsack method
Math:
maximize \sum_{i \in T} v_i
subject to \sum_{i \in T} w_i \leq W
Notes:
dpmat is the dynamic programming memoization matrix.
dpmat[i, w] is the total value of the items with weight at most W
T is idx_subset, the set of indicies i... | [
"r",
"Iterative",
"knapsack",
"method"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L1400-L1477 | train |
Erotemic/utool | utool/util_alg.py | knapsack_iterative_numpy | def knapsack_iterative_numpy(items, maxweight):
"""
Iterative knapsack method
maximize \sum_{i \in T} v_i
subject to \sum_{i \in T} w_i \leq W
Notes:
dpmat is the dynamic programming memoization matrix.
dpmat[i, w] is the total value of the items with weight at most W
T is ... | python | def knapsack_iterative_numpy(items, maxweight):
"""
Iterative knapsack method
maximize \sum_{i \in T} v_i
subject to \sum_{i \in T} w_i \leq W
Notes:
dpmat is the dynamic programming memoization matrix.
dpmat[i, w] is the total value of the items with weight at most W
T is ... | [
"def",
"knapsack_iterative_numpy",
"(",
"items",
",",
"maxweight",
")",
":",
"items",
"=",
"np",
".",
"array",
"(",
"items",
")",
"weights",
"=",
"items",
".",
"T",
"[",
"1",
"]",
"max_exp",
"=",
"max",
"(",
"[",
"number_of_decimals",
"(",
"w_",
")",
... | Iterative knapsack method
maximize \sum_{i \in T} v_i
subject to \sum_{i \in T} w_i \leq W
Notes:
dpmat is the dynamic programming memoization matrix.
dpmat[i, w] is the total value of the items with weight at most W
T is the set of indicies in the optimal solution | [
"Iterative",
"knapsack",
"method"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L1480-L1532 | train |
Erotemic/utool | utool/util_alg.py | knapsack_greedy | def knapsack_greedy(items, maxweight):
r"""
non-optimal greedy version of knapsack algorithm
does not sort input. Sort the input by largest value
first if desired.
Args:
`items` (tuple): is a sequence of tuples `(value, weight, id_)`, where `value`
is a scalar and `weight` is a ... | python | def knapsack_greedy(items, maxweight):
r"""
non-optimal greedy version of knapsack algorithm
does not sort input. Sort the input by largest value
first if desired.
Args:
`items` (tuple): is a sequence of tuples `(value, weight, id_)`, where `value`
is a scalar and `weight` is a ... | [
"def",
"knapsack_greedy",
"(",
"items",
",",
"maxweight",
")",
":",
"r",
"items_subset",
"=",
"[",
"]",
"total_weight",
"=",
"0",
"total_value",
"=",
"0",
"for",
"item",
"in",
"items",
":",
"value",
",",
"weight",
"=",
"item",
"[",
"0",
":",
"2",
"]"... | r"""
non-optimal greedy version of knapsack algorithm
does not sort input. Sort the input by largest value
first if desired.
Args:
`items` (tuple): is a sequence of tuples `(value, weight, id_)`, where `value`
is a scalar and `weight` is a non-negative integer, and `id_` is an
... | [
"r",
"non",
"-",
"optimal",
"greedy",
"version",
"of",
"knapsack",
"algorithm",
"does",
"not",
"sort",
"input",
".",
"Sort",
"the",
"input",
"by",
"largest",
"value",
"first",
"if",
"desired",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L1548-L1587 | train |
Erotemic/utool | utool/util_alg.py | choose | def choose(n, k):
"""
N choose k
binomial combination (without replacement)
scipy.special.binom
"""
import scipy.misc
return scipy.misc.comb(n, k, exact=True, repetition=False) | python | def choose(n, k):
"""
N choose k
binomial combination (without replacement)
scipy.special.binom
"""
import scipy.misc
return scipy.misc.comb(n, k, exact=True, repetition=False) | [
"def",
"choose",
"(",
"n",
",",
"k",
")",
":",
"import",
"scipy",
".",
"misc",
"return",
"scipy",
".",
"misc",
".",
"comb",
"(",
"n",
",",
"k",
",",
"exact",
"=",
"True",
",",
"repetition",
"=",
"False",
")"
] | N choose k
binomial combination (without replacement)
scipy.special.binom | [
"N",
"choose",
"k"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L1653-L1661 | train |
Erotemic/utool | utool/util_alg.py | almost_eq | def almost_eq(arr1, arr2, thresh=1E-11, ret_error=False):
""" checks if floating point number are equal to a threshold
"""
error = np.abs(arr1 - arr2)
passed = error < thresh
if ret_error:
return passed, error
return passed | python | def almost_eq(arr1, arr2, thresh=1E-11, ret_error=False):
""" checks if floating point number are equal to a threshold
"""
error = np.abs(arr1 - arr2)
passed = error < thresh
if ret_error:
return passed, error
return passed | [
"def",
"almost_eq",
"(",
"arr1",
",",
"arr2",
",",
"thresh",
"=",
"1E-11",
",",
"ret_error",
"=",
"False",
")",
":",
"error",
"=",
"np",
".",
"abs",
"(",
"arr1",
"-",
"arr2",
")",
"passed",
"=",
"error",
"<",
"thresh",
"if",
"ret_error",
":",
"retu... | checks if floating point number are equal to a threshold | [
"checks",
"if",
"floating",
"point",
"number",
"are",
"equal",
"to",
"a",
"threshold"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L2002-L2009 | train |
Erotemic/utool | utool/util_alg.py | norm_zero_one | def norm_zero_one(array, dim=None):
"""
normalizes a numpy array from 0 to 1 based in its extent
Args:
array (ndarray):
dim (int):
Returns:
ndarray:
CommandLine:
python -m utool.util_alg --test-norm_zero_one
Example:
>>> # ENABLE_DOCTEST
>>> ... | python | def norm_zero_one(array, dim=None):
"""
normalizes a numpy array from 0 to 1 based in its extent
Args:
array (ndarray):
dim (int):
Returns:
ndarray:
CommandLine:
python -m utool.util_alg --test-norm_zero_one
Example:
>>> # ENABLE_DOCTEST
>>> ... | [
"def",
"norm_zero_one",
"(",
"array",
",",
"dim",
"=",
"None",
")",
":",
"if",
"not",
"util_type",
".",
"is_float",
"(",
"array",
")",
":",
"array",
"=",
"array",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"array_max",
"=",
"array",
".",
"max",
... | normalizes a numpy array from 0 to 1 based in its extent
Args:
array (ndarray):
dim (int):
Returns:
ndarray:
CommandLine:
python -m utool.util_alg --test-norm_zero_one
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>>... | [
"normalizes",
"a",
"numpy",
"array",
"from",
"0",
"to",
"1",
"based",
"in",
"its",
"extent"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L2078-L2109 | train |
Erotemic/utool | utool/util_alg.py | group_indices | def group_indices(groupid_list):
"""
groups indicies of each item in ``groupid_list``
Args:
groupid_list (list): list of group ids
SeeAlso:
vt.group_indices - optimized numpy version
ut.apply_grouping
CommandLine:
python -m utool.util_alg --test-group_indices
... | python | def group_indices(groupid_list):
"""
groups indicies of each item in ``groupid_list``
Args:
groupid_list (list): list of group ids
SeeAlso:
vt.group_indices - optimized numpy version
ut.apply_grouping
CommandLine:
python -m utool.util_alg --test-group_indices
... | [
"def",
"group_indices",
"(",
"groupid_list",
")",
":",
"item_list",
"=",
"range",
"(",
"len",
"(",
"groupid_list",
")",
")",
"grouped_dict",
"=",
"util_dict",
".",
"group_items",
"(",
"item_list",
",",
"groupid_list",
")",
"keys_",
"=",
"list",
"(",
"grouped... | groups indicies of each item in ``groupid_list``
Args:
groupid_list (list): list of group ids
SeeAlso:
vt.group_indices - optimized numpy version
ut.apply_grouping
CommandLine:
python -m utool.util_alg --test-group_indices
python3 -m utool.util_alg --test-group_ind... | [
"groups",
"indicies",
"of",
"each",
"item",
"in",
"groupid_list"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L2162-L2198 | train |
Erotemic/utool | utool/util_alg.py | ungroup_gen | def ungroup_gen(grouped_items, groupxs, fill=None):
"""
Ungroups items returning a generator.
Note that this is much slower than the list version and is not gaurenteed
to have better memory usage.
Args:
grouped_items (list):
groupxs (list):
maxval (int): (default = None)
... | python | def ungroup_gen(grouped_items, groupxs, fill=None):
"""
Ungroups items returning a generator.
Note that this is much slower than the list version and is not gaurenteed
to have better memory usage.
Args:
grouped_items (list):
groupxs (list):
maxval (int): (default = None)
... | [
"def",
"ungroup_gen",
"(",
"grouped_items",
",",
"groupxs",
",",
"fill",
"=",
"None",
")",
":",
"import",
"utool",
"as",
"ut",
"minpergroup",
"=",
"[",
"min",
"(",
"xs",
")",
"if",
"len",
"(",
"xs",
")",
"else",
"0",
"for",
"xs",
"in",
"groupxs",
"... | Ungroups items returning a generator.
Note that this is much slower than the list version and is not gaurenteed
to have better memory usage.
Args:
grouped_items (list):
groupxs (list):
maxval (int): (default = None)
Returns:
list: ungrouped_items
SeeAlso:
v... | [
"Ungroups",
"items",
"returning",
"a",
"generator",
".",
"Note",
"that",
"this",
"is",
"much",
"slower",
"than",
"the",
"list",
"version",
"and",
"is",
"not",
"gaurenteed",
"to",
"have",
"better",
"memory",
"usage",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L2306-L2406 | train |
Erotemic/utool | utool/util_alg.py | ungroup_unique | def ungroup_unique(unique_items, groupxs, maxval=None):
"""
Ungroups unique items to correspond to original non-unique list
Args:
unique_items (list):
groupxs (list):
maxval (int): (default = None)
Returns:
list: ungrouped_items
CommandLine:
python -m utool... | python | def ungroup_unique(unique_items, groupxs, maxval=None):
"""
Ungroups unique items to correspond to original non-unique list
Args:
unique_items (list):
groupxs (list):
maxval (int): (default = None)
Returns:
list: ungrouped_items
CommandLine:
python -m utool... | [
"def",
"ungroup_unique",
"(",
"unique_items",
",",
"groupxs",
",",
"maxval",
"=",
"None",
")",
":",
"if",
"maxval",
"is",
"None",
":",
"maxpergroup",
"=",
"[",
"max",
"(",
"xs",
")",
"if",
"len",
"(",
"xs",
")",
"else",
"0",
"for",
"xs",
"in",
"gro... | Ungroups unique items to correspond to original non-unique list
Args:
unique_items (list):
groupxs (list):
maxval (int): (default = None)
Returns:
list: ungrouped_items
CommandLine:
python -m utool.util_alg ungroup_unique
Example:
>>> # ENABLE_DOCTEST
... | [
"Ungroups",
"unique",
"items",
"to",
"correspond",
"to",
"original",
"non",
"-",
"unique",
"list"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L2409-L2443 | train |
Erotemic/utool | utool/util_alg.py | edit_distance | def edit_distance(string1, string2):
"""
Edit distance algorithm. String1 and string2 can be either
strings or lists of strings
pip install python-Levenshtein
Args:
string1 (str or list):
string2 (str or list):
CommandLine:
python -m utool.util_alg edit_distance --show... | python | def edit_distance(string1, string2):
"""
Edit distance algorithm. String1 and string2 can be either
strings or lists of strings
pip install python-Levenshtein
Args:
string1 (str or list):
string2 (str or list):
CommandLine:
python -m utool.util_alg edit_distance --show... | [
"def",
"edit_distance",
"(",
"string1",
",",
"string2",
")",
":",
"import",
"utool",
"as",
"ut",
"try",
":",
"import",
"Levenshtein",
"except",
"ImportError",
"as",
"ex",
":",
"ut",
".",
"printex",
"(",
"ex",
",",
"'pip install python-Levenshtein'",
")",
"ra... | Edit distance algorithm. String1 and string2 can be either
strings or lists of strings
pip install python-Levenshtein
Args:
string1 (str or list):
string2 (str or list):
CommandLine:
python -m utool.util_alg edit_distance --show
Example:
>>> # DISABLE_DOCTEST
... | [
"Edit",
"distance",
"algorithm",
".",
"String1",
"and",
"string2",
"can",
"be",
"either",
"strings",
"or",
"lists",
"of",
"strings"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L2446-L2499 | train |
Erotemic/utool | utool/util_alg.py | standardize_boolexpr | def standardize_boolexpr(boolexpr_, parens=False):
r"""
Standardizes a boolean expression into an or-ing of and-ed variables
Args:
boolexpr_ (str):
Returns:
str: final_expr
CommandLine:
sudo pip install git+https://github.com/tpircher/quine-mccluskey.git
python -m ... | python | def standardize_boolexpr(boolexpr_, parens=False):
r"""
Standardizes a boolean expression into an or-ing of and-ed variables
Args:
boolexpr_ (str):
Returns:
str: final_expr
CommandLine:
sudo pip install git+https://github.com/tpircher/quine-mccluskey.git
python -m ... | [
"def",
"standardize_boolexpr",
"(",
"boolexpr_",
",",
"parens",
"=",
"False",
")",
":",
"r",
"import",
"utool",
"as",
"ut",
"import",
"re",
"onlyvars",
"=",
"boolexpr_",
"onlyvars",
"=",
"re",
".",
"sub",
"(",
"'\\\\bnot\\\\b'",
",",
"''",
",",
"onlyvars",... | r"""
Standardizes a boolean expression into an or-ing of and-ed variables
Args:
boolexpr_ (str):
Returns:
str: final_expr
CommandLine:
sudo pip install git+https://github.com/tpircher/quine-mccluskey.git
python -m utool.util_alg standardize_boolexpr --show
Example... | [
"r",
"Standardizes",
"a",
"boolean",
"expression",
"into",
"an",
"or",
"-",
"ing",
"of",
"and",
"-",
"ed",
"variables"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L2545-L2629 | train |
Erotemic/utool | utool/util_alg.py | expensive_task_gen | def expensive_task_gen(num=8700):
r"""
Runs a task that takes some time
Args:
num (int): (default = 8700)
CommandLine:
python -m utool.util_alg expensive_task_gen --show
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> import utoo... | python | def expensive_task_gen(num=8700):
r"""
Runs a task that takes some time
Args:
num (int): (default = 8700)
CommandLine:
python -m utool.util_alg expensive_task_gen --show
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> import utoo... | [
"def",
"expensive_task_gen",
"(",
"num",
"=",
"8700",
")",
":",
"r",
"import",
"utool",
"as",
"ut",
"for",
"x",
"in",
"range",
"(",
"0",
",",
"num",
")",
":",
"with",
"ut",
".",
"Timer",
"(",
"verbose",
"=",
"False",
")",
"as",
"t",
":",
"ut",
... | r"""
Runs a task that takes some time
Args:
num (int): (default = 8700)
CommandLine:
python -m utool.util_alg expensive_task_gen --show
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> import utool as ut
>>> #num = 8700
... | [
"r",
"Runs",
"a",
"task",
"that",
"takes",
"some",
"time"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L2751-L2795 | train |
Erotemic/utool | utool/util_alg.py | factors | def factors(n):
"""
Computes all the integer factors of the number `n`
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> import utool as ut
>>> result = sorted(ut.factors(10))
>>> print(result)
[1, 2, 5, 10]
References:
h... | python | def factors(n):
"""
Computes all the integer factors of the number `n`
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> import utool as ut
>>> result = sorted(ut.factors(10))
>>> print(result)
[1, 2, 5, 10]
References:
h... | [
"def",
"factors",
"(",
"n",
")",
":",
"return",
"set",
"(",
"reduce",
"(",
"list",
".",
"__add__",
",",
"(",
"[",
"i",
",",
"n",
"//",
"i",
"]",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"int",
"(",
"n",
"**",
"0.5",
")",
"+",
"1",
")",
"... | Computes all the integer factors of the number `n`
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> import utool as ut
>>> result = sorted(ut.factors(10))
>>> print(result)
[1, 2, 5, 10]
References:
http://stackoverflow.com/ques... | [
"Computes",
"all",
"the",
"integer",
"factors",
"of",
"the",
"number",
"n"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L2801-L2817 | train |
glormph/msstitch | src/app/actions/prottable/info.py | add_protein_data | def add_protein_data(proteins, pgdb, headerfields, genecentric=False,
pool_to_output=False):
"""First creates a map with all master proteins with data,
then outputs protein data dicts for rows of a tsv. If a pool
is given then only output for that pool will be shown in the
protein t... | python | def add_protein_data(proteins, pgdb, headerfields, genecentric=False,
pool_to_output=False):
"""First creates a map with all master proteins with data,
then outputs protein data dicts for rows of a tsv. If a pool
is given then only output for that pool will be shown in the
protein t... | [
"def",
"add_protein_data",
"(",
"proteins",
",",
"pgdb",
",",
"headerfields",
",",
"genecentric",
"=",
"False",
",",
"pool_to_output",
"=",
"False",
")",
":",
"proteindata",
"=",
"create_featuredata_map",
"(",
"pgdb",
",",
"genecentric",
"=",
"genecentric",
",",... | First creates a map with all master proteins with data,
then outputs protein data dicts for rows of a tsv. If a pool
is given then only output for that pool will be shown in the
protein table. | [
"First",
"creates",
"a",
"map",
"with",
"all",
"master",
"proteins",
"with",
"data",
"then",
"outputs",
"protein",
"data",
"dicts",
"for",
"rows",
"of",
"a",
"tsv",
".",
"If",
"a",
"pool",
"is",
"given",
"then",
"only",
"output",
"for",
"that",
"pool",
... | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/prottable/info.py#L13-L34 | train |
glormph/msstitch | src/app/actions/prottable/info.py | get_protein_data_pgrouped | def get_protein_data_pgrouped(proteindata, p_acc, headerfields):
"""Parses protein data for a certain protein into tsv output
dictionary"""
report = get_protein_data_base(proteindata, p_acc, headerfields)
return get_cov_protnumbers(proteindata, p_acc, report) | python | def get_protein_data_pgrouped(proteindata, p_acc, headerfields):
"""Parses protein data for a certain protein into tsv output
dictionary"""
report = get_protein_data_base(proteindata, p_acc, headerfields)
return get_cov_protnumbers(proteindata, p_acc, report) | [
"def",
"get_protein_data_pgrouped",
"(",
"proteindata",
",",
"p_acc",
",",
"headerfields",
")",
":",
"report",
"=",
"get_protein_data_base",
"(",
"proteindata",
",",
"p_acc",
",",
"headerfields",
")",
"return",
"get_cov_protnumbers",
"(",
"proteindata",
",",
"p_acc"... | Parses protein data for a certain protein into tsv output
dictionary | [
"Parses",
"protein",
"data",
"for",
"a",
"certain",
"protein",
"into",
"tsv",
"output",
"dictionary"
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/prottable/info.py#L41-L45 | train |
chriso/gauged | gauged/drivers/postgresql.py | PostgreSQLDriver.keys | def keys(self, namespace, prefix=None, limit=None, offset=None):
"""Get keys from a namespace"""
params = [namespace]
query = 'SELECT key FROM gauged_keys WHERE namespace = %s'
if prefix is not None:
query += ' AND key LIKE %s'
params.append(prefix + '%')
... | python | def keys(self, namespace, prefix=None, limit=None, offset=None):
"""Get keys from a namespace"""
params = [namespace]
query = 'SELECT key FROM gauged_keys WHERE namespace = %s'
if prefix is not None:
query += ' AND key LIKE %s'
params.append(prefix + '%')
... | [
"def",
"keys",
"(",
"self",
",",
"namespace",
",",
"prefix",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"offset",
"=",
"None",
")",
":",
"params",
"=",
"[",
"namespace",
"]",
"query",
"=",
"'SELECT key FROM gauged_keys WHERE namespace = %s'",
"if",
"prefix... | Get keys from a namespace | [
"Get",
"keys",
"from",
"a",
"namespace"
] | cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976 | https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/drivers/postgresql.py#L25-L40 | train |
chriso/gauged | gauged/drivers/postgresql.py | PostgreSQLDriver.get_block | def get_block(self, namespace, offset, key):
"""Get the block identified by namespace, offset, key and
value"""
cursor = self.cursor
cursor.execute('SELECT data, flags FROM gauged_data '
'WHERE namespace = %s AND "offset" = %s AND key = %s',
... | python | def get_block(self, namespace, offset, key):
"""Get the block identified by namespace, offset, key and
value"""
cursor = self.cursor
cursor.execute('SELECT data, flags FROM gauged_data '
'WHERE namespace = %s AND "offset" = %s AND key = %s',
... | [
"def",
"get_block",
"(",
"self",
",",
"namespace",
",",
"offset",
",",
"key",
")",
":",
"cursor",
"=",
"self",
".",
"cursor",
"cursor",
".",
"execute",
"(",
"'SELECT data, flags FROM gauged_data '",
"'WHERE namespace = %s AND \"offset\" = %s AND key = %s'",
",",
"(",
... | Get the block identified by namespace, offset, key and
value | [
"Get",
"the",
"block",
"identified",
"by",
"namespace",
"offset",
"key",
"and",
"value"
] | cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976 | https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/drivers/postgresql.py#L63-L71 | train |
chriso/gauged | gauged/drivers/postgresql.py | PostgreSQLDriver.block_offset_bounds | def block_offset_bounds(self, namespace):
"""Get the minimum and maximum block offset for the specified
namespace"""
cursor = self.cursor
cursor.execute('SELECT MIN("offset"), MAX("offset") '
'FROM gauged_statistics WHERE namespace = %s',
(na... | python | def block_offset_bounds(self, namespace):
"""Get the minimum and maximum block offset for the specified
namespace"""
cursor = self.cursor
cursor.execute('SELECT MIN("offset"), MAX("offset") '
'FROM gauged_statistics WHERE namespace = %s',
(na... | [
"def",
"block_offset_bounds",
"(",
"self",
",",
"namespace",
")",
":",
"cursor",
"=",
"self",
".",
"cursor",
"cursor",
".",
"execute",
"(",
"'SELECT MIN(\"offset\"), MAX(\"offset\") '",
"'FROM gauged_statistics WHERE namespace = %s'",
",",
"(",
"namespace",
",",
")",
... | Get the minimum and maximum block offset for the specified
namespace | [
"Get",
"the",
"minimum",
"and",
"maximum",
"block",
"offset",
"for",
"the",
"specified",
"namespace"
] | cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976 | https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/drivers/postgresql.py#L128-L135 | train |
chriso/gauged | gauged/drivers/postgresql.py | PostgreSQLDriver.set_writer_position | def set_writer_position(self, name, timestamp):
"""Insert a timestamp to keep track of the current writer position"""
execute = self.cursor.execute
execute('DELETE FROM gauged_writer_history WHERE id = %s', (name,))
execute('INSERT INTO gauged_writer_history (id, timestamp) '
... | python | def set_writer_position(self, name, timestamp):
"""Insert a timestamp to keep track of the current writer position"""
execute = self.cursor.execute
execute('DELETE FROM gauged_writer_history WHERE id = %s', (name,))
execute('INSERT INTO gauged_writer_history (id, timestamp) '
... | [
"def",
"set_writer_position",
"(",
"self",
",",
"name",
",",
"timestamp",
")",
":",
"execute",
"=",
"self",
".",
"cursor",
".",
"execute",
"execute",
"(",
"'DELETE FROM gauged_writer_history WHERE id = %s'",
",",
"(",
"name",
",",
")",
")",
"execute",
"(",
"'I... | Insert a timestamp to keep track of the current writer position | [
"Insert",
"a",
"timestamp",
"to",
"keep",
"track",
"of",
"the",
"current",
"writer",
"position"
] | cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976 | https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/drivers/postgresql.py#L161-L166 | train |
chriso/gauged | gauged/drivers/postgresql.py | PostgreSQLDriver.add_cache | def add_cache(self, namespace, key, query_hash, length, cache):
"""Add cached values for the specified date range and query"""
start = 0
bulk_insert = self.bulk_insert
cache_len = len(cache)
row = '(%s,%s,%s,%s,%s,%s)'
query = 'INSERT INTO gauged_cache ' \
'(n... | python | def add_cache(self, namespace, key, query_hash, length, cache):
"""Add cached values for the specified date range and query"""
start = 0
bulk_insert = self.bulk_insert
cache_len = len(cache)
row = '(%s,%s,%s,%s,%s,%s)'
query = 'INSERT INTO gauged_cache ' \
'(n... | [
"def",
"add_cache",
"(",
"self",
",",
"namespace",
",",
"key",
",",
"query_hash",
",",
"length",
",",
"cache",
")",
":",
"start",
"=",
"0",
"bulk_insert",
"=",
"self",
".",
"bulk_insert",
"cache_len",
"=",
"len",
"(",
"cache",
")",
"row",
"=",
"'(%s,%s... | Add cached values for the specified date range and query | [
"Add",
"cached",
"values",
"for",
"the",
"specified",
"date",
"range",
"and",
"query"
] | cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976 | https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/drivers/postgresql.py#L249-L268 | train |
crdoconnor/faketime | faketime/__init__.py | get_environment_vars | def get_environment_vars(filename):
"""Return a dict of environment variables required to run a service under faketime."""
if sys.platform == "linux" or sys.platform == "linux2":
return {
'LD_PRELOAD': path.join(LIBFAKETIME_DIR, "libfaketime.so.1"),
'FAKETIME_SKIP_CMDS': 'nodejs'... | python | def get_environment_vars(filename):
"""Return a dict of environment variables required to run a service under faketime."""
if sys.platform == "linux" or sys.platform == "linux2":
return {
'LD_PRELOAD': path.join(LIBFAKETIME_DIR, "libfaketime.so.1"),
'FAKETIME_SKIP_CMDS': 'nodejs'... | [
"def",
"get_environment_vars",
"(",
"filename",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"\"linux\"",
"or",
"sys",
".",
"platform",
"==",
"\"linux2\"",
":",
"return",
"{",
"'LD_PRELOAD'",
":",
"path",
".",
"join",
"(",
"LIBFAKETIME_DIR",
",",
"\"libfake... | Return a dict of environment variables required to run a service under faketime. | [
"Return",
"a",
"dict",
"of",
"environment",
"variables",
"required",
"to",
"run",
"a",
"service",
"under",
"faketime",
"."
] | 6e81ca070c0e601a52507b945ed45d5d42576b21 | https://github.com/crdoconnor/faketime/blob/6e81ca070c0e601a52507b945ed45d5d42576b21/faketime/__init__.py#L9-L24 | train |
crdoconnor/faketime | faketime/__init__.py | change_time | def change_time(filename, newtime):
"""Change the time of a process or group of processes by writing a new time to the time file."""
with open(filename, "w") as faketimetxt_handle:
faketimetxt_handle.write("@" + newtime.strftime("%Y-%m-%d %H:%M:%S")) | python | def change_time(filename, newtime):
"""Change the time of a process or group of processes by writing a new time to the time file."""
with open(filename, "w") as faketimetxt_handle:
faketimetxt_handle.write("@" + newtime.strftime("%Y-%m-%d %H:%M:%S")) | [
"def",
"change_time",
"(",
"filename",
",",
"newtime",
")",
":",
"with",
"open",
"(",
"filename",
",",
"\"w\"",
")",
"as",
"faketimetxt_handle",
":",
"faketimetxt_handle",
".",
"write",
"(",
"\"@\"",
"+",
"newtime",
".",
"strftime",
"(",
"\"%Y-%m-%d %H:%M:%S\"... | Change the time of a process or group of processes by writing a new time to the time file. | [
"Change",
"the",
"time",
"of",
"a",
"process",
"or",
"group",
"of",
"processes",
"by",
"writing",
"a",
"new",
"time",
"to",
"the",
"time",
"file",
"."
] | 6e81ca070c0e601a52507b945ed45d5d42576b21 | https://github.com/crdoconnor/faketime/blob/6e81ca070c0e601a52507b945ed45d5d42576b21/faketime/__init__.py#L27-L30 | train |
glormph/msstitch | src/app/actions/pycolator/filters.py | filter_unique_peptides | def filter_unique_peptides(peptides, score, ns):
""" Filters unique peptides from multiple Percolator output XML files.
Takes a dir with a set of XMLs, a score to filter on and a namespace.
Outputs an ElementTree.
"""
scores = {'q': 'q_value',
'pep': 'pep',
'p': '... | python | def filter_unique_peptides(peptides, score, ns):
""" Filters unique peptides from multiple Percolator output XML files.
Takes a dir with a set of XMLs, a score to filter on and a namespace.
Outputs an ElementTree.
"""
scores = {'q': 'q_value',
'pep': 'pep',
'p': '... | [
"def",
"filter_unique_peptides",
"(",
"peptides",
",",
"score",
",",
"ns",
")",
":",
"scores",
"=",
"{",
"'q'",
":",
"'q_value'",
",",
"'pep'",
":",
"'pep'",
",",
"'p'",
":",
"'p_value'",
",",
"'svm'",
":",
"'svm_score'",
"}",
"highest",
"=",
"{",
"}",... | Filters unique peptides from multiple Percolator output XML files.
Takes a dir with a set of XMLs, a score to filter on and a namespace.
Outputs an ElementTree. | [
"Filters",
"unique",
"peptides",
"from",
"multiple",
"Percolator",
"output",
"XML",
"files",
".",
"Takes",
"a",
"dir",
"with",
"a",
"set",
"of",
"XMLs",
"a",
"score",
"to",
"filter",
"on",
"and",
"a",
"namespace",
".",
"Outputs",
"an",
"ElementTree",
"."
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/pycolator/filters.py#L102-L136 | train |
timedata-org/loady | loady/importer.py | import_symbol | def import_symbol(name=None, path=None, typename=None, base_path=None):
"""
Import a module, or a typename within a module from its name.
Arguments:
name: An absolute or relative (starts with a .) Python path
path: If name is relative, path is prepended to it.
base_path: (DEPRECATED) Same as p... | python | def import_symbol(name=None, path=None, typename=None, base_path=None):
"""
Import a module, or a typename within a module from its name.
Arguments:
name: An absolute or relative (starts with a .) Python path
path: If name is relative, path is prepended to it.
base_path: (DEPRECATED) Same as p... | [
"def",
"import_symbol",
"(",
"name",
"=",
"None",
",",
"path",
"=",
"None",
",",
"typename",
"=",
"None",
",",
"base_path",
"=",
"None",
")",
":",
"_",
",",
"symbol",
"=",
"_import",
"(",
"name",
"or",
"typename",
",",
"path",
"or",
"base_path",
")",... | Import a module, or a typename within a module from its name.
Arguments:
name: An absolute or relative (starts with a .) Python path
path: If name is relative, path is prepended to it.
base_path: (DEPRECATED) Same as path
typename: (DEPRECATED) Same as path | [
"Import",
"a",
"module",
"or",
"a",
"typename",
"within",
"a",
"module",
"from",
"its",
"name",
"."
] | 94ffcdb92f15a28f3c85f77bd293a9cb59de4cad | https://github.com/timedata-org/loady/blob/94ffcdb92f15a28f3c85f77bd293a9cb59de4cad/loady/importer.py#L35-L47 | train |
Erotemic/utool | utool/util_win32.py | add_to_win32_PATH | def add_to_win32_PATH(script_fpath, *add_path_list):
r"""
Writes a registery script to update the PATH variable into the sync registry
CommandLine:
python -m utool.util_win32 --test-add_to_win32_PATH --newpath "C:\Program Files (x86)\Graphviz2.38\bin"
Example:
>>> # DISABLE_DOCTEST
... | python | def add_to_win32_PATH(script_fpath, *add_path_list):
r"""
Writes a registery script to update the PATH variable into the sync registry
CommandLine:
python -m utool.util_win32 --test-add_to_win32_PATH --newpath "C:\Program Files (x86)\Graphviz2.38\bin"
Example:
>>> # DISABLE_DOCTEST
... | [
"def",
"add_to_win32_PATH",
"(",
"script_fpath",
",",
"*",
"add_path_list",
")",
":",
"r",
"import",
"utool",
"as",
"ut",
"write_dir",
"=",
"dirname",
"(",
"script_fpath",
")",
"key",
"=",
"'[HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environ... | r"""
Writes a registery script to update the PATH variable into the sync registry
CommandLine:
python -m utool.util_win32 --test-add_to_win32_PATH --newpath "C:\Program Files (x86)\Graphviz2.38\bin"
Example:
>>> # DISABLE_DOCTEST
>>> # SCRIPT
>>> from utool.util_win32 impor... | [
"r",
"Writes",
"a",
"registery",
"script",
"to",
"update",
"the",
"PATH",
"variable",
"into",
"the",
"sync",
"registry"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_win32.py#L60-L91 | train |
Erotemic/utool | utool/util_dict.py | dzip | def dzip(list1, list2):
r"""
Zips elementwise pairs between list1 and list2 into a dictionary. Values
from list2 can be broadcast onto list1.
Args:
list1 (sequence): full sequence
list2 (sequence): can either be a sequence of one item or a sequence of
equal length to `list1`... | python | def dzip(list1, list2):
r"""
Zips elementwise pairs between list1 and list2 into a dictionary. Values
from list2 can be broadcast onto list1.
Args:
list1 (sequence): full sequence
list2 (sequence): can either be a sequence of one item or a sequence of
equal length to `list1`... | [
"def",
"dzip",
"(",
"list1",
",",
"list2",
")",
":",
"r",
"try",
":",
"len",
"(",
"list1",
")",
"except",
"TypeError",
":",
"list1",
"=",
"list",
"(",
"list1",
")",
"try",
":",
"len",
"(",
"list2",
")",
"except",
"TypeError",
":",
"list2",
"=",
"... | r"""
Zips elementwise pairs between list1 and list2 into a dictionary. Values
from list2 can be broadcast onto list1.
Args:
list1 (sequence): full sequence
list2 (sequence): can either be a sequence of one item or a sequence of
equal length to `list1`
SeeAlso:
util_... | [
"r",
"Zips",
"elementwise",
"pairs",
"between",
"list1",
"and",
"list2",
"into",
"a",
"dictionary",
".",
"Values",
"from",
"list2",
"can",
"be",
"broadcast",
"onto",
"list1",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dict.py#L25-L76 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.