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
DistrictDataLabs/yellowbrick
yellowbrick/classifier/rocauc.py
https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/classifier/rocauc.py#L296-L316
def finalize(self, **kwargs): """ Finalize executes any subclass-specific axes finalization steps. The user calls poof and poof calls finalize. Parameters ---------- kwargs: generic keyword arguments. """ # Set the title and add the legend self.s...
[ "def", "finalize", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# Set the title and add the legend", "self", ".", "set_title", "(", "'ROC Curves for {}'", ".", "format", "(", "self", ".", "name", ")", ")", "self", ".", "ax", ".", "legend", "(", "loc", ...
Finalize executes any subclass-specific axes finalization steps. The user calls poof and poof calls finalize. Parameters ---------- kwargs: generic keyword arguments.
[ "Finalize", "executes", "any", "subclass", "-", "specific", "axes", "finalization", "steps", ".", "The", "user", "calls", "poof", "and", "poof", "calls", "finalize", "." ]
python
train
maxalbert/tohu
tohu/v2/custom_generator.py
https://github.com/maxalbert/tohu/blob/43380162fadec99cdd5c5c3152dd6b7d3a9d39a8/tohu/v2/custom_generator.py#L195-L225
def add_new_reset_method(obj): """ Attach a new `reset()` method to `obj` which resets the internal seed generator of `obj` and then resets each of its constituent field generators found in `obj.field_gens`. """ # # Create and assign automatically generated reset() method # def ne...
[ "def", "add_new_reset_method", "(", "obj", ")", ":", "#", "# Create and assign automatically generated reset() method", "#", "def", "new_reset", "(", "self", ",", "seed", "=", "None", ")", ":", "logger", ".", "debug", "(", "f'[EEE] Inside automatically generated reset()...
Attach a new `reset()` method to `obj` which resets the internal seed generator of `obj` and then resets each of its constituent field generators found in `obj.field_gens`.
[ "Attach", "a", "new", "reset", "()", "method", "to", "obj", "which", "resets", "the", "internal", "seed", "generator", "of", "obj", "and", "then", "resets", "each", "of", "its", "constituent", "field", "generators", "found", "in", "obj", ".", "field_gens", ...
python
train
bjodah/pycompilation
pycompilation/util.py
https://github.com/bjodah/pycompilation/blob/43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18/pycompilation/util.py#L336-L353
def pyx_is_cplus(path): """ Inspect a Cython source file (.pyx) and look for comment line like: # distutils: language = c++ Returns True if such a file is present in the file, else False. """ for line in open(path, 'rt'): if line.startswith('#') and '=' in line: splitted = ...
[ "def", "pyx_is_cplus", "(", "path", ")", ":", "for", "line", "in", "open", "(", "path", ",", "'rt'", ")", ":", "if", "line", ".", "startswith", "(", "'#'", ")", "and", "'='", "in", "line", ":", "splitted", "=", "line", ".", "split", "(", "'='", "...
Inspect a Cython source file (.pyx) and look for comment line like: # distutils: language = c++ Returns True if such a file is present in the file, else False.
[ "Inspect", "a", "Cython", "source", "file", "(", ".", "pyx", ")", "and", "look", "for", "comment", "line", "like", ":" ]
python
train
archman/beamline
beamline/element.py
https://github.com/archman/beamline/blob/417bc5dc13e754bc89d246427984590fced64d07/beamline/element.py#L1066-L1162
def setDraw(self, p0=(0, 0), angle=0, mode='plain'): """ set element visualization drawing :param p0: start drawing position, (x,y) :param angle: angle [deg] between x-axis, angle is rotating from x-axis to be '+' or '-', '+': clockwise, '-': anticlockwise :param mode: artis...
[ "def", "setDraw", "(", "self", ",", "p0", "=", "(", "0", ",", "0", ")", ",", "angle", "=", "0", ",", "mode", "=", "'plain'", ")", ":", "sconf", "=", "self", ".", "getConfig", "(", "type", "=", "'simu'", ")", "if", "'l'", "in", "sconf", ":", "...
set element visualization drawing :param p0: start drawing position, (x,y) :param angle: angle [deg] between x-axis, angle is rotating from x-axis to be '+' or '-', '+': clockwise, '-': anticlockwise :param mode: artist mode, 'plain' or 'fancy', 'plain' by default
[ "set", "element", "visualization", "drawing", ":", "param", "p0", ":", "start", "drawing", "position", "(", "x", "y", ")", ":", "param", "angle", ":", "angle", "[", "deg", "]", "between", "x", "-", "axis", "angle", "is", "rotating", "from", "x", "-", ...
python
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/collections/util.py
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/collections/util.py#L13-L72
def dtype_reduce(dtype, level=0, depth=0): """ Try to reduce dtype up to a given level when it is possible dtype = [ ('vertex', [('x', 'f4'), ('y', 'f4'), ('z', 'f4')]), ('normal', [('x', 'f4'), ('y', 'f4'), ('z', 'f4')]), ('color', [('r', 'f4'), ('g', 'f4'), ('b', 'f4'),...
[ "def", "dtype_reduce", "(", "dtype", ",", "level", "=", "0", ",", "depth", "=", "0", ")", ":", "dtype", "=", "np", ".", "dtype", "(", "dtype", ")", "fields", "=", "dtype", ".", "fields", "# No fields", "if", "fields", "is", "None", ":", "if", "len"...
Try to reduce dtype up to a given level when it is possible dtype = [ ('vertex', [('x', 'f4'), ('y', 'f4'), ('z', 'f4')]), ('normal', [('x', 'f4'), ('y', 'f4'), ('z', 'f4')]), ('color', [('r', 'f4'), ('g', 'f4'), ('b', 'f4'), ('a', 'f4')])] level ...
[ "Try", "to", "reduce", "dtype", "up", "to", "a", "given", "level", "when", "it", "is", "possible" ]
python
train
ethereum/eth-account
eth_account/account.py
https://github.com/ethereum/eth-account/blob/335199b815ae34fea87f1523e2f29777fd52946e/eth_account/account.py#L137-L196
def encrypt(cls, private_key, password, kdf=None, iterations=None): ''' Creates a dictionary with an encrypted version of your private key. To import this keyfile into Ethereum clients like geth and parity: encode this dictionary with :func:`json.dumps` and save it to disk where your ...
[ "def", "encrypt", "(", "cls", ",", "private_key", ",", "password", ",", "kdf", "=", "None", ",", "iterations", "=", "None", ")", ":", "if", "isinstance", "(", "private_key", ",", "keys", ".", "PrivateKey", ")", ":", "key_bytes", "=", "private_key", ".", ...
Creates a dictionary with an encrypted version of your private key. To import this keyfile into Ethereum clients like geth and parity: encode this dictionary with :func:`json.dumps` and save it to disk where your client keeps key files. :param private_key: The raw private key :t...
[ "Creates", "a", "dictionary", "with", "an", "encrypted", "version", "of", "your", "private", "key", ".", "To", "import", "this", "keyfile", "into", "Ethereum", "clients", "like", "geth", "and", "parity", ":", "encode", "this", "dictionary", "with", ":", "fun...
python
train
theycallmeswift/BreakfastSerial
BreakfastSerial/util.py
https://github.com/theycallmeswift/BreakfastSerial/blob/cb6072f8c200838fc580afe1a04b80bae9509ce8/BreakfastSerial/util.py#L40-L55
def debounce(wait): """ Decorator that will postpone a functions execution until after wait seconds have elapsed since the last time it was invoked. """ def decorator(fn): def debounced(*args, **kwargs): def call_it(): fn(*args, **kwargs) try: ...
[ "def", "debounce", "(", "wait", ")", ":", "def", "decorator", "(", "fn", ")", ":", "def", "debounced", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "call_it", "(", ")", ":", "fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", ...
Decorator that will postpone a functions execution until after wait seconds have elapsed since the last time it was invoked.
[ "Decorator", "that", "will", "postpone", "a", "functions", "execution", "until", "after", "wait", "seconds", "have", "elapsed", "since", "the", "last", "time", "it", "was", "invoked", "." ]
python
train
scanny/python-pptx
pptx/table.py
https://github.com/scanny/python-pptx/blob/d6ab8234f8b03953d2f831ff9394b1852db34130/pptx/table.py#L260-L289
def merge(self, other_cell): """Create merged cell from this cell to *other_cell*. This cell and *other_cell* specify opposite corners of the merged cell range. Either diagonal of the cell region may be specified in either order, e.g. self=bottom-right, other_cell=top-left, etc. ...
[ "def", "merge", "(", "self", ",", "other_cell", ")", ":", "tc_range", "=", "TcRange", "(", "self", ".", "_tc", ",", "other_cell", ".", "_tc", ")", "if", "not", "tc_range", ".", "in_same_table", ":", "raise", "ValueError", "(", "'other_cell from different tab...
Create merged cell from this cell to *other_cell*. This cell and *other_cell* specify opposite corners of the merged cell range. Either diagonal of the cell region may be specified in either order, e.g. self=bottom-right, other_cell=top-left, etc. Raises |ValueError| if the specified r...
[ "Create", "merged", "cell", "from", "this", "cell", "to", "*", "other_cell", "*", "." ]
python
train
dev-pipeline/dev-pipeline-configure
lib/devpipeline_configure/load.py
https://github.com/dev-pipeline/dev-pipeline-configure/blob/26de2dd1b39d9a77d5417244f09319e7dce47495/lib/devpipeline_configure/load.py#L117-L142
def update_cache(force=False, cache_file=None): """ Load a build cache, updating it if necessary. A cache is considered outdated if any of its inputs have changed. Arguments force -- Consider a cache outdated regardless of whether its inputs have been modified. """ if not cach...
[ "def", "update_cache", "(", "force", "=", "False", ",", "cache_file", "=", "None", ")", ":", "if", "not", "cache_file", ":", "cache_file", "=", "find_config", "(", ")", "cache_config", "=", "devpipeline_configure", ".", "parser", ".", "read_config", "(", "ca...
Load a build cache, updating it if necessary. A cache is considered outdated if any of its inputs have changed. Arguments force -- Consider a cache outdated regardless of whether its inputs have been modified.
[ "Load", "a", "build", "cache", "updating", "it", "if", "necessary", "." ]
python
train
knorby/facterpy
facter/__init__.py
https://github.com/knorby/facterpy/blob/4799b020cc8c1bf69b2a828b90d6e20862771a33/facter/__init__.py#L104-L112
def has_cache(self): """Intended to be called before any call that might access the cache. If the cache is not selected, then returns False, otherwise the cache is build if needed and returns True.""" if not self.cache_enabled: return False if self._cache is None: ...
[ "def", "has_cache", "(", "self", ")", ":", "if", "not", "self", ".", "cache_enabled", ":", "return", "False", "if", "self", ".", "_cache", "is", "None", ":", "self", ".", "build_cache", "(", ")", "return", "True" ]
Intended to be called before any call that might access the cache. If the cache is not selected, then returns False, otherwise the cache is build if needed and returns True.
[ "Intended", "to", "be", "called", "before", "any", "call", "that", "might", "access", "the", "cache", ".", "If", "the", "cache", "is", "not", "selected", "then", "returns", "False", "otherwise", "the", "cache", "is", "build", "if", "needed", "and", "return...
python
train
ihmeuw/vivarium
src/vivarium/framework/results_writer.py
https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/results_writer.py#L30-L48
def add_sub_directory(self, key, path): """Adds a sub-directory to the results directory. Parameters ---------- key: str A look-up key for the directory path. path: str The relative path from the root of the results directory to the sub-directory. ...
[ "def", "add_sub_directory", "(", "self", ",", "key", ",", "path", ")", ":", "sub_dir_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "results_root", ",", "path", ")", "os", ".", "makedirs", "(", "sub_dir_path", ",", "exist_ok", "=", "True...
Adds a sub-directory to the results directory. Parameters ---------- key: str A look-up key for the directory path. path: str The relative path from the root of the results directory to the sub-directory. Returns ------- str: ...
[ "Adds", "a", "sub", "-", "directory", "to", "the", "results", "directory", "." ]
python
train
dereneaton/ipyrad
ipyrad/assemble/refmap.py
https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/refmap.py#L819-L890
def check_insert_size(data, sample): """ check mean insert size for this sample and update hackersonly.max_inner_mate_distance if need be. This value controls how far apart mate pairs can be to still be considered for bedtools merging downstream. """ ## pipe stats output to grep cmd1...
[ "def", "check_insert_size", "(", "data", ",", "sample", ")", ":", "## pipe stats output to grep", "cmd1", "=", "[", "ipyrad", ".", "bins", ".", "samtools", ",", "\"stats\"", ",", "sample", ".", "files", ".", "mapped_reads", "]", "cmd2", "=", "[", "\"grep\"",...
check mean insert size for this sample and update hackersonly.max_inner_mate_distance if need be. This value controls how far apart mate pairs can be to still be considered for bedtools merging downstream.
[ "check", "mean", "insert", "size", "for", "this", "sample", "and", "update", "hackersonly", ".", "max_inner_mate_distance", "if", "need", "be", ".", "This", "value", "controls", "how", "far", "apart", "mate", "pairs", "can", "be", "to", "still", "be", "consi...
python
valid
cdgriffith/Box
box.py
https://github.com/cdgriffith/Box/blob/5f09df824022127e7e335e3d993f7ddc1ed97fce/box.py#L1029-L1042
def int(self, item, default=None): """ Return value of key as an int :param item: key of value to transform :param default: value to return if item does not exist :return: int of value """ try: item = self.__getattr__(item) except AttributeError as er...
[ "def", "int", "(", "self", ",", "item", ",", "default", "=", "None", ")", ":", "try", ":", "item", "=", "self", ".", "__getattr__", "(", "item", ")", "except", "AttributeError", "as", "err", ":", "if", "default", "is", "not", "None", ":", "return", ...
Return value of key as an int :param item: key of value to transform :param default: value to return if item does not exist :return: int of value
[ "Return", "value", "of", "key", "as", "an", "int" ]
python
train
openergy/oplus
oplus/epm/queryset.py
https://github.com/openergy/oplus/blob/f095868d1990c1d126e906ada6acbab26348b3d3/oplus/epm/queryset.py#L94-L108
def select(self, filter_by=None): """ Parameters ---------- filter_by: callable, default None Callable must take one argument (a record of queryset), and return True to keep record, or False to skip it. Example : .select(lambda x: x.name == "my_name"). ...
[ "def", "select", "(", "self", ",", "filter_by", "=", "None", ")", ":", "iterator", "=", "self", ".", "_records", "if", "filter_by", "is", "None", "else", "filter", "(", "filter_by", ",", "self", ".", "_records", ")", "return", "Queryset", "(", "self", ...
Parameters ---------- filter_by: callable, default None Callable must take one argument (a record of queryset), and return True to keep record, or False to skip it. Example : .select(lambda x: x.name == "my_name"). If None, records are not filtered. Returns ...
[ "Parameters", "----------", "filter_by", ":", "callable", "default", "None", "Callable", "must", "take", "one", "argument", "(", "a", "record", "of", "queryset", ")", "and", "return", "True", "to", "keep", "record", "or", "False", "to", "skip", "it", ".", ...
python
test
saltstack/salt
salt/roster/terraform.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/roster/terraform.py#L99-L116
def _add_ssh_key(ret): ''' Setups the salt-ssh minion to be accessed with salt-ssh default key ''' priv = None if __opts__.get('ssh_use_home_key') and os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')): priv = os.path.expanduser('~/.ssh/id_rsa') else: priv = __opts__.get( ...
[ "def", "_add_ssh_key", "(", "ret", ")", ":", "priv", "=", "None", "if", "__opts__", ".", "get", "(", "'ssh_use_home_key'", ")", "and", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "expanduser", "(", "'~/.ssh/id_rsa'", ")", ")", ":", ...
Setups the salt-ssh minion to be accessed with salt-ssh default key
[ "Setups", "the", "salt", "-", "ssh", "minion", "to", "be", "accessed", "with", "salt", "-", "ssh", "default", "key" ]
python
train
honeynet/beeswarm
beeswarm/drones/drone.py
https://github.com/honeynet/beeswarm/blob/db51ea0bc29f631c3e3b5312b479ac9d5e31079a/beeswarm/drones/drone.py#L85-L104
def start(self): """ Starts services. """ cert_path = os.path.join(self.work_dir, 'certificates') public_keys_dir = os.path.join(cert_path, 'public_keys') private_keys_dir = os.path.join(cert_path, 'private_keys') client_secret_file = os.path.join(private_keys_dir, "client.key")...
[ "def", "start", "(", "self", ")", ":", "cert_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "work_dir", ",", "'certificates'", ")", "public_keys_dir", "=", "os", ".", "path", ".", "join", "(", "cert_path", ",", "'public_keys'", ")", "pri...
Starts services.
[ "Starts", "services", "." ]
python
train
saltstack/salt
salt/minion.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/minion.py#L773-L798
def _return_retry_timer(self): ''' Based on the minion configuration, either return a randomized timer or just return the value of the return_retry_timer. ''' msg = 'Minion return retry timer set to %s seconds' if self.opts.get('return_retry_timer_max'): try: ...
[ "def", "_return_retry_timer", "(", "self", ")", ":", "msg", "=", "'Minion return retry timer set to %s seconds'", "if", "self", ".", "opts", ".", "get", "(", "'return_retry_timer_max'", ")", ":", "try", ":", "random_retry", "=", "randint", "(", "self", ".", "opt...
Based on the minion configuration, either return a randomized timer or just return the value of the return_retry_timer.
[ "Based", "on", "the", "minion", "configuration", "either", "return", "a", "randomized", "timer", "or", "just", "return", "the", "value", "of", "the", "return_retry_timer", "." ]
python
train
SeleniumHQ/selenium
py/selenium/webdriver/remote/webelement.py
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webelement.py#L545-L554
def size(self): """The size of the element.""" size = {} if self._w3c: size = self._execute(Command.GET_ELEMENT_RECT)['value'] else: size = self._execute(Command.GET_ELEMENT_SIZE)['value'] new_size = {"height": size["height"], "width": ...
[ "def", "size", "(", "self", ")", ":", "size", "=", "{", "}", "if", "self", ".", "_w3c", ":", "size", "=", "self", ".", "_execute", "(", "Command", ".", "GET_ELEMENT_RECT", ")", "[", "'value'", "]", "else", ":", "size", "=", "self", ".", "_execute",...
The size of the element.
[ "The", "size", "of", "the", "element", "." ]
python
train
mitsei/dlkit
dlkit/records/assessment/clix/assessment_offered_records.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/records/assessment/clix/assessment_offered_records.py#L97-L103
def clear_n_of_m(self): """stub""" if (self.get_n_of_m_metadata().is_read_only() or self.get_n_of_m_metadata().is_required()): raise NoAccess() self.my_osid_object_form._my_map['nOfM'] = \ int(self._n_of_m_metadata['default_object_values'][0])
[ "def", "clear_n_of_m", "(", "self", ")", ":", "if", "(", "self", ".", "get_n_of_m_metadata", "(", ")", ".", "is_read_only", "(", ")", "or", "self", ".", "get_n_of_m_metadata", "(", ")", ".", "is_required", "(", ")", ")", ":", "raise", "NoAccess", "(", ...
stub
[ "stub" ]
python
train
xtuml/pyxtuml
xtuml/meta.py
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/meta.py#L1210-L1243
def define_association(self, rel_id, source_kind, source_keys, source_many, source_conditional, source_phrase, target_kind, target_keys, target_many, target_conditional, target_phrase): ''' Define and return an associatio...
[ "def", "define_association", "(", "self", ",", "rel_id", ",", "source_kind", ",", "source_keys", ",", "source_many", ",", "source_conditional", ",", "source_phrase", ",", "target_kind", ",", "target_keys", ",", "target_many", ",", "target_conditional", ",", "target_...
Define and return an association from one kind of class (the source kind) to some other kind of class (the target kind).
[ "Define", "and", "return", "an", "association", "from", "one", "kind", "of", "class", "(", "the", "source", "kind", ")", "to", "some", "other", "kind", "of", "class", "(", "the", "target", "kind", ")", "." ]
python
test
sashs/filebytes
filebytes/pe.py
https://github.com/sashs/filebytes/blob/41ee009832aba19603f33d1fd3483b84d6684ebf/filebytes/pe.py#L689-L699
def __parseThunkData(self, thunk,importSection): """Parses the data of a thunk and sets the data""" offset = to_offset(thunk.header.AddressOfData, importSection) if 0xf0000000 & thunk.header.AddressOfData == 0x80000000: thunk.ordinal = thunk.header.AddressOfData & 0x0fffffff ...
[ "def", "__parseThunkData", "(", "self", ",", "thunk", ",", "importSection", ")", ":", "offset", "=", "to_offset", "(", "thunk", ".", "header", ".", "AddressOfData", ",", "importSection", ")", "if", "0xf0000000", "&", "thunk", ".", "header", ".", "AddressOfDa...
Parses the data of a thunk and sets the data
[ "Parses", "the", "data", "of", "a", "thunk", "and", "sets", "the", "data" ]
python
train
cisco-sas/kitty
kitty/model/low_level/aliases.py
https://github.com/cisco-sas/kitty/blob/cb0760989dcdfe079e43ac574d872d0b18953a32/kitty/model/low_level/aliases.py#L214-L219
def Md5(depends_on, encoder=ENC_STR_DEFAULT, fuzzable=False, name=None): ''' :rtype: :class:`~kitty.model.low_level.calculated.Hash` :return: MD5 hash field ''' return Hash(depends_on=depends_on, algorithm='md5', encoder=encoder, fuzzable=fuzzable, name=name)
[ "def", "Md5", "(", "depends_on", ",", "encoder", "=", "ENC_STR_DEFAULT", ",", "fuzzable", "=", "False", ",", "name", "=", "None", ")", ":", "return", "Hash", "(", "depends_on", "=", "depends_on", ",", "algorithm", "=", "'md5'", ",", "encoder", "=", "enco...
:rtype: :class:`~kitty.model.low_level.calculated.Hash` :return: MD5 hash field
[ ":", "rtype", ":", ":", "class", ":", "~kitty", ".", "model", ".", "low_level", ".", "calculated", ".", "Hash", ":", "return", ":", "MD5", "hash", "field" ]
python
train
google/grr
grr/server/grr_response_server/notification.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/notification.py#L182-L196
def _NotifyLegacy(username, notification_type, message, object_reference): """Schedules a legacy AFF4 user notification.""" try: with aff4.FACTORY.Open( aff4.ROOT_URN.Add("users").Add(username), aff4_type=aff4_users.GRRUser, mode="rw") as fd: args = _MapLegacyArgs(notification_ty...
[ "def", "_NotifyLegacy", "(", "username", ",", "notification_type", ",", "message", ",", "object_reference", ")", ":", "try", ":", "with", "aff4", ".", "FACTORY", ".", "Open", "(", "aff4", ".", "ROOT_URN", ".", "Add", "(", "\"users\"", ")", ".", "Add", "(...
Schedules a legacy AFF4 user notification.
[ "Schedules", "a", "legacy", "AFF4", "user", "notification", "." ]
python
train
fjwCode/cerium
cerium/androiddriver.py
https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L249-L253
def push(self, local: _PATH = 'LICENSE', remote: _PATH = '/sdcard/LICENSE') -> None: '''Copy local files/directories to device.''' if not os.path.exists(local): raise FileNotFoundError(f'Local {local!r} does not exist.') self._execute('-s', self.device_sn, 'push', local, remote)
[ "def", "push", "(", "self", ",", "local", ":", "_PATH", "=", "'LICENSE'", ",", "remote", ":", "_PATH", "=", "'/sdcard/LICENSE'", ")", "->", "None", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "local", ")", ":", "raise", "FileNotFoundError"...
Copy local files/directories to device.
[ "Copy", "local", "files", "/", "directories", "to", "device", "." ]
python
train
thebjorn/pydeps
pydeps/tools/pydeps2requirements.py
https://github.com/thebjorn/pydeps/blob/1e6715b7bea47a40e8042821b57937deaaa0fdc3/pydeps/tools/pydeps2requirements.py#L58-L66
def main(): """Cli entrypoint. """ if len(sys.argv) == 2: fname = sys.argv[1] data = json.load(open(fname, 'rb')) else: data = json.loads(sys.stdin.read()) print(pydeps2reqs(data))
[ "def", "main", "(", ")", ":", "if", "len", "(", "sys", ".", "argv", ")", "==", "2", ":", "fname", "=", "sys", ".", "argv", "[", "1", "]", "data", "=", "json", ".", "load", "(", "open", "(", "fname", ",", "'rb'", ")", ")", "else", ":", "data...
Cli entrypoint.
[ "Cli", "entrypoint", "." ]
python
train
the01/python-paps
paps/si/app/sensor.py
https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensor.py#L272-L291
def _receiving(self): """ Receiving loop :rtype: None """ while self._is_running: try: rlist, wlist, xlist = select.select( self._listening, [], [], self._select_timeout ) except: ...
[ "def", "_receiving", "(", "self", ")", ":", "while", "self", ".", "_is_running", ":", "try", ":", "rlist", ",", "wlist", ",", "xlist", "=", "select", ".", "select", "(", "self", ".", "_listening", ",", "[", "]", ",", "[", "]", ",", "self", ".", "...
Receiving loop :rtype: None
[ "Receiving", "loop" ]
python
train
saltstack/salt
salt/fileserver/__init__.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/__init__.py#L893-L906
def send(self, load, tries=None, timeout=None, raw=False): # pylint: disable=unused-argument ''' Emulate the channel send method, the tries and timeout are not used ''' if 'cmd' not in load: log.error('Malformed request, no cmd: %s', load) return {} cmd =...
[ "def", "send", "(", "self", ",", "load", ",", "tries", "=", "None", ",", "timeout", "=", "None", ",", "raw", "=", "False", ")", ":", "# pylint: disable=unused-argument", "if", "'cmd'", "not", "in", "load", ":", "log", ".", "error", "(", "'Malformed reque...
Emulate the channel send method, the tries and timeout are not used
[ "Emulate", "the", "channel", "send", "method", "the", "tries", "and", "timeout", "are", "not", "used" ]
python
train
mitsei/dlkit
dlkit/json_/learning/objects.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/learning/objects.py#L1290-L1302
def clear_completion(self): """Clears the completion. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.grading.GradeSystemFo...
[ "def", "clear_completion", "(", "self", ")", ":", "# Implemented from template for osid.grading.GradeSystemForm.clear_lowest_numeric_score", "if", "(", "self", ".", "get_completion_metadata", "(", ")", ".", "is_read_only", "(", ")", "or", "self", ".", "get_completion_metada...
Clears the completion. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.*
[ "Clears", "the", "completion", "." ]
python
train
pantsbuild/pex
pex/util.py
https://github.com/pantsbuild/pex/blob/87b2129d860250d3b9edce75b9cb62f9789ee521/pex/util.py#L108-L112
def update_hash(cls, filelike, digest): """Update the digest of a single file in a memory-efficient manner.""" block_size = digest.block_size * 1024 for chunk in iter(lambda: filelike.read(block_size), b''): digest.update(chunk)
[ "def", "update_hash", "(", "cls", ",", "filelike", ",", "digest", ")", ":", "block_size", "=", "digest", ".", "block_size", "*", "1024", "for", "chunk", "in", "iter", "(", "lambda", ":", "filelike", ".", "read", "(", "block_size", ")", ",", "b''", ")",...
Update the digest of a single file in a memory-efficient manner.
[ "Update", "the", "digest", "of", "a", "single", "file", "in", "a", "memory", "-", "efficient", "manner", "." ]
python
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L1676-L1728
def rel_path(self, other): """Return a path to "other" relative to this directory. """ # This complicated and expensive method, which constructs relative # paths between arbitrary Node.FS objects, is no longer used # by SCons itself. It was introduced to store dependency paths ...
[ "def", "rel_path", "(", "self", ",", "other", ")", ":", "# This complicated and expensive method, which constructs relative", "# paths between arbitrary Node.FS objects, is no longer used", "# by SCons itself. It was introduced to store dependency paths", "# in .sconsign files relative to the...
Return a path to "other" relative to this directory.
[ "Return", "a", "path", "to", "other", "relative", "to", "this", "directory", "." ]
python
train
pyviz/holoviews
holoviews/core/data/multipath.py
https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/data/multipath.py#L172-L176
def select_paths(cls, dataset, selection): """ Allows selecting paths with usual NumPy slicing index. """ return [s[0] for s in np.array([{0: p} for p in dataset.data])[selection]]
[ "def", "select_paths", "(", "cls", ",", "dataset", ",", "selection", ")", ":", "return", "[", "s", "[", "0", "]", "for", "s", "in", "np", ".", "array", "(", "[", "{", "0", ":", "p", "}", "for", "p", "in", "dataset", ".", "data", "]", ")", "["...
Allows selecting paths with usual NumPy slicing index.
[ "Allows", "selecting", "paths", "with", "usual", "NumPy", "slicing", "index", "." ]
python
train
osrg/ryu
ryu/services/protocols/bgp/api/rtconf.py
https://github.com/osrg/ryu/blob/6f906e72c92e10bd0264c9b91a2f7bb85b97780c/ryu/services/protocols/bgp/api/rtconf.py#L139-L144
def set_neighbor_in_filter(neigh_ip_address, filters): """Returns a neighbor in_filter for given ip address if exists.""" core = CORE_MANAGER.get_core_service() peer = core.peer_manager.get_by_addr(neigh_ip_address) peer.in_filters = filters return True
[ "def", "set_neighbor_in_filter", "(", "neigh_ip_address", ",", "filters", ")", ":", "core", "=", "CORE_MANAGER", ".", "get_core_service", "(", ")", "peer", "=", "core", ".", "peer_manager", ".", "get_by_addr", "(", "neigh_ip_address", ")", "peer", ".", "in_filte...
Returns a neighbor in_filter for given ip address if exists.
[ "Returns", "a", "neighbor", "in_filter", "for", "given", "ip", "address", "if", "exists", "." ]
python
train
Dallinger/Dallinger
dallinger/nodes.py
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/nodes.py#L63-L66
def create_information(self): """Create new infos on demand.""" info = self._info_type()(origin=self, contents=self._contents()) return info
[ "def", "create_information", "(", "self", ")", ":", "info", "=", "self", ".", "_info_type", "(", ")", "(", "origin", "=", "self", ",", "contents", "=", "self", ".", "_contents", "(", ")", ")", "return", "info" ]
Create new infos on demand.
[ "Create", "new", "infos", "on", "demand", "." ]
python
train
blockstack-packages/blockstack-gpg
blockstack_gpg/gpg.py
https://github.com/blockstack-packages/blockstack-gpg/blob/e4d51e4e51678d9b946596ca9dec53e2d78c8710/blockstack_gpg/gpg.py#L105-L113
def get_gpg_home( appname, config_dir=None ): """ Get the GPG keyring directory for a particular application. Return the path. """ assert is_valid_appname(appname) config_dir = get_config_dir( config_dir ) path = os.path.join( config_dir, "gpgkeys", appname ) return path
[ "def", "get_gpg_home", "(", "appname", ",", "config_dir", "=", "None", ")", ":", "assert", "is_valid_appname", "(", "appname", ")", "config_dir", "=", "get_config_dir", "(", "config_dir", ")", "path", "=", "os", ".", "path", ".", "join", "(", "config_dir", ...
Get the GPG keyring directory for a particular application. Return the path.
[ "Get", "the", "GPG", "keyring", "directory", "for", "a", "particular", "application", ".", "Return", "the", "path", "." ]
python
train
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_policer.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_policer.py#L121-L133
def police_priority_map_conform_map_pri7_conform(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") police_priority_map = ET.SubElement(config, "police-priority-map", xmlns="urn:brocade.com:mgmt:brocade-policer") name_key = ET.SubElement(police_priority_map...
[ "def", "police_priority_map_conform_map_pri7_conform", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "police_priority_map", "=", "ET", ".", "SubElement", "(", "config", ",", "\"police-priority-map\"", ...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
Unidata/MetPy
metpy/plots/_util.py
https://github.com/Unidata/MetPy/blob/16f68a94919b9a82dcf9cada2169cf039129e67b/metpy/plots/_util.py#L206-L282
def convert_gempak_color(c, style='psc'): """Convert GEMPAK color numbers into corresponding Matplotlib colors. Takes a sequence of GEMPAK color numbers and turns them into equivalent Matplotlib colors. Various GEMPAK quirks are respected, such as treating negative values as equivalent to 0. Param...
[ "def", "convert_gempak_color", "(", "c", ",", "style", "=", "'psc'", ")", ":", "def", "normalize", "(", "x", ")", ":", "\"\"\"Transform input x to an int in range 0 to 31 consistent with GEMPAK color quirks.\"\"\"", "x", "=", "int", "(", "x", ")", "if", "x", "<", ...
Convert GEMPAK color numbers into corresponding Matplotlib colors. Takes a sequence of GEMPAK color numbers and turns them into equivalent Matplotlib colors. Various GEMPAK quirks are respected, such as treating negative values as equivalent to 0. Parameters ---------- c : int or sequence of i...
[ "Convert", "GEMPAK", "color", "numbers", "into", "corresponding", "Matplotlib", "colors", "." ]
python
train
rossant/ipymd
ipymd/core/format_manager.py
https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/core/format_manager.py#L87-L103
def register_entrypoints(self): """Look through the `setup_tools` `entry_points` and load all of the formats. """ for spec in iter_entry_points(self.entry_point_group): format_properties = {"name": spec.name} try: format_properties.update(spec.l...
[ "def", "register_entrypoints", "(", "self", ")", ":", "for", "spec", "in", "iter_entry_points", "(", "self", ".", "entry_point_group", ")", ":", "format_properties", "=", "{", "\"name\"", ":", "spec", ".", "name", "}", "try", ":", "format_properties", ".", "...
Look through the `setup_tools` `entry_points` and load all of the formats.
[ "Look", "through", "the", "setup_tools", "entry_points", "and", "load", "all", "of", "the", "formats", "." ]
python
train
saltstack/salt
salt/modules/vboxmanage.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vboxmanage.py#L139-L152
def start(name): ''' Start a VM CLI Example: .. code-block:: bash salt '*' vboxmanage.start my_vm ''' ret = {} cmd = '{0} startvm {1}'.format(vboxcmd(), name) ret = salt.modules.cmdmod.run(cmd).splitlines() return ret
[ "def", "start", "(", "name", ")", ":", "ret", "=", "{", "}", "cmd", "=", "'{0} startvm {1}'", ".", "format", "(", "vboxcmd", "(", ")", ",", "name", ")", "ret", "=", "salt", ".", "modules", ".", "cmdmod", ".", "run", "(", "cmd", ")", ".", "splitli...
Start a VM CLI Example: .. code-block:: bash salt '*' vboxmanage.start my_vm
[ "Start", "a", "VM" ]
python
train
svven/summary
summarize.py
https://github.com/svven/summary/blob/3a6c43d2da08a7452f6b76d1813aa70ba36b8a54/summarize.py#L6-L23
def render(template, **kwargs): """ Renders the HTML containing provided summaries. The summary has to be an instance of summary.Summary, or at least contain similar properties: title, image, url, description and collections: titles, images, descriptions. """ import jinja2 imp...
[ "def", "render", "(", "template", ",", "*", "*", "kwargs", ")", ":", "import", "jinja2", "import", "os", ".", "path", "as", "path", "searchpath", "=", "path", ".", "join", "(", "path", ".", "dirname", "(", "__file__", ")", ",", "\"templates\"", ")", ...
Renders the HTML containing provided summaries. The summary has to be an instance of summary.Summary, or at least contain similar properties: title, image, url, description and collections: titles, images, descriptions.
[ "Renders", "the", "HTML", "containing", "provided", "summaries", ".", "The", "summary", "has", "to", "be", "an", "instance", "of", "summary", ".", "Summary", "or", "at", "least", "contain", "similar", "properties", ":", "title", "image", "url", "description", ...
python
train
mdickinson/bigfloat
bigfloat/core.py
https://github.com/mdickinson/bigfloat/blob/e5fdd1048615191ed32a2b7460e14b3b3ff24662/bigfloat/core.py#L1156-L1163
def divmod(x, y, context=None): """ Return the pair (floordiv(x, y, context), mod(x, y, context)). Semantics for negative inputs match those of Python's divmod function. """ return floordiv(x, y, context=context), mod(x, y, context=context)
[ "def", "divmod", "(", "x", ",", "y", ",", "context", "=", "None", ")", ":", "return", "floordiv", "(", "x", ",", "y", ",", "context", "=", "context", ")", ",", "mod", "(", "x", ",", "y", ",", "context", "=", "context", ")" ]
Return the pair (floordiv(x, y, context), mod(x, y, context)). Semantics for negative inputs match those of Python's divmod function.
[ "Return", "the", "pair", "(", "floordiv", "(", "x", "y", "context", ")", "mod", "(", "x", "y", "context", "))", "." ]
python
train
SHDShim/pytheos
pytheos/eqn_jamieson.py
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_jamieson.py#L30-L59
def jamieson_pst(v, v0, c0, s, gamma0, q, theta0, n, z, mass, c_v, three_r=3. * constants.R, t_ref=300.): """ calculate static pressure at 300 K from Hugoniot data using the constq formulation :param v: unit-cell volume in A^3 :param v0: unit-cell volume in A^3 at 1 bar :param ...
[ "def", "jamieson_pst", "(", "v", ",", "v0", ",", "c0", ",", "s", ",", "gamma0", ",", "q", ",", "theta0", ",", "n", ",", "z", ",", "mass", ",", "c_v", ",", "three_r", "=", "3.", "*", "constants", ".", "R", ",", "t_ref", "=", "300.", ")", ":", ...
calculate static pressure at 300 K from Hugoniot data using the constq formulation :param v: unit-cell volume in A^3 :param v0: unit-cell volume in A^3 at 1 bar :param c0: velocity at 1 bar in km/s :param s: slope of the velocity change :param gamma0: Gruneisen parameter at 1 bar :param q: ...
[ "calculate", "static", "pressure", "at", "300", "K", "from", "Hugoniot", "data", "using", "the", "constq", "formulation" ]
python
train
pytorch/ignite
ignite/engine/engine.py
https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/engine/engine.py#L326-L361
def run(self, data, max_epochs=1): """Runs the process_function over the passed data. Args: data (Iterable): Collection of batches allowing repeated iteration (e.g., list or `DataLoader`). max_epochs (int, optional): max epochs to run for (default: 1). Returns: ...
[ "def", "run", "(", "self", ",", "data", ",", "max_epochs", "=", "1", ")", ":", "self", ".", "state", "=", "State", "(", "dataloader", "=", "data", ",", "epoch", "=", "0", ",", "max_epochs", "=", "max_epochs", ",", "metrics", "=", "{", "}", ")", "...
Runs the process_function over the passed data. Args: data (Iterable): Collection of batches allowing repeated iteration (e.g., list or `DataLoader`). max_epochs (int, optional): max epochs to run for (default: 1). Returns: State: output state.
[ "Runs", "the", "process_function", "over", "the", "passed", "data", "." ]
python
train
readbeyond/aeneas
aeneas/executejob.py
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executejob.py#L298-L316
def clean(self, remove_working_directory=True): """ Remove the temporary directory. If ``remove_working_directory`` is ``True`` remove the working directory as well, otherwise just remove the temporary directory. :param bool remove_working_directory: if ``True``, remove ...
[ "def", "clean", "(", "self", ",", "remove_working_directory", "=", "True", ")", ":", "if", "remove_working_directory", "is", "not", "None", ":", "self", ".", "log", "(", "u\"Removing working directory... \"", ")", "gf", ".", "delete_directory", "(", "self", ".",...
Remove the temporary directory. If ``remove_working_directory`` is ``True`` remove the working directory as well, otherwise just remove the temporary directory. :param bool remove_working_directory: if ``True``, remove the working directory ...
[ "Remove", "the", "temporary", "directory", ".", "If", "remove_working_directory", "is", "True", "remove", "the", "working", "directory", "as", "well", "otherwise", "just", "remove", "the", "temporary", "directory", "." ]
python
train
jaraco/jaraco.ui
jaraco/ui/progress.py
https://github.com/jaraco/jaraco.ui/blob/10e844c03f3afb3d37bd5d727ba9334af2547fcf/jaraco/ui/progress.py#L135-L153
def countdown(template, duration=datetime.timedelta(seconds=5)): """ Do a countdown for duration, printing the template (which may accept one positional argument). Template should be something like ``countdown complete in {} seconds.`` """ now = datetime.datetime.now() deadline = now + duration remaining = dead...
[ "def", "countdown", "(", "template", ",", "duration", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "5", ")", ")", ":", "now", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "deadline", "=", "now", "+", "duration", "remaining", "=", ...
Do a countdown for duration, printing the template (which may accept one positional argument). Template should be something like ``countdown complete in {} seconds.``
[ "Do", "a", "countdown", "for", "duration", "printing", "the", "template", "(", "which", "may", "accept", "one", "positional", "argument", ")", ".", "Template", "should", "be", "something", "like", "countdown", "complete", "in", "{}", "seconds", "." ]
python
train
ThreatConnect-Inc/tcex
tcex/tcex_ti/tcex_ti_tc_request.py
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/tcex_ti_tc_request.py#L49-L63
def delete(self, main_type, sub_type, unique_id, owner=None): """ Deletes the Indicator/Group/Victim or Security Label Args: main_type: sub_type: unique_id: owner: """ params = {'owner': owner} if owner else {} if not sub_ty...
[ "def", "delete", "(", "self", ",", "main_type", ",", "sub_type", ",", "unique_id", ",", "owner", "=", "None", ")", ":", "params", "=", "{", "'owner'", ":", "owner", "}", "if", "owner", "else", "{", "}", "if", "not", "sub_type", ":", "url", "=", "'/...
Deletes the Indicator/Group/Victim or Security Label Args: main_type: sub_type: unique_id: owner:
[ "Deletes", "the", "Indicator", "/", "Group", "/", "Victim", "or", "Security", "Label", "Args", ":", "main_type", ":", "sub_type", ":", "unique_id", ":", "owner", ":" ]
python
train
xtuml/pyxtuml
xtuml/persist.py
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/persist.py#L32-L57
def serialize_value(value, ty): ''' Serialize a value from an xtuml metamodel instance. ''' ty = ty.upper() null_value = { 'BOOLEAN' : False, 'INTEGER' : 0, 'REAL' : 0.0, 'STRING' : '', 'UNIQUE_ID' : 0 } transfer_fn = { 'B...
[ "def", "serialize_value", "(", "value", ",", "ty", ")", ":", "ty", "=", "ty", ".", "upper", "(", ")", "null_value", "=", "{", "'BOOLEAN'", ":", "False", ",", "'INTEGER'", ":", "0", ",", "'REAL'", ":", "0.0", ",", "'STRING'", ":", "''", ",", "'UNIQU...
Serialize a value from an xtuml metamodel instance.
[ "Serialize", "a", "value", "from", "an", "xtuml", "metamodel", "instance", "." ]
python
test
CityOfZion/neo-python-core
neocore/Cryptography/MerkleTree.py
https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/MerkleTree.py#L70-L101
def __Build(leaves): """ Build the merkle tree. Args: leaves (list): items are of type MerkleTreeNode. Returns: MerkleTreeNode: the root node. """ if len(leaves) < 1: raise Exception('Leaves must have length') if len(leaves) =...
[ "def", "__Build", "(", "leaves", ")", ":", "if", "len", "(", "leaves", ")", "<", "1", ":", "raise", "Exception", "(", "'Leaves must have length'", ")", "if", "len", "(", "leaves", ")", "==", "1", ":", "return", "leaves", "[", "0", "]", "num_parents", ...
Build the merkle tree. Args: leaves (list): items are of type MerkleTreeNode. Returns: MerkleTreeNode: the root node.
[ "Build", "the", "merkle", "tree", "." ]
python
train
mithro/python-datetime-tz
datetime_tz/__init__.py
https://github.com/mithro/python-datetime-tz/blob/3c682d003f8b28e39f0c096773e471aeb68e6bbb/datetime_tz/__init__.py#L714-L718
def utcnow(cls): """Return a new datetime representing UTC day and time.""" obj = datetime.datetime.utcnow() obj = cls(obj, tzinfo=pytz.utc) return obj
[ "def", "utcnow", "(", "cls", ")", ":", "obj", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "obj", "=", "cls", "(", "obj", ",", "tzinfo", "=", "pytz", ".", "utc", ")", "return", "obj" ]
Return a new datetime representing UTC day and time.
[ "Return", "a", "new", "datetime", "representing", "UTC", "day", "and", "time", "." ]
python
train
wbond/asn1crypto
asn1crypto/_iri.py
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/_iri.py#L37-L117
def iri_to_uri(value, normalize=False): """ Encodes a unicode IRI into an ASCII byte string URI :param value: A unicode string of an IRI :param normalize: A bool that controls URI normalization :return: A byte string of the ASCII-encoded URI """ if not isinstance(...
[ "def", "iri_to_uri", "(", "value", ",", "normalize", "=", "False", ")", ":", "if", "not", "isinstance", "(", "value", ",", "str_cls", ")", ":", "raise", "TypeError", "(", "unwrap", "(", "'''\n value must be a unicode string, not %s\n '''", ",",...
Encodes a unicode IRI into an ASCII byte string URI :param value: A unicode string of an IRI :param normalize: A bool that controls URI normalization :return: A byte string of the ASCII-encoded URI
[ "Encodes", "a", "unicode", "IRI", "into", "an", "ASCII", "byte", "string", "URI" ]
python
train
llllllllll/codetransformer
codetransformer/utils/pretty.py
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/utils/pretty.py#L275-L304
def display(text, mode='exec', file=None): """ Show `text`, rendered as AST and as Bytecode. Parameters ---------- text : str Text of Python code to render. mode : {'exec', 'eval'}, optional Mode for `ast.parse` and `compile`. Default is 'exec'. file : None or file-like obj...
[ "def", "display", "(", "text", ",", "mode", "=", "'exec'", ",", "file", "=", "None", ")", ":", "if", "file", "is", "None", ":", "file", "=", "sys", ".", "stdout", "ast_section", "=", "StringIO", "(", ")", "a", "(", "text", ",", "mode", "=", "mode...
Show `text`, rendered as AST and as Bytecode. Parameters ---------- text : str Text of Python code to render. mode : {'exec', 'eval'}, optional Mode for `ast.parse` and `compile`. Default is 'exec'. file : None or file-like object, optional File to use to print output. If ...
[ "Show", "text", "rendered", "as", "AST", "and", "as", "Bytecode", "." ]
python
train
PlaidWeb/Pushl
pushl/entries.py
https://github.com/PlaidWeb/Pushl/blob/5ea92275c37a6c1989e3d5f53e26c6e0ebfb9a8c/pushl/entries.py#L99-L105
def get_targets(self, config): """ Given an Entry object, return all of the outgoing links. """ return {urllib.parse.urljoin(self.url, attrs['href']) for attrs in self._targets if self._check_rel(attrs, config.rel_whitelist, config.rel_blacklist) and self...
[ "def", "get_targets", "(", "self", ",", "config", ")", ":", "return", "{", "urllib", ".", "parse", ".", "urljoin", "(", "self", ".", "url", ",", "attrs", "[", "'href'", "]", ")", "for", "attrs", "in", "self", ".", "_targets", "if", "self", ".", "_c...
Given an Entry object, return all of the outgoing links.
[ "Given", "an", "Entry", "object", "return", "all", "of", "the", "outgoing", "links", "." ]
python
train
saltstack/salt
salt/cloud/clouds/gce.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/gce.py#L877-L909
def show_subnetwork(kwargs=None, call=None): ''' ... versionadded:: 2017.7.0 Show details of an existing GCE Subnetwork. Must specify name and region. CLI Example: .. code-block:: bash salt-cloud -f show_subnetwork gce name=mysubnet region=us-west1 ''' if call != 'function': ...
[ "def", "show_subnetwork", "(", "kwargs", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'function'", ":", "raise", "SaltCloudSystemExit", "(", "'The show_subnetwork function must be called with -f or --function.'", ")", "if", "not", "kwargs", ...
... versionadded:: 2017.7.0 Show details of an existing GCE Subnetwork. Must specify name and region. CLI Example: .. code-block:: bash salt-cloud -f show_subnetwork gce name=mysubnet region=us-west1
[ "...", "versionadded", "::", "2017", ".", "7", ".", "0", "Show", "details", "of", "an", "existing", "GCE", "Subnetwork", ".", "Must", "specify", "name", "and", "region", "." ]
python
train
chimera0/accel-brain-code
Reinforcement-Learning/pyqlearning/annealingmodel/costfunctionable/greedy_q_learning_cost.py
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/pyqlearning/annealingmodel/costfunctionable/greedy_q_learning_cost.py#L35-L59
def compute(self, x): ''' Compute cost. Args: x: `np.ndarray` of explanatory variables. Returns: cost ''' q_learning = copy(self.__greedy_q_learning) q_learning.epsilon_greedy_rate = x[0] q_learning.alpha_value ...
[ "def", "compute", "(", "self", ",", "x", ")", ":", "q_learning", "=", "copy", "(", "self", ".", "__greedy_q_learning", ")", "q_learning", ".", "epsilon_greedy_rate", "=", "x", "[", "0", "]", "q_learning", ".", "alpha_value", "=", "x", "[", "1", "]", "q...
Compute cost. Args: x: `np.ndarray` of explanatory variables. Returns: cost
[ "Compute", "cost", ".", "Args", ":", "x", ":", "np", ".", "ndarray", "of", "explanatory", "variables", ".", "Returns", ":", "cost" ]
python
train
YosaiProject/yosai
yosai/core/mgt/mgt.py
https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/mgt/mgt.py#L635-L684
def login(self, subject, authc_token): """ Login authenticates a user using an AuthenticationToken. If authentication is successful AND the Authenticator has determined that authentication is complete for the account, login constructs a Subject instance representing the authenti...
[ "def", "login", "(", "self", ",", "subject", ",", "authc_token", ")", ":", "try", ":", "# account_id is a SimpleIdentifierCollection", "account_id", "=", "self", ".", "authenticator", ".", "authenticate_account", "(", "subject", ".", "identifiers", ",", "authc_token...
Login authenticates a user using an AuthenticationToken. If authentication is successful AND the Authenticator has determined that authentication is complete for the account, login constructs a Subject instance representing the authenticated account's identity. Once a subject instance is constr...
[ "Login", "authenticates", "a", "user", "using", "an", "AuthenticationToken", ".", "If", "authentication", "is", "successful", "AND", "the", "Authenticator", "has", "determined", "that", "authentication", "is", "complete", "for", "the", "account", "login", "construct...
python
train
user-cont/colin
colin/core/checks/check_utils.py
https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/checks/check_utils.py#L7-L34
def check_label(labels, required, value_regex, target_labels): """ Check if the label is required and match the regex :param labels: [str] :param required: bool (if the presence means pass or not) :param value_regex: str (using search method) :param target_labels: [str] :return: bool (requi...
[ "def", "check_label", "(", "labels", ",", "required", ",", "value_regex", ",", "target_labels", ")", ":", "present", "=", "target_labels", "is", "not", "None", "and", "not", "set", "(", "labels", ")", ".", "isdisjoint", "(", "set", "(", "target_labels", ")...
Check if the label is required and match the regex :param labels: [str] :param required: bool (if the presence means pass or not) :param value_regex: str (using search method) :param target_labels: [str] :return: bool (required==True: True if the label is present and match the regex if specified) ...
[ "Check", "if", "the", "label", "is", "required", "and", "match", "the", "regex" ]
python
train
twaddington/django-gravatar
django_gravatar/helpers.py
https://github.com/twaddington/django-gravatar/blob/c4849d93ed43b419eceff0ff2de83d4265597629/django_gravatar/helpers.py#L74-L87
def has_gravatar(email): """ Returns True if the user has a gravatar, False if otherwise """ # Request a 404 response if the gravatar does not exist url = get_gravatar_url(email, default=GRAVATAR_DEFAULT_IMAGE_404) # Verify an OK response was received try: request = Request(url) ...
[ "def", "has_gravatar", "(", "email", ")", ":", "# Request a 404 response if the gravatar does not exist", "url", "=", "get_gravatar_url", "(", "email", ",", "default", "=", "GRAVATAR_DEFAULT_IMAGE_404", ")", "# Verify an OK response was received", "try", ":", "request", "="...
Returns True if the user has a gravatar, False if otherwise
[ "Returns", "True", "if", "the", "user", "has", "a", "gravatar", "False", "if", "otherwise" ]
python
test
ModisWorks/modis
modis/discord_modis/modules/tableflip/api_flipcheck.py
https://github.com/ModisWorks/modis/blob/1f1225c9841835ec1d1831fc196306527567db8b/modis/discord_modis/modules/tableflip/api_flipcheck.py#L1-L59
def flipcheck(content): """Checks a string for anger and soothes said anger Args: content (str): The message to be flipchecked Returns: putitback (str): The righted table or text """ # Prevent tampering with flip punct = """!"#$%&'*+,-./:;<=>?@[\]^_`{|}~ ━─""" tamperdict =...
[ "def", "flipcheck", "(", "content", ")", ":", "# Prevent tampering with flip", "punct", "=", "\"\"\"!\"#$%&'*+,-./:;<=>?@[\\]^_`{|}~ ━─\"\"\"", "tamperdict", "=", "str", ".", "maketrans", "(", "''", ",", "''", ",", "punct", ")", "tamperproof", "=", "content", ".", ...
Checks a string for anger and soothes said anger Args: content (str): The message to be flipchecked Returns: putitback (str): The righted table or text
[ "Checks", "a", "string", "for", "anger", "and", "soothes", "said", "anger" ]
python
train
GPflow/GPflow
gpflow/training/hmc.py
https://github.com/GPflow/GPflow/blob/549394f0b1b0696c7b521a065e49bdae6e7acf27/gpflow/training/hmc.py#L24-L124
def sample(self, model, num_samples, epsilon, lmin=1, lmax=1, thin=1, burn=0, session=None, initialize=True, anchor=True, logprobs=True): """ A straight-forward HMC implementation. The mass matrix is assumed to be the identity. The gpflow mod...
[ "def", "sample", "(", "self", ",", "model", ",", "num_samples", ",", "epsilon", ",", "lmin", "=", "1", ",", "lmax", "=", "1", ",", "thin", "=", "1", ",", "burn", "=", "0", ",", "session", "=", "None", ",", "initialize", "=", "True", ",", "anchor"...
A straight-forward HMC implementation. The mass matrix is assumed to be the identity. The gpflow model must implement `build_objective` method to build `f` function (tensor) which in turn based on model's internal trainable parameters `x`. f(x) = E(x) we then generate samp...
[ "A", "straight", "-", "forward", "HMC", "implementation", ".", "The", "mass", "matrix", "is", "assumed", "to", "be", "the", "identity", "." ]
python
train
kubernetes-client/python
kubernetes/client/apis/certificates_v1beta1_api.py
https://github.com/kubernetes-client/python/blob/5e512ff564c244c50cab780d821542ed56aa965a/kubernetes/client/apis/certificates_v1beta1_api.py#L38-L60
def create_certificate_signing_request(self, body, **kwargs): """ create a CertificateSigningRequest This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_certificate_signing_request(body,...
[ "def", "create_certificate_signing_request", "(", "self", ",", "body", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "create_ce...
create a CertificateSigningRequest This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_certificate_signing_request(body, async_req=True) >>> result = thread.get() :param async_req bool ...
[ "create", "a", "CertificateSigningRequest", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "pass", "async_req", "=", "True", ">>>", "thread", "=", "api", ...
python
train
odlgroup/odl
odl/solvers/functional/default_functionals.py
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/solvers/functional/default_functionals.py#L2676-L2743
def gradient(self): r"""Gradient operator of the functional. The gradient of the Huber functional is given by .. math:: \nabla f_{\gamma}(x) = \begin{cases} \frac{1}{\gamma} x & \text{if } \|x\|_2 \leq \gamma \\ \frac{1}{\|x\|...
[ "def", "gradient", "(", "self", ")", ":", "functional", "=", "self", "class", "HuberGradient", "(", "Operator", ")", ":", "\"\"\"The gradient operator of this functional.\"\"\"", "def", "__init__", "(", "self", ")", ":", "\"\"\"Initialize a new instance.\"\"\"", "super"...
r"""Gradient operator of the functional. The gradient of the Huber functional is given by .. math:: \nabla f_{\gamma}(x) = \begin{cases} \frac{1}{\gamma} x & \text{if } \|x\|_2 \leq \gamma \\ \frac{1}{\|x\|_2} x & \text{else} ...
[ "r", "Gradient", "operator", "of", "the", "functional", "." ]
python
train
pymoca/pymoca
src/pymoca/backends/xml/model.py
https://github.com/pymoca/pymoca/blob/14b5eb7425e96689de6cc5c10f400895d586a978/src/pymoca/backends/xml/model.py#L174-L186
def split_dae_alg(eqs: SYM, dx: SYM) -> Dict[str, SYM]: """Split equations into differential algebraic and algebraic only""" dae = [] alg = [] for eq in ca.vertsplit(eqs): if ca.depends_on(eq, dx): dae.append(eq) else: alg.append(eq) return { 'dae': ca...
[ "def", "split_dae_alg", "(", "eqs", ":", "SYM", ",", "dx", ":", "SYM", ")", "->", "Dict", "[", "str", ",", "SYM", "]", ":", "dae", "=", "[", "]", "alg", "=", "[", "]", "for", "eq", "in", "ca", ".", "vertsplit", "(", "eqs", ")", ":", "if", "...
Split equations into differential algebraic and algebraic only
[ "Split", "equations", "into", "differential", "algebraic", "and", "algebraic", "only" ]
python
train
chardet/chardet
convert_language_model.py
https://github.com/chardet/chardet/blob/b5194bf8250b7d180ac4edff51e09cab9d99febe/convert_language_model.py#L57-L73
def convert_sbcs_model(old_model, alphabet): """Create a SingleByteCharSetModel object representing the charset.""" # Setup tables necessary for computing transition frequencies for model char_to_order = {i: order for i, order in enumerate(old_model['char_to_order_map'])} pos_ratio ...
[ "def", "convert_sbcs_model", "(", "old_model", ",", "alphabet", ")", ":", "# Setup tables necessary for computing transition frequencies for model", "char_to_order", "=", "{", "i", ":", "order", "for", "i", ",", "order", "in", "enumerate", "(", "old_model", "[", "'cha...
Create a SingleByteCharSetModel object representing the charset.
[ "Create", "a", "SingleByteCharSetModel", "object", "representing", "the", "charset", "." ]
python
train
cloudera/cm_api
python/examples/aws.py
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/examples/aws.py#L150-L159
def get_login_credentials(args): """ Gets the login credentials from the user, if not specified while invoking the script. @param args: arguments provided to the script. """ if not args.username: args.username = raw_input("Enter Username: ") if not args.password: args.password = getpass.ge...
[ "def", "get_login_credentials", "(", "args", ")", ":", "if", "not", "args", ".", "username", ":", "args", ".", "username", "=", "raw_input", "(", "\"Enter Username: \"", ")", "if", "not", "args", ".", "password", ":", "args", ".", "password", "=", "getpass...
Gets the login credentials from the user, if not specified while invoking the script. @param args: arguments provided to the script.
[ "Gets", "the", "login", "credentials", "from", "the", "user", "if", "not", "specified", "while", "invoking", "the", "script", "." ]
python
train
InspectorMustache/base16-builder-python
pybase16_builder/cli.py
https://github.com/InspectorMustache/base16-builder-python/blob/586f1f87ee9f70696ab19c542af6ef55c6548a2e/pybase16_builder/cli.py#L6-L20
def build_mode(arg_namespace): """Check command line arguments and run build function.""" custom_temps = arg_namespace.template or [] temp_paths = [rel_to_cwd('templates', temp) for temp in custom_temps] try: builder.build(templates=temp_paths, schemes=arg_namespace.scheme...
[ "def", "build_mode", "(", "arg_namespace", ")", ":", "custom_temps", "=", "arg_namespace", ".", "template", "or", "[", "]", "temp_paths", "=", "[", "rel_to_cwd", "(", "'templates'", ",", "temp", ")", "for", "temp", "in", "custom_temps", "]", "try", ":", "b...
Check command line arguments and run build function.
[ "Check", "command", "line", "arguments", "and", "run", "build", "function", "." ]
python
train
fronzbot/blinkpy
blinkpy/api.py
https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/api.py#L68-L76
def request_system_arm(blink, network): """ Arm system. :param blink: Blink instance. :param network: Sync module network id. """ url = "{}/network/{}/arm".format(blink.urls.base_url, network) return http_post(blink, url)
[ "def", "request_system_arm", "(", "blink", ",", "network", ")", ":", "url", "=", "\"{}/network/{}/arm\"", ".", "format", "(", "blink", ".", "urls", ".", "base_url", ",", "network", ")", "return", "http_post", "(", "blink", ",", "url", ")" ]
Arm system. :param blink: Blink instance. :param network: Sync module network id.
[ "Arm", "system", "." ]
python
train
CI-WATER/mapkit
mapkit/ColorRampGenerator.py
https://github.com/CI-WATER/mapkit/blob/ce5fbded6af7adabdf1eec85631c6811ef8ecc34/mapkit/ColorRampGenerator.py#L197-L228
def generateDefaultColorRamp(cls, colorRampEnum): """ Returns the color ramp as a list of RGB tuples :param colorRampEnum: One of the """ hue = [(255, 0, 255), (231, 0, 255), (208, 0, 255), (185, 0, 255), (162, 0, 255), (139, 0, 255), (115, 0, 255), (92, 0, 255), (69, 0, 255), (4...
[ "def", "generateDefaultColorRamp", "(", "cls", ",", "colorRampEnum", ")", ":", "hue", "=", "[", "(", "255", ",", "0", ",", "255", ")", ",", "(", "231", ",", "0", ",", "255", ")", ",", "(", "208", ",", "0", ",", "255", ")", ",", "(", "185", ",...
Returns the color ramp as a list of RGB tuples :param colorRampEnum: One of the
[ "Returns", "the", "color", "ramp", "as", "a", "list", "of", "RGB", "tuples", ":", "param", "colorRampEnum", ":", "One", "of", "the" ]
python
train
pantsbuild/pants
src/python/pants/goal/products.py
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/goal/products.py#L438-L450
def get_data(self, typename, init_func=None): """Returns a data product. :API: public If the product isn't found, returns None, unless init_func is set, in which case the product's value is set to the return value of init_func(), and returned. """ if typename not in self.data_products: i...
[ "def", "get_data", "(", "self", ",", "typename", ",", "init_func", "=", "None", ")", ":", "if", "typename", "not", "in", "self", ".", "data_products", ":", "if", "not", "init_func", ":", "return", "None", "self", ".", "data_products", "[", "typename", "]...
Returns a data product. :API: public If the product isn't found, returns None, unless init_func is set, in which case the product's value is set to the return value of init_func(), and returned.
[ "Returns", "a", "data", "product", "." ]
python
train
dahlia/sqlalchemy-imageattach
sqlalchemy_imageattach/store.py
https://github.com/dahlia/sqlalchemy-imageattach/blob/b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8/sqlalchemy_imageattach/store.py#L167-L179
def delete(self, image): """Delete the file of the given ``image``. :param image: the image to delete :type image: :class:`sqlalchemy_imageattach.entity.Image` """ from .entity import Image if not isinstance(image, Image): raise TypeError('image must be a sq...
[ "def", "delete", "(", "self", ",", "image", ")", ":", "from", ".", "entity", "import", "Image", "if", "not", "isinstance", "(", "image", ",", "Image", ")", ":", "raise", "TypeError", "(", "'image must be a sqlalchemy_imageattach.entity.'", "'Image instance, not '"...
Delete the file of the given ``image``. :param image: the image to delete :type image: :class:`sqlalchemy_imageattach.entity.Image`
[ "Delete", "the", "file", "of", "the", "given", "image", "." ]
python
train
offu/WeRoBot
werobot/parser.py
https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/parser.py#L20-L34
def process_message(message): """ Process a message dict and return a Message Object :param message: Message dict returned by `parse_xml` function :return: Message Object """ message["type"] = message.pop("MsgType").lower() if message["type"] == 'event': message["type"] = str(message...
[ "def", "process_message", "(", "message", ")", ":", "message", "[", "\"type\"", "]", "=", "message", ".", "pop", "(", "\"MsgType\"", ")", ".", "lower", "(", ")", "if", "message", "[", "\"type\"", "]", "==", "'event'", ":", "message", "[", "\"type\"", "...
Process a message dict and return a Message Object :param message: Message dict returned by `parse_xml` function :return: Message Object
[ "Process", "a", "message", "dict", "and", "return", "a", "Message", "Object", ":", "param", "message", ":", "Message", "dict", "returned", "by", "parse_xml", "function", ":", "return", ":", "Message", "Object" ]
python
train
mayfield/shellish
shellish/command/command.py
https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/command/command.py#L333-L340
def attach_session(self): """ Create a session and inject it as context for this command and any subcommands. """ assert self.session is None root = self.find_root() session = self.Session(root) root.inject_context(session=session) return session
[ "def", "attach_session", "(", "self", ")", ":", "assert", "self", ".", "session", "is", "None", "root", "=", "self", ".", "find_root", "(", ")", "session", "=", "self", ".", "Session", "(", "root", ")", "root", ".", "inject_context", "(", "session", "=...
Create a session and inject it as context for this command and any subcommands.
[ "Create", "a", "session", "and", "inject", "it", "as", "context", "for", "this", "command", "and", "any", "subcommands", "." ]
python
train
briancappello/flask-unchained
flask_unchained/click.py
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/click.py#L430-L464
def option(*param_decls, cls=None, **attrs): """ Options are usually optional values on the command line and have some extra features that arguments don't have. :param param_decls: the parameter declarations for this option or argument. This is a list of flags or argument ...
[ "def", "option", "(", "*", "param_decls", ",", "cls", "=", "None", ",", "*", "*", "attrs", ")", ":", "return", "click", ".", "option", "(", "*", "param_decls", ",", "cls", "=", "cls", "or", "Option", ",", "*", "*", "attrs", ")" ]
Options are usually optional values on the command line and have some extra features that arguments don't have. :param param_decls: the parameter declarations for this option or argument. This is a list of flags or argument names. :param show_default: contro...
[ "Options", "are", "usually", "optional", "values", "on", "the", "command", "line", "and", "have", "some", "extra", "features", "that", "arguments", "don", "t", "have", "." ]
python
train
vladsaveliev/TargQC
targqc/utilz/gtf.py
https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/gtf.py#L55-L81
def gtf_to_bed(gtf, alt_out_dir=None): """ create a BED file of transcript-level features with attached gene name or gene ids """ out_file = os.path.splitext(gtf)[0] + '.bed' if file_exists(out_file): return out_file if not os.access(os.path.dirname(out_file), os.W_OK | os.X_OK): ...
[ "def", "gtf_to_bed", "(", "gtf", ",", "alt_out_dir", "=", "None", ")", ":", "out_file", "=", "os", ".", "path", ".", "splitext", "(", "gtf", ")", "[", "0", "]", "+", "'.bed'", "if", "file_exists", "(", "out_file", ")", ":", "return", "out_file", "if"...
create a BED file of transcript-level features with attached gene name or gene ids
[ "create", "a", "BED", "file", "of", "transcript", "-", "level", "features", "with", "attached", "gene", "name", "or", "gene", "ids" ]
python
train
fboender/ansible-cmdb
lib/mako/codegen.py
https://github.com/fboender/ansible-cmdb/blob/ebd960ac10684e8c9ec2b12751bba2c4c9504ab7/lib/mako/codegen.py#L556-L571
def write_def_decl(self, node, identifiers): """write a locally-available callable referencing a top-level def""" funcname = node.funcname namedecls = node.get_argument_expressions() nameargs = node.get_argument_expressions(as_call=True) if not self.in_def and ( ...
[ "def", "write_def_decl", "(", "self", ",", "node", ",", "identifiers", ")", ":", "funcname", "=", "node", ".", "funcname", "namedecls", "=", "node", ".", "get_argument_expressions", "(", ")", "nameargs", "=", "node", ".", "get_argument_expressions", "(", "as_c...
write a locally-available callable referencing a top-level def
[ "write", "a", "locally", "-", "available", "callable", "referencing", "a", "top", "-", "level", "def" ]
python
train
tanghaibao/jcvi
jcvi/apps/phylo.py
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/phylo.py#L177-L190
def run_ffitch(distfile, outtreefile, intreefile=None, **kwargs): """ Infer tree branch lengths using ffitch in EMBOSS PHYLIP """ cl = FfitchCommandline(datafile=distfile, outtreefile=outtreefile, \ intreefile=intreefile, **kwargs) r, e = cl.run() if e: print("***ffitch coul...
[ "def", "run_ffitch", "(", "distfile", ",", "outtreefile", ",", "intreefile", "=", "None", ",", "*", "*", "kwargs", ")", ":", "cl", "=", "FfitchCommandline", "(", "datafile", "=", "distfile", ",", "outtreefile", "=", "outtreefile", ",", "intreefile", "=", "...
Infer tree branch lengths using ffitch in EMBOSS PHYLIP
[ "Infer", "tree", "branch", "lengths", "using", "ffitch", "in", "EMBOSS", "PHYLIP" ]
python
train
Neurita/boyle
boyle/utils/strings.py
https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/utils/strings.py#L99-L111
def append_to_keys(adict, preffix): """ Parameters ---------- adict: preffix: Returns ------- """ return {preffix + str(key): (value if isinstance(value, dict) else value) for key, value in list(adict.items())}
[ "def", "append_to_keys", "(", "adict", ",", "preffix", ")", ":", "return", "{", "preffix", "+", "str", "(", "key", ")", ":", "(", "value", "if", "isinstance", "(", "value", ",", "dict", ")", "else", "value", ")", "for", "key", ",", "value", "in", "...
Parameters ---------- adict: preffix: Returns -------
[ "Parameters", "----------", "adict", ":", "preffix", ":" ]
python
valid
baguette-io/baguette-messaging
farine/stream/sse.py
https://github.com/baguette-io/baguette-messaging/blob/8d1c4707ea7eace8617fed2d97df2fcc9d0cdee1/farine/stream/sse.py#L40-L63
def run(self, limit=None, timeout=None): """ Consume the event stream. :param timeout: Duration of the connection timeout. :type timeout: int :param limit: Number of events to consume. :type limit: int :rtype: None """ counter = 0 self.stre...
[ "def", "run", "(", "self", ",", "limit", "=", "None", ",", "timeout", "=", "None", ")", ":", "counter", "=", "0", "self", ".", "stream", "=", "sseclient", ".", "SSEClient", "(", "self", ".", "endpoint", ")", "while", "True", ":", "with", "utils", "...
Consume the event stream. :param timeout: Duration of the connection timeout. :type timeout: int :param limit: Number of events to consume. :type limit: int :rtype: None
[ "Consume", "the", "event", "stream", ".", ":", "param", "timeout", ":", "Duration", "of", "the", "connection", "timeout", ".", ":", "type", "timeout", ":", "int", ":", "param", "limit", ":", "Number", "of", "events", "to", "consume", ".", ":", "type", ...
python
train
inveniosoftware/invenio-pidstore
invenio_pidstore/ext.py
https://github.com/inveniosoftware/invenio-pidstore/blob/8bf35f4e62d5dcaf1a2cfe5803245ba5220a9b78/invenio_pidstore/ext.py#L49-L56
def register_minter(self, name, minter): """Register a minter. :param name: Minter name. :param minter: The new minter. """ assert name not in self.minters self.minters[name] = minter
[ "def", "register_minter", "(", "self", ",", "name", ",", "minter", ")", ":", "assert", "name", "not", "in", "self", ".", "minters", "self", ".", "minters", "[", "name", "]", "=", "minter" ]
Register a minter. :param name: Minter name. :param minter: The new minter.
[ "Register", "a", "minter", "." ]
python
train
mayfield/cellulario
cellulario/tier.py
https://github.com/mayfield/cellulario/blob/e9dc10532a0357bc90ebaa2655b36822f9249673/cellulario/tier.py#L144-L148
def coord_wrap(self, *args): """ Wrap the coroutine with coordination throttles. """ yield from self.cell.coord.start(self) yield from self.coro(*args) yield from self.cell.coord.finish(self)
[ "def", "coord_wrap", "(", "self", ",", "*", "args", ")", ":", "yield", "from", "self", ".", "cell", ".", "coord", ".", "start", "(", "self", ")", "yield", "from", "self", ".", "coro", "(", "*", "args", ")", "yield", "from", "self", ".", "cell", "...
Wrap the coroutine with coordination throttles.
[ "Wrap", "the", "coroutine", "with", "coordination", "throttles", "." ]
python
train
psd-tools/psd-tools
src/psd_tools/psd/descriptor.py
https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/psd/descriptor.py#L60-L66
def write_length_and_key(fp, value): """ Helper to write descriptor key. """ written = write_fmt(fp, 'I', 0 if value in _TERMS else len(value)) written += write_bytes(fp, value) return written
[ "def", "write_length_and_key", "(", "fp", ",", "value", ")", ":", "written", "=", "write_fmt", "(", "fp", ",", "'I'", ",", "0", "if", "value", "in", "_TERMS", "else", "len", "(", "value", ")", ")", "written", "+=", "write_bytes", "(", "fp", ",", "val...
Helper to write descriptor key.
[ "Helper", "to", "write", "descriptor", "key", "." ]
python
train
cpburnz/python-path-specification
pathspec/patterns/gitwildmatch.py
https://github.com/cpburnz/python-path-specification/blob/6fc7567a58cb68ec7d72cc287e7fb97dbe22c017/pathspec/patterns/gitwildmatch.py#L177-L280
def _translate_segment_glob(pattern): """ Translates the glob pattern to a regular expression. This is used in the constructor to translate a path segment glob pattern to its corresponding regular expression. *pattern* (:class:`str`) is the glob pattern. Returns the regular expression (:class:`str`). ""...
[ "def", "_translate_segment_glob", "(", "pattern", ")", ":", "# NOTE: This is derived from `fnmatch.translate()` and is similar to", "# the POSIX function `fnmatch()` with the `FNM_PATHNAME` flag set.", "escape", "=", "False", "regex", "=", "''", "i", ",", "end", "=", "0", ",", ...
Translates the glob pattern to a regular expression. This is used in the constructor to translate a path segment glob pattern to its corresponding regular expression. *pattern* (:class:`str`) is the glob pattern. Returns the regular expression (:class:`str`).
[ "Translates", "the", "glob", "pattern", "to", "a", "regular", "expression", ".", "This", "is", "used", "in", "the", "constructor", "to", "translate", "a", "path", "segment", "glob", "pattern", "to", "its", "corresponding", "regular", "expression", "." ]
python
train
MoseleyBioinformaticsLab/mwtab
mwtab/fileio.py
https://github.com/MoseleyBioinformaticsLab/mwtab/blob/8c0ae8ab2aa621662f99589ed41e481cf8b7152b/mwtab/fileio.py#L128-L183
def open(self): """Generator that opens and yields filehandles using appropriate facilities: test if path represents a local file or file over URL, if file is compressed or not. :return: Filehandle to be processed into an instance. """ is_url = self.is_url(self.path) ...
[ "def", "open", "(", "self", ")", ":", "is_url", "=", "self", ".", "is_url", "(", "self", ".", "path", ")", "compression_type", "=", "self", ".", "is_compressed", "(", "self", ".", "path", ")", "if", "not", "compression_type", ":", "if", "is_url", ":", ...
Generator that opens and yields filehandles using appropriate facilities: test if path represents a local file or file over URL, if file is compressed or not. :return: Filehandle to be processed into an instance.
[ "Generator", "that", "opens", "and", "yields", "filehandles", "using", "appropriate", "facilities", ":", "test", "if", "path", "represents", "a", "local", "file", "or", "file", "over", "URL", "if", "file", "is", "compressed", "or", "not", "." ]
python
train
manns/pyspread
pyspread/src/interfaces/xls.py
https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/interfaces/xls.py#L820-L835
def _col_widths2xls(self, worksheets): """Writes col_widths to xls file Format: <col>\t<tab>\t<value>\n """ xls_max_cols, xls_max_tabs = self.xls_max_cols, self.xls_max_tabs dict_grid = self.code_array.dict_grid for col, tab in dict_grid.col_widths: if co...
[ "def", "_col_widths2xls", "(", "self", ",", "worksheets", ")", ":", "xls_max_cols", ",", "xls_max_tabs", "=", "self", ".", "xls_max_cols", ",", "self", ".", "xls_max_tabs", "dict_grid", "=", "self", ".", "code_array", ".", "dict_grid", "for", "col", ",", "ta...
Writes col_widths to xls file Format: <col>\t<tab>\t<value>\n
[ "Writes", "col_widths", "to", "xls", "file" ]
python
train
CalebBell/fluids
fluids/fittings.py
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/fittings.py#L4408-L4515
def K_branch_diverging_Crane(D_run, D_branch, Q_run, Q_branch, angle=90): r'''Returns the loss coefficient for the branch of a diverging tee or wye according to the Crane method [1]_. .. math:: K_{branch} = G\left[1 + H\left(\frac{Q_{branch}}{Q_{comb} \beta_{branch}^2}\right)^2 - J\left...
[ "def", "K_branch_diverging_Crane", "(", "D_run", ",", "D_branch", ",", "Q_run", ",", "Q_branch", ",", "angle", "=", "90", ")", ":", "beta", "=", "(", "D_branch", "/", "D_run", ")", "beta2", "=", "beta", "*", "beta", "Q_comb", "=", "Q_run", "+", "Q_bran...
r'''Returns the loss coefficient for the branch of a diverging tee or wye according to the Crane method [1]_. .. math:: K_{branch} = G\left[1 + H\left(\frac{Q_{branch}}{Q_{comb} \beta_{branch}^2}\right)^2 - J\left(\frac{Q_{branch}}{Q_{comb} \beta_{branch}^2}\right)\cos\theta\right] ...
[ "r", "Returns", "the", "loss", "coefficient", "for", "the", "branch", "of", "a", "diverging", "tee", "or", "wye", "according", "to", "the", "Crane", "method", "[", "1", "]", "_", ".", "..", "math", "::", "K_", "{", "branch", "}", "=", "G", "\\", "l...
python
train
jmbeach/KEP.py
src/keppy/simulator_device.py
https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/simulator_device.py#L48-L58
def process_tag(self, tag): """Processes tag and detects which function to use""" try: if not self._is_function(tag): self._tag_type_processor[tag.data_type](tag) except KeyError as ex: raise Exception('Tag type {0} not recognized for tag {1}' ...
[ "def", "process_tag", "(", "self", ",", "tag", ")", ":", "try", ":", "if", "not", "self", ".", "_is_function", "(", "tag", ")", ":", "self", ".", "_tag_type_processor", "[", "tag", ".", "data_type", "]", "(", "tag", ")", "except", "KeyError", "as", "...
Processes tag and detects which function to use
[ "Processes", "tag", "and", "detects", "which", "function", "to", "use" ]
python
train
CalebBell/fluids
fluids/two_phase.py
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/two_phase.py#L1539-L1634
def Wang_Chiang_Lu(m, x, rhol, rhog, mul, mug, D, roughness=0, L=1): r'''Calculates two-phase pressure drop with the Wang, Chiang, and Lu (1997) correlation given in [1]_ and reviewed in [2]_ and [3]_. .. math:: \Delta P = \Delta P_{g} \phi_g^2 .. math:: \phi_g^2 = 1 + 9.397X^{0.62} + ...
[ "def", "Wang_Chiang_Lu", "(", "m", ",", "x", ",", "rhol", ",", "rhog", ",", "mul", ",", "mug", ",", "D", ",", "roughness", "=", "0", ",", "L", "=", "1", ")", ":", "G_tp", "=", "m", "/", "(", "pi", "/", "4", "*", "D", "**", "2", ")", "# Ac...
r'''Calculates two-phase pressure drop with the Wang, Chiang, and Lu (1997) correlation given in [1]_ and reviewed in [2]_ and [3]_. .. math:: \Delta P = \Delta P_{g} \phi_g^2 .. math:: \phi_g^2 = 1 + 9.397X^{0.62} + 0.564X^{2.45} \text{ for } G >= 200 kg/m^2/s .. math:: \phi_...
[ "r", "Calculates", "two", "-", "phase", "pressure", "drop", "with", "the", "Wang", "Chiang", "and", "Lu", "(", "1997", ")", "correlation", "given", "in", "[", "1", "]", "_", "and", "reviewed", "in", "[", "2", "]", "_", "and", "[", "3", "]", "_", ...
python
train
hyperledger/indy-plenum
plenum/common/ledger.py
https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/common/ledger.py#L129-L143
def treeWithAppliedTxns(self, txns: List, currentTree=None): """ Return a copy of merkle tree after applying the txns :param txns: :return: """ currentTree = currentTree or self.tree # Copying the tree is not a problem since its a Compact Merkle Tree # so ...
[ "def", "treeWithAppliedTxns", "(", "self", ",", "txns", ":", "List", ",", "currentTree", "=", "None", ")", ":", "currentTree", "=", "currentTree", "or", "self", ".", "tree", "# Copying the tree is not a problem since its a Compact Merkle Tree", "# so the size of the tree ...
Return a copy of merkle tree after applying the txns :param txns: :return:
[ "Return", "a", "copy", "of", "merkle", "tree", "after", "applying", "the", "txns", ":", "param", "txns", ":", ":", "return", ":" ]
python
train
apache/spark
python/pyspark/rdd.py
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L223-L229
def cache(self): """ Persist this RDD with the default storage level (C{MEMORY_ONLY}). """ self.is_cached = True self.persist(StorageLevel.MEMORY_ONLY) return self
[ "def", "cache", "(", "self", ")", ":", "self", ".", "is_cached", "=", "True", "self", ".", "persist", "(", "StorageLevel", ".", "MEMORY_ONLY", ")", "return", "self" ]
Persist this RDD with the default storage level (C{MEMORY_ONLY}).
[ "Persist", "this", "RDD", "with", "the", "default", "storage", "level", "(", "C", "{", "MEMORY_ONLY", "}", ")", "." ]
python
train
dereneaton/ipyrad
ipyrad/analysis/tetrad2.py
https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad2.py#L290-L326
def _refresh(self): """ Remove all existing results files and reinit the h5 arrays so that the tetrad object is just like fresh from a CLI start. """ ## clear any existing results files oldfiles = [self.files.qdump] + \ self.database.__dict__.values...
[ "def", "_refresh", "(", "self", ")", ":", "## clear any existing results files", "oldfiles", "=", "[", "self", ".", "files", ".", "qdump", "]", "+", "self", ".", "database", ".", "__dict__", ".", "values", "(", ")", "+", "self", ".", "trees", ".", "__dic...
Remove all existing results files and reinit the h5 arrays so that the tetrad object is just like fresh from a CLI start.
[ "Remove", "all", "existing", "results", "files", "and", "reinit", "the", "h5", "arrays", "so", "that", "the", "tetrad", "object", "is", "just", "like", "fresh", "from", "a", "CLI", "start", "." ]
python
valid
poldracklab/niworkflows
niworkflows/utils/misc.py
https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/utils/misc.py#L116-L132
def splitext(fname): """Splits filename and extension (.gz safe) >>> splitext('some/file.nii.gz') ('file', '.nii.gz') >>> splitext('some/other/file.nii') ('file', '.nii') >>> splitext('otherext.tar.gz') ('otherext', '.tar.gz') >>> splitext('text.txt') ('text', '.txt') """ f...
[ "def", "splitext", "(", "fname", ")", ":", "from", "pathlib", "import", "Path", "basename", "=", "str", "(", "Path", "(", "fname", ")", ".", "name", ")", "stem", "=", "Path", "(", "basename", ".", "rstrip", "(", "'.gz'", ")", ")", ".", "stem", "ret...
Splits filename and extension (.gz safe) >>> splitext('some/file.nii.gz') ('file', '.nii.gz') >>> splitext('some/other/file.nii') ('file', '.nii') >>> splitext('otherext.tar.gz') ('otherext', '.tar.gz') >>> splitext('text.txt') ('text', '.txt')
[ "Splits", "filename", "and", "extension", "(", ".", "gz", "safe", ")" ]
python
train
brmscheiner/ideogram
ideogram/writer.py
https://github.com/brmscheiner/ideogram/blob/422bf566c51fd56f7bbb6e75b16d18d52b4c7568/ideogram/writer.py#L179-L196
def tagAttributes_while(fdef_master_list,root): '''Tag each node under root with the appropriate depth. ''' depth = 0 current = root untagged_nodes = [root] while untagged_nodes: current = untagged_nodes.pop() for x in fdef_master_list: if jsName(x.path,x.name) == current...
[ "def", "tagAttributes_while", "(", "fdef_master_list", ",", "root", ")", ":", "depth", "=", "0", "current", "=", "root", "untagged_nodes", "=", "[", "root", "]", "while", "untagged_nodes", ":", "current", "=", "untagged_nodes", ".", "pop", "(", ")", "for", ...
Tag each node under root with the appropriate depth.
[ "Tag", "each", "node", "under", "root", "with", "the", "appropriate", "depth", "." ]
python
train
Iotic-Labs/py-IoticAgent
src/IoticAgent/IOT/ResourceMeta.py
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/IOT/ResourceMeta.py#L196-L213
def set_description(self, description, lang=None): """Sets the `description` metadata property on your Thing/Point. Only one description is allowed per language, so any other descriptions in this language are removed before adding this one Raises `ValueError` containing an error message if the...
[ "def", "set_description", "(", "self", ",", "description", ",", "lang", "=", "None", ")", ":", "description", "=", "Validation", ".", "description_check_convert", "(", "description", ")", "lang", "=", "Validation", ".", "lang_check_convert", "(", "lang", ",", ...
Sets the `description` metadata property on your Thing/Point. Only one description is allowed per language, so any other descriptions in this language are removed before adding this one Raises `ValueError` containing an error message if the parameters fail validation `description` (mandatory)...
[ "Sets", "the", "description", "metadata", "property", "on", "your", "Thing", "/", "Point", ".", "Only", "one", "description", "is", "allowed", "per", "language", "so", "any", "other", "descriptions", "in", "this", "language", "are", "removed", "before", "addin...
python
train
dturanski/springcloudstream
springcloudstream/stdio/stream.py
https://github.com/dturanski/springcloudstream/blob/208b542f9eba82e97882d52703af8e965a62a980/springcloudstream/stdio/stream.py#L62-L69
def validate(self, options): """ Validate the options or exit() """ try: codecs.getencoder(options.char_encoding) except LookupError: self.parser.error("invalid 'char-encoding' %s" % options.char_encoding)
[ "def", "validate", "(", "self", ",", "options", ")", ":", "try", ":", "codecs", ".", "getencoder", "(", "options", ".", "char_encoding", ")", "except", "LookupError", ":", "self", ".", "parser", ".", "error", "(", "\"invalid 'char-encoding' %s\"", "%", "opti...
Validate the options or exit()
[ "Validate", "the", "options", "or", "exit", "()" ]
python
train
edx/pa11ycrawler
pa11ycrawler/spiders/edx.py
https://github.com/edx/pa11ycrawler/blob/fc672d4524463bc050ade4c7c97801c0d5bf8c9e/pa11ycrawler/spiders/edx.py#L230-L258
def after_initial_csrf(self, response): """ This method is called *only* if the crawler is started with an email and password combination. In order to log in, we need a CSRF token from a GET request. This method takes the result of a GET request, extracts the CSRF token, ...
[ "def", "after_initial_csrf", "(", "self", ",", "response", ")", ":", "login_url", "=", "(", "URLObject", "(", "\"http://\"", ")", ".", "with_hostname", "(", "self", ".", "domain", ")", ".", "with_port", "(", "self", ".", "port", ")", ".", "with_path", "(...
This method is called *only* if the crawler is started with an email and password combination. In order to log in, we need a CSRF token from a GET request. This method takes the result of a GET request, extracts the CSRF token, and uses it to make a login request. The response to this lo...
[ "This", "method", "is", "called", "*", "only", "*", "if", "the", "crawler", "is", "started", "with", "an", "email", "and", "password", "combination", ".", "In", "order", "to", "log", "in", "we", "need", "a", "CSRF", "token", "from", "a", "GET", "reques...
python
train
hendrix/hendrix
hendrix/utils/__init__.py
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/utils/__init__.py#L27-L44
def responseInColor(request, status, headers, prefix='Response', opts=None): "Prints the response info in color" code, message = status.split(None, 1) message = '%s [%s] => Request %s %s %s on pid %d' % ( prefix, code, str(request.host), request.method, request.path, ...
[ "def", "responseInColor", "(", "request", ",", "status", ",", "headers", ",", "prefix", "=", "'Response'", ",", "opts", "=", "None", ")", ":", "code", ",", "message", "=", "status", ".", "split", "(", "None", ",", "1", ")", "message", "=", "'%s [%s] =>...
Prints the response info in color
[ "Prints", "the", "response", "info", "in", "color" ]
python
train
CalebBell/thermo
thermo/thermal_conductivity.py
https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/thermal_conductivity.py#L369-L423
def Bahadori_liquid(T, M): r'''Estimates the thermal conductivity of parafin liquid hydrocarbons. Fits their data well, and is useful as only MW is required. X is the Molecular weight, and Y the temperature. .. math:: K = a + bY + CY^2 + dY^3 a = A_1 + B_1 X + C_1 X^2 + D_1 X^3 ...
[ "def", "Bahadori_liquid", "(", "T", ",", "M", ")", ":", "A", "=", "[", "-", "6.48326E-2", ",", "2.715015E-3", ",", "-", "1.08580E-5", ",", "9.853917E-9", "]", "B", "=", "[", "1.565612E-2", ",", "-", "1.55833E-4", ",", "5.051114E-7", ",", "-", "4.68030E...
r'''Estimates the thermal conductivity of parafin liquid hydrocarbons. Fits their data well, and is useful as only MW is required. X is the Molecular weight, and Y the temperature. .. math:: K = a + bY + CY^2 + dY^3 a = A_1 + B_1 X + C_1 X^2 + D_1 X^3 b = A_2 + B_2 X + C_2 X^2 + D...
[ "r", "Estimates", "the", "thermal", "conductivity", "of", "parafin", "liquid", "hydrocarbons", ".", "Fits", "their", "data", "well", "and", "is", "useful", "as", "only", "MW", "is", "required", ".", "X", "is", "the", "Molecular", "weight", "and", "Y", "the...
python
valid
kodexlab/reliure
reliure/offline.py
https://github.com/kodexlab/reliure/blob/0450c7a9254c5c003162738458bbe0c49e777ba5/reliure/offline.py#L119-L142
def main(): """ Small run usage exemple """ #TODO: need to be mv in .rst doc from reliure.pipeline import Composable @Composable def doc_analyse(docs): for doc in docs: yield { "title": doc, "url": "http://lost.com/%s" % doc, } ...
[ "def", "main", "(", ")", ":", "#TODO: need to be mv in .rst doc", "from", "reliure", ".", "pipeline", "import", "Composable", "@", "Composable", "def", "doc_analyse", "(", "docs", ")", ":", "for", "doc", "in", "docs", ":", "yield", "{", "\"title\"", ":", "do...
Small run usage exemple
[ "Small", "run", "usage", "exemple" ]
python
train
alefnula/tea
tea/utils/crypto.py
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/utils/crypto.py#L437-L448
def decrypt(data, digest=True): """Decrypt provided data.""" alg, _, data = data.rpartition("$") if not alg: return data data = _from_hex_digest(data) if digest else data try: return implementations["decryption"][alg]( data, implementations["get_key"]() ) exce...
[ "def", "decrypt", "(", "data", ",", "digest", "=", "True", ")", ":", "alg", ",", "_", ",", "data", "=", "data", ".", "rpartition", "(", "\"$\"", ")", "if", "not", "alg", ":", "return", "data", "data", "=", "_from_hex_digest", "(", "data", ")", "if"...
Decrypt provided data.
[ "Decrypt", "provided", "data", "." ]
python
train
debrouwere/google-analytics
googleanalytics/utils/functional.py
https://github.com/debrouwere/google-analytics/blob/7d585c2f6f5ca191e975e6e3eaf7d5e2424fa11c/googleanalytics/utils/functional.py#L20-L45
def vectorize(fn): """ Allows a method to accept one or more values, but internally deal only with a single item, and returning a list or a single item depending on what is desired. """ @functools.wraps(fn) def vectorized_method(self, values, *vargs, **kwargs): wrap = not isinst...
[ "def", "vectorize", "(", "fn", ")", ":", "@", "functools", ".", "wraps", "(", "fn", ")", "def", "vectorized_method", "(", "self", ",", "values", ",", "*", "vargs", ",", "*", "*", "kwargs", ")", ":", "wrap", "=", "not", "isinstance", "(", "values", ...
Allows a method to accept one or more values, but internally deal only with a single item, and returning a list or a single item depending on what is desired.
[ "Allows", "a", "method", "to", "accept", "one", "or", "more", "values", "but", "internally", "deal", "only", "with", "a", "single", "item", "and", "returning", "a", "list", "or", "a", "single", "item", "depending", "on", "what", "is", "desired", "." ]
python
train
ambitioninc/django-query-builder
querybuilder/tables.py
https://github.com/ambitioninc/django-query-builder/blob/113a7d845d3ddc6a45621b9880308e756f87c5bf/querybuilder/tables.py#L311-L328
def find_field(self, field=None, alias=None): """ Finds a field by name or alias. :param field: string of the field name or alias, dict of {'alias': field}, or a Field instance :type field: str or dict or Field :returns: The field if it is found, otherwise None :rtype: ...
[ "def", "find_field", "(", "self", ",", "field", "=", "None", ",", "alias", "=", "None", ")", ":", "if", "alias", ":", "field", "=", "alias", "field", "=", "FieldFactory", "(", "field", ",", "table", "=", "self", ",", "alias", "=", "alias", ")", "id...
Finds a field by name or alias. :param field: string of the field name or alias, dict of {'alias': field}, or a Field instance :type field: str or dict or Field :returns: The field if it is found, otherwise None :rtype: :class:`Field <querybuilder.fields.Field>` or None
[ "Finds", "a", "field", "by", "name", "or", "alias", "." ]
python
train
aiidateam/aiida-codtools
aiida_codtools/parsers/cif_cod_deposit.py
https://github.com/aiidateam/aiida-codtools/blob/da5e4259b7a2e86cf0cc3f997e11dd36d445fa94/aiida_codtools/parsers/cif_cod_deposit.py#L35-L63
def _get_output_nodes(self, output_path, error_path): """ Extracts output nodes from the standard output and standard error files """ status = cod_deposition_states.UNKNOWN messages = [] if output_path is not None: content = None with open(output_...
[ "def", "_get_output_nodes", "(", "self", ",", "output_path", ",", "error_path", ")", ":", "status", "=", "cod_deposition_states", ".", "UNKNOWN", "messages", "=", "[", "]", "if", "output_path", "is", "not", "None", ":", "content", "=", "None", "with", "open"...
Extracts output nodes from the standard output and standard error files
[ "Extracts", "output", "nodes", "from", "the", "standard", "output", "and", "standard", "error", "files" ]
python
train