repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 3
values | summary stringlengths 4 350 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
steveYeah/PyBomb | pybomb/clients/games_client.py | GamesClient.search | def search(
self,
filter_by,
return_fields=None,
sort_by=None,
desc=True,
limit=None,
offset=None,
):
"""
Full search of games resource, supporting all search fields
available in API
http://www.giantbomb.com/api/documentation#to... | python | def search(
self,
filter_by,
return_fields=None,
sort_by=None,
desc=True,
limit=None,
offset=None,
):
"""
Full search of games resource, supporting all search fields
available in API
http://www.giantbomb.com/api/documentation#to... | [
"def",
"search",
"(",
"self",
",",
"filter_by",
",",
"return_fields",
"=",
"None",
",",
"sort_by",
"=",
"None",
",",
"desc",
"=",
"True",
",",
"limit",
"=",
"None",
",",
"offset",
"=",
"None",
",",
")",
":",
"self",
".",
"_validate_filter_fields",
"(",... | Full search of games resource, supporting all search fields
available in API
http://www.giantbomb.com/api/documentation#toc-0-17
:param filter_by: dict
:param return_fields: tuple
:param sort_by: string
:param desc: bool
:param limit: int
:param offset: i... | [
"Full",
"search",
"of",
"games",
"resource",
"supporting",
"all",
"search",
"fields",
"available",
"in",
"API",
"http",
":",
"//",
"www",
".",
"giantbomb",
".",
"com",
"/",
"api",
"/",
"documentation#toc",
"-",
"0",
"-",
"17"
] | 54045d74e642f8a1c4366c24bd6a330ae3da6257 | https://github.com/steveYeah/PyBomb/blob/54045d74e642f8a1c4366c24bd6a330ae3da6257/pybomb/clients/games_client.py#L35-L86 | train | Search for the resource in the cluster. |
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 | Quick search method that allows you to search for a game using only the name and the platform |
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 | Sends a ping to the handler. |
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 | Called when a pong is received. |
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 | Check to see if var is an instance of known compatible types for type_ |
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 isinstance(type_, tuple):",
"# for trytype in type_:",
"# try:",
"# return trytype(var)",
"# except Exception:",
"# pass",
"# raise TypeError('Cant figure out type=%r' % (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
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 | This function casts a variable to a type and tries to be clever when var is a string |
Erotemic/utool | utool/util_type.py | smart_cast2 | def smart_cast2(var):
r"""
if the variable is a string tries to cast it to a reasonable value.
maybe can just use eval. FIXME: funcname
Args:
var (unknown):
Returns:
unknown: some var
CommandLine:
python -m utool.util_type --test-smart_cast2
Example:
>>> #... | python | def smart_cast2(var):
r"""
if the variable is a string tries to cast it to a reasonable value.
maybe can just use eval. FIXME: funcname
Args:
var (unknown):
Returns:
unknown: some var
CommandLine:
python -m utool.util_type --test-smart_cast2
Example:
>>> #... | [
"def",
"smart_cast2",
"(",
"var",
")",
":",
"if",
"var",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"var",
",",
"six",
".",
"string_types",
")",
":",
"castvar",
"=",
"None",
"lower",
"=",
"var",
".",
"lower",
"(",
")",
"if",
"low... | r"""
if the variable is a string tries to cast it to a reasonable value.
maybe can just use eval. FIXME: funcname
Args:
var (unknown):
Returns:
unknown: some var
CommandLine:
python -m utool.util_type --test-smart_cast2
Example:
>>> # ENABLE_DOCTEST
>>... | [
"r",
"if",
"the",
"variable",
"is",
"a",
"string",
"tries",
"to",
"cast",
"it",
"to",
"a",
"reasonable",
"value",
".",
"maybe",
"can",
"just",
"use",
"eval",
".",
"FIXME",
":",
"funcname"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_type.py#L263-L318 | train | r This function takes a string and attempts to cast it to a reasonable value. |
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 | returns a list of all fuzzy names in a string |
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",
":",
"# Parse comma separated values as ints",
"if",
"re",
".",
"match",
"(",
"r'\\d*,\\d*,?\\d*'",
",",
"str_",
")",
":",
"... | 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 | Fuzzy int function. |
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",
":",
"# This is a weird system specific error",
"# https://github.com/numpy/numpy/issues/3667",
"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) | [
"Gets",
"types",
"accounting",
"for",
"numpy"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_type.py#L377-L403 | train | Gets types accounting for numpy
Taxonomy |
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_",
")",
":",
"# TODO Expand and make work correctly",
"if",
"HAVE_NUMPY",
"and",
"isinstance",
"(",
"list_",
",",
"np",
".",
"ndarray",
")",
":",
"item",
"=",
"list_",
"elif",
"isinstance",
"(",
"list_",
",",
"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 | Returns the type of the homogenous list. |
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 | Pops a value off the top of the stack. |
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 | Stores all spectra rt injection time and scan nr in db |
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",
")",
":",
"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 | r Check that a function raises an error when given specific arguments. |
Erotemic/utool | utool/util_assert.py | lists_eq | def lists_eq(list1, list2):
""" recursive """
if len(list1) != len(list2):
return False
for count, (item1, item2) in enumerate(zip(list1, list2)):
if isinstance(item1, np.ndarray) or isinstance(item2, np.ndarray):
failed = not np.all(item1 == item2) # lists_eq(item1, item2)
... | python | def lists_eq(list1, list2):
""" recursive """
if len(list1) != len(list2):
return False
for count, (item1, item2) in enumerate(zip(list1, list2)):
if isinstance(item1, np.ndarray) or isinstance(item2, np.ndarray):
failed = not np.all(item1 == item2) # lists_eq(item1, item2)
... | [
"def",
"lists_eq",
"(",
"list1",
",",
"list2",
")",
":",
"if",
"len",
"(",
"list1",
")",
"!=",
"len",
"(",
"list2",
")",
":",
"return",
"False",
"for",
"count",
",",
"(",
"item1",
",",
"item2",
")",
"in",
"enumerate",
"(",
"zip",
"(",
"list1",
",... | recursive | [
"recursive"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_assert.py#L131-L142 | train | recursive function to compare lists |
Erotemic/utool | utool/util_assert.py | assert_inbounds | def assert_inbounds(num, low, high, msg='', eq=False, verbose=not util_arg.QUIET):
r"""
Args:
num (scalar):
low (scalar):
high (scalar):
msg (str):
"""
from utool import util_str
if util_arg.NO_ASSERTS:
return
passed = util_alg.inbounds(num, low, high, eq=... | python | def assert_inbounds(num, low, high, msg='', eq=False, verbose=not util_arg.QUIET):
r"""
Args:
num (scalar):
low (scalar):
high (scalar):
msg (str):
"""
from utool import util_str
if util_arg.NO_ASSERTS:
return
passed = util_alg.inbounds(num, low, high, eq=... | [
"def",
"assert_inbounds",
"(",
"num",
",",
"low",
",",
"high",
",",
"msg",
"=",
"''",
",",
"eq",
"=",
"False",
",",
"verbose",
"=",
"not",
"util_arg",
".",
"QUIET",
")",
":",
"from",
"utool",
"import",
"util_str",
"if",
"util_arg",
".",
"NO_ASSERTS",
... | r"""
Args:
num (scalar):
low (scalar):
high (scalar):
msg (str): | [
"r",
"Args",
":",
"num",
"(",
"scalar",
")",
":",
"low",
"(",
"scalar",
")",
":",
"high",
"(",
"scalar",
")",
":",
"msg",
"(",
"str",
")",
":"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_assert.py#L184-L210 | train | r Asserts that num is within the given low and high bounds. |
Erotemic/utool | utool/util_assert.py | assert_almost_eq | def assert_almost_eq(arr_test, arr_target, thresh=1E-11):
r"""
Args:
arr_test (ndarray or list):
arr_target (ndarray or list):
thresh (scalar or ndarray or list):
"""
if util_arg.NO_ASSERTS:
return
import utool as ut
arr1 = np.array(arr_test)
arr2 = np.array(a... | python | def assert_almost_eq(arr_test, arr_target, thresh=1E-11):
r"""
Args:
arr_test (ndarray or list):
arr_target (ndarray or list):
thresh (scalar or ndarray or list):
"""
if util_arg.NO_ASSERTS:
return
import utool as ut
arr1 = np.array(arr_test)
arr2 = np.array(a... | [
"def",
"assert_almost_eq",
"(",
"arr_test",
",",
"arr_target",
",",
"thresh",
"=",
"1E-11",
")",
":",
"if",
"util_arg",
".",
"NO_ASSERTS",
":",
"return",
"import",
"utool",
"as",
"ut",
"arr1",
"=",
"np",
".",
"array",
"(",
"arr_test",
")",
"arr2",
"=",
... | r"""
Args:
arr_test (ndarray or list):
arr_target (ndarray or list):
thresh (scalar or ndarray or list): | [
"r",
"Args",
":",
"arr_test",
"(",
"ndarray",
"or",
"list",
")",
":",
"arr_target",
"(",
"ndarray",
"or",
"list",
")",
":",
"thresh",
"(",
"scalar",
"or",
"ndarray",
"or",
"list",
")",
":"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_assert.py#L213-L241 | train | r Tests if two arrays are equal. |
Erotemic/utool | utool/util_assert.py | assert_lessthan | def assert_lessthan(arr_test, arr_max, msg=''):
r"""
Args:
arr_test (ndarray or list):
arr_target (ndarray or list):
thresh (scalar or ndarray or list):
"""
if util_arg.NO_ASSERTS:
return
arr1 = np.array(arr_test)
arr2 = np.array(arr_max)
error = arr_max - arr... | python | def assert_lessthan(arr_test, arr_max, msg=''):
r"""
Args:
arr_test (ndarray or list):
arr_target (ndarray or list):
thresh (scalar or ndarray or list):
"""
if util_arg.NO_ASSERTS:
return
arr1 = np.array(arr_test)
arr2 = np.array(arr_max)
error = arr_max - arr... | [
"def",
"assert_lessthan",
"(",
"arr_test",
",",
"arr_max",
",",
"msg",
"=",
"''",
")",
":",
"if",
"util_arg",
".",
"NO_ASSERTS",
":",
"return",
"arr1",
"=",
"np",
".",
"array",
"(",
"arr_test",
")",
"arr2",
"=",
"np",
".",
"array",
"(",
"arr_max",
")... | r"""
Args:
arr_test (ndarray or list):
arr_target (ndarray or list):
thresh (scalar or ndarray or list): | [
"r",
"Args",
":",
"arr_test",
"(",
"ndarray",
"or",
"list",
")",
":",
"arr_target",
"(",
"ndarray",
"or",
"list",
")",
":",
"thresh",
"(",
"scalar",
"or",
"ndarray",
"or",
"list",
")",
":"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_assert.py#L244-L273 | train | r Tests that arr_test < arr_max and raises AssertionError if not. |
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 | Invoke the callback with a command - object for each connection. |
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 | Helper that writes a file if - w is given on command line otherwise it just prints it out. |
Erotemic/utool | utool/util_autogen.py | makeinit | def makeinit(mod_dpath, exclude_modnames=[], use_star=False):
r"""
Args:
mod_dpath (str):
exclude_modnames (list): (Defaults to [])
use_star (bool): (Defaults to False)
Returns:
str: init_codeblock
CommandLine:
python -m utool.util_autogen makeinit --modname=ibe... | python | def makeinit(mod_dpath, exclude_modnames=[], use_star=False):
r"""
Args:
mod_dpath (str):
exclude_modnames (list): (Defaults to [])
use_star (bool): (Defaults to False)
Returns:
str: init_codeblock
CommandLine:
python -m utool.util_autogen makeinit --modname=ibe... | [
"def",
"makeinit",
"(",
"mod_dpath",
",",
"exclude_modnames",
"=",
"[",
"]",
",",
"use_star",
"=",
"False",
")",
":",
"from",
"utool",
".",
"_internal",
"import",
"util_importer",
"import",
"utool",
"as",
"ut",
"module_name",
"=",
"ut",
".",
"get_modname_fro... | r"""
Args:
mod_dpath (str):
exclude_modnames (list): (Defaults to [])
use_star (bool): (Defaults to False)
Returns:
str: init_codeblock
CommandLine:
python -m utool.util_autogen makeinit --modname=ibeis.algo
Example:
>>> # DISABLE_DOCTEST
>>> # ... | [
"r",
"Args",
":",
"mod_dpath",
"(",
"str",
")",
":",
"exclude_modnames",
"(",
"list",
")",
":",
"(",
"Defaults",
"to",
"[]",
")",
"use_star",
"(",
"bool",
")",
":",
"(",
"Defaults",
"to",
"False",
")"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_autogen.py#L72-L160 | train | r This function creates a new version of the current language of the current language. |
Erotemic/utool | utool/util_autogen.py | write_modscript_alias | def write_modscript_alias(fpath, modname, args='', pyscript='python'):
"""
convinience function because $@ is annoying to paste into the terminal
"""
import utool as ut
from os.path import splitext
allargs_dict = {
'.sh': ' $@',
'.bat': ' %1', }
_, script_ext = splitext(fpath... | python | def write_modscript_alias(fpath, modname, args='', pyscript='python'):
"""
convinience function because $@ is annoying to paste into the terminal
"""
import utool as ut
from os.path import splitext
allargs_dict = {
'.sh': ' $@',
'.bat': ' %1', }
_, script_ext = splitext(fpath... | [
"def",
"write_modscript_alias",
"(",
"fpath",
",",
"modname",
",",
"args",
"=",
"''",
",",
"pyscript",
"=",
"'python'",
")",
":",
"import",
"utool",
"as",
"ut",
"from",
"os",
".",
"path",
"import",
"splitext",
"allargs_dict",
"=",
"{",
"'.sh'",
":",
"' $... | convinience function because $@ is annoying to paste into the terminal | [
"convinience",
"function",
"because",
"$"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_autogen.py#L163-L183 | train | write a modscript alias to a file |
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",
")",
":",
"# FIXME idk how to remove the blank line following the function with",
"# a... | 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 | r Autofixes a codeblock. |
Erotemic/utool | utool/util_autogen.py | load_func_from_module | def load_func_from_module(modname, funcname, verbose=True, moddir=None, modpath=None):
r"""
Args:
modname (str): module name
funcname (str): function name
verbose (bool): verbosity flag(Defaults to True)
moddir (None): (Defaults to None)
CommandLine:
python -m uto... | python | def load_func_from_module(modname, funcname, verbose=True, moddir=None, modpath=None):
r"""
Args:
modname (str): module name
funcname (str): function name
verbose (bool): verbosity flag(Defaults to True)
moddir (None): (Defaults to None)
CommandLine:
python -m uto... | [
"def",
"load_func_from_module",
"(",
"modname",
",",
"funcname",
",",
"verbose",
"=",
"True",
",",
"moddir",
"=",
"None",
",",
"modpath",
"=",
"None",
")",
":",
"import",
"utool",
"as",
"ut",
"from",
"os",
".",
"path",
"import",
"join",
"import",
"imp",
... | r"""
Args:
modname (str): module name
funcname (str): function name
verbose (bool): verbosity flag(Defaults to True)
moddir (None): (Defaults to None)
CommandLine:
python -m utool.util_autogen load_func_from_module
Example:
>>> # DISABLE_DOCTEST
>... | [
"r",
"Args",
":",
"modname",
"(",
"str",
")",
":",
"module",
"name",
"funcname",
"(",
"str",
")",
":",
"function",
"name",
"verbose",
"(",
"bool",
")",
":",
"verbosity",
"flag",
"(",
"Defaults",
"to",
"True",
")",
"moddir",
"(",
"None",
")",
":",
"... | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_autogen.py#L226-L393 | train | r Loads a function from a module |
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",
")",
":",
"#import utool as ut",
"func",
",",
"module",
",",
"error_str",
"=",
"load_fun... | 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 | r Automatically generates a string of filename and modnames for a single object. |
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",
"=",
"[",
"]",
")",
":",
"import",
"utool",
"as",
"ut",
"if",
"ismethod",
... | 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 | r Creates the argument docstring for the current object |
Erotemic/utool | utool/util_autogen.py | make_example_docstr | def make_example_docstr(funcname=None, modname=None, argname_list=None,
defaults=None, return_type=None, return_name=None,
ismethod=False):
"""
Creates skeleton code to build an example doctest
Args:
funcname (str): function name
modname (str... | python | def make_example_docstr(funcname=None, modname=None, argname_list=None,
defaults=None, return_type=None, return_name=None,
ismethod=False):
"""
Creates skeleton code to build an example doctest
Args:
funcname (str): function name
modname (str... | [
"def",
"make_example_docstr",
"(",
"funcname",
"=",
"None",
",",
"modname",
"=",
"None",
",",
"argname_list",
"=",
"None",
",",
"defaults",
"=",
"None",
",",
"return_type",
"=",
"None",
",",
"return_name",
"=",
"None",
",",
"ismethod",
"=",
"False",
")",
... | Creates skeleton code to build an example doctest
Args:
funcname (str): function name
modname (str): module name
argname_list (str): list of argument names
defaults (None):
return_type (None):
return_name (str): return variable name
ismethod (bool):
... | [
"Creates",
"skeleton",
"code",
"to",
"build",
"an",
"example",
"doctest"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_autogen.py#L542-L732 | train | This function creates an example doctest for the current object. |
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",
")",
":",
"im... | 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 | r Creates a sensible default docstr for a live python function |
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",
")",
":",
"flags",
"=",
"re",
".",
"MULTILINE",
"|",
"re",
".",
"DOTALL",
"code_text_",
"=",
"code_text",
"code_text_",
"=",
"re",
".",
"sub",
"(",
"r'^ *# *REM [^\\n]*$\\n?'",
",",
"''",
",",
"code... | 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 | r Removes template comments vim sentinals and vim sentinals from the code_text. |
glormph/msstitch | src/app/actions/mzidtsv/proteingroup_sorters.py | sort_protein_groups | def sort_protein_groups(pgroups, evidence):
"""Gets a protein groups containing dict pgroups, for each master (key)
there is a list of protein tuples that comprise a proteingroup. This loops
the groups and returns a sorted group. Assumes master is already sorted
as the proper master"""
sortfnxs = ge... | python | def sort_protein_groups(pgroups, evidence):
"""Gets a protein groups containing dict pgroups, for each master (key)
there is a list of protein tuples that comprise a proteingroup. This loops
the groups and returns a sorted group. Assumes master is already sorted
as the proper master"""
sortfnxs = ge... | [
"def",
"sort_protein_groups",
"(",
"pgroups",
",",
"evidence",
")",
":",
"sortfnxs",
"=",
"get_sortfnxs",
"(",
"evidence",
")",
"pgroups_out",
"=",
"{",
"}",
"for",
"master",
",",
"pgroup",
"in",
"pgroups",
".",
"items",
"(",
")",
":",
"sorted_pg",
"=",
... | Gets a protein groups containing dict pgroups, for each master (key)
there is a list of protein tuples that comprise a proteingroup. This loops
the groups and returns a sorted group. Assumes master is already sorted
as the proper master | [
"Gets",
"a",
"protein",
"groups",
"containing",
"dict",
"pgroups",
"for",
"each",
"master",
"(",
"key",
")",
"there",
"is",
"a",
"list",
"of",
"protein",
"tuples",
"that",
"comprise",
"a",
"proteingroup",
".",
"This",
"loops",
"the",
"groups",
"and",
"retu... | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/mzidtsv/proteingroup_sorters.py#L22-L32 | train | Returns a dict pgroups containing dict pgroups for each master in the dict pgroups that comprise a proteins group. |
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 | Recursive function that sorts a protein group by a number of sorting
functions. |
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 | Generic function for sorting peptides and psms. Assumes a higher
number is better for what is passed at sort_index position in protein. |
glormph/msstitch | src/app/actions/pycolator/reassign.py | lookup_statistic | def lookup_statistic(score, stats):
""" Finds statistics that correspond to PSM/peptide/protein feature's
score. Loops through list of qvality generated scores until it finds
values closest to the feature's svm_score."""
if score in stats:
return stats[score]['q'], stats[score]['PEP'], None
... | python | def lookup_statistic(score, stats):
""" Finds statistics that correspond to PSM/peptide/protein feature's
score. Loops through list of qvality generated scores until it finds
values closest to the feature's svm_score."""
if score in stats:
return stats[score]['q'], stats[score]['PEP'], None
... | [
"def",
"lookup_statistic",
"(",
"score",
",",
"stats",
")",
":",
"if",
"score",
"in",
"stats",
":",
"return",
"stats",
"[",
"score",
"]",
"[",
"'q'",
"]",
",",
"stats",
"[",
"score",
"]",
"[",
"'PEP'",
"]",
",",
"None",
"else",
":",
"lower",
",",
... | Finds statistics that correspond to PSM/peptide/protein feature's
score. Loops through list of qvality generated scores until it finds
values closest to the feature's svm_score. | [
"Finds",
"statistics",
"that",
"correspond",
"to",
"PSM",
"/",
"peptide",
"/",
"protein",
"feature",
"s",
"score",
".",
"Loops",
"through",
"list",
"of",
"qvality",
"generated",
"scores",
"until",
"it",
"finds",
"values",
"closest",
"to",
"the",
"feature",
"... | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/pycolator/reassign.py#L34-L56 | train | Finds statistics that correspond to PSM / peptide feature s
score. Loops through list of qvality generated scores until it finds a score that is greater than the score. Returns None if no statistics are found. |
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 | Free the map. |
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 | Append an array to the end of the map. |
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 | Slice the map from start and end. |
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 | Concat a map. |
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 | Get a copy of the map buffer |
chriso/gauged | gauged/structures/sparse_map.py | SparseMap.percentile | def percentile(self, percentile):
"""Get a percentile of all floats in the map. Since the sorting is
done in-place, the map is no longer safe to use after calling this
or median()"""
percentile = float(percentile)
if percentile != percentile or percentile < 0 or percentile > 100:... | python | def percentile(self, percentile):
"""Get a percentile of all floats in the map. Since the sorting is
done in-place, the map is no longer safe to use after calling this
or median()"""
percentile = float(percentile)
if percentile != percentile or percentile < 0 or percentile > 100:... | [
"def",
"percentile",
"(",
"self",
",",
"percentile",
")",
":",
"percentile",
"=",
"float",
"(",
"percentile",
")",
"if",
"percentile",
"!=",
"percentile",
"or",
"percentile",
"<",
"0",
"or",
"percentile",
">",
"100",
":",
"raise",
"ValueError",
"(",
"'Expe... | Get a percentile of all floats in the map. Since the sorting is
done in-place, the map is no longer safe to use after calling this
or median() | [
"Get",
"a",
"percentile",
"of",
"all",
"floats",
"in",
"the",
"map",
".",
"Since",
"the",
"sorting",
"is",
"done",
"in",
"-",
"place",
"the",
"map",
"is",
"no",
"longer",
"safe",
"to",
"use",
"after",
"calling",
"this",
"or",
"median",
"()"
] | cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976 | https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/structures/sparse_map.py#L148-L158 | train | Get a percentile of all floats in the map. |
chriso/gauged | gauged/structures/sparse_map.py | SparseMap.iteritems | def iteritems(self):
"""Get a generator which yields (offset, array)"""
current_buf = self.ptr.contents.buffer
length = self.ptr.contents.length
seen_length = 0
header = c_size_t()
position = c_uint32()
arraylength = c_size_t()
arrayptr = FloatPtr()
... | python | def iteritems(self):
"""Get a generator which yields (offset, array)"""
current_buf = self.ptr.contents.buffer
length = self.ptr.contents.length
seen_length = 0
header = c_size_t()
position = c_uint32()
arraylength = c_size_t()
arrayptr = FloatPtr()
... | [
"def",
"iteritems",
"(",
"self",
")",
":",
"current_buf",
"=",
"self",
".",
"ptr",
".",
"contents",
".",
"buffer",
"length",
"=",
"self",
".",
"ptr",
".",
"contents",
".",
"length",
"seen_length",
"=",
"0",
"header",
"=",
"c_size_t",
"(",
")",
"positio... | Get a generator which yields (offset, array) | [
"Get",
"a",
"generator",
"which",
"yields",
"(",
"offset",
"array",
")"
] | cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976 | https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/structures/sparse_map.py#L168-L188 | train | Get a generator which yields ( offset array ) |
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",
")",
":",
"# It must match all the non-empty entries.",
"for",
"t",
",",
"e",
"in",
"itertools",
".",
"zip_longest",
"(",
"target",
",",
"entry",
")",
":",
"if",
"e",
"and",
"t",
"!=",
"e",
":",
"return",
"F... | 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 | Does the target match the whitelist entry? |
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 | Throws an exception if the entry isn t on the whitelist. |
MoseleyBioinformaticsLab/ctfile | ctfile/api.py | read_file | def read_file(path, verbose=False):
"""Read single ``CTfile`` formatted file.
:param str path: Path to ``CTfile``.
:return: Subclass of :class:`~ctfile.ctfile.CTfile`.
:rtype: :class:`~ctfile.ctfile.CTfile`
"""
for filehandle in filehandles(path, verbose=verbose):
return CTfile.loa... | python | def read_file(path, verbose=False):
"""Read single ``CTfile`` formatted file.
:param str path: Path to ``CTfile``.
:return: Subclass of :class:`~ctfile.ctfile.CTfile`.
:rtype: :class:`~ctfile.ctfile.CTfile`
"""
for filehandle in filehandles(path, verbose=verbose):
return CTfile.loa... | [
"def",
"read_file",
"(",
"path",
",",
"verbose",
"=",
"False",
")",
":",
"for",
"filehandle",
"in",
"filehandles",
"(",
"path",
",",
"verbose",
"=",
"verbose",
")",
":",
"return",
"CTfile",
".",
"load",
"(",
"filehandle",
")"
] | Read single ``CTfile`` formatted file.
:param str path: Path to ``CTfile``.
:return: Subclass of :class:`~ctfile.ctfile.CTfile`.
:rtype: :class:`~ctfile.ctfile.CTfile` | [
"Read",
"single",
"CTfile",
"formatted",
"file",
".",
":",
"param",
"str",
"path",
":",
"Path",
"to",
"CTfile",
".",
":",
"return",
":",
"Subclass",
"of",
":",
"class",
":",
"~ctfile",
".",
"ctfile",
".",
"CTfile",
".",
":",
"rtype",
":",
":",
"class... | eae864126cd9102207df5d363a3222256a0f1396 | https://github.com/MoseleyBioinformaticsLab/ctfile/blob/eae864126cd9102207df5d363a3222256a0f1396/ctfile/api.py#L24-L32 | train | Read CTfile formatted file. |
MoseleyBioinformaticsLab/ctfile | ctfile/api.py | read_files | def read_files(path, verbose=True):
"""Read multiple ``CTfile`` formatted files.
:param str path: Path to ``CTfile``.
:return: Subclass of :class:`~ctfile.ctfile.CTfile`.
:rtype: :class:`~ctfile.ctfile.CTfile`
"""
for filehandle in filehandles(path, verbose=verbose):
yield CTfile.l... | python | def read_files(path, verbose=True):
"""Read multiple ``CTfile`` formatted files.
:param str path: Path to ``CTfile``.
:return: Subclass of :class:`~ctfile.ctfile.CTfile`.
:rtype: :class:`~ctfile.ctfile.CTfile`
"""
for filehandle in filehandles(path, verbose=verbose):
yield CTfile.l... | [
"def",
"read_files",
"(",
"path",
",",
"verbose",
"=",
"True",
")",
":",
"for",
"filehandle",
"in",
"filehandles",
"(",
"path",
",",
"verbose",
"=",
"verbose",
")",
":",
"yield",
"CTfile",
".",
"load",
"(",
"filehandle",
")"
] | Read multiple ``CTfile`` formatted files.
:param str path: Path to ``CTfile``.
:return: Subclass of :class:`~ctfile.ctfile.CTfile`.
:rtype: :class:`~ctfile.ctfile.CTfile` | [
"Read",
"multiple",
"CTfile",
"formatted",
"files",
".",
":",
"param",
"str",
"path",
":",
"Path",
"to",
"CTfile",
".",
":",
"return",
":",
"Subclass",
"of",
":",
"class",
":",
"~ctfile",
".",
"ctfile",
".",
"CTfile",
".",
":",
"rtype",
":",
":",
"cl... | eae864126cd9102207df5d363a3222256a0f1396 | https://github.com/MoseleyBioinformaticsLab/ctfile/blob/eae864126cd9102207df5d363a3222256a0f1396/ctfile/api.py#L35-L43 | train | Read multiple CTfile formatted files. |
trendels/gevent_inotifyx | gevent_inotifyx/__init__.py | get_events | def get_events(fd, timeout=None):
"""get_events(fd[, timeout])
Return a list of InotifyEvent instances representing events read from
inotify. If timeout is None, this will block forever until at least one
event can be read. Otherwise, timeout should be an integer or float
specifying a timeout in ... | python | def get_events(fd, timeout=None):
"""get_events(fd[, timeout])
Return a list of InotifyEvent instances representing events read from
inotify. If timeout is None, this will block forever until at least one
event can be read. Otherwise, timeout should be an integer or float
specifying a timeout in ... | [
"def",
"get_events",
"(",
"fd",
",",
"timeout",
"=",
"None",
")",
":",
"(",
"rlist",
",",
"_",
",",
"_",
")",
"=",
"select",
"(",
"[",
"fd",
"]",
",",
"[",
"]",
",",
"[",
"]",
",",
"timeout",
")",
"if",
"not",
"rlist",
":",
"return",
"[",
"... | get_events(fd[, timeout])
Return a list of InotifyEvent instances representing events read from
inotify. If timeout is None, this will block forever until at least one
event can be read. Otherwise, timeout should be an integer or float
specifying a timeout in seconds. If get_events times out waiting... | [
"get_events",
"(",
"fd",
"[",
"timeout",
"]",
")"
] | b1e531616d150e86b13aeca450a61c66f9bbc855 | https://github.com/trendels/gevent_inotifyx/blob/b1e531616d150e86b13aeca450a61c66f9bbc855/gevent_inotifyx/__init__.py#L43-L78 | train | Get events from a file descriptor. |
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 | Load an uncached version of a
Taxonomy from a file or URL. |
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",
")",
":",
"import",
"utool",
"as",
"ut",
"# For each group, build mapping from each item to the members the group",
"item_to_others1",
"=",
"{",
"item",
":",
"set",
"(",
"_group",
")",
"-",
"{",
"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 | r Finds the differences between two groups of items in a single node. |
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",
")",
":",
"group1_list",
"=",
"{",
"tuple",
"(",
"sorted",
"(",
"_group",
")",
")",
"for",
"_group",
"in",
"groups1",
"}",
"group2_list",
"=",
"{",
"tuple",
"(",
"sorted",
"(",
"_group",
... | 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 | r Finds the common group consistency between two groups |
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",
")",
":",
"import",
"utool",
"as",
"ut",
"true",
"=",
"{",
"frozenset",
"(",
"_group",
")",
"for",
"_group",
"in",
"true_groups",
"}",
"pred",
"=",
"{",
"frozenset",
"(",
"_group",
")",
"fo... | 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 | r Compare two true_groups and pred_groups. |
Erotemic/utool | utool/util_alg.py | grouping_delta | def grouping_delta(old, new, pure=True):
r"""
Finds what happened to the old groups to form the new groups.
Args:
old (set of frozensets): old grouping
new (set of frozensets): new grouping
pure (bool): hybrids are separated from pure merges and splits if
pure is True, o... | python | def grouping_delta(old, new, pure=True):
r"""
Finds what happened to the old groups to form the new groups.
Args:
old (set of frozensets): old grouping
new (set of frozensets): new grouping
pure (bool): hybrids are separated from pure merges and splits if
pure is True, o... | [
"def",
"grouping_delta",
"(",
"old",
",",
"new",
",",
"pure",
"=",
"True",
")",
":",
"import",
"utool",
"as",
"ut",
"_old",
"=",
"{",
"frozenset",
"(",
"_group",
")",
"for",
"_group",
"in",
"old",
"}",
"_new",
"=",
"{",
"frozenset",
"(",
"_group",
... | r"""
Finds what happened to the old groups to form the new groups.
Args:
old (set of frozensets): old grouping
new (set of frozensets): new grouping
pure (bool): hybrids are separated from pure merges and splits if
pure is True, otherwise hybrid cases are grouped in merges a... | [
"r",
"Finds",
"what",
"happened",
"to",
"the",
"old",
"groups",
"to",
"form",
"the",
"new",
"groups",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L237-L437 | train | r Returns a dictionary of changes that are made to the new groups and the merged ones. |
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 | Returns statistics about grouping changes between two sets of items |
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 | This function returns the upper diagnoal of cartesian product of self and self. |
Erotemic/utool | utool/util_alg.py | diagonalized_iter | def diagonalized_iter(size):
r"""
TODO: generalize to more than 2 dimensions to be more like
itertools.product.
CommandLine:
python -m utool.util_alg --exec-diagonalized_iter
python -m utool.util_alg --exec-diagonalized_iter --size=5
Example:
>>> # ENABLE_DOCTEST
>>... | python | def diagonalized_iter(size):
r"""
TODO: generalize to more than 2 dimensions to be more like
itertools.product.
CommandLine:
python -m utool.util_alg --exec-diagonalized_iter
python -m utool.util_alg --exec-diagonalized_iter --size=5
Example:
>>> # ENABLE_DOCTEST
>>... | [
"def",
"diagonalized_iter",
"(",
"size",
")",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"size",
"+",
"1",
")",
":",
"for",
"r",
",",
"c",
"in",
"zip",
"(",
"reversed",
"(",
"range",
"(",
"i",
")",
")",
",",
"(",
"range",
"(",
"i",
")",
... | r"""
TODO: generalize to more than 2 dimensions to be more like
itertools.product.
CommandLine:
python -m utool.util_alg --exec-diagonalized_iter
python -m utool.util_alg --exec-diagonalized_iter --size=5
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * #... | [
"r",
"TODO",
":",
"generalize",
"to",
"more",
"than",
"2",
"dimensions",
"to",
"be",
"more",
"like",
"itertools",
".",
"product",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L514-L544 | train | r Returns an iterator over the elements of the current language tree. |
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 | product of list1 and list2 where items are non equal |
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 | Greedy algorithm for maximum independent set cover |
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",
")",
":",
"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 | r Greedy algorithm for various covering problems. |
Erotemic/utool | utool/util_alg.py | setcover_ilp | def setcover_ilp(candidate_sets_dict, items=None, set_weights=None, item_values=None, max_weight=None, verbose=False):
"""
Set cover / Weighted Maximum Cover exact algorithm
https://en.wikipedia.org/wiki/Maximum_coverage_problem
"""
import utool as ut
import pulp
if items is None:
i... | python | def setcover_ilp(candidate_sets_dict, items=None, set_weights=None, item_values=None, max_weight=None, verbose=False):
"""
Set cover / Weighted Maximum Cover exact algorithm
https://en.wikipedia.org/wiki/Maximum_coverage_problem
"""
import utool as ut
import pulp
if items is None:
i... | [
"def",
"setcover_ilp",
"(",
"candidate_sets_dict",
",",
"items",
"=",
"None",
",",
"set_weights",
"=",
"None",
",",
"item_values",
"=",
"None",
",",
"max_weight",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"import",
"utool",
"as",
"ut",
"import",... | Set cover / Weighted Maximum Cover exact algorithm
https://en.wikipedia.org/wiki/Maximum_coverage_problem | [
"Set",
"cover",
"/",
"Weighted",
"Maximum",
"Cover",
"exact",
"algorithm"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L755-L843 | train | Set cover exact algorithm for the set covering problem |
Erotemic/utool | utool/util_alg.py | xywh_to_tlbr | def xywh_to_tlbr(bbox, img_wh):
""" converts xywh format to (tlx, tly, blx, bly) """
(img_w, img_h) = img_wh
if img_w == 0 or img_h == 0:
img_w = 1
img_h = 1
msg = '[cc2.1] Your csv tables have an invalid ANNOTATION.'
print(msg)
#warnings.warn(msg)
#ht = 1
... | python | def xywh_to_tlbr(bbox, img_wh):
""" converts xywh format to (tlx, tly, blx, bly) """
(img_w, img_h) = img_wh
if img_w == 0 or img_h == 0:
img_w = 1
img_h = 1
msg = '[cc2.1] Your csv tables have an invalid ANNOTATION.'
print(msg)
#warnings.warn(msg)
#ht = 1
... | [
"def",
"xywh_to_tlbr",
"(",
"bbox",
",",
"img_wh",
")",
":",
"(",
"img_w",
",",
"img_h",
")",
"=",
"img_wh",
"if",
"img_w",
"==",
"0",
"or",
"img_h",
"==",
"0",
":",
"img_w",
"=",
"1",
"img_h",
"=",
"1",
"msg",
"=",
"'[cc2.1] Your csv tables have an in... | converts xywh format to (tlx, tly, blx, bly) | [
"converts",
"xywh",
"format",
"to",
"(",
"tlx",
"tly",
"blx",
"bly",
")"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L881-L898 | train | converts xywh format to tlbr format |
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",
"=",
"{",
"}",
"# Insert each item into the correct group",
"for",
"item",
"in",
"list_",
":",
"if",
"item",
"not",
"in",
"dict_hist",
":",
"dict_hist",
"[",
"item",
"]",
"=",
"0",
"dict_hist",
"[",
... | 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 | counts the number of times each item appears in the dictionary |
Erotemic/utool | utool/util_alg.py | fibonacci_iterative | def fibonacci_iterative(n):
"""
Args:
n (int):
Returns:
int: the n-th fibonacci number
References:
http://stackoverflow.com/questions/15047116/iterative-alg-fib
CommandLine:
python -m utool.util_alg fibonacci_iterative
Example:
>>> # ENABLE_DOCTEST
... | python | def fibonacci_iterative(n):
"""
Args:
n (int):
Returns:
int: the n-th fibonacci number
References:
http://stackoverflow.com/questions/15047116/iterative-alg-fib
CommandLine:
python -m utool.util_alg fibonacci_iterative
Example:
>>> # ENABLE_DOCTEST
... | [
"def",
"fibonacci_iterative",
"(",
"n",
")",
":",
"a",
",",
"b",
"=",
"0",
",",
"1",
"for",
"_",
"in",
"range",
"(",
"0",
",",
"n",
")",
":",
"a",
",",
"b",
"=",
"b",
",",
"a",
"+",
"b",
"return",
"a"
] | Args:
n (int):
Returns:
int: the n-th fibonacci number
References:
http://stackoverflow.com/questions/15047116/iterative-alg-fib
CommandLine:
python -m utool.util_alg fibonacci_iterative
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * #... | [
"Args",
":",
"n",
"(",
"int",
")",
":"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L985-L1012 | train | This function is iterative version of fibonacci_iterative. |
Erotemic/utool | utool/util_alg.py | fibonacci_approx | def fibonacci_approx(n):
r"""
approximate value (due to numerical errors) of fib(n) using closed form
expression
Args:
n (int):
Returns:
int: the n-th fib number
CommandLine:
python -m utool.util_alg fibonacci_approx
Example:
>>> # DISABLE_DOCTEST
... | python | def fibonacci_approx(n):
r"""
approximate value (due to numerical errors) of fib(n) using closed form
expression
Args:
n (int):
Returns:
int: the n-th fib number
CommandLine:
python -m utool.util_alg fibonacci_approx
Example:
>>> # DISABLE_DOCTEST
... | [
"def",
"fibonacci_approx",
"(",
"n",
")",
":",
"sqrt_5",
"=",
"math",
".",
"sqrt",
"(",
"5",
")",
"phi",
"=",
"(",
"1",
"+",
"sqrt_5",
")",
"/",
"2",
"return",
"(",
"(",
"phi",
"**",
"n",
")",
"-",
"(",
"-",
"phi",
")",
"**",
"(",
"-",
"n",... | r"""
approximate value (due to numerical errors) of fib(n) using closed form
expression
Args:
n (int):
Returns:
int: the n-th fib number
CommandLine:
python -m utool.util_alg fibonacci_approx
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_alg impor... | [
"r",
"approximate",
"value",
"(",
"due",
"to",
"numerical",
"errors",
")",
"of",
"fib",
"(",
"n",
")",
"using",
"closed",
"form",
"expression"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L1015-L1039 | train | r Returns approximate value of n using closed form
expression |
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 | find nth prime for small test |
Erotemic/utool | utool/util_alg.py | get_nth_prime_bruteforce | def get_nth_prime_bruteforce(n, start_guess=2, start_num_primes=0):
"""
Args:
n (int): the n-th prime (n=2000 takes about a second)
CommandLine:
python -m utool.util_alg get_nth_prime_bruteforce --show
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_alg import * # N... | python | def get_nth_prime_bruteforce(n, start_guess=2, start_num_primes=0):
"""
Args:
n (int): the n-th prime (n=2000 takes about a second)
CommandLine:
python -m utool.util_alg get_nth_prime_bruteforce --show
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_alg import * # N... | [
"def",
"get_nth_prime_bruteforce",
"(",
"n",
",",
"start_guess",
"=",
"2",
",",
"start_num_primes",
"=",
"0",
")",
":",
"guess",
"=",
"start_guess",
"num_primes_found",
"=",
"start_num_primes",
"while",
"True",
":",
"if",
"is_prime",
"(",
"guess",
")",
":",
... | Args:
n (int): the n-th prime (n=2000 takes about a second)
CommandLine:
python -m utool.util_alg get_nth_prime_bruteforce --show
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> import utool as ut
>>> n_list = []
>>> time_list... | [
"Args",
":",
"n",
"(",
"int",
")",
":",
"the",
"n",
"-",
"th",
"prime",
"(",
"n",
"=",
"2000",
"takes",
"about",
"a",
"second",
")"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L1073-L1106 | train | Get the nth prime of a set of n - th ones |
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'",
")",
":",
"if",
"method",
"==",
"'recursive'",
":",
"return",
"knapsack_recursive",
"(",
"items",
",",
"maxweight",
")",
"elif",
"method",
"==",
"'iterative'",
":",
"return... | 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 | r Solve the knapsack problem by finding the most valuable subsequence of items subject that weighs no more than maxweight. |
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",
"# Given Input",
"values",
"=",
"[",
"t",
"[",
"0",
"]",
"for",
"t",
"in",
"items",
"]",
"weights",
"=",
"[",
"t",
"[",
"1",
"]",
"for"... | 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 | This function solves a knapsack using an integer linear program |
Erotemic/utool | utool/util_alg.py | number_of_decimals | def number_of_decimals(num):
r"""
Args:
num (float):
References:
stackoverflow.com/questions/6189956/finding-decimal-places
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> num = 15.05
>>> result = number_of_decimals(num)
... | python | def number_of_decimals(num):
r"""
Args:
num (float):
References:
stackoverflow.com/questions/6189956/finding-decimal-places
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> num = 15.05
>>> result = number_of_decimals(num)
... | [
"def",
"number_of_decimals",
"(",
"num",
")",
":",
"exp",
"=",
"decimal",
".",
"Decimal",
"(",
"str",
"(",
"num",
")",
")",
".",
"as_tuple",
"(",
")",
".",
"exponent",
"return",
"max",
"(",
"0",
",",
"-",
"exp",
")"
] | r"""
Args:
num (float):
References:
stackoverflow.com/questions/6189956/finding-decimal-places
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> num = 15.05
>>> result = number_of_decimals(num)
>>> print(result)
2 | [
"r",
"Args",
":",
"num",
"(",
"float",
")",
":"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L1365-L1382 | train | r Returns the number of decimals |
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",
")",
":",
"# Knapsack requires integral weights",
"weights",
"=",
"[",
"t",
"[",
"1",
"]",
"for",
"t",
"in",
"items",
"]",
"max_exp",
"=",
"max",
"(",
"[",
"number_of_decimals",
"(",
"w_",
")",
"... | 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 | Iterative version of knapsack_iterative. |
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",
")",
":",
"values",
"=",
"[",
"t",
"[",
"0",
"]",
"for",
"t",
"in",
"items",
"]",
"weights",
"=",
"[",
"t",
"[",
"1",
"]",
"for",
"t",
"in",
"items",
"]",
"maxsize",
"=",
"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 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 | r Return the iteration of the knapsack method for the given items and maxweight. |
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",
")",
":",
"#import numpy as np",
"items",
"=",
"np",
".",
"array",
"(",
"items",
")",
"weights",
"=",
"items",
".",
"T",
"[",
"1",
"]",
"# Find maximum decimal place (this problem is in NP)",
"max_... | 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 | Iterative knapsack method for iteration over knapsack items in numpy format |
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",
")",
":",
"items_subset",
"=",
"[",
"]",
"total_weight",
"=",
"0",
"total_value",
"=",
"0",
"for",
"item",
"in",
"items",
":",
"value",
",",
"weight",
"=",
"item",
"[",
"0",
":",
"2",
"]",
"if... | 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 | r Greedy version of knapsack algorithm
does not sort input by largest value
first if desired. |
Erotemic/utool | utool/util_alg.py | cumsum | def cumsum(item_list, initial=0):
""" python cumsum
Args:
item_list (list): list of numbers or items supporting addition
initial (value): initial zero value
Returns:
list: list of accumulated values
References:
stackoverflow.com/questions/9258602/elegant-pythonic-cumsu... | python | def cumsum(item_list, initial=0):
""" python cumsum
Args:
item_list (list): list of numbers or items supporting addition
initial (value): initial zero value
Returns:
list: list of accumulated values
References:
stackoverflow.com/questions/9258602/elegant-pythonic-cumsu... | [
"def",
"cumsum",
"(",
"item_list",
",",
"initial",
"=",
"0",
")",
":",
"def",
"accum",
"(",
"acc",
",",
"itm",
")",
":",
"return",
"op",
".",
"iadd",
"(",
"acc",
",",
"[",
"acc",
"[",
"-",
"1",
"]",
"+",
"itm",
"]",
")",
"return",
"reduce",
"... | python cumsum
Args:
item_list (list): list of numbers or items supporting addition
initial (value): initial zero value
Returns:
list: list of accumulated values
References:
stackoverflow.com/questions/9258602/elegant-pythonic-cumsum
CommandLine:
python -m utoo... | [
"python",
"cumsum"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L1613-L1646 | train | Python wrapper for the cumsum function |
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 | N choose k binomial combinations without replacement |
Erotemic/utool | utool/util_alg.py | maximin_distance_subset1d | def maximin_distance_subset1d(items, K=None, min_thresh=None, verbose=False):
r"""
Greedy algorithm, may be exact for 1d case.
First, choose the first item, then choose the next item that is farthest
away from all previously chosen items. Iterate.
CommandLine:
python -m utool.util_alg --exe... | python | def maximin_distance_subset1d(items, K=None, min_thresh=None, verbose=False):
r"""
Greedy algorithm, may be exact for 1d case.
First, choose the first item, then choose the next item that is farthest
away from all previously chosen items. Iterate.
CommandLine:
python -m utool.util_alg --exe... | [
"def",
"maximin_distance_subset1d",
"(",
"items",
",",
"K",
"=",
"None",
",",
"min_thresh",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"False",
":",
"import",
"pulp",
"# Formulate integer program",
"prob",
"=",
"pulp",
".",
"LpProblem",
"(",
... | r"""
Greedy algorithm, may be exact for 1d case.
First, choose the first item, then choose the next item that is farthest
away from all previously chosen items. Iterate.
CommandLine:
python -m utool.util_alg --exec-maximin_distance_subset1d
Notes:
Given a set of items V.
Le... | [
"r",
"Greedy",
"algorithm",
"may",
"be",
"exact",
"for",
"1d",
"case",
".",
"First",
"choose",
"the",
"first",
"item",
"then",
"choose",
"the",
"next",
"item",
"that",
"is",
"farthest",
"away",
"from",
"all",
"previously",
"chosen",
"items",
".",
"Iterate"... | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L1678-L1823 | train | r Return the maximum distance between items in a set of items in a set of items. |
Erotemic/utool | utool/util_alg.py | maximum_distance_subset | def maximum_distance_subset(items, K, verbose=False):
"""
FIXME: I believe this does not work.
Returns a subset of size K from items with the maximum pairwise distance
References:
stackoverflow.com/questions/12278528/subset-elements-furthest-apart-eachother
stackoverflow.com/questions/... | python | def maximum_distance_subset(items, K, verbose=False):
"""
FIXME: I believe this does not work.
Returns a subset of size K from items with the maximum pairwise distance
References:
stackoverflow.com/questions/12278528/subset-elements-furthest-apart-eachother
stackoverflow.com/questions/... | [
"def",
"maximum_distance_subset",
"(",
"items",
",",
"K",
",",
"verbose",
"=",
"False",
")",
":",
"from",
"utool",
"import",
"util_decor",
"if",
"verbose",
":",
"print",
"(",
"'maximum_distance_subset len(items)=%r, K=%r'",
"%",
"(",
"len",
"(",
"items",
")",
... | FIXME: I believe this does not work.
Returns a subset of size K from items with the maximum pairwise distance
References:
stackoverflow.com/questions/12278528/subset-elements-furthest-apart-eachother
stackoverflow.com/questions/13079563/condensed-distance-matrix-pdist
Recurance:
L... | [
"FIXME",
":",
"I",
"believe",
"this",
"does",
"not",
"work",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L1826-L1940 | train | Returns a subset of items with the maximum pairwise distance matrix. |
Erotemic/utool | utool/util_alg.py | inbounds | def inbounds(num, low, high, eq=False):
r"""
Args:
num (scalar or ndarray):
low (scalar or ndarray):
high (scalar or ndarray):
eq (bool):
Returns:
scalar or ndarray: is_inbounds
CommandLine:
python -m utool.util_alg --test-inbounds
Example:
... | python | def inbounds(num, low, high, eq=False):
r"""
Args:
num (scalar or ndarray):
low (scalar or ndarray):
high (scalar or ndarray):
eq (bool):
Returns:
scalar or ndarray: is_inbounds
CommandLine:
python -m utool.util_alg --test-inbounds
Example:
... | [
"def",
"inbounds",
"(",
"num",
",",
"low",
",",
"high",
",",
"eq",
"=",
"False",
")",
":",
"less",
"=",
"op",
".",
"le",
"if",
"eq",
"else",
"op",
".",
"lt",
"greater",
"=",
"op",
".",
"ge",
"if",
"eq",
"else",
"op",
".",
"gt",
"and_",
"=",
... | r"""
Args:
num (scalar or ndarray):
low (scalar or ndarray):
high (scalar or ndarray):
eq (bool):
Returns:
scalar or ndarray: is_inbounds
CommandLine:
python -m utool.util_alg --test-inbounds
Example:
>>> # DISABLE_DOCTEST
>>> from utool... | [
"r",
"Args",
":",
"num",
"(",
"scalar",
"or",
"ndarray",
")",
":",
"low",
"(",
"scalar",
"or",
"ndarray",
")",
":",
"high",
"(",
"scalar",
"or",
"ndarray",
")",
":",
"eq",
"(",
"bool",
")",
":"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L1963-L1999 | train | r Tests if a single entry in the cache is in bounds. |
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 | checks if floating point numbers are equal to a threshold |
Erotemic/utool | utool/util_alg.py | safe_pdist | def safe_pdist(arr, *args, **kwargs):
"""
Kwargs:
metric = ut.absdiff
SeeAlso:
scipy.spatial.distance.pdist
TODO: move to vtool
"""
if arr is None or len(arr) < 2:
return None
else:
import vtool as vt
arr_ = vt.atleast_nd(arr, 2)
return spdis... | python | def safe_pdist(arr, *args, **kwargs):
"""
Kwargs:
metric = ut.absdiff
SeeAlso:
scipy.spatial.distance.pdist
TODO: move to vtool
"""
if arr is None or len(arr) < 2:
return None
else:
import vtool as vt
arr_ = vt.atleast_nd(arr, 2)
return spdis... | [
"def",
"safe_pdist",
"(",
"arr",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"arr",
"is",
"None",
"or",
"len",
"(",
"arr",
")",
"<",
"2",
":",
"return",
"None",
"else",
":",
"import",
"vtool",
"as",
"vt",
"arr_",
"=",
"vt",
".",
... | Kwargs:
metric = ut.absdiff
SeeAlso:
scipy.spatial.distance.pdist
TODO: move to vtool | [
"Kwargs",
":",
"metric",
"=",
"ut",
".",
"absdiff",
"SeeAlso",
":",
"scipy",
".",
"spatial",
".",
"distance",
".",
"pdist"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L2049-L2064 | train | safe version of pdist |
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 | This function normalizes a numpy array from 0 to 1 based in its extent |
Erotemic/utool | utool/util_alg.py | max_size_max_distance_subset | def max_size_max_distance_subset(items, min_thresh=0, Kstart=2, verbose=False):
r"""
Args:
items (?):
min_thresh (int): (default = 0)
Kstart (int): (default = 2)
Returns:
?: prev_subset_idx
CommandLine:
python -m utool.util_alg --exec-max_size_max_distance_subse... | python | def max_size_max_distance_subset(items, min_thresh=0, Kstart=2, verbose=False):
r"""
Args:
items (?):
min_thresh (int): (default = 0)
Kstart (int): (default = 2)
Returns:
?: prev_subset_idx
CommandLine:
python -m utool.util_alg --exec-max_size_max_distance_subse... | [
"def",
"max_size_max_distance_subset",
"(",
"items",
",",
"min_thresh",
"=",
"0",
",",
"Kstart",
"=",
"2",
",",
"verbose",
"=",
"False",
")",
":",
"import",
"utool",
"as",
"ut",
"assert",
"Kstart",
">=",
"2",
",",
"'must start with group of size 2'",
"best_idx... | r"""
Args:
items (?):
min_thresh (int): (default = 0)
Kstart (int): (default = 2)
Returns:
?: prev_subset_idx
CommandLine:
python -m utool.util_alg --exec-max_size_max_distance_subset
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_alg import... | [
"r",
"Args",
":",
"items",
"(",
"?",
")",
":",
"min_thresh",
"(",
"int",
")",
":",
"(",
"default",
"=",
"0",
")",
"Kstart",
"(",
"int",
")",
":",
"(",
"default",
"=",
"2",
")"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L2118-L2159 | train | r Returns the index of the best entry in the items list that is within a given threshold |
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",
")",
"# Sort by groupid for cache efficiency",
... | 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 | Returns a list of tuples with the keys and groupxs of each item in groupid_list |
Erotemic/utool | utool/util_alg.py | ungroup | def ungroup(grouped_items, groupxs, maxval=None, fill=None):
"""
Ungroups items
Args:
grouped_items (list):
groupxs (list):
maxval (int): (default = None)
Returns:
list: ungrouped_items
SeeAlso:
vt.invert_apply_grouping
CommandLine:
python -m u... | python | def ungroup(grouped_items, groupxs, maxval=None, fill=None):
"""
Ungroups items
Args:
grouped_items (list):
groupxs (list):
maxval (int): (default = None)
Returns:
list: ungrouped_items
SeeAlso:
vt.invert_apply_grouping
CommandLine:
python -m u... | [
"def",
"ungroup",
"(",
"grouped_items",
",",
"groupxs",
",",
"maxval",
"=",
"None",
",",
"fill",
"=",
"None",
")",
":",
"if",
"maxval",
"is",
"None",
":",
"# Determine the number of items if unknown",
"maxpergroup",
"=",
"[",
"max",
"(",
"xs",
")",
"if",
"... | Ungroups items
Args:
grouped_items (list):
groupxs (list):
maxval (int): (default = None)
Returns:
list: ungrouped_items
SeeAlso:
vt.invert_apply_grouping
CommandLine:
python -m utool.util_alg ungroup_unique
Example:
>>> # ENABLE_DOCTEST
... | [
"Ungroups",
"items"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L2263-L2303 | train | Ungroups items in a list of items by the given groupxs. |
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",
"# Determine the number of items if unknown",
"#maxpergroup = [max(xs) if len(xs) else 0 for xs in groupxs]",
"#maxval = max(maxpergroup) if len(maxpergr... | 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 | Ungroups items returning a generator. |
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 | Ungroups unique items to correspond to original non - unique list
|
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 | Edit distance algorithm. |
Erotemic/utool | utool/util_alg.py | get_nth_bell_number | def get_nth_bell_number(n):
"""
Returns the (num_items - 1)-th Bell number using recursion.
The Bell numbers count the number of partitions of a set.
Args:
n (int): number of items in a set
Returns:
int:
References:
http://adorio-research.org/wordpress/?p=11460
Co... | python | def get_nth_bell_number(n):
"""
Returns the (num_items - 1)-th Bell number using recursion.
The Bell numbers count the number of partitions of a set.
Args:
n (int): number of items in a set
Returns:
int:
References:
http://adorio-research.org/wordpress/?p=11460
Co... | [
"def",
"get_nth_bell_number",
"(",
"n",
")",
":",
"import",
"utool",
"as",
"ut",
"import",
"scipy",
".",
"special",
"@",
"ut",
".",
"memoize",
"def",
"bell_",
"(",
"n",
")",
":",
"if",
"n",
"<",
"2",
":",
"return",
"1",
"sum_",
"=",
"0",
"for",
"... | Returns the (num_items - 1)-th Bell number using recursion.
The Bell numbers count the number of partitions of a set.
Args:
n (int): number of items in a set
Returns:
int:
References:
http://adorio-research.org/wordpress/?p=11460
CommandLine:
python -m utool.util_... | [
"Returns",
"the",
"(",
"num_items",
"-",
"1",
")",
"-",
"th",
"Bell",
"number",
"using",
"recursion",
".",
"The",
"Bell",
"numbers",
"count",
"the",
"number",
"of",
"partitions",
"of",
"a",
"set",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L2502-L2538 | train | Returns the nth Bell number using recursion. |
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",
")",
":",
"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 | r Standardizes a boolean expression into an or - ing of and - ed variables |
Erotemic/utool | utool/util_alg.py | solve_boolexpr | def solve_boolexpr():
"""
sudo pip install git+https://github.com/tpircher/quine-mccluskey.git
sudo pip uninstall quine_mccluskey
pip uninstall quine_mccluskey
pip install git+https://github.com/tpircher/quine-mccluskey.git
Args:
varnames (?):
Returns:
?:
CommandLine... | python | def solve_boolexpr():
"""
sudo pip install git+https://github.com/tpircher/quine-mccluskey.git
sudo pip uninstall quine_mccluskey
pip uninstall quine_mccluskey
pip install git+https://github.com/tpircher/quine-mccluskey.git
Args:
varnames (?):
Returns:
?:
CommandLine... | [
"def",
"solve_boolexpr",
"(",
")",
":",
"#false_cases = [",
"# int('111', 2),",
"# int('011', 2),",
"# int('001', 2),",
"#]",
"#true_cases = list(set(range(2 ** 3)) - set(false_cases))",
"varnames",
"=",
"[",
"'sa'",
",",
"'said'",
",",
"'aid'",
"]",
"#import utool a... | sudo pip install git+https://github.com/tpircher/quine-mccluskey.git
sudo pip uninstall quine_mccluskey
pip uninstall quine_mccluskey
pip install git+https://github.com/tpircher/quine-mccluskey.git
Args:
varnames (?):
Returns:
?:
CommandLine:
python -m utool.util_alg... | [
"sudo",
"pip",
"install",
"git",
"+",
"https",
":",
"//",
"github",
".",
"com",
"/",
"tpircher",
"/",
"quine",
"-",
"mccluskey",
".",
"git",
"sudo",
"pip",
"uninstall",
"quine_mccluskey",
"pip",
"uninstall",
"quine_mccluskey"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L2632-L2728 | train | Solve the non - empty tree of the current node and return the tree of the tree of the tree that is not empty |
Erotemic/utool | utool/util_alg.py | longest_common_substring | def longest_common_substring(s1, s2):
"""
References:
# https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_substring#Python2
"""
m = [[0] * (1 + len(s2)) for i in range(1 + len(s1))]
longest, x_longest = 0, 0
for x in range(1, 1 + len(s1)):
for y in ran... | python | def longest_common_substring(s1, s2):
"""
References:
# https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_substring#Python2
"""
m = [[0] * (1 + len(s2)) for i in range(1 + len(s1))]
longest, x_longest = 0, 0
for x in range(1, 1 + len(s1)):
for y in ran... | [
"def",
"longest_common_substring",
"(",
"s1",
",",
"s2",
")",
":",
"m",
"=",
"[",
"[",
"0",
"]",
"*",
"(",
"1",
"+",
"len",
"(",
"s2",
")",
")",
"for",
"i",
"in",
"range",
"(",
"1",
"+",
"len",
"(",
"s1",
")",
")",
"]",
"longest",
",",
"x_l... | References:
# https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_substring#Python2 | [
"References",
":",
"#",
"https",
":",
"//",
"en",
".",
"wikibooks",
".",
"org",
"/",
"wiki",
"/",
"Algorithm_Implementation",
"/",
"Strings",
"/",
"Longest_common_substring#Python2"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L2731-L2747 | train | Return the longest common substring of two strings. |
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",
")",
":",
"import",
"utool",
"as",
"ut",
"#time_list = []",
"for",
"x",
"in",
"range",
"(",
"0",
",",
"num",
")",
":",
"with",
"ut",
".",
"Timer",
"(",
"verbose",
"=",
"False",
")",
"as",
"t",
"... | 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 | r A function that takes some time and returns a new set of expensive task terms. |
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 | Computes all the integer factors of the number n |
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 | Create a map with all master proteins with data and outputs protein data dicts for rows of a tsv. |
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 | Parses protein data for a certain protein into tsv output
dictionary |
moluwole/Bast | bast/validator/validator.py | validator.run | def run(cls, return_results=False):
""" Iterates through all associated Fields and applies all attached Rules. Depending on 'return_collated_results',
this method will either return True (all rules successful), False (all, or some, rules failed)
or a dictionary list
containing the collat... | python | def run(cls, return_results=False):
""" Iterates through all associated Fields and applies all attached Rules. Depending on 'return_collated_results',
this method will either return True (all rules successful), False (all, or some, rules failed)
or a dictionary list
containing the collat... | [
"def",
"run",
"(",
"cls",
",",
"return_results",
"=",
"False",
")",
":",
"cls",
".",
"result",
"=",
"[",
"]",
"passed",
"=",
"True",
"for",
"field",
"in",
"cls",
".",
"fields",
":",
"result",
",",
"errors",
"=",
"field",
".",
"run",
"(",
")",
"re... | Iterates through all associated Fields and applies all attached Rules. Depending on 'return_collated_results',
this method will either return True (all rules successful), False (all, or some, rules failed)
or a dictionary list
containing the collated results of all Field Rules.
Keyword a... | [
"Iterates",
"through",
"all",
"associated",
"Fields",
"and",
"applies",
"all",
"attached",
"Rules",
".",
"Depending",
"on",
"return_collated_results",
"this",
"method",
"will",
"either",
"return",
"True",
"(",
"all",
"rules",
"successful",
")",
"False",
"(",
"al... | eecf55ae72e6f24af7c101549be0422cd2c1c95a | https://github.com/moluwole/Bast/blob/eecf55ae72e6f24af7c101549be0422cd2c1c95a/bast/validator/validator.py#L101-L132 | train | Runs all associated Fields and applies all attached Rules. Returns a dictionary list containing the collated results of all attached Fields. |
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 | Get keys from a namespace |
chriso/gauged | gauged/drivers/postgresql.py | PostgreSQLDriver.lookup_ids | def lookup_ids(self, keys):
"""Lookup the integer ID associated with each (namespace, key) in the
keys list"""
keys_len = len(keys)
ids = {namespace_key: None for namespace_key in keys}
start = 0
bulk_insert = self.bulk_insert
query = 'SELECT namespace, key, id FR... | python | def lookup_ids(self, keys):
"""Lookup the integer ID associated with each (namespace, key) in the
keys list"""
keys_len = len(keys)
ids = {namespace_key: None for namespace_key in keys}
start = 0
bulk_insert = self.bulk_insert
query = 'SELECT namespace, key, id FR... | [
"def",
"lookup_ids",
"(",
"self",
",",
"keys",
")",
":",
"keys_len",
"=",
"len",
"(",
"keys",
")",
"ids",
"=",
"{",
"namespace_key",
":",
"None",
"for",
"namespace_key",
"in",
"keys",
"}",
"start",
"=",
"0",
"bulk_insert",
"=",
"self",
".",
"bulk_inser... | Lookup the integer ID associated with each (namespace, key) in the
keys list | [
"Lookup",
"the",
"integer",
"ID",
"associated",
"with",
"each",
"(",
"namespace",
"key",
")",
"in",
"the",
"keys",
"list"
] | cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976 | https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/drivers/postgresql.py#L42-L61 | train | Lookup the integer ID associated with each namespace key in the the
keys list |
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 | Get the block identified by namespace offset key and
value |
chriso/gauged | gauged/drivers/postgresql.py | PostgreSQLDriver.insert_or_append_blocks | def insert_or_append_blocks(self, blocks):
"""Insert multiple blocks. If a block already exists, the data is
appended. blocks must be a list of tuples where each tuple consists
of (namespace, offset, key, data)"""
binary = self.psycopg2.Binary
execute = self.cursor.execute
... | python | def insert_or_append_blocks(self, blocks):
"""Insert multiple blocks. If a block already exists, the data is
appended. blocks must be a list of tuples where each tuple consists
of (namespace, offset, key, data)"""
binary = self.psycopg2.Binary
execute = self.cursor.execute
... | [
"def",
"insert_or_append_blocks",
"(",
"self",
",",
"blocks",
")",
":",
"binary",
"=",
"self",
".",
"psycopg2",
".",
"Binary",
"execute",
"=",
"self",
".",
"cursor",
".",
"execute",
"query",
"=",
"'UPDATE gauged_data SET data = data || %s, flags = %s '",
"'WHERE nam... | Insert multiple blocks. If a block already exists, the data is
appended. blocks must be a list of tuples where each tuple consists
of (namespace, offset, key, data) | [
"Insert",
"multiple",
"blocks",
".",
"If",
"a",
"block",
"already",
"exists",
"the",
"data",
"is",
"appended",
".",
"blocks",
"must",
"be",
"a",
"list",
"of",
"tuples",
"where",
"each",
"tuple",
"consists",
"of",
"(",
"namespace",
"offset",
"key",
"data",
... | cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976 | https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/drivers/postgresql.py#L111-L126 | train | Insert multiple blocks. If a block already exists the data is
appended. |
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 | Get the minimum and maximum block offset for the specified
namespace |
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 | Insert a timestamp to keep track of the current writer position |
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 | Add cached values for the specified date range and query |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.