repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
tanghaibao/goatools
goatools/cli/compare_gos.py
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/compare_gos.py#L153-L157
def _wr_ver_n_key(self, fout_txt, verbose): """Write GO DAG version and key indicating presence of GO ID in a list.""" with open(fout_txt, 'w') as prt: self._prt_ver_n_key(prt, verbose) print(' WROTE: {TXT}'.format(TXT=fout_txt))
[ "def", "_wr_ver_n_key", "(", "self", ",", "fout_txt", ",", "verbose", ")", ":", "with", "open", "(", "fout_txt", ",", "'w'", ")", "as", "prt", ":", "self", ".", "_prt_ver_n_key", "(", "prt", ",", "verbose", ")", "print", "(", "' WROTE: {TXT}'...
Write GO DAG version and key indicating presence of GO ID in a list.
[ "Write", "GO", "DAG", "version", "and", "key", "indicating", "presence", "of", "GO", "ID", "in", "a", "list", "." ]
python
train
zero-os/0-core
client/py-client/zeroos/core0/client/client.py
https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L442-L464
def open(self, file, mode='r', perm=0o0644): """ Opens a file on the node :param file: file path to open :param mode: open mode :param perm: file permission in octet form mode: 'r' read only 'w' write only (truncate) '+' read/write ...
[ "def", "open", "(", "self", ",", "file", ",", "mode", "=", "'r'", ",", "perm", "=", "0o0644", ")", ":", "args", "=", "{", "'file'", ":", "file", ",", "'mode'", ":", "mode", ",", "'perm'", ":", "perm", ",", "}", "return", "self", ".", "_client", ...
Opens a file on the node :param file: file path to open :param mode: open mode :param perm: file permission in octet form mode: 'r' read only 'w' write only (truncate) '+' read/write 'x' create if not exist 'a' append :return: a...
[ "Opens", "a", "file", "on", "the", "node" ]
python
train
cdeboever3/cdpybio
cdpybio/analysis.py
https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/analysis.py#L131-L149
def make_grasp_phenotype_file(fn, pheno, out): """ Subset the GRASP database on a specific phenotype. Parameters ---------- fn : str Path to GRASP database file. pheno : str Phenotype to extract from database. out : sttr Path to output file for subset of GRASP ...
[ "def", "make_grasp_phenotype_file", "(", "fn", ",", "pheno", ",", "out", ")", ":", "import", "subprocess", "c", "=", "'awk -F \"\\\\t\" \\'NR == 1 || $12 == \"{}\" \\' {} > {}'", ".", "format", "(", "pheno", ".", "replace", "(", "\"'\"", ",", "'\\\\x27'", ")", ","...
Subset the GRASP database on a specific phenotype. Parameters ---------- fn : str Path to GRASP database file. pheno : str Phenotype to extract from database. out : sttr Path to output file for subset of GRASP database.
[ "Subset", "the", "GRASP", "database", "on", "a", "specific", "phenotype", ".", "Parameters", "----------", "fn", ":", "str", "Path", "to", "GRASP", "database", "file", "." ]
python
train
creare-com/pydem
pydem/dem_processing.py
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L2269-L2279
def _plot_connectivity(self, A, data=None, lims=[None, None]): """ A debug function used to plot the adjacency/connectivity matrix. This is really just a light wrapper around _plot_connectivity_helper """ if data is None: data = self.data B = A.tocoo() ...
[ "def", "_plot_connectivity", "(", "self", ",", "A", ",", "data", "=", "None", ",", "lims", "=", "[", "None", ",", "None", "]", ")", ":", "if", "data", "is", "None", ":", "data", "=", "self", ".", "data", "B", "=", "A", ".", "tocoo", "(", ")", ...
A debug function used to plot the adjacency/connectivity matrix. This is really just a light wrapper around _plot_connectivity_helper
[ "A", "debug", "function", "used", "to", "plot", "the", "adjacency", "/", "connectivity", "matrix", ".", "This", "is", "really", "just", "a", "light", "wrapper", "around", "_plot_connectivity_helper" ]
python
train
kevinconway/daemons
daemons/message/gevent.py
https://github.com/kevinconway/daemons/blob/b0fe0db5821171a35aa9078596d19d630c570b38/daemons/message/gevent.py#L18-L21
def pool(self): """Get an gevent pool used to dispatch requests.""" self._pool = self._pool or gevent.pool.Pool(size=self.pool_size) return self._pool
[ "def", "pool", "(", "self", ")", ":", "self", ".", "_pool", "=", "self", ".", "_pool", "or", "gevent", ".", "pool", ".", "Pool", "(", "size", "=", "self", ".", "pool_size", ")", "return", "self", ".", "_pool" ]
Get an gevent pool used to dispatch requests.
[ "Get", "an", "gevent", "pool", "used", "to", "dispatch", "requests", "." ]
python
train
bskinn/opan
opan/xyz.py
https://github.com/bskinn/opan/blob/0b1b21662df6abc971407a9386db21a8796fbfe5/opan/xyz.py#L1104-L1288
def dihed_single(self, g_num, at_1, at_2, at_3, at_4): """ Dihedral/out-of-plane angle among four atoms. Returns the out-of-plane angle among four atoms from geometry `g_num`, in degrees. The reference plane is spanned by `at_1`, `at_2` and `at_3`. The out-of-plane angle is def...
[ "def", "dihed_single", "(", "self", ",", "g_num", ",", "at_1", ",", "at_2", ",", "at_3", ",", "at_4", ")", ":", "# library imports", "import", "numpy", "as", "np", "from", "scipy", "import", "linalg", "as", "spla", "from", ".", "utils", ".", "vector", ...
Dihedral/out-of-plane angle among four atoms. Returns the out-of-plane angle among four atoms from geometry `g_num`, in degrees. The reference plane is spanned by `at_1`, `at_2` and `at_3`. The out-of-plane angle is defined such that a positive angle represents a counter-clockwise ...
[ "Dihedral", "/", "out", "-", "of", "-", "plane", "angle", "among", "four", "atoms", "." ]
python
train
pycontribs/pyrax
pyrax/autoscale.py
https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/autoscale.py#L706-L716
def update_webhook_metadata(self, scaling_group, policy, webhook, metadata): """ Adds the given metadata dict to the existing metadata for the specified webhook. """ if not isinstance(webhook, AutoScaleWebhook): webhook = self.get_webhook(scaling_group, policy, webhoo...
[ "def", "update_webhook_metadata", "(", "self", ",", "scaling_group", ",", "policy", ",", "webhook", ",", "metadata", ")", ":", "if", "not", "isinstance", "(", "webhook", ",", "AutoScaleWebhook", ")", ":", "webhook", "=", "self", ".", "get_webhook", "(", "sca...
Adds the given metadata dict to the existing metadata for the specified webhook.
[ "Adds", "the", "given", "metadata", "dict", "to", "the", "existing", "metadata", "for", "the", "specified", "webhook", "." ]
python
train
flavio/scsgate
scsgate/monitor/__init__.py
https://github.com/flavio/scsgate/blob/aad1d181eef4714ab475f4ff7fcfac4a6425fbb4/scsgate/monitor/__init__.py#L134-L142
def _home_assistant_config(self): """ Creates home assistant configuration for the known devices """ devices = {} for scs_id, dev in self._devices.items(): devices[dev['ha_id']] = { 'name': dev['name'], 'scs_id': scs_id} return {'devices': dev...
[ "def", "_home_assistant_config", "(", "self", ")", ":", "devices", "=", "{", "}", "for", "scs_id", ",", "dev", "in", "self", ".", "_devices", ".", "items", "(", ")", ":", "devices", "[", "dev", "[", "'ha_id'", "]", "]", "=", "{", "'name'", ":", "de...
Creates home assistant configuration for the known devices
[ "Creates", "home", "assistant", "configuration", "for", "the", "known", "devices" ]
python
train
nvbn/thefuck
thefuck/rules/ln_s_order.py
https://github.com/nvbn/thefuck/blob/40ab4eb62db57627bff10cf029d29c94704086a2/thefuck/rules/ln_s_order.py#L5-L9
def _get_destination(script_parts): """When arguments order is wrong first argument will be destination.""" for part in script_parts: if part not in {'ln', '-s', '--symbolic'} and os.path.exists(part): return part
[ "def", "_get_destination", "(", "script_parts", ")", ":", "for", "part", "in", "script_parts", ":", "if", "part", "not", "in", "{", "'ln'", ",", "'-s'", ",", "'--symbolic'", "}", "and", "os", ".", "path", ".", "exists", "(", "part", ")", ":", "return",...
When arguments order is wrong first argument will be destination.
[ "When", "arguments", "order", "is", "wrong", "first", "argument", "will", "be", "destination", "." ]
python
train
yinkaisheng/Python-UIAutomation-for-Windows
uiautomation/uiautomation.py
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2816-L2842
def ColorfullyWrite(log: str, consoleColor: int = -1, writeToFile: bool = True, printToStdout: bool = True, logFile: str = None) -> None: """ log: str. consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`. writeToFile: bool. printToStdout: bool. ...
[ "def", "ColorfullyWrite", "(", "log", ":", "str", ",", "consoleColor", ":", "int", "=", "-", "1", ",", "writeToFile", ":", "bool", "=", "True", ",", "printToStdout", ":", "bool", "=", "True", ",", "logFile", ":", "str", "=", "None", ")", "->", "None"...
log: str. consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`. writeToFile: bool. printToStdout: bool. logFile: str, log file path. ColorfullyWrite('Hello <Color=Green>Green</Color> !!!'), color name must be in Logger.ColorNames.
[ "log", ":", "str", ".", "consoleColor", ":", "int", "a", "value", "in", "class", "ConsoleColor", "such", "as", "ConsoleColor", ".", "DarkGreen", ".", "writeToFile", ":", "bool", ".", "printToStdout", ":", "bool", ".", "logFile", ":", "str", "log", "file", ...
python
valid
bitesofcode/projexui
projexui/widgets/xlineedit.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xlineedit.py#L110-L118
def adjustText(self): """ Updates the text based on the current format options. """ pos = self.cursorPosition() self.blockSignals(True) super(XLineEdit, self).setText(self.formatText(self.text())) self.setCursorPosition(pos) self.blockSignals(False)
[ "def", "adjustText", "(", "self", ")", ":", "pos", "=", "self", ".", "cursorPosition", "(", ")", "self", ".", "blockSignals", "(", "True", ")", "super", "(", "XLineEdit", ",", "self", ")", ".", "setText", "(", "self", ".", "formatText", "(", "self", ...
Updates the text based on the current format options.
[ "Updates", "the", "text", "based", "on", "the", "current", "format", "options", "." ]
python
train
jcassee/django-geckoboard
django_geckoboard/decorators.py
https://github.com/jcassee/django-geckoboard/blob/6ebdaa86015fe645360abf1ba1290132de4cf6d6/django_geckoboard/decorators.py#L463-L479
def _render(request, data, encrypted, format=None): """ Render the data to Geckoboard. If the `format` parameter is passed to the widget it defines the output format. Otherwise the output format is based on the `format` request parameter. A `format` paramater of ``json`` or ``2`` renders JSON outpu...
[ "def", "_render", "(", "request", ",", "data", ",", "encrypted", ",", "format", "=", "None", ")", ":", "if", "not", "format", ":", "format", "=", "request", ".", "POST", ".", "get", "(", "'format'", ",", "''", ")", "if", "not", "format", ":", "form...
Render the data to Geckoboard. If the `format` parameter is passed to the widget it defines the output format. Otherwise the output format is based on the `format` request parameter. A `format` paramater of ``json`` or ``2`` renders JSON output, any other value renders XML.
[ "Render", "the", "data", "to", "Geckoboard", ".", "If", "the", "format", "parameter", "is", "passed", "to", "the", "widget", "it", "defines", "the", "output", "format", ".", "Otherwise", "the", "output", "format", "is", "based", "on", "the", "format", "req...
python
train
Bogdanp/dramatiq
dramatiq/composition.py
https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/composition.py#L264-L273
def wait(self, *, timeout=None): """Block until all the jobs in the group have finished or until the timeout expires. Parameters: timeout(int): The maximum amount of time, in ms, to wait. Defaults to 10 seconds. """ for _ in self.get_results(block=True, tim...
[ "def", "wait", "(", "self", ",", "*", ",", "timeout", "=", "None", ")", ":", "for", "_", "in", "self", ".", "get_results", "(", "block", "=", "True", ",", "timeout", "=", "timeout", ")", ":", "# pragma: no cover", "pass" ]
Block until all the jobs in the group have finished or until the timeout expires. Parameters: timeout(int): The maximum amount of time, in ms, to wait. Defaults to 10 seconds.
[ "Block", "until", "all", "the", "jobs", "in", "the", "group", "have", "finished", "or", "until", "the", "timeout", "expires", "." ]
python
train
GNS3/gns3-server
gns3server/compute/qemu/qemu_vm.py
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qemu_vm.py#L629-L639
def process_priority(self, process_priority): """ Sets the process priority. :param process_priority: string """ log.info('QEMU VM "{name}" [{id}] has set the process priority to {priority}'.format(name=self._name, ...
[ "def", "process_priority", "(", "self", ",", "process_priority", ")", ":", "log", ".", "info", "(", "'QEMU VM \"{name}\" [{id}] has set the process priority to {priority}'", ".", "format", "(", "name", "=", "self", ".", "_name", ",", "id", "=", "self", ".", "_id",...
Sets the process priority. :param process_priority: string
[ "Sets", "the", "process", "priority", "." ]
python
train
MacHu-GWU/superjson-project
superjson/pkg/dateutil/tz/_common.py
https://github.com/MacHu-GWU/superjson-project/blob/782ca4b2edbd4b4018b8cedee42eeae7c921b917/superjson/pkg/dateutil/tz/_common.py#L98-L112
def _validate_fromutc_inputs(f): """ The CPython version of ``fromutc`` checks that the input is a ``datetime`` object and that ``self`` is attached as its ``tzinfo``. """ @wraps(f) def fromutc(self, dt): if not isinstance(dt, datetime): raise TypeError("fromutc() requires a ...
[ "def", "_validate_fromutc_inputs", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "fromutc", "(", "self", ",", "dt", ")", ":", "if", "not", "isinstance", "(", "dt", ",", "datetime", ")", ":", "raise", "TypeError", "(", "\"fromutc() requires a da...
The CPython version of ``fromutc`` checks that the input is a ``datetime`` object and that ``self`` is attached as its ``tzinfo``.
[ "The", "CPython", "version", "of", "fromutc", "checks", "that", "the", "input", "is", "a", "datetime", "object", "and", "that", "self", "is", "attached", "as", "its", "tzinfo", "." ]
python
valid
mlperf/training
translation/tensorflow/transformer/model/beam_search.py
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/model/beam_search.py#L446-L456
def _shape_list(tensor): """Return a list of the tensor's shape, and ensure no None values in list.""" # Get statically known shape (may contain None's for unknown dimensions) shape = tensor.get_shape().as_list() # Ensure that the shape values are not None dynamic_shape = tf.shape(tensor) for i in range(le...
[ "def", "_shape_list", "(", "tensor", ")", ":", "# Get statically known shape (may contain None's for unknown dimensions)", "shape", "=", "tensor", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "# Ensure that the shape values are not None", "dynamic_shape", "=", "tf"...
Return a list of the tensor's shape, and ensure no None values in list.
[ "Return", "a", "list", "of", "the", "tensor", "s", "shape", "and", "ensure", "no", "None", "values", "in", "list", "." ]
python
train
erocarrera/pefile
pefile.py
https://github.com/erocarrera/pefile/blob/8a78a2e251a3f2336c232bf411133927b479edf2/pefile.py#L5242-L5254
def get_qword_from_data(self, data, offset): """Convert eight bytes of data to a word (little endian) 'offset' is assumed to index into a word array. So setting it to N will return a dword out of the data starting at offset N*8. Returns None if the data can't be turned into a quad word...
[ "def", "get_qword_from_data", "(", "self", ",", "data", ",", "offset", ")", ":", "if", "(", "offset", "+", "1", ")", "*", "8", ">", "len", "(", "data", ")", ":", "return", "None", "return", "struct", ".", "unpack", "(", "'<Q'", ",", "data", "[", ...
Convert eight bytes of data to a word (little endian) 'offset' is assumed to index into a word array. So setting it to N will return a dword out of the data starting at offset N*8. Returns None if the data can't be turned into a quad word.
[ "Convert", "eight", "bytes", "of", "data", "to", "a", "word", "(", "little", "endian", ")" ]
python
train
nicolargo/glances
glances/plugins/glances_fs.py
https://github.com/nicolargo/glances/blob/5bd4d587a736e0d2b03170b56926841d2a3eb7ee/glances/plugins/glances_fs.py#L194-L245
def msg_curse(self, args=None, max_width=None): """Return the dict to display in the curse interface.""" # Init the return message ret = [] # Only process if stats exist and display plugin enable... if not self.stats or self.is_disable(): return ret # Max si...
[ "def", "msg_curse", "(", "self", ",", "args", "=", "None", ",", "max_width", "=", "None", ")", ":", "# Init the return message", "ret", "=", "[", "]", "# Only process if stats exist and display plugin enable...", "if", "not", "self", ".", "stats", "or", "self", ...
Return the dict to display in the curse interface.
[ "Return", "the", "dict", "to", "display", "in", "the", "curse", "interface", "." ]
python
train
Tinche/cattrs
src/cattr/converters.py
https://github.com/Tinche/cattrs/blob/481bc9bdb69b2190d699b54f331c8c5c075506d5/src/cattr/converters.py#L341-L348
def _structure_frozenset(self, obj, cl): """Convert an iterable into a potentially generic frozenset.""" if is_bare(cl) or cl.__args__[0] is Any: return frozenset(obj) else: elem_type = cl.__args__[0] dispatch = self._structure_func.dispatch return...
[ "def", "_structure_frozenset", "(", "self", ",", "obj", ",", "cl", ")", ":", "if", "is_bare", "(", "cl", ")", "or", "cl", ".", "__args__", "[", "0", "]", "is", "Any", ":", "return", "frozenset", "(", "obj", ")", "else", ":", "elem_type", "=", "cl",...
Convert an iterable into a potentially generic frozenset.
[ "Convert", "an", "iterable", "into", "a", "potentially", "generic", "frozenset", "." ]
python
train
manns/pyspread
pyspread/src/lib/vlc.py
https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/lib/vlc.py#L5588-L5603
def libvlc_video_set_key_input(p_mi, on): '''Enable or disable key press events handling, according to the LibVLC hotkeys configuration. By default and for historical reasons, keyboard events are handled by the LibVLC video widget. @note: On X11, there can be only one subscriber for key press and mouse ...
[ "def", "libvlc_video_set_key_input", "(", "p_mi", ",", "on", ")", ":", "f", "=", "_Cfunctions", ".", "get", "(", "'libvlc_video_set_key_input'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_video_set_key_input'", ",", "(", "(", "1", ",", ")", ",", "("...
Enable or disable key press events handling, according to the LibVLC hotkeys configuration. By default and for historical reasons, keyboard events are handled by the LibVLC video widget. @note: On X11, there can be only one subscriber for key press and mouse click events per window. If your application ...
[ "Enable", "or", "disable", "key", "press", "events", "handling", "according", "to", "the", "LibVLC", "hotkeys", "configuration", ".", "By", "default", "and", "for", "historical", "reasons", "keyboard", "events", "are", "handled", "by", "the", "LibVLC", "video", ...
python
train
pydata/xarray
xarray/plot/utils.py
https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/plot/utils.py#L458-L462
def _valid_other_type(x, types): """ Do all elements of x have a type from types? """ return all(any(isinstance(el, t) for t in types) for el in np.ravel(x))
[ "def", "_valid_other_type", "(", "x", ",", "types", ")", ":", "return", "all", "(", "any", "(", "isinstance", "(", "el", ",", "t", ")", "for", "t", "in", "types", ")", "for", "el", "in", "np", ".", "ravel", "(", "x", ")", ")" ]
Do all elements of x have a type from types?
[ "Do", "all", "elements", "of", "x", "have", "a", "type", "from", "types?" ]
python
train
bykof/billomapy
billomapy/billomapy.py
https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L2308-L2322
def get_comments_of_offer_per_page(self, offer_id, per_page=1000, page=1): """ Get comments of offer per page :param offer_id: the offer id :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :return: list """ ret...
[ "def", "get_comments_of_offer_per_page", "(", "self", ",", "offer_id", ",", "per_page", "=", "1000", ",", "page", "=", "1", ")", ":", "return", "self", ".", "_get_resource_per_page", "(", "resource", "=", "OFFER_COMMENTS", ",", "per_page", "=", "per_page", ","...
Get comments of offer per page :param offer_id: the offer id :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :return: list
[ "Get", "comments", "of", "offer", "per", "page" ]
python
train
llllllllll/codetransformer
codetransformer/decompiler/_343.py
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L856-L881
def _make_expr(toplevel, stack_builders): """ Override the single-dispatched make_expr with wrapper logic for handling short-circuiting expressions. """ base_expr = _make_expr_internal(toplevel, stack_builders) if not toplevel._next_target_of: return base_expr subexprs = deque([base...
[ "def", "_make_expr", "(", "toplevel", ",", "stack_builders", ")", ":", "base_expr", "=", "_make_expr_internal", "(", "toplevel", ",", "stack_builders", ")", "if", "not", "toplevel", ".", "_next_target_of", ":", "return", "base_expr", "subexprs", "=", "deque", "(...
Override the single-dispatched make_expr with wrapper logic for handling short-circuiting expressions.
[ "Override", "the", "single", "-", "dispatched", "make_expr", "with", "wrapper", "logic", "for", "handling", "short", "-", "circuiting", "expressions", "." ]
python
train
DataDog/integrations-core
marathon/datadog_checks/marathon/marathon.py
https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/marathon/datadog_checks/marathon/marathon.py#L263-L276
def ensure_queue_count( self, queued, url, timeout, auth, acs_url, ssl_verify, tags=None, label_tags=None, group=None ): """ Ensure `marathon.queue.count` is reported as zero for apps without queued instances. """ metric_name = '{}.count'.format(self.QUEUE_PREFIX) ap...
[ "def", "ensure_queue_count", "(", "self", ",", "queued", ",", "url", ",", "timeout", ",", "auth", ",", "acs_url", ",", "ssl_verify", ",", "tags", "=", "None", ",", "label_tags", "=", "None", ",", "group", "=", "None", ")", ":", "metric_name", "=", "'{}...
Ensure `marathon.queue.count` is reported as zero for apps without queued instances.
[ "Ensure", "marathon", ".", "queue", ".", "count", "is", "reported", "as", "zero", "for", "apps", "without", "queued", "instances", "." ]
python
train
bwesterb/displays
src/main.py
https://github.com/bwesterb/displays/blob/37764a3ce1be5e7b3c3bee8e4853554ed0417a82/src/main.py#L33-L54
def cmp_mode(b, a): """ A comparison function for displaymodes """ tmp = cmp(Q.CGDisplayModeIsUsableForDesktopGUI(a), Q.CGDisplayModeIsUsableForDesktopGUI(b)) if tmp != 0: return tmp tmp = cmp(our_IsUsableForDesktopGUI(a), our_IsUsableForDesktopGUI(b))...
[ "def", "cmp_mode", "(", "b", ",", "a", ")", ":", "tmp", "=", "cmp", "(", "Q", ".", "CGDisplayModeIsUsableForDesktopGUI", "(", "a", ")", ",", "Q", ".", "CGDisplayModeIsUsableForDesktopGUI", "(", "b", ")", ")", "if", "tmp", "!=", "0", ":", "return", "tmp...
A comparison function for displaymodes
[ "A", "comparison", "function", "for", "displaymodes" ]
python
train
data-8/datascience
datascience/formats.py
https://github.com/data-8/datascience/blob/4cee38266903ca169cea4a53b8cc39502d85c464/datascience/formats.py#L123-L131
def convert_value(self, value): """Convert value to float. If value is a string, ensure that the first character is the same as symbol ie. the value is in the currency this formatter is representing. """ if isinstance(value, str): assert value.startswith(self.symbol),...
[ "def", "convert_value", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "str", ")", ":", "assert", "value", ".", "startswith", "(", "self", ".", "symbol", ")", ",", "\"Currency does not start with \"", "+", "self", ".", "symbol"...
Convert value to float. If value is a string, ensure that the first character is the same as symbol ie. the value is in the currency this formatter is representing.
[ "Convert", "value", "to", "float", ".", "If", "value", "is", "a", "string", "ensure", "that", "the", "first", "character", "is", "the", "same", "as", "symbol", "ie", ".", "the", "value", "is", "in", "the", "currency", "this", "formatter", "is", "represen...
python
train
carawarner/pantheon
pantheon/pantheons.py
https://github.com/carawarner/pantheon/blob/7e8718f4397eaa389fb3d5dc04fa01c7cb556512/pantheon/pantheons.py#L62-L74
def breed(self, egg_donor, sperm_donor): """Get it on.""" offspring = [] try: num_children = npchoice([1,2], 1, p=[0.8, 0.2])[0] # 20% chance of twins for _ in range(num_children): child = God(egg_donor, sperm_donor) offspring.append(child)...
[ "def", "breed", "(", "self", ",", "egg_donor", ",", "sperm_donor", ")", ":", "offspring", "=", "[", "]", "try", ":", "num_children", "=", "npchoice", "(", "[", "1", ",", "2", "]", ",", "1", ",", "p", "=", "[", "0.8", ",", "0.2", "]", ")", "[", ...
Get it on.
[ "Get", "it", "on", "." ]
python
valid
ozak/georasters
georasters/georasters.py
https://github.com/ozak/georasters/blob/0612bd91bb2a2cb2f1d59ba89c1ff131dae27d70/georasters/georasters.py#L593-L613
def median(self, *args, **kwargs): ''' geo.median(axis=None, out=None, overwrite_input=False) axis : int, optional Axis along which the medians are computed. The default (axis=None) is to compute the median along a flattened version of the array. out : ndarray, o...
[ "def", "median", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "np", ".", "ma", ".", "median", "(", "self", ".", "raster", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
geo.median(axis=None, out=None, overwrite_input=False) axis : int, optional Axis along which the medians are computed. The default (axis=None) is to compute the median along a flattened version of the array. out : ndarray, optional Alternative output array in which t...
[ "geo", ".", "median", "(", "axis", "=", "None", "out", "=", "None", "overwrite_input", "=", "False", ")" ]
python
train
vsoch/helpme
helpme/utils/terminal.py
https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/utils/terminal.py#L91-L104
def which(software, strip_newline=True): '''get_install will return the path to where an executable is installed. ''' if software is None: software = "singularity" cmd = ['which', software ] try: result = run_command(cmd) if strip_newline is True: result['message'...
[ "def", "which", "(", "software", ",", "strip_newline", "=", "True", ")", ":", "if", "software", "is", "None", ":", "software", "=", "\"singularity\"", "cmd", "=", "[", "'which'", ",", "software", "]", "try", ":", "result", "=", "run_command", "(", "cmd",...
get_install will return the path to where an executable is installed.
[ "get_install", "will", "return", "the", "path", "to", "where", "an", "executable", "is", "installed", "." ]
python
train
zerotk/easyfs
zerotk/easyfs/_easyfs.py
https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L1849-L1881
def Md5Hex(filename=None, contents=None): ''' :param unicode filename: The file from which the md5 should be calculated. If the filename is given, the contents should NOT be given. :param unicode contents: The contents for which the md5 should be calculated. If the contents are give...
[ "def", "Md5Hex", "(", "filename", "=", "None", ",", "contents", "=", "None", ")", ":", "import", "io", "import", "hashlib", "md5", "=", "hashlib", ".", "md5", "(", ")", "if", "filename", ":", "stream", "=", "io", ".", "open", "(", "filename", ",", ...
:param unicode filename: The file from which the md5 should be calculated. If the filename is given, the contents should NOT be given. :param unicode contents: The contents for which the md5 should be calculated. If the contents are given, the filename should NOT be given. :rty...
[ ":", "param", "unicode", "filename", ":", "The", "file", "from", "which", "the", "md5", "should", "be", "calculated", ".", "If", "the", "filename", "is", "given", "the", "contents", "should", "NOT", "be", "given", "." ]
python
valid
brechtm/rinohtype
src/rinoh/document.py
https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/document.py#L457-L486
def create_outlines(self): """Create an outline in the output file that allows for easy navigation of the document. The outline is a hierarchical tree of all the sections in the document.""" sections = parent = [] current_level = 1 stack = [] fake_container = Fake...
[ "def", "create_outlines", "(", "self", ")", ":", "sections", "=", "parent", "=", "[", "]", "current_level", "=", "1", "stack", "=", "[", "]", "fake_container", "=", "FakeContainer", "(", "self", ")", "for", "section", "in", "self", ".", "_sections", ":",...
Create an outline in the output file that allows for easy navigation of the document. The outline is a hierarchical tree of all the sections in the document.
[ "Create", "an", "outline", "in", "the", "output", "file", "that", "allows", "for", "easy", "navigation", "of", "the", "document", ".", "The", "outline", "is", "a", "hierarchical", "tree", "of", "all", "the", "sections", "in", "the", "document", "." ]
python
train
quantmind/pulsar
pulsar/apps/wsgi/routers.py
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/routers.py#L591-L635
def file_response(request, filepath, block=None, status_code=None, content_type=None, encoding=None, cache_control=None): """Utility for serving a local file Typical usage:: from pulsar.apps import wsgi class MyRouter(wsgi.Router): def get(self, request): ...
[ "def", "file_response", "(", "request", ",", "filepath", ",", "block", "=", "None", ",", "status_code", "=", "None", ",", "content_type", "=", "None", ",", "encoding", "=", "None", ",", "cache_control", "=", "None", ")", ":", "file_wrapper", "=", "request"...
Utility for serving a local file Typical usage:: from pulsar.apps import wsgi class MyRouter(wsgi.Router): def get(self, request): return wsgi.file_response(request, "<filepath>") :param request: Wsgi request :param filepath: full path of file to serve :p...
[ "Utility", "for", "serving", "a", "local", "file" ]
python
train
pywavefront/PyWavefront
pywavefront/material.py
https://github.com/pywavefront/PyWavefront/blob/39ee5186cb37750d4654d19ebe43f723ecd01e2f/pywavefront/material.py#L229-L232
def parse_map_Ns(self): """Specular color map""" Kd = os.path.join(self.dir, " ".join(self.values[1:])) self.this_material.set_texture_specular_highlight(Kd)
[ "def", "parse_map_Ns", "(", "self", ")", ":", "Kd", "=", "os", ".", "path", ".", "join", "(", "self", ".", "dir", ",", "\" \"", ".", "join", "(", "self", ".", "values", "[", "1", ":", "]", ")", ")", "self", ".", "this_material", ".", "set_texture...
Specular color map
[ "Specular", "color", "map" ]
python
train
SmokinCaterpillar/pypet
pypet/storageservice.py
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/storageservice.py#L1406-L1424
def _srvc_store_several_items(self, iterable, *args, **kwargs): """Stores several items from an iterable Iterables are supposed to be of a format like `[(msg, item, args, kwarg),...]` If `args` and `kwargs` are not part of a tuple, they are taken from the current `args` and `kwargs` pro...
[ "def", "_srvc_store_several_items", "(", "self", ",", "iterable", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "input_tuple", "in", "iterable", ":", "msg", "=", "input_tuple", "[", "0", "]", "item", "=", "input_tuple", "[", "1", "]", "if...
Stores several items from an iterable Iterables are supposed to be of a format like `[(msg, item, args, kwarg),...]` If `args` and `kwargs` are not part of a tuple, they are taken from the current `args` and `kwargs` provided to this function.
[ "Stores", "several", "items", "from", "an", "iterable" ]
python
test
aio-libs/aiohttp
aiohttp/web_request.py
https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/web_request.py#L436-L444
def _http_date(_date_str: str) -> Optional[datetime.datetime]: """Process a date string, return a datetime object """ if _date_str is not None: timetuple = parsedate(_date_str) if timetuple is not None: return datetime.datetime(*timetuple[:6], ...
[ "def", "_http_date", "(", "_date_str", ":", "str", ")", "->", "Optional", "[", "datetime", ".", "datetime", "]", ":", "if", "_date_str", "is", "not", "None", ":", "timetuple", "=", "parsedate", "(", "_date_str", ")", "if", "timetuple", "is", "not", "None...
Process a date string, return a datetime object
[ "Process", "a", "date", "string", "return", "a", "datetime", "object" ]
python
train
Nic30/hwt
hwt/simulator/hdlSimulator.py
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/simulator/hdlSimulator.py#L237-L255
def _addHdlProcToRun(self, trigger: SimSignal, proc) -> None: """ Add hdl process to execution queue :param trigger: instance of SimSignal :param proc: python generator function representing HDL process """ # first process in time has to plan executing of apply values on...
[ "def", "_addHdlProcToRun", "(", "self", ",", "trigger", ":", "SimSignal", ",", "proc", ")", "->", "None", ":", "# first process in time has to plan executing of apply values on the", "# end of this time", "if", "not", "self", ".", "_applyValPlaned", ":", "# (apply on end ...
Add hdl process to execution queue :param trigger: instance of SimSignal :param proc: python generator function representing HDL process
[ "Add", "hdl", "process", "to", "execution", "queue" ]
python
test
Erotemic/ubelt
ubelt/util_hash.py
https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_hash.py#L639-L695
def _convert_hexstr_base(hexstr, base): r""" Packs a long hexstr into a shorter length string with a larger base. Args: hexstr (str): string of hexidecimal symbols to convert base (list): symbols of the conversion base Example: >>> print(_convert_hexstr_base('ffffffff', _ALPHAB...
[ "def", "_convert_hexstr_base", "(", "hexstr", ",", "base", ")", ":", "if", "base", "is", "_ALPHABET_16", ":", "# already in hex, no conversion needed", "return", "hexstr", "baselen", "=", "len", "(", "base", ")", "x", "=", "int", "(", "hexstr", ",", "16", ")...
r""" Packs a long hexstr into a shorter length string with a larger base. Args: hexstr (str): string of hexidecimal symbols to convert base (list): symbols of the conversion base Example: >>> print(_convert_hexstr_base('ffffffff', _ALPHABET_26)) nxmrlxv >>> print(_c...
[ "r", "Packs", "a", "long", "hexstr", "into", "a", "shorter", "length", "string", "with", "a", "larger", "base", "." ]
python
valid
saltstack/salt
salt/modules/state.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L1644-L1760
def sls_id(id_, mods, test=None, queue=False, **kwargs): ''' Call a single ID from the named module(s) and handle all requisites The state ID comes *before* the module ID(s) on the command line. id ID to call mods Comma-delimited list of modules to search for given id and its requ...
[ "def", "sls_id", "(", "id_", ",", "mods", ",", "test", "=", "None", ",", "queue", "=", "False", ",", "*", "*", "kwargs", ")", ":", "conflict", "=", "_check_queue", "(", "queue", ",", "kwargs", ")", "if", "conflict", "is", "not", "None", ":", "retur...
Call a single ID from the named module(s) and handle all requisites The state ID comes *before* the module ID(s) on the command line. id ID to call mods Comma-delimited list of modules to search for given id and its requisites .. versionadded:: 2014.7.0 saltenv : base Sp...
[ "Call", "a", "single", "ID", "from", "the", "named", "module", "(", "s", ")", "and", "handle", "all", "requisites" ]
python
train
scikit-learn-contrib/forest-confidence-interval
forestci/forestci.py
https://github.com/scikit-learn-contrib/forest-confidence-interval/blob/401c63a74a27d775eff0f72b6c20ffd568491fe0/forestci/forestci.py#L135-L164
def _bias_correction(V_IJ, inbag, pred_centered, n_trees): """ Helper functions that implements bias correction Parameters ---------- V_IJ : ndarray Intermediate result in the computation. inbag : ndarray The inbag matrix that fit the data. If set to `None` (default) it ...
[ "def", "_bias_correction", "(", "V_IJ", ",", "inbag", ",", "pred_centered", ",", "n_trees", ")", ":", "n_train_samples", "=", "inbag", ".", "shape", "[", "0", "]", "n_var", "=", "np", ".", "mean", "(", "np", ".", "square", "(", "inbag", "[", "0", ":"...
Helper functions that implements bias correction Parameters ---------- V_IJ : ndarray Intermediate result in the computation. inbag : ndarray The inbag matrix that fit the data. If set to `None` (default) it will be inferred from the forest. However, this only works for trees ...
[ "Helper", "functions", "that", "implements", "bias", "correction" ]
python
valid
rene-aguirre/pywinusb
examples/raw_set.py
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/examples/raw_set.py#L13-L57
def set_mute(mute_value): "Browse for mute usages and set value" all_mutes = ( \ (0x8, 0x9), # LED page (0x1, 0xA7), # desktop page (0xb, 0x2f), ) all_target_usages = [hid.get_full_usage_id(u[0], u[1]) for u in all_mutes] # usually you'll find and open the target...
[ "def", "set_mute", "(", "mute_value", ")", ":", "all_mutes", "=", "(", "(", "0x8", ",", "0x9", ")", ",", "# LED page", "(", "0x1", ",", "0xA7", ")", ",", "# desktop page", "(", "0xb", ",", "0x2f", ")", ",", ")", "all_target_usages", "=", "[", "hid", ...
Browse for mute usages and set value
[ "Browse", "for", "mute", "usages", "and", "set", "value" ]
python
train
MIT-LCP/wfdb-python
wfdb/io/_signal.py
https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/io/_signal.py#L419-L513
def dac(self, expanded=False, return_res=64, inplace=False): """ Performs the digital to analogue conversion of the signal stored in `d_signal` if expanded is False, or `e_d_signal` if expanded is True. The d_signal/e_d_signal, fmt, gain, and baseline fields must all be ...
[ "def", "dac", "(", "self", ",", "expanded", "=", "False", ",", "return_res", "=", "64", ",", "inplace", "=", "False", ")", ":", "# The digital nan values for each channel", "d_nans", "=", "_digi_nan", "(", "self", ".", "fmt", ")", "# Get the appropriate float dt...
Performs the digital to analogue conversion of the signal stored in `d_signal` if expanded is False, or `e_d_signal` if expanded is True. The d_signal/e_d_signal, fmt, gain, and baseline fields must all be valid. If inplace is True, the dac will be performed inplace on the ...
[ "Performs", "the", "digital", "to", "analogue", "conversion", "of", "the", "signal", "stored", "in", "d_signal", "if", "expanded", "is", "False", "or", "e_d_signal", "if", "expanded", "is", "True", "." ]
python
train
cytomine/Cytomine-python-client
cytomine/models/annotation.py
https://github.com/cytomine/Cytomine-python-client/blob/bac19722b900dd32c6cfd6bdb9354fc784d33bc4/cytomine/models/annotation.py#L62-L144
def dump(self, dest_pattern="{id}.jpg", override=True, mask=False, alpha=False, bits=8, zoom=None, max_size=None, increase_area=None, contrast=None, gamma=None, colormap=None, inverse=None): """ Download the annotation crop, with optional image modifications. Parameters ---...
[ "def", "dump", "(", "self", ",", "dest_pattern", "=", "\"{id}.jpg\"", ",", "override", "=", "True", ",", "mask", "=", "False", ",", "alpha", "=", "False", ",", "bits", "=", "8", ",", "zoom", "=", "None", ",", "max_size", "=", "None", ",", "increase_a...
Download the annotation crop, with optional image modifications. Parameters ---------- dest_pattern : str, optional Destination path for the downloaded image. "{X}" patterns are replaced by the value of X attribute if it exists. override : bool, optional ...
[ "Download", "the", "annotation", "crop", "with", "optional", "image", "modifications", "." ]
python
train
CamDavidsonPilon/lifelines
lifelines/generate_datasets.py
https://github.com/CamDavidsonPilon/lifelines/blob/bdf6be6f1d10eea4c46365ee0ee6a47d8c30edf8/lifelines/generate_datasets.py#L219-L246
def generate_hazard_rates(n, d, timelines, constant=False, independent=0, n_binary=0, model="aalen"): """ n: the number of instances d: the number of covariates lifelines: the observational times constant: make the coeffients constant (not time dependent) n_binary: the number of binary...
[ "def", "generate_hazard_rates", "(", "n", ",", "d", ",", "timelines", ",", "constant", "=", "False", ",", "independent", "=", "0", ",", "n_binary", "=", "0", ",", "model", "=", "\"aalen\"", ")", ":", "covariates", "=", "generate_covariates", "(", "n", ",...
n: the number of instances d: the number of covariates lifelines: the observational times constant: make the coeffients constant (not time dependent) n_binary: the number of binary covariates model: from ["aalen", "cox"] Returns:s hazard rates: (t,n) dataframe, coefficient...
[ "n", ":", "the", "number", "of", "instances", "d", ":", "the", "number", "of", "covariates", "lifelines", ":", "the", "observational", "times", "constant", ":", "make", "the", "coeffients", "constant", "(", "not", "time", "dependent", ")", "n_binary", ":", ...
python
train
jmgilman/Neolib
neolib/pyamf/util/pure.py
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/util/pure.py#L203-L210
def _is_big_endian(self): """ Whether the current endian is big endian. """ if self.endian == DataTypeMixIn.ENDIAN_NATIVE: return SYSTEM_ENDIAN == DataTypeMixIn.ENDIAN_BIG return self.endian in (DataTypeMixIn.ENDIAN_BIG, DataTypeMixIn.ENDIAN_NETWORK)
[ "def", "_is_big_endian", "(", "self", ")", ":", "if", "self", ".", "endian", "==", "DataTypeMixIn", ".", "ENDIAN_NATIVE", ":", "return", "SYSTEM_ENDIAN", "==", "DataTypeMixIn", ".", "ENDIAN_BIG", "return", "self", ".", "endian", "in", "(", "DataTypeMixIn", "."...
Whether the current endian is big endian.
[ "Whether", "the", "current", "endian", "is", "big", "endian", "." ]
python
train
epfl-lts2/pygsp
pygsp/filters/filter.py
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/filters/filter.py#L334-L339
def analyze(self, s, method='chebyshev', order=30): r"""Convenience alias to :meth:`filter`.""" if s.ndim == 3 and s.shape[-1] != 1: raise ValueError('Last dimension (#features) should be ' '1, got {}.'.format(s.shape)) return self.filter(s, method, order...
[ "def", "analyze", "(", "self", ",", "s", ",", "method", "=", "'chebyshev'", ",", "order", "=", "30", ")", ":", "if", "s", ".", "ndim", "==", "3", "and", "s", ".", "shape", "[", "-", "1", "]", "!=", "1", ":", "raise", "ValueError", "(", "'Last d...
r"""Convenience alias to :meth:`filter`.
[ "r", "Convenience", "alias", "to", ":", "meth", ":", "filter", "." ]
python
train
jarrekk/imgkit
imgkit/imgkit.py
https://github.com/jarrekk/imgkit/blob/763296cc2e81b16b9c3ebd2cd4355ddd02d5ab16/imgkit/imgkit.py#L187-L207
def _find_options_in_meta(self, content): """Reads 'content' and extracts options encoded in HTML meta tags :param content: str or file-like object - contains HTML to parse returns: dict: {config option: value} """ if (isinstance(content, io.IOBase) or con...
[ "def", "_find_options_in_meta", "(", "self", ",", "content", ")", ":", "if", "(", "isinstance", "(", "content", ",", "io", ".", "IOBase", ")", "or", "content", ".", "__class__", ".", "__name__", "==", "'StreamReaderWriter'", ")", ":", "content", "=", "cont...
Reads 'content' and extracts options encoded in HTML meta tags :param content: str or file-like object - contains HTML to parse returns: dict: {config option: value}
[ "Reads", "content", "and", "extracts", "options", "encoded", "in", "HTML", "meta", "tags" ]
python
train
noahbenson/pimms
pimms/util.py
https://github.com/noahbenson/pimms/blob/9051b86d6b858a7a13511b72c48dc21bc903dab2/pimms/util.py#L363-L386
def is_nparray(u, dtype=None, dims=None): ''' is_nparray(u) yields True if u is an instance of a numpy array and False otherwise. is_nparray(u, dtype) yields True if is_nparray(u) and the dtype of u is a sub-dtype of the given dtype. is_nparray(u, dtype, dims) yields True if is_nparray(u, dtype) a...
[ "def", "is_nparray", "(", "u", ",", "dtype", "=", "None", ",", "dims", "=", "None", ")", ":", "if", "is_quantity", "(", "u", ")", ":", "return", "is_nparray", "(", "mag", "(", "u", ")", ",", "dtype", "=", "dtype", ",", "dims", "=", "dims", ")", ...
is_nparray(u) yields True if u is an instance of a numpy array and False otherwise. is_nparray(u, dtype) yields True if is_nparray(u) and the dtype of u is a sub-dtype of the given dtype. is_nparray(u, dtype, dims) yields True if is_nparray(u, dtype) and the number of dimensions is equal to dims (no...
[ "is_nparray", "(", "u", ")", "yields", "True", "if", "u", "is", "an", "instance", "of", "a", "numpy", "array", "and", "False", "otherwise", ".", "is_nparray", "(", "u", "dtype", ")", "yields", "True", "if", "is_nparray", "(", "u", ")", "and", "the", ...
python
train
foremast/foremast
src/foremast/utils/lookups.py
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/utils/lookups.py#L207-L226
def get(self, branch='master', filename=''): """Retrieve _filename_ from GitLab. Args: branch (str): Git Branch to find file. filename (str): Name of file to retrieve relative to root of Git repository, or _runway_dir_ if specified. Returns: ...
[ "def", "get", "(", "self", ",", "branch", "=", "'master'", ",", "filename", "=", "''", ")", ":", "file_contents", "=", "''", "if", "self", ".", "runway_dir", ":", "file_contents", "=", "self", ".", "local_file", "(", "filename", "=", "filename", ")", "...
Retrieve _filename_ from GitLab. Args: branch (str): Git Branch to find file. filename (str): Name of file to retrieve relative to root of Git repository, or _runway_dir_ if specified. Returns: str: Contents of file.
[ "Retrieve", "_filename_", "from", "GitLab", "." ]
python
train
Opentrons/opentrons
api/src/opentrons/protocol_api/contexts.py
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/protocol_api/contexts.py#L1106-L1258
def transfer(self, volume: Union[float, Sequence[float]], source, dest, **kwargs) -> 'InstrumentContext': # source: Union[Well, List[Well], List[List[Well]]], # dest: Union[Well, List[Well], List[List[Well]]], # TODO: Reach cons...
[ "def", "transfer", "(", "self", ",", "volume", ":", "Union", "[", "float", ",", "Sequence", "[", "float", "]", "]", ",", "source", ",", "dest", ",", "*", "*", "kwargs", ")", "->", "'InstrumentContext'", ":", "# source: Union[Well, List[Well], List[List[Well]]]...
r""" Transfer will move a volume of liquid from a source location(s) to a dest location(s). It is a higher-level command, incorporating other :py:class:`InstrumentContext` commands, like :py:meth:`aspirate` and :py:meth:`dispense`, designed to make protocol writing easier at the ...
[ "r", "Transfer", "will", "move", "a", "volume", "of", "liquid", "from", "a", "source", "location", "(", "s", ")", "to", "a", "dest", "location", "(", "s", ")", ".", "It", "is", "a", "higher", "-", "level", "command", "incorporating", "other", ":", "p...
python
train
chrisrink10/basilisp
src/basilisp/importer.py
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/importer.py#L82-L87
def _cache_from_source(path: str) -> str: """Return the path to the cached file for the given path. The original path does not have to exist.""" cache_path, cache_file = os.path.split(importlib.util.cache_from_source(path)) filename, _ = os.path.splitext(cache_file) return os.path.join(cache_path, f...
[ "def", "_cache_from_source", "(", "path", ":", "str", ")", "->", "str", ":", "cache_path", ",", "cache_file", "=", "os", ".", "path", ".", "split", "(", "importlib", ".", "util", ".", "cache_from_source", "(", "path", ")", ")", "filename", ",", "_", "=...
Return the path to the cached file for the given path. The original path does not have to exist.
[ "Return", "the", "path", "to", "the", "cached", "file", "for", "the", "given", "path", ".", "The", "original", "path", "does", "not", "have", "to", "exist", "." ]
python
test
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/dvips.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/dvips.py#L45-L52
def DviPsStrFunction(target = None, source= None, env=None): """A strfunction for dvipdf that returns the appropriate command string for the no_exec options.""" if env.GetOption("no_exec"): result = env.subst('$PSCOM',0,target,source) else: result = '' return result
[ "def", "DviPsStrFunction", "(", "target", "=", "None", ",", "source", "=", "None", ",", "env", "=", "None", ")", ":", "if", "env", ".", "GetOption", "(", "\"no_exec\"", ")", ":", "result", "=", "env", ".", "subst", "(", "'$PSCOM'", ",", "0", ",", "...
A strfunction for dvipdf that returns the appropriate command string for the no_exec options.
[ "A", "strfunction", "for", "dvipdf", "that", "returns", "the", "appropriate", "command", "string", "for", "the", "no_exec", "options", "." ]
python
train
har07/PySastrawi
src/Sastrawi/StopWordRemover/StopWordRemover.py
https://github.com/har07/PySastrawi/blob/01afc81c579bde14dcb41c33686b26af8afab121/src/Sastrawi/StopWordRemover/StopWordRemover.py#L10-L15
def remove(self, text): """Remove stop words.""" words = text.split(' ') stopped_words = [word for word in words if not self.dictionary.contains(word)] return ' '.join(stopped_words)
[ "def", "remove", "(", "self", ",", "text", ")", ":", "words", "=", "text", ".", "split", "(", "' '", ")", "stopped_words", "=", "[", "word", "for", "word", "in", "words", "if", "not", "self", ".", "dictionary", ".", "contains", "(", "word", ")", "]...
Remove stop words.
[ "Remove", "stop", "words", "." ]
python
train
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py#L12802-L12831
def home_position_send(self, latitude, longitude, altitude, x, y, z, q, approach_x, approach_y, approach_z, force_mavlink1=False): ''' This message can be requested by sending the MAV_CMD_GET_HOME_POSITION command. The position the system will return to and ...
[ "def", "home_position_send", "(", "self", ",", "latitude", ",", "longitude", ",", "altitude", ",", "x", ",", "y", ",", "z", ",", "q", ",", "approach_x", ",", "approach_y", ",", "approach_z", ",", "force_mavlink1", "=", "False", ")", ":", "return", "self"...
This message can be requested by sending the MAV_CMD_GET_HOME_POSITION command. The position the system will return to and land on. The position is set automatically by the system during the takeoff in case it was not explicitely set by the operator before...
[ "This", "message", "can", "be", "requested", "by", "sending", "the", "MAV_CMD_GET_HOME_POSITION", "command", ".", "The", "position", "the", "system", "will", "return", "to", "and", "land", "on", ".", "The", "position", "is", "set", "automatically", "by", "the"...
python
train
alantygel/ckanext-semantictags
ckanext/semantictags/db.py
https://github.com/alantygel/ckanext-semantictags/blob/10bb31d29f34b2b5a6feae693961842f93007ce1/ckanext/semantictags/db.py#L305-L324
def by_name(self, tag_name, semantictag_URI, autoflush=True): '''Return the TagSemanticTag for the given tag name and semantic tag URI, or None. :param tag_name: the name of the tag to look for :type tag_name: string :param tag_URI: the name of the tag to look for :type tag_URI: string :returns: the Ta...
[ "def", "by_name", "(", "self", ",", "tag_name", ",", "semantictag_URI", ",", "autoflush", "=", "True", ")", ":", "query", "=", "(", "meta", ".", "Session", ".", "query", "(", "TagSemanticTag", ")", ".", "filter", "(", "_tag", ".", "Tag", ".", "name", ...
Return the TagSemanticTag for the given tag name and semantic tag URI, or None. :param tag_name: the name of the tag to look for :type tag_name: string :param tag_URI: the name of the tag to look for :type tag_URI: string :returns: the TagSemanticTag for the given tag name and semantic tag URI, or None i...
[ "Return", "the", "TagSemanticTag", "for", "the", "given", "tag", "name", "and", "semantic", "tag", "URI", "or", "None", "." ]
python
train
lowandrew/OLCTools
accessoryFunctions/accessoryFunctions.py
https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/accessoryFunctions/accessoryFunctions.py#L403-L456
def execute(command, outfile=""): """ Allows for dots to be printed to the terminal while waiting for a long system call to run :param command: the command to be executed :param outfile: optional string of an output file from https://stackoverflow.com/questions/4417546/constantly-print-subprocess-ou...
[ "def", "execute", "(", "command", ",", "outfile", "=", "\"\"", ")", ":", "# Initialise count", "count", "=", "0", "# Initialise the starting time", "start", "=", "int", "(", "time", ".", "time", "(", ")", ")", "maxtime", "=", "0", "# Removing Shell=True to pre...
Allows for dots to be printed to the terminal while waiting for a long system call to run :param command: the command to be executed :param outfile: optional string of an output file from https://stackoverflow.com/questions/4417546/constantly-print-subprocess-output-while-process-is-running
[ "Allows", "for", "dots", "to", "be", "printed", "to", "the", "terminal", "while", "waiting", "for", "a", "long", "system", "call", "to", "run", ":", "param", "command", ":", "the", "command", "to", "be", "executed", ":", "param", "outfile", ":", "optiona...
python
train
topic2k/pygcgen
pygcgen/generator.py
https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L1088-L1102
def apply_exclude_tags_regex(self, all_tags): """ Filter tags according exclude_tags_regex option. :param list(dict) all_tags: Pre-filtered tags. :rtype: list(dict) :return: Filtered tags. """ filtered = [] for tag in all_tags: if not re.match...
[ "def", "apply_exclude_tags_regex", "(", "self", ",", "all_tags", ")", ":", "filtered", "=", "[", "]", "for", "tag", "in", "all_tags", ":", "if", "not", "re", ".", "match", "(", "self", ".", "options", ".", "exclude_tags_regex", ",", "tag", "[", "\"name\"...
Filter tags according exclude_tags_regex option. :param list(dict) all_tags: Pre-filtered tags. :rtype: list(dict) :return: Filtered tags.
[ "Filter", "tags", "according", "exclude_tags_regex", "option", "." ]
python
valid
drslump/pyshould
pyshould/matchers.py
https://github.com/drslump/pyshould/blob/7210859d4c84cfbaa64f91b30c2a541aea788ddf/pyshould/matchers.py#L94-L102
def normalize(alias): """ Normalizes an alias by removing adverbs defined in IGNORED_WORDS """ # Convert from CamelCase to snake_case alias = re.sub(r'([a-z])([A-Z])', r'\1_\2', alias) # Ignore words words = alias.lower().split('_') words = filter(lambda w: w not in IGNORED_WORDS, words) ...
[ "def", "normalize", "(", "alias", ")", ":", "# Convert from CamelCase to snake_case", "alias", "=", "re", ".", "sub", "(", "r'([a-z])([A-Z])'", ",", "r'\\1_\\2'", ",", "alias", ")", "# Ignore words", "words", "=", "alias", ".", "lower", "(", ")", ".", "split",...
Normalizes an alias by removing adverbs defined in IGNORED_WORDS
[ "Normalizes", "an", "alias", "by", "removing", "adverbs", "defined", "in", "IGNORED_WORDS" ]
python
train
mk-fg/txboxdotnet
txboxdotnet/api_v2.py
https://github.com/mk-fg/txboxdotnet/blob/4a3e48fbe1388c5e2a17e808aaaf6b2460e61f48/txboxdotnet/api_v2.py#L269-L273
def mkdir(self, name=None, folder_id='0'): '''Create a folder with a specified "name" attribute. folder_id allows to specify a parent folder.''' return self( 'folders', method='post', encode='json', data=dict(name=name, parent=dict(id=folder_id)) )
[ "def", "mkdir", "(", "self", ",", "name", "=", "None", ",", "folder_id", "=", "'0'", ")", ":", "return", "self", "(", "'folders'", ",", "method", "=", "'post'", ",", "encode", "=", "'json'", ",", "data", "=", "dict", "(", "name", "=", "name", ",", ...
Create a folder with a specified "name" attribute. folder_id allows to specify a parent folder.
[ "Create", "a", "folder", "with", "a", "specified", "name", "attribute", ".", "folder_id", "allows", "to", "specify", "a", "parent", "folder", "." ]
python
train
admiralobvious/justbackoff
justbackoff/__init__.py
https://github.com/admiralobvious/justbackoff/blob/4fe69cdded4e1d506bf16464a5acf72bca6ebd28/justbackoff/__init__.py#L59-L68
def duration(self): """ Returns the current value of the counter and then multiplies it by :attr:`factor` :rtype: float """ d = self.for_attempt(self.cur_attempt) self.cur_attempt += 1 return d
[ "def", "duration", "(", "self", ")", ":", "d", "=", "self", ".", "for_attempt", "(", "self", ".", "cur_attempt", ")", "self", ".", "cur_attempt", "+=", "1", "return", "d" ]
Returns the current value of the counter and then multiplies it by :attr:`factor` :rtype: float
[ "Returns", "the", "current", "value", "of", "the", "counter", "and", "then", "multiplies", "it", "by", ":", "attr", ":", "factor" ]
python
train
Kunstmord/datalib
src/dataset.py
https://github.com/Kunstmord/datalib/blob/9d7db3e7c3a5feeeb5d19eb0dbee858bd2b50886/src/dataset.py#L621-L648
def prepopulate(self): """ Creates a database file (if it doesn't exist, writes each data point's path, real_id into it) Parameters ---------- self Returns ------- None """ if self._prepopulated is False: engine = create_engin...
[ "def", "prepopulate", "(", "self", ")", ":", "if", "self", ".", "_prepopulated", "is", "False", ":", "engine", "=", "create_engine", "(", "'sqlite:////'", "+", "self", ".", "dbpath", ")", "self", ".", "_db_base", ".", "metadata", ".", "create_all", "(", ...
Creates a database file (if it doesn't exist, writes each data point's path, real_id into it) Parameters ---------- self Returns ------- None
[ "Creates", "a", "database", "file", "(", "if", "it", "doesn", "t", "exist", "writes", "each", "data", "point", "s", "path", "real_id", "into", "it", ")" ]
python
train
lemieuxl/pyGenClean
pyGenClean/SexCheck/sex_check.py
https://github.com/lemieuxl/pyGenClean/blob/6173a48ccc0cf3a3bd711b1f2a1fa16248b8bf55/pyGenClean/SexCheck/sex_check.py#L219-L263
def computeNoCall(fileName): """Computes the number of no call. :param fileName: the name of the file :type fileName: str Reads the ``ped`` file created by Plink using the ``recodeA`` options (see :py:func:`createPedChr24UsingPlink`) and computes the number and percentage of no calls on the c...
[ "def", "computeNoCall", "(", "fileName", ")", ":", "outputFile", "=", "None", "try", ":", "outputFile", "=", "open", "(", "fileName", "+", "\".noCall\"", ",", "\"w\"", ")", "except", "IOError", ":", "msg", "=", "\"%s: can't write file\"", "%", "fileName", "+...
Computes the number of no call. :param fileName: the name of the file :type fileName: str Reads the ``ped`` file created by Plink using the ``recodeA`` options (see :py:func:`createPedChr24UsingPlink`) and computes the number and percentage of no calls on the chromosome ``24``.
[ "Computes", "the", "number", "of", "no", "call", "." ]
python
train
mitsei/dlkit
dlkit/json_/repository/sessions.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/repository/sessions.py#L5642-L5662
def get_child_repositories(self, repository_id): """Gets the children of the given repository. arg: repository_id (osid.id.Id): the ``Id`` to query return: (osid.repository.RepositoryList) - the children of the repository raise: NotFound - ``repository_id`` not found...
[ "def", "get_child_repositories", "(", "self", ",", "repository_id", ")", ":", "# Implemented from template for", "# osid.resource.BinHierarchySession.get_child_bins", "if", "self", ".", "_catalog_session", "is", "not", "None", ":", "return", "self", ".", "_catalog_session",...
Gets the children of the given repository. arg: repository_id (osid.id.Id): the ``Id`` to query return: (osid.repository.RepositoryList) - the children of the repository raise: NotFound - ``repository_id`` not found raise: NullArgument - ``repository_id`` is ``null`...
[ "Gets", "the", "children", "of", "the", "given", "repository", "." ]
python
train
rackerlabs/rackspace-python-neutronclient
neutronclient/v2_0/client.py
https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/v2_0/client.py#L1062-L1065
def show_lbaas_pool(self, lbaas_pool, **_params): """Fetches information for a lbaas_pool.""" return self.get(self.lbaas_pool_path % (lbaas_pool), params=_params)
[ "def", "show_lbaas_pool", "(", "self", ",", "lbaas_pool", ",", "*", "*", "_params", ")", ":", "return", "self", ".", "get", "(", "self", ".", "lbaas_pool_path", "%", "(", "lbaas_pool", ")", ",", "params", "=", "_params", ")" ]
Fetches information for a lbaas_pool.
[ "Fetches", "information", "for", "a", "lbaas_pool", "." ]
python
train
tanghaibao/goatools
goatools/cli/find_enrichment.py
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/find_enrichment.py#L291-L300
def get_results_sig(self): """Get significant results.""" # Only print results when uncorrected p-value < this value. print("{N:7,} of {M:,} results have uncorrected P-values <= {PVAL}=pval\n".format( N=sum(1 for r in self.results_all if r.p_uncorrected < self.args.pval), ...
[ "def", "get_results_sig", "(", "self", ")", ":", "# Only print results when uncorrected p-value < this value.", "print", "(", "\"{N:7,} of {M:,} results have uncorrected P-values <= {PVAL}=pval\\n\"", ".", "format", "(", "N", "=", "sum", "(", "1", "for", "r", "in", "self", ...
Get significant results.
[ "Get", "significant", "results", "." ]
python
train
fjwCode/cerium
cerium/elements.py
https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/elements.py#L87-L90
def send_keys(self, text: str = 'cerium') -> None: '''Simulates typing keys.''' self.click() self._parent.send_keys(text)
[ "def", "send_keys", "(", "self", ",", "text", ":", "str", "=", "'cerium'", ")", "->", "None", ":", "self", ".", "click", "(", ")", "self", ".", "_parent", ".", "send_keys", "(", "text", ")" ]
Simulates typing keys.
[ "Simulates", "typing", "keys", "." ]
python
train
PlaidWeb/Publ
publ/image/local.py
https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/image/local.py#L333-L381
def get_rendition_fill_size(spec, input_w, input_h, output_scale): """ Determine the scale-crop size given the provided spec """ width = input_w height = input_h scale = spec.get('scale') if scale: width = width / scale height = height / scale i...
[ "def", "get_rendition_fill_size", "(", "spec", ",", "input_w", ",", "input_h", ",", "output_scale", ")", ":", "width", "=", "input_w", "height", "=", "input_h", "scale", "=", "spec", ".", "get", "(", "'scale'", ")", "if", "scale", ":", "width", "=", "wid...
Determine the scale-crop size given the provided spec
[ "Determine", "the", "scale", "-", "crop", "size", "given", "the", "provided", "spec" ]
python
train
hjacobs/python-timeperiod2
timeperiod.py
https://github.com/hjacobs/python-timeperiod2/blob/6e59c0ef220b20e9213901195842e0283491593f/timeperiod.py#L42-L134
def in_period(period, dt=None): """ Determines if a datetime is within a certain time period. If the time is omitted the current time will be used. in_period return True is the datetime is within the time period, False if not. If the expression is malformed a TimePeriod.InvalidFormat exception ...
[ "def", "in_period", "(", "period", ",", "dt", "=", "None", ")", ":", "if", "dt", "is", "None", ":", "dt", "=", "datetime", ".", "now", "(", ")", "# transform whatever crazy format we're given and turn it into", "# something like this:", "#", "# md{1}|hr{midnight-noo...
Determines if a datetime is within a certain time period. If the time is omitted the current time will be used. in_period return True is the datetime is within the time period, False if not. If the expression is malformed a TimePeriod.InvalidFormat exception will be raised. (Note that this differs from...
[ "Determines", "if", "a", "datetime", "is", "within", "a", "certain", "time", "period", ".", "If", "the", "time", "is", "omitted", "the", "current", "time", "will", "be", "used", "." ]
python
train
UCL-INGI/INGInious
inginious/frontend/pages/course_admin/task_edit.py
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course_admin/task_edit.py#L73-L80
def contains_is_html(cls, data): """ Detect if the problem has at least one "xyzIsHTML" key """ for key, val in data.items(): if isinstance(key, str) and key.endswith("IsHTML"): return True if isinstance(val, (OrderedDict, dict)) and cls.contains_is_html(val): ...
[ "def", "contains_is_html", "(", "cls", ",", "data", ")", ":", "for", "key", ",", "val", "in", "data", ".", "items", "(", ")", ":", "if", "isinstance", "(", "key", ",", "str", ")", "and", "key", ".", "endswith", "(", "\"IsHTML\"", ")", ":", "return"...
Detect if the problem has at least one "xyzIsHTML" key
[ "Detect", "if", "the", "problem", "has", "at", "least", "one", "xyzIsHTML", "key" ]
python
train
tanghaibao/goatools
goatools/grouper/grprobj_init.py
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/grprobj_init.py#L86-L121
def _init_h2us(self, fnc_most_specific): """Given a set of user GO ids, return GO ids grouped under the "GO high" terms. Example of a grouped go list: gos = ['GO:0044464':[ # grp_term: D1 cell part 'GO:0005737', # child: D3 cytoplasm 'GO:...
[ "def", "_init_h2us", "(", "self", ",", "fnc_most_specific", ")", ":", "# Header GO IDs are main. User GO IDs are as specified by the user", "hdrgo2usrgos", "=", "cx", ".", "defaultdict", "(", "set", ")", "# Contains user GO IDs which are also header GO IDs, plus user main GO if nee...
Given a set of user GO ids, return GO ids grouped under the "GO high" terms. Example of a grouped go list: gos = ['GO:0044464':[ # grp_term: D1 cell part 'GO:0005737', # child: D3 cytoplasm 'GO:0048471', # child: D4 perinuclear region of cytop...
[ "Given", "a", "set", "of", "user", "GO", "ids", "return", "GO", "ids", "grouped", "under", "the", "GO", "high", "terms", "." ]
python
train
titusjan/argos
argos/inspector/pgplugins/pgctis.py
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pgctis.py#L470-L475
def _closeResources(self): """ Disconnects signals. Is called by self.finalize when the cti is deleted. """ self.histLutItem.sigLevelsChanged.disconnect(self.setAutoRangeOff) self.histLutItem.sigLevelsChanged.disconnect(self.refreshMinMax)
[ "def", "_closeResources", "(", "self", ")", ":", "self", ".", "histLutItem", ".", "sigLevelsChanged", ".", "disconnect", "(", "self", ".", "setAutoRangeOff", ")", "self", ".", "histLutItem", ".", "sigLevelsChanged", ".", "disconnect", "(", "self", ".", "refres...
Disconnects signals. Is called by self.finalize when the cti is deleted.
[ "Disconnects", "signals", ".", "Is", "called", "by", "self", ".", "finalize", "when", "the", "cti", "is", "deleted", "." ]
python
train
adafruit/Adafruit_Python_PlatformDetect
adafruit_platformdetect/chip.py
https://github.com/adafruit/Adafruit_Python_PlatformDetect/blob/cddd4d47e530026778dc4e3c3ccabad14e6eac46/adafruit_platformdetect/chip.py#L73-L105
def _linux_id(self): """Attempt to detect the CPU on a computer running the Linux kernel.""" linux_id = None hardware = self.detector.get_cpuinfo_field("Hardware") if hardware is None: vendor_id = self.detector.get_cpuinfo_field("vendor_id") if vendor_id in ("Ge...
[ "def", "_linux_id", "(", "self", ")", ":", "linux_id", "=", "None", "hardware", "=", "self", ".", "detector", ".", "get_cpuinfo_field", "(", "\"Hardware\"", ")", "if", "hardware", "is", "None", ":", "vendor_id", "=", "self", ".", "detector", ".", "get_cpui...
Attempt to detect the CPU on a computer running the Linux kernel.
[ "Attempt", "to", "detect", "the", "CPU", "on", "a", "computer", "running", "the", "Linux", "kernel", "." ]
python
train
saltstack/salt
salt/modules/ilo.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ilo.py#L586-L617
def configure_snmp(community, snmp_port=161, snmp_trapport=161): ''' Configure SNMP CLI Example: .. code-block:: bash salt '*' ilo.configure_snmp [COMMUNITY STRING] [SNMP PORT] [SNMP TRAP PORT] ''' _xml = """<RIBCL VERSION="2.2"> <LOGIN USER_LOGIN="x" PASSWORD="y"> ...
[ "def", "configure_snmp", "(", "community", ",", "snmp_port", "=", "161", ",", "snmp_trapport", "=", "161", ")", ":", "_xml", "=", "\"\"\"<RIBCL VERSION=\"2.2\">\n <LOGIN USER_LOGIN=\"x\" PASSWORD=\"y\">\n <RIB_INFO mode=\"write\">\n ...
Configure SNMP CLI Example: .. code-block:: bash salt '*' ilo.configure_snmp [COMMUNITY STRING] [SNMP PORT] [SNMP TRAP PORT]
[ "Configure", "SNMP" ]
python
train
sdispater/orator
orator/orm/relations/belongs_to_many.py
https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/belongs_to_many.py#L665-L678
def _create_attach_records(self, ids, attributes): """ Create a list of records to insert into the pivot table. """ records = [] timed = self._has_pivot_column(self.created_at()) or self._has_pivot_column( self.updated_at() ) for key, value in enumer...
[ "def", "_create_attach_records", "(", "self", ",", "ids", ",", "attributes", ")", ":", "records", "=", "[", "]", "timed", "=", "self", ".", "_has_pivot_column", "(", "self", ".", "created_at", "(", ")", ")", "or", "self", ".", "_has_pivot_column", "(", "...
Create a list of records to insert into the pivot table.
[ "Create", "a", "list", "of", "records", "to", "insert", "into", "the", "pivot", "table", "." ]
python
train
IdentityPython/fedoidcmsg
src/fedoidcmsg/utils.py
https://github.com/IdentityPython/fedoidcmsg/blob/d30107be02521fa6cdfe285da3b6b0cdd153c8cc/src/fedoidcmsg/utils.py#L36-L67
def verify_self_signed_jwks(sjwt): """ Verify the signature of a signed JWT containing a JWKS. The JWT is signed by one of the keys in the JWKS. In the JWT the JWKS is stored using this format :: 'jwks': { 'keys': [ ] } :param sjwt: Signed Jason Web Token :retu...
[ "def", "verify_self_signed_jwks", "(", "sjwt", ")", ":", "_jws", "=", "factory", "(", "sjwt", ")", "_json", "=", "_jws", ".", "jwt", ".", "part", "[", "1", "]", "_body", "=", "json", ".", "loads", "(", "as_unicode", "(", "_json", ")", ")", "iss", "...
Verify the signature of a signed JWT containing a JWKS. The JWT is signed by one of the keys in the JWKS. In the JWT the JWKS is stored using this format :: 'jwks': { 'keys': [ ] } :param sjwt: Signed Jason Web Token :return: Dictionary containing 'jwks' (the JWKS) and...
[ "Verify", "the", "signature", "of", "a", "signed", "JWT", "containing", "a", "JWKS", ".", "The", "JWT", "is", "signed", "by", "one", "of", "the", "keys", "in", "the", "JWKS", ".", "In", "the", "JWT", "the", "JWKS", "is", "stored", "using", "this", "f...
python
test
pybel/pybel-tools
src/pybel_tools/utils.py
https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/utils.py#L185-L198
def safe_add_edge(graph, u, v, key, attr_dict, **attr): """Adds an edge while preserving negative keys, and paying no respect to positive ones :param pybel.BELGraph graph: A BEL Graph :param tuple u: The source BEL node :param tuple v: The target BEL node :param int key: The edge key. If less than ...
[ "def", "safe_add_edge", "(", "graph", ",", "u", ",", "v", ",", "key", ",", "attr_dict", ",", "*", "*", "attr", ")", ":", "if", "key", "<", "0", ":", "graph", ".", "add_edge", "(", "u", ",", "v", ",", "key", "=", "key", ",", "attr_dict", "=", ...
Adds an edge while preserving negative keys, and paying no respect to positive ones :param pybel.BELGraph graph: A BEL Graph :param tuple u: The source BEL node :param tuple v: The target BEL node :param int key: The edge key. If less than zero, corresponds to an unqualified edge, else is disregarded ...
[ "Adds", "an", "edge", "while", "preserving", "negative", "keys", "and", "paying", "no", "respect", "to", "positive", "ones" ]
python
valid
core/uricore
uricore/wkz_datastructures.py
https://github.com/core/uricore/blob/dc5ef4be7bd93da4c39e5c1cbd1ae4f3ad3f1f2a/uricore/wkz_datastructures.py#L333-L339
def popitem(self): """Pop an item from the dict.""" try: item = dict.popitem(self) return (item[0], item[1][0]) except KeyError, e: raise BadRequestKeyError(str(e))
[ "def", "popitem", "(", "self", ")", ":", "try", ":", "item", "=", "dict", ".", "popitem", "(", "self", ")", "return", "(", "item", "[", "0", "]", ",", "item", "[", "1", "]", "[", "0", "]", ")", "except", "KeyError", ",", "e", ":", "raise", "B...
Pop an item from the dict.
[ "Pop", "an", "item", "from", "the", "dict", "." ]
python
train
rstoneback/pysat
pysat/_files.py
https://github.com/rstoneback/pysat/blob/4ae1afd80e15e4449397d39dce8c3e969c32c422/pysat/_files.py#L382-L411
def get_file_array(self, start, end): """Return a list of filenames between and including start and end. Parameters ---------- start: array_like or single string filenames for start of returned filelist stop: array_like or single string ...
[ "def", "get_file_array", "(", "self", ",", "start", ",", "end", ")", ":", "if", "hasattr", "(", "start", ",", "'__iter__'", ")", "&", "hasattr", "(", "end", ",", "'__iter__'", ")", ":", "files", "=", "[", "]", "for", "(", "sta", ",", "stp", ")", ...
Return a list of filenames between and including start and end. Parameters ---------- start: array_like or single string filenames for start of returned filelist stop: array_like or single string filenames inclusive end of list ...
[ "Return", "a", "list", "of", "filenames", "between", "and", "including", "start", "and", "end", ".", "Parameters", "----------", "start", ":", "array_like", "or", "single", "string", "filenames", "for", "start", "of", "returned", "filelist", "stop", ":", "arra...
python
train
scieloorg/processing
accesses/dumpdata.py
https://github.com/scieloorg/processing/blob/629b50b45ba7a176651cd3bfcdb441dab6fddfcc/accesses/dumpdata.py#L72-L84
def fbpe_key(code): """ input: 'S0102-67202009000300001' output: 'S0102-6720(09)000300001' """ begin = code[0:10] year = code[12:14] end = code[14:] return '%s(%s)%s' % (begin, year, end)
[ "def", "fbpe_key", "(", "code", ")", ":", "begin", "=", "code", "[", "0", ":", "10", "]", "year", "=", "code", "[", "12", ":", "14", "]", "end", "=", "code", "[", "14", ":", "]", "return", "'%s(%s)%s'", "%", "(", "begin", ",", "year", ",", "e...
input: 'S0102-67202009000300001' output: 'S0102-6720(09)000300001'
[ "input", ":", "S0102", "-", "67202009000300001", "output", ":", "S0102", "-", "6720", "(", "09", ")", "000300001" ]
python
train
saltstack/salt
salt/utils/pkg/deb.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pkg/deb.py#L31-L40
def strip_uri(repo): ''' Remove the trailing slash from the URI in a repo definition ''' splits = repo.split() for idx in range(len(splits)): if any(splits[idx].startswith(x) for x in ('http://', 'https://', 'ftp://')): splits[idx] = splits[idx].rstrip('/') ret...
[ "def", "strip_uri", "(", "repo", ")", ":", "splits", "=", "repo", ".", "split", "(", ")", "for", "idx", "in", "range", "(", "len", "(", "splits", ")", ")", ":", "if", "any", "(", "splits", "[", "idx", "]", ".", "startswith", "(", "x", ")", "for...
Remove the trailing slash from the URI in a repo definition
[ "Remove", "the", "trailing", "slash", "from", "the", "URI", "in", "a", "repo", "definition" ]
python
train
vxgmichel/aiostream
aiostream/stream/advanced.py
https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/advanced.py#L15-L96
async def base_combine(source, switch=False, ordered=False, task_limit=None): """Base operator for managing an asynchronous sequence of sequences. The sequences are awaited concurrently, although it's possible to limit the amount of running sequences using the `task_limit` argument. The ``switch`` arg...
[ "async", "def", "base_combine", "(", "source", ",", "switch", "=", "False", ",", "ordered", "=", "False", ",", "task_limit", "=", "None", ")", ":", "# Task limit", "if", "task_limit", "is", "not", "None", "and", "not", "task_limit", ">", "0", ":", "raise...
Base operator for managing an asynchronous sequence of sequences. The sequences are awaited concurrently, although it's possible to limit the amount of running sequences using the `task_limit` argument. The ``switch`` argument enables the switch mecanism, which cause the previous subsequence to be dis...
[ "Base", "operator", "for", "managing", "an", "asynchronous", "sequence", "of", "sequences", "." ]
python
train
contentful-labs/contentful.py
contentful/cda/serialization.py
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/serialization.py#L189-L209
def process_array_items(self, array, json): """Iterate through all `items` and create a resource for each. In addition map the resources under the `items_mapped` by the resource id and type. :param array: Array resource. :param json: Raw JSON dictionary. """ for item in...
[ "def", "process_array_items", "(", "self", ",", "array", ",", "json", ")", ":", "for", "item", "in", "json", "[", "'items'", "]", ":", "key", "=", "None", "processed", "=", "self", ".", "from_json", "(", "item", ")", "if", "isinstance", "(", "processed...
Iterate through all `items` and create a resource for each. In addition map the resources under the `items_mapped` by the resource id and type. :param array: Array resource. :param json: Raw JSON dictionary.
[ "Iterate", "through", "all", "items", "and", "create", "a", "resource", "for", "each", "." ]
python
train
scibi/django-teryt
teryt/south_migrations/0003_ustaw_aktywny.py
https://github.com/scibi/django-teryt/blob/a4a6c981d58a2e5fdd0ffdcdc938e9de4f434b99/teryt/south_migrations/0003_ustaw_aktywny.py#L12-L35
def forwards(self, orm): "Write your forwards methods here." # Note: Don't use "from appname.models import ModelName". # Use orm.ModelName to refer to models in this application, # and orm['appname.ModelName'] for models in other applications. print("Updating: JednostkaAdministr...
[ "def", "forwards", "(", "self", ",", "orm", ")", ":", "# Note: Don't use \"from appname.models import ModelName\". ", "# Use orm.ModelName to refer to models in this application,", "# and orm['appname.ModelName'] for models in other applications.", "print", "(", "\"Updating: JednostkaAdmin...
Write your forwards methods here.
[ "Write", "your", "forwards", "methods", "here", "." ]
python
valid
ultrabug/py3status
py3status/events.py
https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/events.py#L262-L290
def run(self): """ Wait for an i3bar JSON event, then find the right module to dispatch the message to based on the 'name' and 'instance' of the event. In case the module does NOT support click_events, the default implementation is to clear the module's cache when the MI...
[ "def", "run", "(", "self", ")", ":", "try", ":", "while", "self", ".", "py3_wrapper", ".", "running", ":", "event_str", "=", "self", ".", "poller_inp", ".", "readline", "(", ")", "if", "not", "event_str", ":", "continue", "try", ":", "# remove leading co...
Wait for an i3bar JSON event, then find the right module to dispatch the message to based on the 'name' and 'instance' of the event. In case the module does NOT support click_events, the default implementation is to clear the module's cache when the MIDDLE button (2) is pressed on it. ...
[ "Wait", "for", "an", "i3bar", "JSON", "event", "then", "find", "the", "right", "module", "to", "dispatch", "the", "message", "to", "based", "on", "the", "name", "and", "instance", "of", "the", "event", "." ]
python
train
SmokinCaterpillar/pypet
pypet/brian2/network.py
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/brian2/network.py#L276-L303
def execute_network_pre_run(self, traj, network, network_dict, component_list, analyser_list): """Runs a network before the actual experiment. Called by a :class:`~pypet.brian2.network.NetworkManager`. Similar to :func:`~pypet.brian2.network.NetworkRunner.run_network`. Subruns and thei...
[ "def", "execute_network_pre_run", "(", "self", ",", "traj", ",", "network", ",", "network_dict", ",", "component_list", ",", "analyser_list", ")", ":", "self", ".", "_execute_network_run", "(", "traj", ",", "network", ",", "network_dict", ",", "component_list", ...
Runs a network before the actual experiment. Called by a :class:`~pypet.brian2.network.NetworkManager`. Similar to :func:`~pypet.brian2.network.NetworkRunner.run_network`. Subruns and their durations are extracted from the trajectory. All :class:`~pypet.brian2.parameter.Brian2Parameter...
[ "Runs", "a", "network", "before", "the", "actual", "experiment", "." ]
python
test
zhmcclient/python-zhmcclient
zhmcclient/_cpc.py
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_cpc.py#L1143-L1201
def get_energy_management_properties(self): """ Return the energy management properties of the CPC. The returned energy management properties are a subset of the properties of the CPC resource, and are also available as normal properties of the CPC resource. In so far, there is ...
[ "def", "get_energy_management_properties", "(", "self", ")", ":", "result", "=", "self", ".", "manager", ".", "session", ".", "get", "(", "self", ".", "uri", "+", "'/energy-management-data'", ")", "em_list", "=", "result", "[", "'objects'", "]", "if", "len",...
Return the energy management properties of the CPC. The returned energy management properties are a subset of the properties of the CPC resource, and are also available as normal properties of the CPC resource. In so far, there is no new data provided by this method. However, because on...
[ "Return", "the", "energy", "management", "properties", "of", "the", "CPC", "." ]
python
train
SolutionsCloud/apidoc
apidoc/object/source_dto.py
https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/object/source_dto.py#L204-L208
def get_comparable_values_for_ordering(self): """Return a tupple of values representing the unicity of the object """ return (0 if self.position >= 0 else 1, int(self.position), str(self.name), str(self.description))
[ "def", "get_comparable_values_for_ordering", "(", "self", ")", ":", "return", "(", "0", "if", "self", ".", "position", ">=", "0", "else", "1", ",", "int", "(", "self", ".", "position", ")", ",", "str", "(", "self", ".", "name", ")", ",", "str", "(", ...
Return a tupple of values representing the unicity of the object
[ "Return", "a", "tupple", "of", "values", "representing", "the", "unicity", "of", "the", "object" ]
python
train
astrocatalogs/astrocats
astrocats/catalog/entry.py
https://github.com/astrocatalogs/astrocats/blob/11abc3131c6366ecd23964369e55ff264add7805/astrocats/catalog/entry.py#L904-L934
def get_stub(self): """Get a new `Entry` which contains the 'stub' of this one. The 'stub' is only the name and aliases. Usage: ----- To convert a normal entry into a stub (for example), overwrite the entry in place, i.e. >>> entries[name] = entries[name].get_st...
[ "def", "get_stub", "(", "self", ")", ":", "stub", "=", "type", "(", "self", ")", "(", "self", ".", "catalog", ",", "self", "[", "self", ".", "_KEYS", ".", "NAME", "]", ",", "stub", "=", "True", ")", "if", "self", ".", "_KEYS", ".", "ALIAS", "in...
Get a new `Entry` which contains the 'stub' of this one. The 'stub' is only the name and aliases. Usage: ----- To convert a normal entry into a stub (for example), overwrite the entry in place, i.e. >>> entries[name] = entries[name].get_stub() Returns -...
[ "Get", "a", "new", "Entry", "which", "contains", "the", "stub", "of", "this", "one", "." ]
python
train
wbond/vat_moss-python
vat_moss/declared_residence.py
https://github.com/wbond/vat_moss-python/blob/5089dcf036eb2e9abc58e78186fd46b522a50620/vat_moss/declared_residence.py#L16-L62
def calculate_rate(country_code, exception_name): """ Calculates the VAT rate for a customer based on their declared country and any declared exception information. :param country_code: The two-character country code where the user resides :param exception_name: The name of an exce...
[ "def", "calculate_rate", "(", "country_code", ",", "exception_name", ")", ":", "if", "not", "country_code", "or", "not", "isinstance", "(", "country_code", ",", "str_cls", ")", "or", "len", "(", "country_code", ")", "!=", "2", ":", "raise", "ValueError", "("...
Calculates the VAT rate for a customer based on their declared country and any declared exception information. :param country_code: The two-character country code where the user resides :param exception_name: The name of an exception for the country, as returned from vat_moss.decla...
[ "Calculates", "the", "VAT", "rate", "for", "a", "customer", "based", "on", "their", "declared", "country", "and", "any", "declared", "exception", "information", "." ]
python
train
aiogram/aiogram
examples/callback_data_factory.py
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/examples/callback_data_factory.py#L36-L47
def get_keyboard() -> types.InlineKeyboardMarkup: """ Generate keyboard with list of posts """ markup = types.InlineKeyboardMarkup() for post_id, post in POSTS.items(): markup.add( types.InlineKeyboardButton( post['title'], callback_data=posts_cb.n...
[ "def", "get_keyboard", "(", ")", "->", "types", ".", "InlineKeyboardMarkup", ":", "markup", "=", "types", ".", "InlineKeyboardMarkup", "(", ")", "for", "post_id", ",", "post", "in", "POSTS", ".", "items", "(", ")", ":", "markup", ".", "add", "(", "types"...
Generate keyboard with list of posts
[ "Generate", "keyboard", "with", "list", "of", "posts" ]
python
train
marcinmiklitz/pywindow
pywindow/molecular.py
https://github.com/marcinmiklitz/pywindow/blob/e5264812157224f22a691741ca2e0aefdc9bd2eb/pywindow/molecular.py#L1116-L1163
def dump_system_json(self, filepath=None, modular=False, **kwargs): """ Dump a :class:`MolecularSystem` to a JSON dictionary. The dumped JSON dictionary, with :class:`MolecularSystem`, can then be loaded through a JSON loader and then through :func:`load_system()` to retrieve a ...
[ "def", "dump_system_json", "(", "self", ",", "filepath", "=", "None", ",", "modular", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# We pass a copy of the properties dictionary.", "dict_obj", "=", "deepcopy", "(", "self", ".", "system", ")", "# In case we w...
Dump a :class:`MolecularSystem` to a JSON dictionary. The dumped JSON dictionary, with :class:`MolecularSystem`, can then be loaded through a JSON loader and then through :func:`load_system()` to retrieve a :class:`MolecularSystem`. Kwargs are passed to :func:`pywindow.io_tools.Output....
[ "Dump", "a", ":", "class", ":", "MolecularSystem", "to", "a", "JSON", "dictionary", "." ]
python
train
rwl/godot
godot/ui/graph_tree.py
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_tree.py#L79-L87
def get_children ( self, object ): """ Gets the object's children. """ children = [] children.extend( object.subgraphs ) children.extend( object.clusters ) children.extend( object.nodes ) children.extend( object.edges ) return children
[ "def", "get_children", "(", "self", ",", "object", ")", ":", "children", "=", "[", "]", "children", ".", "extend", "(", "object", ".", "subgraphs", ")", "children", ".", "extend", "(", "object", ".", "clusters", ")", "children", ".", "extend", "(", "ob...
Gets the object's children.
[ "Gets", "the", "object", "s", "children", "." ]
python
test
elehcimd/pynb
pynb/notebook.py
https://github.com/elehcimd/pynb/blob/a32af1f0e574f880eccda4a46aede6d65151f8c9/pynb/notebook.py#L278-L306
def add_cell_footer(self): """ Add footer cell """ # check if there's already a cell footer... if true, do not add a second cell footer. # this situation happens when exporting to ipynb and then importing from ipynb. logging.info('Adding footer cell') for cell ...
[ "def", "add_cell_footer", "(", "self", ")", ":", "# check if there's already a cell footer... if true, do not add a second cell footer.", "# this situation happens when exporting to ipynb and then importing from ipynb.", "logging", ".", "info", "(", "'Adding footer cell'", ")", "for", ...
Add footer cell
[ "Add", "footer", "cell" ]
python
train
piotr-rusin/spam-lists
spam_lists/clients.py
https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/clients.py#L270-L280
def lookup_matching(self, urls): """Get items for all listed URLs. :param urls: a sequence of URLs to be tested :returns: objects representing listed URLs :raises InvalidURLError: if there are any invalid URLs in the sequence """ for url, _class in self._get_matc...
[ "def", "lookup_matching", "(", "self", ",", "urls", ")", ":", "for", "url", ",", "_class", "in", "self", ".", "_get_match_and_classification", "(", "urls", ")", ":", "classification", "=", "set", "(", "_class", ".", "split", "(", "','", ")", ")", "yield"...
Get items for all listed URLs. :param urls: a sequence of URLs to be tested :returns: objects representing listed URLs :raises InvalidURLError: if there are any invalid URLs in the sequence
[ "Get", "items", "for", "all", "listed", "URLs", "." ]
python
train
flatangle/flatlib
flatlib/utils.py
https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/utils.py#L14-L19
def ascdiff(decl, lat): """ Returns the Ascensional Difference of a point. """ delta = math.radians(decl) phi = math.radians(lat) ad = math.asin(math.tan(delta) * math.tan(phi)) return math.degrees(ad)
[ "def", "ascdiff", "(", "decl", ",", "lat", ")", ":", "delta", "=", "math", ".", "radians", "(", "decl", ")", "phi", "=", "math", ".", "radians", "(", "lat", ")", "ad", "=", "math", ".", "asin", "(", "math", ".", "tan", "(", "delta", ")", "*", ...
Returns the Ascensional Difference of a point.
[ "Returns", "the", "Ascensional", "Difference", "of", "a", "point", "." ]
python
train
Diviyan-Kalainathan/CausalDiscoveryToolbox
cdt/utils/loss.py
https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/utils/loss.py#L177-L191
def forward(self, pred, target): """Compute the loss model. :param pred: predicted Variable :param target: Target Variable :return: Loss """ loss = th.FloatTensor([0]) for i in range(1, self.moments): mk_pred = th.mean(th.pow(pred, i), 0) ...
[ "def", "forward", "(", "self", ",", "pred", ",", "target", ")", ":", "loss", "=", "th", ".", "FloatTensor", "(", "[", "0", "]", ")", "for", "i", "in", "range", "(", "1", ",", "self", ".", "moments", ")", ":", "mk_pred", "=", "th", ".", "mean", ...
Compute the loss model. :param pred: predicted Variable :param target: Target Variable :return: Loss
[ "Compute", "the", "loss", "model", "." ]
python
valid
sethmlarson/virtualbox-python
virtualbox/library.py
https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L22962-L22997
def set_ids(self, set_image_id, image_id, set_parent_id, parent_id): """Changes the UUID and parent UUID for a hard disk medium. in set_image_id of type bool Select whether a new image UUID is set or not. in image_id of type str New UUID for the image. If an empty strin...
[ "def", "set_ids", "(", "self", ",", "set_image_id", ",", "image_id", ",", "set_parent_id", ",", "parent_id", ")", ":", "if", "not", "isinstance", "(", "set_image_id", ",", "bool", ")", ":", "raise", "TypeError", "(", "\"set_image_id can only be an instance of type...
Changes the UUID and parent UUID for a hard disk medium. in set_image_id of type bool Select whether a new image UUID is set or not. in image_id of type str New UUID for the image. If an empty string is passed, then a new UUID is automatically created, provided that...
[ "Changes", "the", "UUID", "and", "parent", "UUID", "for", "a", "hard", "disk", "medium", "." ]
python
train
gitpython-developers/GitPython
git/refs/log.py
https://github.com/gitpython-developers/GitPython/blob/1f66e25c25cde2423917ee18c4704fff83b837d1/git/refs/log.py#L180-L186
def path(cls, ref): """ :return: string to absolute path at which the reflog of the given ref instance would be found. The path is not guaranteed to point to a valid file though. :param ref: SymbolicReference instance""" return osp.join(ref.repo.git_dir, "logs", t...
[ "def", "path", "(", "cls", ",", "ref", ")", ":", "return", "osp", ".", "join", "(", "ref", ".", "repo", ".", "git_dir", ",", "\"logs\"", ",", "to_native_path", "(", "ref", ".", "path", ")", ")" ]
:return: string to absolute path at which the reflog of the given ref instance would be found. The path is not guaranteed to point to a valid file though. :param ref: SymbolicReference instance
[ ":", "return", ":", "string", "to", "absolute", "path", "at", "which", "the", "reflog", "of", "the", "given", "ref", "instance", "would", "be", "found", ".", "The", "path", "is", "not", "guaranteed", "to", "point", "to", "a", "valid", "file", "though", ...
python
train
lemieuxl/pyGenClean
pyGenClean/LaTeX/merge_reports.py
https://github.com/lemieuxl/pyGenClean/blob/6173a48ccc0cf3a3bd711b1f2a1fa16248b8bf55/pyGenClean/LaTeX/merge_reports.py#L358-L381
def add_custom_options(parser): """Adds custom options to a parser. :param parser: the parser to which to add options. :type parser: argparse.ArgumentParser """ parser.add_argument("--report-title", type=str, metavar="TITLE", default="Genetic Data Clean Up", ...
[ "def", "add_custom_options", "(", "parser", ")", ":", "parser", ".", "add_argument", "(", "\"--report-title\"", ",", "type", "=", "str", ",", "metavar", "=", "\"TITLE\"", ",", "default", "=", "\"Genetic Data Clean Up\"", ",", "help", "=", "\"The report title. [def...
Adds custom options to a parser. :param parser: the parser to which to add options. :type parser: argparse.ArgumentParser
[ "Adds", "custom", "options", "to", "a", "parser", "." ]
python
train
econ-ark/HARK
HARK/ConsumptionSaving/ConsIndShockModel.py
https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsIndShockModel.py#L1627-L1650
def getStates(self): ''' Calculates updated values of normalized market resources and permanent income level for each agent. Uses pLvlNow, aNrmNow, PermShkNow, TranShkNow. Parameters ---------- None Returns ------- None ''' pLvlP...
[ "def", "getStates", "(", "self", ")", ":", "pLvlPrev", "=", "self", ".", "pLvlNow", "aNrmPrev", "=", "self", ".", "aNrmNow", "RfreeNow", "=", "self", ".", "getRfree", "(", ")", "# Calculate new states: normalized market resources and permanent income level", "self", ...
Calculates updated values of normalized market resources and permanent income level for each agent. Uses pLvlNow, aNrmNow, PermShkNow, TranShkNow. Parameters ---------- None Returns ------- None
[ "Calculates", "updated", "values", "of", "normalized", "market", "resources", "and", "permanent", "income", "level", "for", "each", "agent", ".", "Uses", "pLvlNow", "aNrmNow", "PermShkNow", "TranShkNow", "." ]
python
train
googlefonts/fontbakery
Lib/fontbakery/profiles/googlefonts.py
https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L1821-L1846
def com_google_fonts_check_metadata_valid_full_name_values(style, font_metadata, font_familynames, typographic_familynames): """METADATA.pb f...
[ "def", "com_google_fonts_check_metadata_valid_full_name_values", "(", "style", ",", "font_metadata", ",", "font_familynames", ",", "typographic_familynames", ")", ":", "from", "fontbakery", ".", "constants", "import", "RIBBI_STYLE_NAMES", "if", "style", "in", "RIBBI_STYLE_N...
METADATA.pb font.full_name field contains font name in right format?
[ "METADATA", ".", "pb", "font", ".", "full_name", "field", "contains", "font", "name", "in", "right", "format?" ]
python
train