repo
stringlengths
7
55
path
stringlengths
4
223
url
stringlengths
87
315
code
stringlengths
75
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
avg_line_len
float64
7.91
980
MartijnBraam/pyElectronics
electronics/gateways/buspirate.py
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/gateways/buspirate.py#L79-L101
def switch_mode(self, new_mode): """ Explicitly switch the Bus Pirate mode :param new_mode: The mode to switch to. Use the buspirate.MODE_* constants """ packet = bytearray() packet.append(new_mode) self.device.write(packet) possible_responses = { sel...
[ "def", "switch_mode", "(", "self", ",", "new_mode", ")", ":", "packet", "=", "bytearray", "(", ")", "packet", ".", "append", "(", "new_mode", ")", "self", ".", "device", ".", "write", "(", "packet", ")", "possible_responses", "=", "{", "self", ".", "MO...
Explicitly switch the Bus Pirate mode :param new_mode: The mode to switch to. Use the buspirate.MODE_* constants
[ "Explicitly", "switch", "the", "Bus", "Pirate", "mode" ]
python
train
34.086957
Workiva/furious
furious/context/context.py
https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/context/context.py#L419-L426
def _tasks_to_reinsert(tasks, transactional): """Return a list containing the tasks that should be reinserted based on the was_enqueued property and whether the insert is transactional or not. """ if transactional: return tasks return [task for task in tasks if not task.was_enqueued]
[ "def", "_tasks_to_reinsert", "(", "tasks", ",", "transactional", ")", ":", "if", "transactional", ":", "return", "tasks", "return", "[", "task", "for", "task", "in", "tasks", "if", "not", "task", ".", "was_enqueued", "]" ]
Return a list containing the tasks that should be reinserted based on the was_enqueued property and whether the insert is transactional or not.
[ "Return", "a", "list", "containing", "the", "tasks", "that", "should", "be", "reinserted", "based", "on", "the", "was_enqueued", "property", "and", "whether", "the", "insert", "is", "transactional", "or", "not", "." ]
python
train
38.25
dylanaraps/pywal
pywal/reload.py
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/reload.py#L13-L19
def tty(tty_reload): """Load colors in tty.""" tty_script = os.path.join(CACHE_DIR, "colors-tty.sh") term = os.environ.get("TERM") if tty_reload and term == "linux": subprocess.Popen(["sh", tty_script])
[ "def", "tty", "(", "tty_reload", ")", ":", "tty_script", "=", "os", ".", "path", ".", "join", "(", "CACHE_DIR", ",", "\"colors-tty.sh\"", ")", "term", "=", "os", ".", "environ", ".", "get", "(", "\"TERM\"", ")", "if", "tty_reload", "and", "term", "==",...
Load colors in tty.
[ "Load", "colors", "in", "tty", "." ]
python
train
31.571429
log2timeline/dfvfs
dfvfs/file_io/file_object_io.py
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/file_io/file_object_io.py#L44-L66
def _Open(self, path_spec=None, mode='rb'): """Opens the file-like object defined by path specification. Args: path_spec (Optional[PathSpec]): path specification. mode (Optional[str]): file access mode. Raises: AccessError: if the access to open the file was denied. IOError: if the...
[ "def", "_Open", "(", "self", ",", "path_spec", "=", "None", ",", "mode", "=", "'rb'", ")", ":", "if", "not", "self", ".", "_file_object_set_in_init", "and", "not", "path_spec", ":", "raise", "ValueError", "(", "'Missing path specification.'", ")", "if", "sel...
Opens the file-like object defined by path specification. Args: path_spec (Optional[PathSpec]): path specification. mode (Optional[str]): file access mode. Raises: AccessError: if the access to open the file was denied. IOError: if the file-like object could not be opened. OSErro...
[ "Opens", "the", "file", "-", "like", "object", "defined", "by", "path", "specification", "." ]
python
train
36.434783
yeraydiazdiaz/lunr.py
lunr/builder.py
https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/builder.py#L199-L202
def _create_token_set(self): """Creates a token set of all tokens in the index using `lunr.TokenSet` """ self.token_set = TokenSet.from_list(sorted(list(self.inverted_index.keys())))
[ "def", "_create_token_set", "(", "self", ")", ":", "self", ".", "token_set", "=", "TokenSet", ".", "from_list", "(", "sorted", "(", "list", "(", "self", ".", "inverted_index", ".", "keys", "(", ")", ")", ")", ")" ]
Creates a token set of all tokens in the index using `lunr.TokenSet`
[ "Creates", "a", "token", "set", "of", "all", "tokens", "in", "the", "index", "using", "lunr", ".", "TokenSet" ]
python
train
50.75
Arkq/flake8-requirements
src/flake8_requirements/checker.py
https://github.com/Arkq/flake8-requirements/blob/d7cb84af2429a63635528b531111a5da527bf2d1/src/flake8_requirements/checker.py#L322-L385
def run(self): """Run checker.""" def split(module): """Split module into submodules.""" return tuple(module.split(".")) def modcmp(lib=(), test=()): """Compare import modules.""" if len(lib) > len(test): return False ...
[ "def", "run", "(", "self", ")", ":", "def", "split", "(", "module", ")", ":", "\"\"\"Split module into submodules.\"\"\"", "return", "tuple", "(", "module", ".", "split", "(", "\".\"", ")", ")", "def", "modcmp", "(", "lib", "=", "(", ")", ",", "test", ...
Run checker.
[ "Run", "checker", "." ]
python
train
37.875
GNS3/gns3-server
gns3server/compute/qemu/qcow2.py
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/qemu/qcow2.py#L91-L106
def rebase(self, qemu_img, base_image): """ Rebase a linked clone in order to use the correct disk :param qemu_img: Path to the qemu-img binary :param base_image: Path to the base image """ if not os.path.exists(base_image): raise FileNotFoundError(base_imag...
[ "def", "rebase", "(", "self", ",", "qemu_img", ",", "base_image", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "base_image", ")", ":", "raise", "FileNotFoundError", "(", "base_image", ")", "command", "=", "[", "qemu_img", ",", "\"rebase\...
Rebase a linked clone in order to use the correct disk :param qemu_img: Path to the qemu-img binary :param base_image: Path to the base image
[ "Rebase", "a", "linked", "clone", "in", "order", "to", "use", "the", "correct", "disk" ]
python
train
37.6875
foxx/python-helpful
helpful.py
https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L599-L607
def cleanup(self): """Remove any created temp paths""" for path in self.paths: if isinstance(path, tuple): os.close(path[0]) os.unlink(path[1]) else: shutil.rmtree(path) self.paths = []
[ "def", "cleanup", "(", "self", ")", ":", "for", "path", "in", "self", ".", "paths", ":", "if", "isinstance", "(", "path", ",", "tuple", ")", ":", "os", ".", "close", "(", "path", "[", "0", "]", ")", "os", ".", "unlink", "(", "path", "[", "1", ...
Remove any created temp paths
[ "Remove", "any", "created", "temp", "paths" ]
python
train
30.333333
streamlink/streamlink
src/streamlink/plugin/plugin.py
https://github.com/streamlink/streamlink/blob/c8ed1daff14ac03195870238b9b900c1109dd5c1/src/streamlink/plugin/plugin.py#L465-L484
def load_cookies(self): """ Load any stored cookies for the plugin that have not expired. :return: list of the restored cookie names """ if not self.session or not self.cache: raise RuntimeError("Cannot loaded cached cookies in unbound plugin") restored = []...
[ "def", "load_cookies", "(", "self", ")", ":", "if", "not", "self", ".", "session", "or", "not", "self", ".", "cache", ":", "raise", "RuntimeError", "(", "\"Cannot loaded cached cookies in unbound plugin\"", ")", "restored", "=", "[", "]", "for", "key", ",", ...
Load any stored cookies for the plugin that have not expired. :return: list of the restored cookie names
[ "Load", "any", "stored", "cookies", "for", "the", "plugin", "that", "have", "not", "expired", "." ]
python
test
35.05
ucsb-cs-education/hairball
hairball/plugins/checks.py
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/checks.py#L101-L113
def analyze(self, scratch, **kwargs): """Run and return the results from the Animation plugin.""" results = Counter() for script in self.iter_scripts(scratch): gen = self.iter_blocks(script.blocks) name = 'start' level = None while name != '': ...
[ "def", "analyze", "(", "self", ",", "scratch", ",", "*", "*", "kwargs", ")", ":", "results", "=", "Counter", "(", ")", "for", "script", "in", "self", ".", "iter_scripts", "(", "scratch", ")", ":", "gen", "=", "self", ".", "iter_blocks", "(", "script"...
Run and return the results from the Animation plugin.
[ "Run", "and", "return", "the", "results", "from", "the", "Animation", "plugin", "." ]
python
train
42.692308
jtwhite79/pyemu
pyemu/utils/gw_utils.py
https://github.com/jtwhite79/pyemu/blob/c504d8e7a4097cec07655a6318d275739bd8148a/pyemu/utils/gw_utils.py#L2107-L2180
def modflow_sfr_gag_to_instruction_file(gage_output_file, ins_file=None, parse_filename=False): """writes an instruction file for an SFR gage output file to read Flow only at all times Parameters ---------- gage_output_file : str the gage output filename (ASCII). ...
[ "def", "modflow_sfr_gag_to_instruction_file", "(", "gage_output_file", ",", "ins_file", "=", "None", ",", "parse_filename", "=", "False", ")", ":", "if", "ins_file", "is", "None", ":", "ins_file", "=", "gage_output_file", "+", "'.ins'", "# navigate the file to be sure...
writes an instruction file for an SFR gage output file to read Flow only at all times Parameters ---------- gage_output_file : str the gage output filename (ASCII). ins_file : str the name of the instruction file to create. If None, the name ...
[ "writes", "an", "instruction", "file", "for", "an", "SFR", "gage", "output", "file", "to", "read", "Flow", "only", "at", "all", "times" ]
python
train
38.891892
thiagopbueno/pyrddl
pyrddl/rddl.py
https://github.com/thiagopbueno/pyrddl/blob/3bcfa850b1a7532c7744358f3c6b9e0f8ab978c9/pyrddl/rddl.py#L202-L211
def action_range_type(self) -> Sequence[str]: '''The range type of each action fluent in canonical order. Returns: Sequence[str]: A tuple of range types representing the range of each fluent. ''' fluents = self.domain.action_fluents ordering = self.domain...
[ "def", "action_range_type", "(", "self", ")", "->", "Sequence", "[", "str", "]", ":", "fluents", "=", "self", ".", "domain", ".", "action_fluents", "ordering", "=", "self", ".", "domain", ".", "action_fluent_ordering", "return", "self", ".", "_fluent_range_typ...
The range type of each action fluent in canonical order. Returns: Sequence[str]: A tuple of range types representing the range of each fluent.
[ "The", "range", "type", "of", "each", "action", "fluent", "in", "canonical", "order", "." ]
python
train
39.2
doconix/django-mako-plus
django_mako_plus/converter/converters.py
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/converter/converters.py#L171-L178
def _check_default(value, parameter, default_chars): '''Returns the default if the value is "empty"''' # not using a set here because it fails when value is unhashable if value in default_chars: if parameter.default is inspect.Parameter.empty: raise ValueError('Value was empty, but no de...
[ "def", "_check_default", "(", "value", ",", "parameter", ",", "default_chars", ")", ":", "# not using a set here because it fails when value is unhashable", "if", "value", "in", "default_chars", ":", "if", "parameter", ".", "default", "is", "inspect", ".", "Parameter", ...
Returns the default if the value is "empty"
[ "Returns", "the", "default", "if", "the", "value", "is", "empty" ]
python
train
58.5
MediaFire/mediafire-python-open-sdk
mediafire/client.py
https://github.com/MediaFire/mediafire-python-open-sdk/blob/8f1f23db1b16f16e026f5c6777aec32d00baa05f/mediafire/client.py#L619-L633
def _parse_uri(uri): """Parse and validate MediaFire URI.""" tokens = urlparse(uri) if tokens.netloc != '': logger.error("Invalid URI: %s", uri) raise ValueError("MediaFire URI format error: " "host should be empty - mf:///path") if...
[ "def", "_parse_uri", "(", "uri", ")", ":", "tokens", "=", "urlparse", "(", "uri", ")", "if", "tokens", ".", "netloc", "!=", "''", ":", "logger", ".", "error", "(", "\"Invalid URI: %s\"", ",", "uri", ")", "raise", "ValueError", "(", "\"MediaFire URI format ...
Parse and validate MediaFire URI.
[ "Parse", "and", "validate", "MediaFire", "URI", "." ]
python
train
35.2
mrstephenneal/looptools
looptools/timer.py
https://github.com/mrstephenneal/looptools/blob/c4ef88d78e0fb672d09a18de0aa0edd31fd4db72/looptools/timer.py#L37-L60
def decorator(func): """A function timer decorator.""" def function_timer(*args, **kwargs): """A nested function for timing other functions.""" # Capture start time start = time.time() # Execute function with arguments value = func(*args, **k...
[ "def", "decorator", "(", "func", ")", ":", "def", "function_timer", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"A nested function for timing other functions.\"\"\"", "# Capture start time", "start", "=", "time", ".", "time", "(", ")", "# Execute fu...
A function timer decorator.
[ "A", "function", "timer", "decorator", "." ]
python
train
31.916667
DataBiosphere/toil
src/toil/jobStores/abstractJobStore.py
https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/jobStores/abstractJobStore.py#L222-L246
def _jobStoreClasses(self): """ A list of concrete AbstractJobStore implementations whose dependencies are installed. :rtype: list[AbstractJobStore] """ jobStoreClassNames = ( "toil.jobStores.azureJobStore.AzureJobStore", "toil.jobStores.fileJobStore.File...
[ "def", "_jobStoreClasses", "(", "self", ")", ":", "jobStoreClassNames", "=", "(", "\"toil.jobStores.azureJobStore.AzureJobStore\"", ",", "\"toil.jobStores.fileJobStore.FileJobStore\"", ",", "\"toil.jobStores.googleJobStore.GoogleJobStore\"", ",", "\"toil.jobStores.aws.jobStore.AWSJobSt...
A list of concrete AbstractJobStore implementations whose dependencies are installed. :rtype: list[AbstractJobStore]
[ "A", "list", "of", "concrete", "AbstractJobStore", "implementations", "whose", "dependencies", "are", "installed", "." ]
python
train
44.12
LaoLiulaoliu/pgwrapper
pgwrapper/pgwrapper.py
https://github.com/LaoLiulaoliu/pgwrapper/blob/063a164713b79bfadb56a01c4ae19911f508d01e/pgwrapper/pgwrapper.py#L78-L99
def insert(self, table, kwargs, execute=True): """.. :py:method:: Usage:: >>> insert('hospital', {'id': '12de3wrv', 'province': 'shanghai'}) insert into hospital (id, province) values ('12de3wrv', 'shanghai'); :param string table: table name :param dict kwargs:...
[ "def", "insert", "(", "self", ",", "table", ",", "kwargs", ",", "execute", "=", "True", ")", ":", "sql", "=", "\"insert into \"", "+", "table", "+", "\" ({}) values ({});\"", "keys", ",", "values", "=", "[", "]", ",", "[", "]", "[", "(", "keys", ".",...
.. :py:method:: Usage:: >>> insert('hospital', {'id': '12de3wrv', 'province': 'shanghai'}) insert into hospital (id, province) values ('12de3wrv', 'shanghai'); :param string table: table name :param dict kwargs: name and value :param bool execute: if not execut...
[ "..", ":", "py", ":", "method", "::" ]
python
train
36.136364
cloudera/cm_api
python/src/cm_api/endpoints/clusters.py
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/clusters.py#L263-L290
def restart(self, restart_only_stale_services=None, redeploy_client_configuration=None, restart_service_names=None): """ Restart all services in the cluster. Services are restarted in the appropriate order given their dependencies. @param restart_only_stale_services: Only restart services that ...
[ "def", "restart", "(", "self", ",", "restart_only_stale_services", "=", "None", ",", "redeploy_client_configuration", "=", "None", ",", "restart_service_names", "=", "None", ")", ":", "if", "self", ".", "_get_resource_root", "(", ")", ".", "version", "<", "6", ...
Restart all services in the cluster. Services are restarted in the appropriate order given their dependencies. @param restart_only_stale_services: Only restart services that have stale configuration and their dependent services. De...
[ "Restart", "all", "services", "in", "the", "cluster", ".", "Services", "are", "restarted", "in", "the", "appropriate", "order", "given", "their", "dependencies", "." ]
python
train
47
django-danceschool/django-danceschool
danceschool/core/mixins.py
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/mixins.py#L336-L444
def get_annotations(self): ''' This method gets the annotations for the queryset. Unlike get_ordering() below, it passes the actual Case() and F() objects that will be evaluated with the queryset, returned in a dictionary that is compatible with get_ordering(). ''' ...
[ "def", "get_annotations", "(", "self", ")", ":", "rule", "=", "getConstant", "(", "'registration__orgRule'", ")", "# Initialize with null values that get filled in based on the logic below.\r", "annotations", "=", "{", "'nullParam'", ":", "Case", "(", "default_value", "=", ...
This method gets the annotations for the queryset. Unlike get_ordering() below, it passes the actual Case() and F() objects that will be evaluated with the queryset, returned in a dictionary that is compatible with get_ordering().
[ "This", "method", "gets", "the", "annotations", "for", "the", "queryset", ".", "Unlike", "get_ordering", "()", "below", "it", "passes", "the", "actual", "Case", "()", "and", "F", "()", "objects", "that", "will", "be", "evaluated", "with", "the", "queryset", ...
python
train
45.302752
totalgood/nlpia
src/nlpia/loaders.py
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L233-L236
def get_en2fr(url='http://www.manythings.org/anki/fra-eng.zip'): """ Download and parse English->French translation dataset used in Keras seq2seq example """ download_unzip(url) return pd.read_table(url, compression='zip', header=None, skip_blank_lines=True, sep='\t', skiprows=0, names='en fr'.split())
[ "def", "get_en2fr", "(", "url", "=", "'http://www.manythings.org/anki/fra-eng.zip'", ")", ":", "download_unzip", "(", "url", ")", "return", "pd", ".", "read_table", "(", "url", ",", "compression", "=", "'zip'", ",", "header", "=", "None", ",", "skip_blank_lines"...
Download and parse English->French translation dataset used in Keras seq2seq example
[ "Download", "and", "parse", "English", "-", ">", "French", "translation", "dataset", "used", "in", "Keras", "seq2seq", "example" ]
python
train
78
wtolson/gnsq
gnsq/nsqd.py
https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L507-L523
def publish(self, topic, data, defer=None): """Publish a message to the given topic over http. :param topic: the topic to publish to :param data: bytestring data to publish :param defer: duration in millisconds to defer before publishing (requires nsq 0.3.6) """ ...
[ "def", "publish", "(", "self", ",", "topic", ",", "data", ",", "defer", "=", "None", ")", ":", "nsq", ".", "assert_valid_topic_name", "(", "topic", ")", "fields", "=", "{", "'topic'", ":", "topic", "}", "if", "defer", "is", "not", "None", ":", "field...
Publish a message to the given topic over http. :param topic: the topic to publish to :param data: bytestring data to publish :param defer: duration in millisconds to defer before publishing (requires nsq 0.3.6)
[ "Publish", "a", "message", "to", "the", "given", "topic", "over", "http", "." ]
python
train
31.176471
saltstack/salt
salt/states/ceph.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ceph.py#L47-L51
def _ordereddict2dict(input_ordered_dict): ''' Convert ordered dictionary to a dictionary ''' return salt.utils.json.loads(salt.utils.json.dumps(input_ordered_dict))
[ "def", "_ordereddict2dict", "(", "input_ordered_dict", ")", ":", "return", "salt", ".", "utils", ".", "json", ".", "loads", "(", "salt", ".", "utils", ".", "json", ".", "dumps", "(", "input_ordered_dict", ")", ")" ]
Convert ordered dictionary to a dictionary
[ "Convert", "ordered", "dictionary", "to", "a", "dictionary" ]
python
train
35.4
saltstack/salt
salt/loader.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L2044-L2058
def global_injector_decorator(inject_globals): ''' Decorator used by the LazyLoader to inject globals into a function at execute time. globals Dictionary with global variables to inject ''' def inner_decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): ...
[ "def", "global_injector_decorator", "(", "inject_globals", ")", ":", "def", "inner_decorator", "(", "f", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "salt", "."...
Decorator used by the LazyLoader to inject globals into a function at execute time. globals Dictionary with global variables to inject
[ "Decorator", "used", "by", "the", "LazyLoader", "to", "inject", "globals", "into", "a", "function", "at", "execute", "time", "." ]
python
train
31.2
adamreeve/npTDMS
nptdms/tdms.py
https://github.com/adamreeve/npTDMS/blob/d7d6632d4ebc2e78ed941477c2f1c56bd7493d74/nptdms/tdms.py#L534-L562
def _read_interleaved_numpy(self, f, data_objects): """Read interleaved data where all channels have a numpy type""" log.debug("Reading interleaved data all at once") # Read all data into 1 byte unsigned ints first all_channel_bytes = data_objects[0].raw_data_width if all_channe...
[ "def", "_read_interleaved_numpy", "(", "self", ",", "f", ",", "data_objects", ")", ":", "log", ".", "debug", "(", "\"Reading interleaved data all at once\"", ")", "# Read all data into 1 byte unsigned ints first", "all_channel_bytes", "=", "data_objects", "[", "0", "]", ...
Read interleaved data where all channels have a numpy type
[ "Read", "interleaved", "data", "where", "all", "channels", "have", "a", "numpy", "type" ]
python
train
55.034483
pudo/jsonmapping
jsonmapping/statements.py
https://github.com/pudo/jsonmapping/blob/4cf0a20a393ba82e00651c6fd39522a67a0155de/jsonmapping/statements.py#L89-L106
def objectify(self, load, node, depth=2, path=None): """ Given a node ID, return an object the information available about this node. This accepts a loader function as it's first argument, which is expected to return all tuples of (predicate, object, source) for the given subject. """ ...
[ "def", "objectify", "(", "self", ",", "load", ",", "node", ",", "depth", "=", "2", ",", "path", "=", "None", ")", ":", "if", "path", "is", "None", ":", "path", "=", "set", "(", ")", "if", "self", ".", "is_object", ":", "if", "depth", "<", "1", ...
Given a node ID, return an object the information available about this node. This accepts a loader function as it's first argument, which is expected to return all tuples of (predicate, object, source) for the given subject.
[ "Given", "a", "node", "ID", "return", "an", "object", "the", "information", "available", "about", "this", "node", ".", "This", "accepts", "a", "loader", "function", "as", "it", "s", "first", "argument", "which", "is", "expected", "to", "return", "all", "tu...
python
train
37.555556
influxdata/influxdb-python
influxdb/influxdb08/client.py
https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/influxdb08/client.py#L607-L621
def add_cluster_admin(self, new_username, new_password): """Add cluster admin.""" data = { 'name': new_username, 'password': new_password } self.request( url="cluster_admins", method='POST', data=data, expected_resp...
[ "def", "add_cluster_admin", "(", "self", ",", "new_username", ",", "new_password", ")", ":", "data", "=", "{", "'name'", ":", "new_username", ",", "'password'", ":", "new_password", "}", "self", ".", "request", "(", "url", "=", "\"cluster_admins\"", ",", "me...
Add cluster admin.
[ "Add", "cluster", "admin", "." ]
python
train
23.333333
cds-astro/mocpy
mocpy/abstract_moc.py
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/abstract_moc.py#L129-L149
def difference(self, another_moc, *args): """ Difference between the MOC instance and other MOCs. Parameters ---------- another_moc : `~mocpy.moc.MOC` The MOC used that will be substracted to self. args : `~mocpy.moc.MOC` Other additional MOCs to ...
[ "def", "difference", "(", "self", ",", "another_moc", ",", "*", "args", ")", ":", "interval_set", "=", "self", ".", "_interval_set", ".", "difference", "(", "another_moc", ".", "_interval_set", ")", "for", "moc", "in", "args", ":", "interval_set", "=", "in...
Difference between the MOC instance and other MOCs. Parameters ---------- another_moc : `~mocpy.moc.MOC` The MOC used that will be substracted to self. args : `~mocpy.moc.MOC` Other additional MOCs to perform the difference with. Returns ------- ...
[ "Difference", "between", "the", "MOC", "instance", "and", "other", "MOCs", "." ]
python
train
32.52381
AltSchool/dynamic-rest
dynamic_rest/serializers.py
https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/serializers.py#L642-L672
def _to_representation(self, instance): """Uncached `to_representation`.""" if self.enable_optimization: representation = self._faster_to_representation(instance) else: representation = super( WithDynamicSerializerMixin, self )...
[ "def", "_to_representation", "(", "self", ",", "instance", ")", ":", "if", "self", ".", "enable_optimization", ":", "representation", "=", "self", ".", "_faster_to_representation", "(", "instance", ")", "else", ":", "representation", "=", "super", "(", "WithDyna...
Uncached `to_representation`.
[ "Uncached", "to_representation", "." ]
python
train
31.16129
raymontag/kppy
kppy/database.py
https://github.com/raymontag/kppy/blob/a43f1fff7d49da1da4b3d8628a1b3ebbaf47f43a/kppy/database.py#L581-L619
def move_group(self, group = None, parent = None): """Append group to a new parent. group and parent must be v1Group-instances. """ if group is None or type(group) is not v1Group: raise KPError("A valid group must be given.") elif parent is not None and type(parent...
[ "def", "move_group", "(", "self", ",", "group", "=", "None", ",", "parent", "=", "None", ")", ":", "if", "group", "is", "None", "or", "type", "(", "group", ")", "is", "not", "v1Group", ":", "raise", "KPError", "(", "\"A valid group must be given.\"", ")"...
Append group to a new parent. group and parent must be v1Group-instances.
[ "Append", "group", "to", "a", "new", "parent", "." ]
python
train
38.769231
aisayko/Django-tinymce-filebrowser
mce_filebrowser/views.py
https://github.com/aisayko/Django-tinymce-filebrowser/blob/f34c9e8f8c5e32c1d1221270314f31ee07f24409/mce_filebrowser/views.py#L47-L55
def filebrowser_remove_file(request, item_id, file_type): """ Remove file """ fobj = get_object_or_404(FileBrowserFile, file_type=file_type, id=item_id) fobj.delete() if file_type == 'doc': return HttpResponseRedirect(reverse('mce-filebrowser-documents')) return HttpResponseRedirec...
[ "def", "filebrowser_remove_file", "(", "request", ",", "item_id", ",", "file_type", ")", ":", "fobj", "=", "get_object_or_404", "(", "FileBrowserFile", ",", "file_type", "=", "file_type", ",", "id", "=", "item_id", ")", "fobj", ".", "delete", "(", ")", "if",...
Remove file
[ "Remove", "file" ]
python
train
38.666667
log2timeline/plaso
plaso/parsers/mac_keychain.py
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/parsers/mac_keychain.py#L695-L733
def _ParseDateTimeValue(self, parser_mediator, date_time_value): """Parses a date time value. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. date_time_value (str): date time value (CSSM_DB_ATTRIBUTE_...
[ "def", "_ParseDateTimeValue", "(", "self", ",", "parser_mediator", ",", "date_time_value", ")", ":", "if", "date_time_value", "[", "14", "]", "!=", "'Z'", ":", "parser_mediator", ".", "ProduceExtractionWarning", "(", "'invalid date and time value: {0!s}'", ".", "forma...
Parses a date time value. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. date_time_value (str): date time value (CSSM_DB_ATTRIBUTE_FORMAT_TIME_DATE) in the format: "YYYYMMDDhhmmssZ". Returns: ...
[ "Parses", "a", "date", "time", "value", "." ]
python
train
37.974359
bitesofcode/projexui
projexui/widgets/xpopupwidget.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xpopupwidget.py#L224-L244
def adjustMask(self): """ Updates the alpha mask for this popup widget. """ if self.currentMode() == XPopupWidget.Mode.Dialog: self.clearMask() return path = self.borderPath() bitmap = QBitmap(self.width(), self.height()) ...
[ "def", "adjustMask", "(", "self", ")", ":", "if", "self", ".", "currentMode", "(", ")", "==", "XPopupWidget", ".", "Mode", ".", "Dialog", ":", "self", ".", "clearMask", "(", ")", "return", "path", "=", "self", ".", "borderPath", "(", ")", "bitmap", "...
Updates the alpha mask for this popup widget.
[ "Updates", "the", "alpha", "mask", "for", "this", "popup", "widget", "." ]
python
train
31.904762
sgaynetdinov/py-vkontakte
vk/users.py
https://github.com/sgaynetdinov/py-vkontakte/blob/c09654f89008b5847418bb66f1f9c408cd7aa128/vk/users.py#L130-L136
def get_country(self): """ :return: Country or None """ response = self._session.fetch("users.get", user_ids=self.id, fields="country")[0] if response.get('country'): return Country.from_json(self._session, response.get('country'))
[ "def", "get_country", "(", "self", ")", ":", "response", "=", "self", ".", "_session", ".", "fetch", "(", "\"users.get\"", ",", "user_ids", "=", "self", ".", "id", ",", "fields", "=", "\"country\"", ")", "[", "0", "]", "if", "response", ".", "get", "...
:return: Country or None
[ ":", "return", ":", "Country", "or", "None" ]
python
train
39.571429
PSPC-SPAC-buyandsell/von_agent
von_agent/wallet.py
https://github.com/PSPC-SPAC-buyandsell/von_agent/blob/0b1c17cca3bd178b6e6974af84dbac1dfce5cf45/von_agent/wallet.py#L353-L366
async def remove(self) -> None: """ Remove serialized wallet if it exists. """ LOGGER.debug('Wallet.remove >>>') try: LOGGER.info('Removing wallet: %s', self.name) await wallet.delete_wallet(json.dumps(self.cfg), json.dumps(self.access_creds)) ex...
[ "async", "def", "remove", "(", "self", ")", "->", "None", ":", "LOGGER", ".", "debug", "(", "'Wallet.remove >>>'", ")", "try", ":", "LOGGER", ".", "info", "(", "'Removing wallet: %s'", ",", "self", ".", "name", ")", "await", "wallet", ".", "delete_wallet",...
Remove serialized wallet if it exists.
[ "Remove", "serialized", "wallet", "if", "it", "exists", "." ]
python
train
34
mandeep/Travis-Encrypt
travis/encrypt.py
https://github.com/mandeep/Travis-Encrypt/blob/0dd2da1c71feaadcb84bdeb26827e6dfe1bd3b41/travis/encrypt.py#L21-L52
def retrieve_public_key(user_repo): """Retrieve the public key from the Travis API. The Travis API response is accessed as JSON so that Travis-Encrypt can easily find the public key that is to be passed to cryptography's load_pem_public_key function. Due to issues with some public keys being return...
[ "def", "retrieve_public_key", "(", "user_repo", ")", ":", "url", "=", "'https://api.travis-ci.org/repos/{}/key'", ".", "format", "(", "user_repo", ")", "response", "=", "requests", ".", "get", "(", "url", ")", "try", ":", "return", "response", ".", "json", "("...
Retrieve the public key from the Travis API. The Travis API response is accessed as JSON so that Travis-Encrypt can easily find the public key that is to be passed to cryptography's load_pem_public_key function. Due to issues with some public keys being returned from the Travis API as PKCS8 encoded, th...
[ "Retrieve", "the", "public", "key", "from", "the", "Travis", "API", "." ]
python
train
38.15625
yinkaisheng/Python-UIAutomation-for-Windows
uiautomation/uiautomation.py
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L1970-L1982
def DragDrop(x1: int, y1: int, x2: int, y2: int, moveSpeed: float = 1, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate mouse left button drag from point x1, y1 drop to point x2, y2. x1: int. y1: int. x2: int. y2: int. moveSpeed: float, 1 normal speed, < 1 move slower, > 1 move f...
[ "def", "DragDrop", "(", "x1", ":", "int", ",", "y1", ":", "int", ",", "x2", ":", "int", ",", "y2", ":", "int", ",", "moveSpeed", ":", "float", "=", "1", ",", "waitTime", ":", "float", "=", "OPERATION_WAIT_TIME", ")", "->", "None", ":", "PressMouse"...
Simulate mouse left button drag from point x1, y1 drop to point x2, y2. x1: int. y1: int. x2: int. y2: int. moveSpeed: float, 1 normal speed, < 1 move slower, > 1 move faster. waitTime: float.
[ "Simulate", "mouse", "left", "button", "drag", "from", "point", "x1", "y1", "drop", "to", "point", "x2", "y2", ".", "x1", ":", "int", ".", "y1", ":", "int", ".", "x2", ":", "int", ".", "y2", ":", "int", ".", "moveSpeed", ":", "float", "1", "norma...
python
valid
33.461538
dropbox/stone
stone/backends/python_types.py
https://github.com/dropbox/stone/blob/2e95cbcd1c48e05cca68c919fd8d24adec6b0f58/stone/backends/python_types.py#L1138-L1202
def generate_validator_constructor(ns, data_type): """ Given a Stone data type, returns a string that can be used to construct the appropriate validation object in Python. """ dt, nullable_dt = unwrap_nullable(data_type) if is_list_type(dt): v = generate_func_call( 'bv.List',...
[ "def", "generate_validator_constructor", "(", "ns", ",", "data_type", ")", ":", "dt", ",", "nullable_dt", "=", "unwrap_nullable", "(", "data_type", ")", "if", "is_list_type", "(", "dt", ")", ":", "v", "=", "generate_func_call", "(", "'bv.List'", ",", "args", ...
Given a Stone data type, returns a string that can be used to construct the appropriate validation object in Python.
[ "Given", "a", "Stone", "data", "type", "returns", "a", "string", "that", "can", "be", "used", "to", "construct", "the", "appropriate", "validation", "object", "in", "Python", "." ]
python
train
33.923077
jongracecox/anybadge
anybadge.py
https://github.com/jongracecox/anybadge/blob/1850a9580697e019c601d09f5de490056fed2bab/anybadge.py#L219-L222
def color_split_position(self): """The SVG x position where the color split should occur.""" return self.get_text_width(' ') + self.label_width + \ int(float(self.font_width) * float(self.num_padding_chars))
[ "def", "color_split_position", "(", "self", ")", ":", "return", "self", ".", "get_text_width", "(", "' '", ")", "+", "self", ".", "label_width", "+", "int", "(", "float", "(", "self", ".", "font_width", ")", "*", "float", "(", "self", ".", "num_padding_c...
The SVG x position where the color split should occur.
[ "The", "SVG", "x", "position", "where", "the", "color", "split", "should", "occur", "." ]
python
train
58
cathalgarvey/deadlock
deadlock/crypto.py
https://github.com/cathalgarvey/deadlock/blob/30099b476ff767611ce617150a0c574fc03fdf79/deadlock/crypto.py#L224-L234
def piece_file(input_f, chunk_size): """ Provides a streaming interface to file data in chunks of even size, which avoids memoryerrors from loading whole files into RAM to pass to `pieces`. """ chunk = input_f.read(chunk_size) total_bytes = 0 while chunk: ...
[ "def", "piece_file", "(", "input_f", ",", "chunk_size", ")", ":", "chunk", "=", "input_f", ".", "read", "(", "chunk_size", ")", "total_bytes", "=", "0", "while", "chunk", ":", "yield", "chunk", "chunk", "=", "input_f", ".", "read", "(", "chunk_size", ")"...
Provides a streaming interface to file data in chunks of even size, which avoids memoryerrors from loading whole files into RAM to pass to `pieces`.
[ "Provides", "a", "streaming", "interface", "to", "file", "data", "in", "chunks", "of", "even", "size", "which", "avoids", "memoryerrors", "from", "loading", "whole", "files", "into", "RAM", "to", "pass", "to", "pieces", "." ]
python
train
37.090909
Julian/Filesystems
filesystems/common.py
https://github.com/Julian/Filesystems/blob/f366e877d6970712bb91d47167209ee2d1e489c5/filesystems/common.py#L11-L34
def _realpath(fs, path, seen=pset()): """ .. warning:: The ``os.path`` module's realpath does not error or warn about loops, but we do, following the behavior of GNU ``realpath(1)``! """ real = Path.root() for segment in path.segments: current = real / segment seen ...
[ "def", "_realpath", "(", "fs", ",", "path", ",", "seen", "=", "pset", "(", ")", ")", ":", "real", "=", "Path", ".", "root", "(", ")", "for", "segment", "in", "path", ".", "segments", ":", "current", "=", "real", "/", "segment", "seen", "=", "seen...
.. warning:: The ``os.path`` module's realpath does not error or warn about loops, but we do, following the behavior of GNU ``realpath(1)``!
[ "..", "warning", "::" ]
python
train
31.291667
hotdoc/hotdoc
hotdoc/core/config.py
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/config.py#L164-L179
def get_markdown_files(self, dir_): """ Get all the markdown files in a folder, recursively Args: dir_: str, a toplevel folder to walk. """ md_files = OrderedSet() for root, _, files in os.walk(dir_): for name in files: split = os....
[ "def", "get_markdown_files", "(", "self", ",", "dir_", ")", ":", "md_files", "=", "OrderedSet", "(", ")", "for", "root", ",", "_", ",", "files", "in", "os", ".", "walk", "(", "dir_", ")", ":", "for", "name", "in", "files", ":", "split", "=", "os", ...
Get all the markdown files in a folder, recursively Args: dir_: str, a toplevel folder to walk.
[ "Get", "all", "the", "markdown", "files", "in", "a", "folder", "recursively" ]
python
train
33.375
KelSolaar/Foundations
foundations/parsers.py
https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/parsers.py#L863-L904
def get_attributes(self, section, strip_namespaces=False): """ Returns given section attributes. Usage:: >>> content = ["[Section A]\\n", "; Comment.\\n", "Attribute 1 = \\"Value A\\"\\n", "\\n", \ "[Section B]\\n", "Attribute 2 = \\"Value B\\"\\n"] >>> sections_file_pa...
[ "def", "get_attributes", "(", "self", ",", "section", ",", "strip_namespaces", "=", "False", ")", ":", "LOGGER", ".", "debug", "(", "\"> Getting section '{0}' attributes.\"", ".", "format", "(", "section", ")", ")", "attributes", "=", "OrderedDict", "(", ")", ...
Returns given section attributes. Usage:: >>> content = ["[Section A]\\n", "; Comment.\\n", "Attribute 1 = \\"Value A\\"\\n", "\\n", \ "[Section B]\\n", "Attribute 2 = \\"Value B\\"\\n"] >>> sections_file_parser = SectionsFileParser() >>> sections_file_parser.content = cont...
[ "Returns", "given", "section", "attributes", "." ]
python
train
44.571429
GaretJax/coolfig
coolfig/schema.py
https://github.com/GaretJax/coolfig/blob/6952aabc6ad2c9684d5d98dc470313f8f13fe636/coolfig/schema.py#L166-L174
def merge(cls, *others): """ Merge the `others` schema into this instance. The values will all be read from the provider of the original object. """ for other in others: for k, v in other: setattr(cls, k, BoundValue(cls, k, v.value))
[ "def", "merge", "(", "cls", ",", "*", "others", ")", ":", "for", "other", "in", "others", ":", "for", "k", ",", "v", "in", "other", ":", "setattr", "(", "cls", ",", "k", ",", "BoundValue", "(", "cls", ",", "k", ",", "v", ".", "value", ")", ")...
Merge the `others` schema into this instance. The values will all be read from the provider of the original object.
[ "Merge", "the", "others", "schema", "into", "this", "instance", "." ]
python
train
32.666667
pantsbuild/pants
src/python/pants/base/fingerprint_strategy.py
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/fingerprint_strategy.py#L38-L44
def fingerprint_target(self, target): """Consumers of subclass instances call this to get a fingerprint labeled with the name""" fingerprint = self.compute_fingerprint(target) if fingerprint: return '{fingerprint}-{name}'.format(fingerprint=fingerprint, name=type(self).__name__) else: return...
[ "def", "fingerprint_target", "(", "self", ",", "target", ")", ":", "fingerprint", "=", "self", ".", "compute_fingerprint", "(", "target", ")", "if", "fingerprint", ":", "return", "'{fingerprint}-{name}'", ".", "format", "(", "fingerprint", "=", "fingerprint", ",...
Consumers of subclass instances call this to get a fingerprint labeled with the name
[ "Consumers", "of", "subclass", "instances", "call", "this", "to", "get", "a", "fingerprint", "labeled", "with", "the", "name" ]
python
train
45.571429
ibis-project/ibis
ibis/pandas/execution/generic.py
https://github.com/ibis-project/ibis/blob/1e39a5fd9ef088b45c155e8a5f541767ee8ef2e7/ibis/pandas/execution/generic.py#L290-L301
def execute_cast_timestamp_to_timestamp(op, data, type, **kwargs): """Cast timestamps to other timestamps including timezone if necessary""" input_timezone = data.tz target_timezone = type.timezone if input_timezone == target_timezone: return data if input_timezone is None or target_timezo...
[ "def", "execute_cast_timestamp_to_timestamp", "(", "op", ",", "data", ",", "type", ",", "*", "*", "kwargs", ")", ":", "input_timezone", "=", "data", ".", "tz", "target_timezone", "=", "type", ".", "timezone", "if", "input_timezone", "==", "target_timezone", ":...
Cast timestamps to other timestamps including timezone if necessary
[ "Cast", "timestamps", "to", "other", "timestamps", "including", "timezone", "if", "necessary" ]
python
train
34.5
edx/ease
ease/util_functions.py
https://github.com/edx/ease/blob/a7890ed403da94d03726b0639cd8ebda45af6bbb/ease/util_functions.py#L178-L190
def regenerate_good_tokens(string): """ Given an input string, part of speech tags the string, then generates a list of ngrams that appear in the string. Used to define grammatically correct part of speech tag sequences. Returns a list of part of speech tag sequences. """ toks = nltk.word_to...
[ "def", "regenerate_good_tokens", "(", "string", ")", ":", "toks", "=", "nltk", ".", "word_tokenize", "(", "string", ")", "pos_string", "=", "nltk", ".", "pos_tag", "(", "toks", ")", "pos_seq", "=", "[", "tag", "[", "1", "]", "for", "tag", "in", "pos_st...
Given an input string, part of speech tags the string, then generates a list of ngrams that appear in the string. Used to define grammatically correct part of speech tag sequences. Returns a list of part of speech tag sequences.
[ "Given", "an", "input", "string", "part", "of", "speech", "tags", "the", "string", "then", "generates", "a", "list", "of", "ngrams", "that", "appear", "in", "the", "string", ".", "Used", "to", "define", "grammatically", "correct", "part", "of", "speech", "...
python
valid
38.769231
IdentityPython/pysaml2
src/saml2/client_base.py
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/client_base.py#L749-L756
def parse_authn_query_response(self, response, binding=BINDING_SOAP): """ Verify that the response is OK """ kwargs = {"entity_id": self.config.entityid, "attribute_converters": self.config.attribute_converters} return self._parse_response(response, AuthnQueryResponse,...
[ "def", "parse_authn_query_response", "(", "self", ",", "response", ",", "binding", "=", "BINDING_SOAP", ")", ":", "kwargs", "=", "{", "\"entity_id\"", ":", "self", ".", "config", ".", "entityid", ",", "\"attribute_converters\"", ":", "self", ".", "config", "."...
Verify that the response is OK
[ "Verify", "that", "the", "response", "is", "OK" ]
python
train
46.5
iterative/dvc
dvc/repo/metrics/show.py
https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/repo/metrics/show.py#L117-L134
def _format_output(content, typ): """Tabularize the content according to its type. Args: content (str): The content of a metric. typ (str): The type of metric -- (raw|json|tsv|htsv|csv|hcsv). Returns: str: Content in a raw or tabular format. """ if "csv" in str(typ): ...
[ "def", "_format_output", "(", "content", ",", "typ", ")", ":", "if", "\"csv\"", "in", "str", "(", "typ", ")", ":", "return", "_format_csv", "(", "content", ",", "delimiter", "=", "\",\"", ")", "if", "\"tsv\"", "in", "str", "(", "typ", ")", ":", "retu...
Tabularize the content according to its type. Args: content (str): The content of a metric. typ (str): The type of metric -- (raw|json|tsv|htsv|csv|hcsv). Returns: str: Content in a raw or tabular format.
[ "Tabularize", "the", "content", "according", "to", "its", "type", "." ]
python
train
24.833333
cackharot/suds-py3
suds/sax/element.py
https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/sax/element.py#L1023-L1034
def getNamespaces(self): """ Get the I{unique} set of namespaces referenced in the branch. @return: A set of namespaces. @rtype: set """ s = set() for n in self.branch + self.node.ancestors(): if self.permit(n.expns): s.add(n.expns) ...
[ "def", "getNamespaces", "(", "self", ")", ":", "s", "=", "set", "(", ")", "for", "n", "in", "self", ".", "branch", "+", "self", ".", "node", ".", "ancestors", "(", ")", ":", "if", "self", ".", "permit", "(", "n", ".", "expns", ")", ":", "s", ...
Get the I{unique} set of namespaces referenced in the branch. @return: A set of namespaces. @rtype: set
[ "Get", "the", "I", "{", "unique", "}", "set", "of", "namespaces", "referenced", "in", "the", "branch", "." ]
python
train
30
frasertweedale/ledgertools
ltlib/balance.py
https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/balance.py#L24-L41
def match_to_dict(match): """Convert a match object into a dict. Values are: indent: amount of indentation of this [sub]account parent: the parent dict (None) account_fragment: account name fragment balance: decimal.Decimal balance children: sub-accounts ([]) """ ...
[ "def", "match_to_dict", "(", "match", ")", ":", "balance", ",", "indent", ",", "account_fragment", "=", "match", ".", "group", "(", "1", ",", "2", ",", "3", ")", "return", "{", "'balance'", ":", "decimal", ".", "Decimal", "(", "balance", ")", ",", "'...
Convert a match object into a dict. Values are: indent: amount of indentation of this [sub]account parent: the parent dict (None) account_fragment: account name fragment balance: decimal.Decimal balance children: sub-accounts ([])
[ "Convert", "a", "match", "object", "into", "a", "dict", "." ]
python
train
30.5
saimn/sigal
sigal/gallery.py
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/gallery.py#L657-L664
def get_albums(self, path): """Return the list of all sub-directories of path.""" for name in self.albums[path].subdirs: subdir = os.path.normpath(join(path, name)) yield subdir, self.albums[subdir] for subname, album in self.get_albums(subdir): yield...
[ "def", "get_albums", "(", "self", ",", "path", ")", ":", "for", "name", "in", "self", ".", "albums", "[", "path", "]", ".", "subdirs", ":", "subdir", "=", "os", ".", "path", ".", "normpath", "(", "join", "(", "path", ",", "name", ")", ")", "yield...
Return the list of all sub-directories of path.
[ "Return", "the", "list", "of", "all", "sub", "-", "directories", "of", "path", "." ]
python
valid
42.75
PSPC-SPAC-buyandsell/von_anchor
von_anchor/anchor/holderprover.py
https://github.com/PSPC-SPAC-buyandsell/von_anchor/blob/78ac1de67be42a676274f4bf71fe12f66e72f309/von_anchor/anchor/holderprover.py#L149-L199
async def _sync_revoc_for_proof(self, rr_id: str) -> None: """ Pick up tails file reader handle for input revocation registry identifier. If no symbolic link is present, get the revocation registry definition to retrieve its tails file hash, then find the tails file and link it. ...
[ "async", "def", "_sync_revoc_for_proof", "(", "self", ",", "rr_id", ":", "str", ")", "->", "None", ":", "LOGGER", ".", "debug", "(", "'HolderProver._sync_revoc_for_proof >>> rr_id: %s'", ",", "rr_id", ")", "if", "not", "ok_rev_reg_id", "(", "rr_id", ")", ":", ...
Pick up tails file reader handle for input revocation registry identifier. If no symbolic link is present, get the revocation registry definition to retrieve its tails file hash, then find the tails file and link it. Raise AbsentTails for missing corresponding tails file. :param rr_id...
[ "Pick", "up", "tails", "file", "reader", "handle", "for", "input", "revocation", "registry", "identifier", ".", "If", "no", "symbolic", "link", "is", "present", "get", "the", "revocation", "registry", "definition", "to", "retrieve", "its", "tails", "file", "ha...
python
train
49.078431
saltstack/salt
salt/modules/aptly.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptly.py#L36-L50
def _cmd_run(cmd): ''' Run the aptly command. :return: The string output of the command. :rtype: str ''' cmd.insert(0, 'aptly') cmd_ret = __salt__['cmd.run_all'](cmd, ignore_retcode=True) if cmd_ret['retcode'] != 0: log.debug('Unable to execute command: %s\nError: %s', cmd, ...
[ "def", "_cmd_run", "(", "cmd", ")", ":", "cmd", ".", "insert", "(", "0", ",", "'aptly'", ")", "cmd_ret", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "cmd", ",", "ignore_retcode", "=", "True", ")", "if", "cmd_ret", "[", "'retcode'", "]", "!=", "0...
Run the aptly command. :return: The string output of the command. :rtype: str
[ "Run", "the", "aptly", "command", "." ]
python
train
24.666667
djgagne/hagelslag
hagelslag/processing/TrackModeler.py
https://github.com/djgagne/hagelslag/blob/6fb6c3df90bf4867e13a97d3460b14471d107df1/hagelslag/processing/TrackModeler.py#L747-L799
def load_models(self, model_path): """ Load models from pickle files. """ condition_model_files = sorted(glob(model_path + "*_condition.pkl")) if len(condition_model_files) > 0: for condition_model_file in condition_model_files: model_comps = condition...
[ "def", "load_models", "(", "self", ",", "model_path", ")", ":", "condition_model_files", "=", "sorted", "(", "glob", "(", "model_path", "+", "\"*_condition.pkl\"", ")", ")", "if", "len", "(", "condition_model_files", ")", ">", "0", ":", "for", "condition_model...
Load models from pickle files.
[ "Load", "models", "from", "pickle", "files", "." ]
python
train
58.566038
farshidce/touchworks-python
touchworks/api/http.py
https://github.com/farshidce/touchworks-python/blob/ea8f93a0f4273de1317a318e945a571f5038ba62/touchworks/api/http.py#L139-L161
def get_token(self, appname, username, password): """ get the security token by connecting to TouchWorks API """ ext_exception = TouchWorksException( TouchWorksErrorMessages.GET_TOKEN_FAILED_ERROR) data = {'Username': username, 'Password': password...
[ "def", "get_token", "(", "self", ",", "appname", ",", "username", ",", "password", ")", ":", "ext_exception", "=", "TouchWorksException", "(", "TouchWorksErrorMessages", ".", "GET_TOKEN_FAILED_ERROR", ")", "data", "=", "{", "'Username'", ":", "username", ",", "'...
get the security token by connecting to TouchWorks API
[ "get", "the", "security", "token", "by", "connecting", "to", "TouchWorks", "API" ]
python
train
37.217391
QInfer/python-qinfer
src/qinfer/domains.py
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/domains.py#L238-L251
def values(self): """ Returns an `np.array` of type `dtype` containing some values from the domain. For domains where `is_finite` is ``True``, all elements of the domain will be yielded exactly once. :rtype: `np.ndarray` """ separate_values = [domain.valu...
[ "def", "values", "(", "self", ")", ":", "separate_values", "=", "[", "domain", ".", "values", "for", "domain", "in", "self", ".", "_domains", "]", "return", "np", ".", "concatenate", "(", "[", "join_struct_arrays", "(", "list", "(", "map", "(", "np", "...
Returns an `np.array` of type `dtype` containing some values from the domain. For domains where `is_finite` is ``True``, all elements of the domain will be yielded exactly once. :rtype: `np.ndarray`
[ "Returns", "an", "np", ".", "array", "of", "type", "dtype", "containing", "some", "values", "from", "the", "domain", ".", "For", "domains", "where", "is_finite", "is", "True", "all", "elements", "of", "the", "domain", "will", "be", "yielded", "exactly", "o...
python
train
35.142857
chriso/gauged
gauged/gauged.py
https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/gauged.py#L88-L95
def aggregate_series(self, key, aggregate, start=None, end=None, interval=None, namespace=None, cache=None, percentile=None): """Get a time series of gauge aggregates""" return self.make_context(key=key, aggregate=aggregate, start=start, ...
[ "def", "aggregate_series", "(", "self", ",", "key", ",", "aggregate", ",", "start", "=", "None", ",", "end", "=", "None", ",", "interval", "=", "None", ",", "namespace", "=", "None", ",", "cache", "=", "None", ",", "percentile", "=", "None", ")", ":"...
Get a time series of gauge aggregates
[ "Get", "a", "time", "series", "of", "gauge", "aggregates" ]
python
train
62.375
innogames/polysh
polysh/control_commands_helpers.py
https://github.com/innogames/polysh/blob/fbea36f3bc9f47a62d72040c48dad1776124dae3/polysh/control_commands_helpers.py#L29-L42
def toggle_shells(command, enable): """Enable or disable the specified shells. If the command would have no effect, it changes all other shells to the inverse enable value.""" selection = list(selected_shells(command)) if command and command != '*' and selection: for i in selection: ...
[ "def", "toggle_shells", "(", "command", ",", "enable", ")", ":", "selection", "=", "list", "(", "selected_shells", "(", "command", ")", ")", "if", "command", "and", "command", "!=", "'*'", "and", "selection", ":", "for", "i", "in", "selection", ":", "if"...
Enable or disable the specified shells. If the command would have no effect, it changes all other shells to the inverse enable value.
[ "Enable", "or", "disable", "the", "specified", "shells", ".", "If", "the", "command", "would", "have", "no", "effect", "it", "changes", "all", "other", "shells", "to", "the", "inverse", "enable", "value", "." ]
python
train
40.285714
UCL-INGI/INGInious
inginious/common/task_factory.py
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/task_factory.py#L122-L129
def get_readable_tasks(self, course): """ Returns the list of all available tasks in a course """ course_fs = self._filesystem.from_subfolder(course.get_id()) tasks = [ task[0:len(task)-1] # remove trailing / for task in course_fs.list(folders=True, files=False, recursiv...
[ "def", "get_readable_tasks", "(", "self", ",", "course", ")", ":", "course_fs", "=", "self", ".", "_filesystem", ".", "from_subfolder", "(", "course", ".", "get_id", "(", ")", ")", "tasks", "=", "[", "task", "[", "0", ":", "len", "(", "task", ")", "-...
Returns the list of all available tasks in a course
[ "Returns", "the", "list", "of", "all", "available", "tasks", "in", "a", "course" ]
python
train
51.625
couchbase/couchbase-python-client
couchbase/subdocument.py
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/subdocument.py#L49-L63
def _gen_4spec(op, path, value, create_path=False, xattr=False, _expand_macros=False): """ Like `_gen_3spec`, but also accepts a mandatory value as its third argument :param bool _expand_macros: Whether macros in the value should be expanded. The macros themselves are defined at the s...
[ "def", "_gen_4spec", "(", "op", ",", "path", ",", "value", ",", "create_path", "=", "False", ",", "xattr", "=", "False", ",", "_expand_macros", "=", "False", ")", ":", "flags", "=", "0", "if", "create_path", ":", "flags", "|=", "_P", ".", "SDSPEC_F_MKD...
Like `_gen_3spec`, but also accepts a mandatory value as its third argument :param bool _expand_macros: Whether macros in the value should be expanded. The macros themselves are defined at the server side
[ "Like", "_gen_3spec", "but", "also", "accepts", "a", "mandatory", "value", "as", "its", "third", "argument", ":", "param", "bool", "_expand_macros", ":", "Whether", "macros", "in", "the", "value", "should", "be", "expanded", ".", "The", "macros", "themselves",...
python
train
36.6
pjuren/pyokit
src/pyokit/datastruct/sequence.py
https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/datastruct/sequence.py#L323-L339
def reverseComplement(self, isRNA=None): """ Reverse complement this sequence in-place. :param isRNA: if True, treat this sequence as RNA. If False, treat it as DNA. If None (default), inspect the sequence and make a guess as to whether it is RNA or DNA. """ ...
[ "def", "reverseComplement", "(", "self", ",", "isRNA", "=", "None", ")", ":", "isRNA_l", "=", "self", ".", "isRNA", "(", ")", "if", "isRNA", "is", "None", "else", "isRNA", "tmp", "=", "\"\"", "for", "n", "in", "self", ".", "sequenceData", ":", "if", ...
Reverse complement this sequence in-place. :param isRNA: if True, treat this sequence as RNA. If False, treat it as DNA. If None (default), inspect the sequence and make a guess as to whether it is RNA or DNA.
[ "Reverse", "complement", "this", "sequence", "in", "-", "place", "." ]
python
train
31.529412
OCHA-DAP/hdx-python-api
src/hdx/data/showcase.py
https://github.com/OCHA-DAP/hdx-python-api/blob/212440f54f73805826a16db77dbcb6033b18a313/src/hdx/data/showcase.py#L195-L213
def _get_showcase_dataset_dict(self, dataset): # type: (Union[hdx.data.dataset.Dataset,Dict,str]) -> Dict """Get showcase dataset dict Args: showcase (Union[Showcase,Dict,str]): Either a showcase id or Showcase metadata from a Showcase object or dictionary Returns: ...
[ "def", "_get_showcase_dataset_dict", "(", "self", ",", "dataset", ")", ":", "# type: (Union[hdx.data.dataset.Dataset,Dict,str]) -> Dict", "if", "isinstance", "(", "dataset", ",", "hdx", ".", "data", ".", "dataset", ".", "Dataset", ")", "or", "isinstance", "(", "data...
Get showcase dataset dict Args: showcase (Union[Showcase,Dict,str]): Either a showcase id or Showcase metadata from a Showcase object or dictionary Returns: Dict: showcase dataset dict
[ "Get", "showcase", "dataset", "dict" ]
python
train
49.736842
assamite/creamas
creamas/vote.py
https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/vote.py#L512-L522
def _remove_last(votes, fpl, cl, ranking): """Remove last candidate in IRV voting. """ for v in votes: for r in v: if r == fpl[-1]: v.remove(r) for c in cl: if c == fpl[-1]: if c not in ranking: ranking.append((c, len(ranking) + 1))
[ "def", "_remove_last", "(", "votes", ",", "fpl", ",", "cl", ",", "ranking", ")", ":", "for", "v", "in", "votes", ":", "for", "r", "in", "v", ":", "if", "r", "==", "fpl", "[", "-", "1", "]", ":", "v", ".", "remove", "(", "r", ")", "for", "c"...
Remove last candidate in IRV voting.
[ "Remove", "last", "candidate", "in", "IRV", "voting", "." ]
python
train
28.181818
pybel/pybel
src/pybel/struct/query/query.py
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/query/query.py#L94-L101
def append_pipeline(self, name, *args, **kwargs) -> Pipeline: """Add an entry to the pipeline. Defers to :meth:`pybel_tools.pipeline.Pipeline.append`. :param name: The name of the function :type name: str or types.FunctionType :return: This pipeline for fluid query building """ ...
[ "def", "append_pipeline", "(", "self", ",", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "Pipeline", ":", "return", "self", ".", "pipeline", ".", "append", "(", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Add an entry to the pipeline. Defers to :meth:`pybel_tools.pipeline.Pipeline.append`. :param name: The name of the function :type name: str or types.FunctionType :return: This pipeline for fluid query building
[ "Add", "an", "entry", "to", "the", "pipeline", ".", "Defers", "to", ":", "meth", ":", "pybel_tools", ".", "pipeline", ".", "Pipeline", ".", "append", "." ]
python
train
46.375
cloud-custodian/cloud-custodian
tools/sandbox/c7n_sphere11/c7n_sphere11/admin.py
https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/sandbox/c7n_sphere11/c7n_sphere11/admin.py#L40-L44
def format_json(config): """format config for lambda exec """ with open(config) as fh: print(json.dumps(yaml.safe_load(fh.read()), indent=2))
[ "def", "format_json", "(", "config", ")", ":", "with", "open", "(", "config", ")", "as", "fh", ":", "print", "(", "json", ".", "dumps", "(", "yaml", ".", "safe_load", "(", "fh", ".", "read", "(", ")", ")", ",", "indent", "=", "2", ")", ")" ]
format config for lambda exec
[ "format", "config", "for", "lambda", "exec" ]
python
train
31.4
linkhub-sdk/popbill.py
popbill/statementService.py
https://github.com/linkhub-sdk/popbill.py/blob/68a0dd7f7a937603318e93be321fde73c50b96cc/popbill/statementService.py#L543-L568
def deleteFile(self, CorpNum, ItemCode, MgtKey, FileID, UserID=None): """ 첨부파일 삭제 args CorpNum : 팝빌회원 사업자번호 ItemCode : 명세서 종류 코드 [121 - 거래명세서], [122 - 청구서], [123 - 견적서], [124 - 발주서], [125 - 입금표], [126 - 영수증] ...
[ "def", "deleteFile", "(", "self", ",", "CorpNum", ",", "ItemCode", ",", "MgtKey", ",", "FileID", ",", "UserID", "=", "None", ")", ":", "if", "MgtKey", "==", "None", "or", "MgtKey", "==", "\"\"", ":", "raise", "PopbillException", "(", "-", "99999999", "...
첨부파일 삭제 args CorpNum : 팝빌회원 사업자번호 ItemCode : 명세서 종류 코드 [121 - 거래명세서], [122 - 청구서], [123 - 견적서], [124 - 발주서], [125 - 입금표], [126 - 영수증] MgtKey : 파트너 문서관리번호 FileID : 파일아이디, 첨부파일 목록확인(getFiles) API 응답전...
[ "첨부파일", "삭제", "args", "CorpNum", ":", "팝빌회원", "사업자번호", "ItemCode", ":", "명세서", "종류", "코드", "[", "121", "-", "거래명세서", "]", "[", "122", "-", "청구서", "]", "[", "123", "-", "견적서", "]", "[", "124", "-", "발주서", "]", "[", "125", "-", "입금표", "]", "[",...
python
train
42.038462
Azure/azure-cosmos-python
azure/cosmos/cosmos_client.py
https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L1233-L1252
def ReadTrigger(self, trigger_link, options=None): """Reads a trigger. :param str trigger_link: The link to the trigger. :param dict options: The request options for the request. :return: The read Trigger. :rtype: dict ""...
[ "def", "ReadTrigger", "(", "self", ",", "trigger_link", ",", "options", "=", "None", ")", ":", "if", "options", "is", "None", ":", "options", "=", "{", "}", "path", "=", "base", ".", "GetPathFromLink", "(", "trigger_link", ")", "trigger_id", "=", "base",...
Reads a trigger. :param str trigger_link: The link to the trigger. :param dict options: The request options for the request. :return: The read Trigger. :rtype: dict
[ "Reads", "a", "trigger", "." ]
python
train
27.4
dshean/pygeotools
pygeotools/lib/geolib.py
https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/geolib.py#L404-L419
def mapToPixel(mX, mY, geoTransform): """Convert map coordinates to pixel coordinates based on geotransform Accepts float or NumPy arrays GDAL model used here - upper left corner of upper left pixel for mX, mY (and in GeoTransform) """ mX = np.asarray(mX) mY = np.asarray(mY) if geoTran...
[ "def", "mapToPixel", "(", "mX", ",", "mY", ",", "geoTransform", ")", ":", "mX", "=", "np", ".", "asarray", "(", "mX", ")", "mY", "=", "np", ".", "asarray", "(", "mY", ")", "if", "geoTransform", "[", "2", "]", "+", "geoTransform", "[", "4", "]", ...
Convert map coordinates to pixel coordinates based on geotransform Accepts float or NumPy arrays GDAL model used here - upper left corner of upper left pixel for mX, mY (and in GeoTransform)
[ "Convert", "map", "coordinates", "to", "pixel", "coordinates", "based", "on", "geotransform", "Accepts", "float", "or", "NumPy", "arrays" ]
python
train
37.1875
quantopian/pyfolio
pyfolio/timeseries.py
https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/timeseries.py#L1075-L1108
def simulate_paths(is_returns, num_days, starting_value=1, num_samples=1000, random_seed=None): """ Gnerate alternate paths using available values from in-sample returns. Parameters ---------- is_returns : pandas.core.frame.DataFrame Non-cumulative in-sample returns. ...
[ "def", "simulate_paths", "(", "is_returns", ",", "num_days", ",", "starting_value", "=", "1", ",", "num_samples", "=", "1000", ",", "random_seed", "=", "None", ")", ":", "samples", "=", "np", ".", "empty", "(", "(", "num_samples", ",", "num_days", ")", "...
Gnerate alternate paths using available values from in-sample returns. Parameters ---------- is_returns : pandas.core.frame.DataFrame Non-cumulative in-sample returns. num_days : int Number of days to project the probability cone forward. starting_value : int or float Starti...
[ "Gnerate", "alternate", "paths", "using", "available", "values", "from", "in", "-", "sample", "returns", "." ]
python
valid
33.676471
Opentrons/opentrons
api/src/opentrons/drivers/serial_communication.py
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/drivers/serial_communication.py#L98-L105
def write_and_return( command, ack, serial_connection, timeout=DEFAULT_WRITE_TIMEOUT): '''Write a command and return the response''' clear_buffer(serial_connection) with serial_with_temp_timeout( serial_connection, timeout) as device_connection: response = _write_to_device_and_re...
[ "def", "write_and_return", "(", "command", ",", "ack", ",", "serial_connection", ",", "timeout", "=", "DEFAULT_WRITE_TIMEOUT", ")", ":", "clear_buffer", "(", "serial_connection", ")", "with", "serial_with_temp_timeout", "(", "serial_connection", ",", "timeout", ")", ...
Write a command and return the response
[ "Write", "a", "command", "and", "return", "the", "response" ]
python
train
46.25
wright-group/WrightTools
WrightTools/kit/_calculate.py
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_calculate.py#L20-L88
def fluence( power_mW, color, beam_radius, reprate_Hz, pulse_width, color_units="wn", beam_radius_units="mm", pulse_width_units="fs_t", area_type="even", ) -> tuple: """Calculate the fluence of a beam. Parameters ---------- power_mW : number Time integrated p...
[ "def", "fluence", "(", "power_mW", ",", "color", ",", "beam_radius", ",", "reprate_Hz", ",", "pulse_width", ",", "color_units", "=", "\"wn\"", ",", "beam_radius_units", "=", "\"mm\"", ",", "pulse_width_units", "=", "\"fs_t\"", ",", "area_type", "=", "\"even\"", ...
Calculate the fluence of a beam. Parameters ---------- power_mW : number Time integrated power of beam. color : number Color of beam in units. beam_radius : number Radius of beam in units. reprate_Hz : number Laser repetition rate in inverse seconds (Hz). pul...
[ "Calculate", "the", "fluence", "of", "a", "beam", "." ]
python
train
32.536232
shaypal5/strct
strct/sortedlists/sortedlist.py
https://github.com/shaypal5/strct/blob/f3a301692d052ddb79331230b3c00625db1d83fc/strct/sortedlists/sortedlist.py#L4-L53
def find_point_in_section_list(point, section_list): """Returns the start of the section the given point belongs to. The given list is assumed to contain start points of consecutive sections, except for the final point, assumed to be the end point of the last section. For example, the list [5, 8, 30, 3...
[ "def", "find_point_in_section_list", "(", "point", ",", "section_list", ")", ":", "if", "point", "<", "section_list", "[", "0", "]", "or", "point", ">", "section_list", "[", "-", "1", "]", ":", "return", "None", "if", "point", "in", "section_list", ":", ...
Returns the start of the section the given point belongs to. The given list is assumed to contain start points of consecutive sections, except for the final point, assumed to be the end point of the last section. For example, the list [5, 8, 30, 31] is interpreted as the following list of sections: [5-...
[ "Returns", "the", "start", "of", "the", "section", "the", "given", "point", "belongs", "to", "." ]
python
train
32.68
google/flatbuffers
python/flatbuffers/builder.py
https://github.com/google/flatbuffers/blob/6cc30b3272d79c85db7d4871ac0aa69541dc89de/python/flatbuffers/builder.py#L398-L422
def CreateString(self, s, encoding='utf-8', errors='strict'): """CreateString writes a null-terminated byte string as a vector.""" self.assertNotNested() ## @cond FLATBUFFERS_INTERNAL self.nested = True ## @endcond if isinstance(s, compat.string_types): x = ...
[ "def", "CreateString", "(", "self", ",", "s", ",", "encoding", "=", "'utf-8'", ",", "errors", "=", "'strict'", ")", ":", "self", ".", "assertNotNested", "(", ")", "## @cond FLATBUFFERS_INTERNAL", "self", ".", "nested", "=", "True", "## @endcond", "if", "isin...
CreateString writes a null-terminated byte string as a vector.
[ "CreateString", "writes", "a", "null", "-", "terminated", "byte", "string", "as", "a", "vector", "." ]
python
train
33.36
Mindwerks/worldengine
worldengine/draw.py
https://github.com/Mindwerks/worldengine/blob/64dff8eb7824ce46b5b6cb8006bcef21822ef144/worldengine/draw.py#L628-L738
def draw_scatter_plot(world, size, target): """ This function can be used on a generic canvas (either an image to save on disk or a canvas part of a GUI) """ #Find min and max values of humidity and temperature on land so we can #normalize temperature and humidity to the chart humid = numpy...
[ "def", "draw_scatter_plot", "(", "world", ",", "size", ",", "target", ")", ":", "#Find min and max values of humidity and temperature on land so we can", "#normalize temperature and humidity to the chart", "humid", "=", "numpy", ".", "ma", ".", "masked_array", "(", "world", ...
This function can be used on a generic canvas (either an image to save on disk or a canvas part of a GUI)
[ "This", "function", "can", "be", "used", "on", "a", "generic", "canvas", "(", "either", "an", "image", "to", "save", "on", "disk", "or", "a", "canvas", "part", "of", "a", "GUI", ")" ]
python
train
42.756757
farshidce/touchworks-python
touchworks/api/http.py
https://github.com/farshidce/touchworks-python/blob/ea8f93a0f4273de1317a318e945a571f5038ba62/touchworks/api/http.py#L764-L779
def search_task_views(self, user, search_string): """ invokes TouchWorksMagicConstants.ACTION_GET_ENCOUNTER_LIST_FOR_PATIENT action :return: JSON response """ magic = self._magic_json( action=TouchWorksMagicConstants.ACTION_SEARCH_TASK_VIEWS, parameter1=us...
[ "def", "search_task_views", "(", "self", ",", "user", ",", "search_string", ")", ":", "magic", "=", "self", ".", "_magic_json", "(", "action", "=", "TouchWorksMagicConstants", ".", "ACTION_SEARCH_TASK_VIEWS", ",", "parameter1", "=", "user", ",", "parameter2", "=...
invokes TouchWorksMagicConstants.ACTION_GET_ENCOUNTER_LIST_FOR_PATIENT action :return: JSON response
[ "invokes", "TouchWorksMagicConstants", ".", "ACTION_GET_ENCOUNTER_LIST_FOR_PATIENT", "action", ":", "return", ":", "JSON", "response" ]
python
train
38.5625
praekeltfoundation/seed-message-sender
message_sender/tasks.py
https://github.com/praekeltfoundation/seed-message-sender/blob/257b01635171b9dbe1f5f13baa810c971bb2620e/message_sender/tasks.py#L225-L383
def run(self, message_id, **kwargs): """ Load and contruct message and send them off """ log = self.get_logger(**kwargs) error_retry_count = kwargs.get("error_retry_count", 0) if error_retry_count >= self.max_error_retries: raise MaxRetriesExceededError( ...
[ "def", "run", "(", "self", ",", "message_id", ",", "*", "*", "kwargs", ")", ":", "log", "=", "self", ".", "get_logger", "(", "*", "*", "kwargs", ")", "error_retry_count", "=", "kwargs", ".", "get", "(", "\"error_retry_count\"", ",", "0", ")", "if", "...
Load and contruct message and send them off
[ "Load", "and", "contruct", "message", "and", "send", "them", "off" ]
python
train
42.584906
saltstack/salt
salt/states/win_smtp_server.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_smtp_server.py#L54-L128
def server_setting(name, settings=None, server=_DEFAULT_SERVER): ''' Ensure the value is set for the specified setting. .. note:: The setting names are case-sensitive. :param str settings: A dictionary of the setting names and their values. :param str server: The SMTP server name. Ex...
[ "def", "server_setting", "(", "name", ",", "settings", "=", "None", ",", "server", "=", "_DEFAULT_SERVER", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'comment'", ":", "six", ".", "text_type", "(", ")", ",...
Ensure the value is set for the specified setting. .. note:: The setting names are case-sensitive. :param str settings: A dictionary of the setting names and their values. :param str server: The SMTP server name. Example of usage: .. code-block:: yaml smtp-settings: ...
[ "Ensure", "the", "value", "is", "set", "for", "the", "specified", "setting", "." ]
python
train
36.92
bspaans/python-mingus
mingus/core/intervals.py
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/intervals.py#L235-L249
def measure(note1, note2): """Return an integer in the range of 0-11, determining the half note steps between note1 and note2. Examples: >>> measure('C', 'D') 2 >>> measure('D', 'C') 10 """ res = notes.note_to_int(note2) - notes.note_to_int(note1) if res < 0: return 12 -...
[ "def", "measure", "(", "note1", ",", "note2", ")", ":", "res", "=", "notes", ".", "note_to_int", "(", "note2", ")", "-", "notes", ".", "note_to_int", "(", "note1", ")", "if", "res", "<", "0", ":", "return", "12", "-", "res", "*", "-", "1", "else"...
Return an integer in the range of 0-11, determining the half note steps between note1 and note2. Examples: >>> measure('C', 'D') 2 >>> measure('D', 'C') 10
[ "Return", "an", "integer", "in", "the", "range", "of", "0", "-", "11", "determining", "the", "half", "note", "steps", "between", "note1", "and", "note2", "." ]
python
train
22.933333
twilio/twilio-python
twilio/rest/flex_api/v1/configuration.py
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/flex_api/v1/configuration.py#L138-L153
def create(self): """ Create a new ConfigurationInstance :returns: Newly created ConfigurationInstance :rtype: twilio.rest.flex_api.v1.configuration.ConfigurationInstance """ data = values.of({}) payload = self._version.create( 'POST', se...
[ "def", "create", "(", "self", ")", ":", "data", "=", "values", ".", "of", "(", "{", "}", ")", "payload", "=", "self", ".", "_version", ".", "create", "(", "'POST'", ",", "self", ".", "_uri", ",", "data", "=", "data", ",", ")", "return", "Configur...
Create a new ConfigurationInstance :returns: Newly created ConfigurationInstance :rtype: twilio.rest.flex_api.v1.configuration.ConfigurationInstance
[ "Create", "a", "new", "ConfigurationInstance" ]
python
train
25.625
globocom/GloboNetworkAPI-client-python
networkapiclient/ClientFactory.py
https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/ClientFactory.py#L626-L632
def create_vlan(self): """Get an instance of vlan services facade.""" return Vlan( self.networkapi_url, self.user, self.password, self.user_ldap)
[ "def", "create_vlan", "(", "self", ")", ":", "return", "Vlan", "(", "self", ".", "networkapi_url", ",", "self", ".", "user", ",", "self", ".", "password", ",", "self", ".", "user_ldap", ")" ]
Get an instance of vlan services facade.
[ "Get", "an", "instance", "of", "vlan", "services", "facade", "." ]
python
train
29
pantsbuild/pex
pex/vendor/__init__.py
https://github.com/pantsbuild/pex/blob/87b2129d860250d3b9edce75b9cb62f9789ee521/pex/vendor/__init__.py#L94-L112
def setup_interpreter(distributions, interpreter=None): """Return an interpreter configured with vendored distributions as extras. Any distributions that are present in the vendored set will be added to the interpreter as extras. :param distributions: The names of distributions to setup the interpreter with. ...
[ "def", "setup_interpreter", "(", "distributions", ",", "interpreter", "=", "None", ")", ":", "from", "pex", ".", "interpreter", "import", "PythonInterpreter", "interpreter", "=", "interpreter", "or", "PythonInterpreter", ".", "get", "(", ")", "for", "dist", "in"...
Return an interpreter configured with vendored distributions as extras. Any distributions that are present in the vendored set will be added to the interpreter as extras. :param distributions: The names of distributions to setup the interpreter with. :type distributions: list of str :param interpreter: An opt...
[ "Return", "an", "interpreter", "configured", "with", "vendored", "distributions", "as", "extras", "." ]
python
train
48
kinegratii/borax
borax/calendars/lunardate.py
https://github.com/kinegratii/borax/blob/921649f9277e3f657b6dea5a80e67de9ee5567f6/borax/calendars/lunardate.py#L71-L78
def parse_year_days(year_info): """Parse year days from a year info. """ leap_month, leap_days = _parse_leap(year_info) res = leap_days for month in range(1, 13): res += (year_info >> (16 - month)) % 2 + 29 return res
[ "def", "parse_year_days", "(", "year_info", ")", ":", "leap_month", ",", "leap_days", "=", "_parse_leap", "(", "year_info", ")", "res", "=", "leap_days", "for", "month", "in", "range", "(", "1", ",", "13", ")", ":", "res", "+=", "(", "year_info", ">>", ...
Parse year days from a year info.
[ "Parse", "year", "days", "from", "a", "year", "info", "." ]
python
train
30.25
twisted/mantissa
xmantissa/websession.py
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/websession.py#L216-L225
def removeSessionWithKey(self, key): """ Remove a persistent session, if it exists. @type key: L{bytes} @param key: The persistent session identifier. """ self.store.query( PersistentSession, PersistentSession.sessionKey == key).deleteFromStore()
[ "def", "removeSessionWithKey", "(", "self", ",", "key", ")", ":", "self", ".", "store", ".", "query", "(", "PersistentSession", ",", "PersistentSession", ".", "sessionKey", "==", "key", ")", ".", "deleteFromStore", "(", ")" ]
Remove a persistent session, if it exists. @type key: L{bytes} @param key: The persistent session identifier.
[ "Remove", "a", "persistent", "session", "if", "it", "exists", "." ]
python
train
31
sdss/sdss_access
python/sdss_access/path/path.py
https://github.com/sdss/sdss_access/blob/76375bbf37d39d2e4ccbed90bdfa9a4298784470/python/sdss_access/path/path.py#L105-L134
def _check_special_kwargs(self, name): ''' check special functions for kwargs Checks the content of the special functions (%methodname) for any keyword arguments referenced within Parameters: name (str): A path key name Returns: ...
[ "def", "_check_special_kwargs", "(", "self", ",", "name", ")", ":", "keys", "=", "[", "]", "# find any %method names in the template string", "functions", "=", "re", ".", "findall", "(", "r\"\\%\\w+\"", ",", "self", ".", "templates", "[", "name", "]", ")", "if...
check special functions for kwargs Checks the content of the special functions (%methodname) for any keyword arguments referenced within Parameters: name (str): A path key name Returns: A list of keyword arguments found in any special fu...
[ "check", "special", "functions", "for", "kwargs", "Checks", "the", "content", "of", "the", "special", "functions", "(", "%methodname", ")", "for", "any", "keyword", "arguments", "referenced", "within" ]
python
train
34.4
tjcsl/cslbot
cslbot/commands/nuke.py
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/nuke.py#L23-L41
def cmd(send, msg, args): """Nukes somebody. Syntax: {command} <target> """ c, nick = args['handler'].connection, args['nick'] channel = args['target'] if args['target'] != 'private' else args['config']['core']['channel'] if not msg: send("Nuke who?") return with args['hand...
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "c", ",", "nick", "=", "args", "[", "'handler'", "]", ".", "connection", ",", "args", "[", "'nick'", "]", "channel", "=", "args", "[", "'target'", "]", "if", "args", "[", "'target'", "...
Nukes somebody. Syntax: {command} <target>
[ "Nukes", "somebody", "." ]
python
train
33.052632
nchopin/particles
book/smoothing/offline_smoothing.py
https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/book/smoothing/offline_smoothing.py#L63-L69
def psit(t, x, xf): """ A function of t, X_t and X_{t+1} (f=future) """ if t == 0: return psi0(x) + psit(1, x, xf) else: return -0.5 / sigma0**2 + (0.5 / sigma0**4) * ((xf - mu0) - phi0 * (x - mu0))**2
[ "def", "psit", "(", "t", ",", "x", ",", "xf", ")", ":", "if", "t", "==", "0", ":", "return", "psi0", "(", "x", ")", "+", "psit", "(", "1", ",", "x", ",", "xf", ")", "else", ":", "return", "-", "0.5", "/", "sigma0", "**", "2", "+", "(", ...
A function of t, X_t and X_{t+1} (f=future)
[ "A", "function", "of", "t", "X_t", "and", "X_", "{", "t", "+", "1", "}", "(", "f", "=", "future", ")" ]
python
train
39.857143
vi3k6i5/flashtext
flashtext/keyword.py
https://github.com/vi3k6i5/flashtext/blob/50c45f1f4a394572381249681046f57e2bf5a591/flashtext/keyword.py#L395-L411
def remove_keywords_from_list(self, keyword_list): """To remove keywords present in list Args: keyword_list (list(str)): List of keywords to remove Examples: >>> keyword_processor.remove_keywords_from_list(["java", "python"]}) Raises: AttributeError:...
[ "def", "remove_keywords_from_list", "(", "self", ",", "keyword_list", ")", ":", "if", "not", "isinstance", "(", "keyword_list", ",", "list", ")", ":", "raise", "AttributeError", "(", "\"keyword_list should be a list\"", ")", "for", "keyword", "in", "keyword_list", ...
To remove keywords present in list Args: keyword_list (list(str)): List of keywords to remove Examples: >>> keyword_processor.remove_keywords_from_list(["java", "python"]}) Raises: AttributeError: If `keyword_list` is not a list.
[ "To", "remove", "keywords", "present", "in", "list" ]
python
train
32.117647
major/supernova
supernova/credentials.py
https://github.com/major/supernova/blob/4a217ae53c1c05567014b047c0b6b9dea2d383b3/supernova/credentials.py#L90-L95
def set_user_password(environment, parameter, password): """ Sets a user's password in the keyring storage """ username = '%s:%s' % (environment, parameter) return password_set(username, password)
[ "def", "set_user_password", "(", "environment", ",", "parameter", ",", "password", ")", ":", "username", "=", "'%s:%s'", "%", "(", "environment", ",", "parameter", ")", "return", "password_set", "(", "username", ",", "password", ")" ]
Sets a user's password in the keyring storage
[ "Sets", "a", "user", "s", "password", "in", "the", "keyring", "storage" ]
python
train
35.166667
yahoo/TensorFlowOnSpark
examples/mnist/mnist_data_setup.py
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/mnist/mnist_data_setup.py#L44-L81
def writeMNIST(sc, input_images, input_labels, output, format, num_partitions): """Writes MNIST image/label vectors into parallelized files on HDFS""" # load MNIST gzip into memory with open(input_images, 'rb') as f: images = numpy.array(mnist.extract_images(f)) with open(input_labels, 'rb') as f: if f...
[ "def", "writeMNIST", "(", "sc", ",", "input_images", ",", "input_labels", ",", "output", ",", "format", ",", "num_partitions", ")", ":", "# load MNIST gzip into memory", "with", "open", "(", "input_images", ",", "'rb'", ")", "as", "f", ":", "images", "=", "n...
Writes MNIST image/label vectors into parallelized files on HDFS
[ "Writes", "MNIST", "image", "/", "label", "vectors", "into", "parallelized", "files", "on", "HDFS" ]
python
train
44.368421
tensorflow/tensor2tensor
tensor2tensor/models/mtf_transformer.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_transformer.py#L1171-L1186
def mtf_transformer_lm_baseline(): """Small language model to run on 1 TPU. Run this on 2x2 on languagemodel_lm1b32k_packed for 272000 steps (10 epochs) Results: params/10^9 log-ppl(per-token) 0.14 3.202 Returns: a hparams """ hparams = mtf_transformer_paper_lm(-1) hparams...
[ "def", "mtf_transformer_lm_baseline", "(", ")", ":", "hparams", "=", "mtf_transformer_paper_lm", "(", "-", "1", ")", "hparams", ".", "batch_size", "=", "128", "hparams", ".", "learning_rate_decay_steps", "=", "27200", "# one epoch on lm1b", "hparams", ".", "mesh_sha...
Small language model to run on 1 TPU. Run this on 2x2 on languagemodel_lm1b32k_packed for 272000 steps (10 epochs) Results: params/10^9 log-ppl(per-token) 0.14 3.202 Returns: a hparams
[ "Small", "language", "model", "to", "run", "on", "1", "TPU", "." ]
python
train
27.3125
walkr/nanoservice
benchmarks/bench_req_rep_raw.py
https://github.com/walkr/nanoservice/blob/e2098986b1baa5f283167ae487d14f3c6c21961a/benchmarks/bench_req_rep_raw.py#L24-L39
def bench(client, n): """ Benchmark n requests """ items = list(range(n)) # Time client publish operations # ------------------------------ started = time.time() msg = b'x' for i in items: client.socket.send(msg) res = client.socket.recv() assert msg == res durat...
[ "def", "bench", "(", "client", ",", "n", ")", ":", "items", "=", "list", "(", "range", "(", "n", ")", ")", "# Time client publish operations", "# ------------------------------", "started", "=", "time", ".", "time", "(", ")", "msg", "=", "b'x'", "for", "i"...
Benchmark n requests
[ "Benchmark", "n", "requests" ]
python
train
25.125
sorgerlab/indra
indra/assemblers/pysb/preassembler.py
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/pysb/preassembler.py#L28-L39
def _gather_active_forms(self): """Collect all the active forms of each Agent in the Statements.""" for stmt in self.statements: if isinstance(stmt, ActiveForm): base_agent = self.agent_set.get_create_base_agent(stmt.agent) # Handle the case where an activity ...
[ "def", "_gather_active_forms", "(", "self", ")", ":", "for", "stmt", "in", "self", ".", "statements", ":", "if", "isinstance", "(", "stmt", ",", "ActiveForm", ")", ":", "base_agent", "=", "self", ".", "agent_set", ".", "get_create_base_agent", "(", "stmt", ...
Collect all the active forms of each Agent in the Statements.
[ "Collect", "all", "the", "active", "forms", "of", "each", "Agent", "in", "the", "Statements", "." ]
python
train
52.166667
bioasp/caspo
caspo/core/setup.py
https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/core/setup.py#L142-L164
def filter(self, networks): """ Returns a new experimental setup restricted to species present in the given list of networks Parameters ---------- networks : :class:`caspo.core.logicalnetwork.LogicalNetworkList` List of logical networks Returns -----...
[ "def", "filter", "(", "self", ",", "networks", ")", ":", "cues", "=", "self", ".", "stimuli", "+", "self", ".", "inhibitors", "active_cues", "=", "set", "(", ")", "active_readouts", "=", "set", "(", ")", "for", "clause", ",", "var", "in", "networks", ...
Returns a new experimental setup restricted to species present in the given list of networks Parameters ---------- networks : :class:`caspo.core.logicalnetwork.LogicalNetworkList` List of logical networks Returns ------- caspo.core.setup.Setup Th...
[ "Returns", "a", "new", "experimental", "setup", "restricted", "to", "species", "present", "in", "the", "given", "list", "of", "networks" ]
python
train
35.826087
Robpol86/libnl
libnl/nl.py
https://github.com/Robpol86/libnl/blob/274e9fdaa39822d06ef70b799ed4a95937a4d923/libnl/nl.py#L379-L621
def recvmsgs(sk, cb): """https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L775. This is where callbacks are called. Positional arguments: sk -- Netlink socket (nl_sock class instance). cb -- callbacks (nl_cb class instance). Returns: Number of bytes received or a negative error ...
[ "def", "recvmsgs", "(", "sk", ",", "cb", ")", ":", "multipart", "=", "0", "interrupted", "=", "0", "nrecv", "=", "0", "buf", "=", "bytearray", "(", ")", "# nla is passed on to not only to nl_recv() but may also be passed to a function pointer provided by the caller", "#...
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L775. This is where callbacks are called. Positional arguments: sk -- Netlink socket (nl_sock class instance). cb -- callbacks (nl_cb class instance). Returns: Number of bytes received or a negative error code.
[ "https", ":", "//", "github", ".", "com", "/", "thom311", "/", "libnl", "/", "blob", "/", "libnl3_2_25", "/", "lib", "/", "nl", ".", "c#L775", "." ]
python
train
46.131687
signetlabdei/sem
sem/cli.py
https://github.com/signetlabdei/sem/blob/5077dd7a6d15644a18790bb6fde320e905f0fef0/sem/cli.py#L338-L346
def get_params_and_defaults(param_list, db): """ Deduce [parameter, default] pairs from simulations available in the db. Args: param_list (list): List of parameters to query for. db (DatabaseManager): Database where to query for defaults. """ return [[p, d] for p, d in db.get_all_values...
[ "def", "get_params_and_defaults", "(", "param_list", ",", "db", ")", ":", "return", "[", "[", "p", ",", "d", "]", "for", "p", ",", "d", "in", "db", ".", "get_all_values_of_all_params", "(", ")", ".", "items", "(", ")", "]" ]
Deduce [parameter, default] pairs from simulations available in the db. Args: param_list (list): List of parameters to query for. db (DatabaseManager): Database where to query for defaults.
[ "Deduce", "[", "parameter", "default", "]", "pairs", "from", "simulations", "available", "in", "the", "db", "." ]
python
train
37.444444
priestc/giotto
giotto/contrib/auth/manifest.py
https://github.com/priestc/giotto/blob/d4c26380caefa7745bb27135e315de830f7254d3/giotto/contrib/auth/manifest.py#L9-L89
def create_auth_manifest(**kwargs): """ Creates a basic authentication manifest for logging in, logging out and registering new accounts. """ class AuthProgram(Program): pre_input_middleware = [AuthenticationMiddleware] def register(username, password, password2): """ De...
[ "def", "create_auth_manifest", "(", "*", "*", "kwargs", ")", ":", "class", "AuthProgram", "(", "Program", ")", ":", "pre_input_middleware", "=", "[", "AuthenticationMiddleware", "]", "def", "register", "(", "username", ",", "password", ",", "password2", ")", "...
Creates a basic authentication manifest for logging in, logging out and registering new accounts.
[ "Creates", "a", "basic", "authentication", "manifest", "for", "logging", "in", "logging", "out", "and", "registering", "new", "accounts", "." ]
python
train
35.345679
openstack/networking-cisco
networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py#L329-L335
def get_out_seg_vlan(cls, tenant_id): """Retrieves the OUT Seg, VLAN, mob domain. """ if tenant_id not in cls.serv_obj_dict: LOG.error("Fabric not prepared for tenant %s", tenant_id) return None, None tenant_obj = cls.serv_obj_dict.get(tenant_id) return tenant_obj...
[ "def", "get_out_seg_vlan", "(", "cls", ",", "tenant_id", ")", ":", "if", "tenant_id", "not", "in", "cls", ".", "serv_obj_dict", ":", "LOG", ".", "error", "(", "\"Fabric not prepared for tenant %s\"", ",", "tenant_id", ")", "return", "None", ",", "None", "tenan...
Retrieves the OUT Seg, VLAN, mob domain.
[ "Retrieves", "the", "OUT", "Seg", "VLAN", "mob", "domain", "." ]
python
train
47.571429
aiscenblue/flask-blueprint
flask_blueprint/package_extractor.py
https://github.com/aiscenblue/flask-blueprint/blob/c558d9d5d9630bab53c297ce2c33f4ceb3874724/flask_blueprint/package_extractor.py#L59-L78
def __extract_modules(self, loader, name, is_pkg): """ if module found load module and save all attributes in the module found """ mod = loader.find_module(name).load_module(name) """ find the attribute method on each module """ if hasattr(mod, '__method__'): """ register ...
[ "def", "__extract_modules", "(", "self", ",", "loader", ",", "name", ",", "is_pkg", ")", ":", "mod", "=", "loader", ".", "find_module", "(", "name", ")", ".", "load_module", "(", "name", ")", "\"\"\" find the attribute method on each module \"\"\"", "if", "hasat...
if module found load module and save all attributes in the module found
[ "if", "module", "found", "load", "module", "and", "save", "all", "attributes", "in", "the", "module", "found" ]
python
train
40.9
allenai/allennlp
allennlp/common/from_params.py
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/from_params.py#L92-L103
def remove_optional(annotation: type): """ Optional[X] annotations are actually represented as Union[X, NoneType]. For our purposes, the "Optional" part is not interesting, so here we throw it away. """ origin = getattr(annotation, '__origin__', None) args = getattr(annotation, '__args__', (...
[ "def", "remove_optional", "(", "annotation", ":", "type", ")", ":", "origin", "=", "getattr", "(", "annotation", ",", "'__origin__'", ",", "None", ")", "args", "=", "getattr", "(", "annotation", ",", "'__args__'", ",", "(", ")", ")", "if", "origin", "=="...
Optional[X] annotations are actually represented as Union[X, NoneType]. For our purposes, the "Optional" part is not interesting, so here we throw it away.
[ "Optional", "[", "X", "]", "annotations", "are", "actually", "represented", "as", "Union", "[", "X", "NoneType", "]", ".", "For", "our", "purposes", "the", "Optional", "part", "is", "not", "interesting", "so", "here", "we", "throw", "it", "away", "." ]
python
train
36.583333
flo-compbio/genometools
genometools/expression/gene_table.py
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/expression/gene_table.py#L86-L89
def hash(self): """Generate a hash value.""" h = hash_pandas_object(self, index=True) return hashlib.md5(h.values.tobytes()).hexdigest()
[ "def", "hash", "(", "self", ")", ":", "h", "=", "hash_pandas_object", "(", "self", ",", "index", "=", "True", ")", "return", "hashlib", ".", "md5", "(", "h", ".", "values", ".", "tobytes", "(", ")", ")", ".", "hexdigest", "(", ")" ]
Generate a hash value.
[ "Generate", "a", "hash", "value", "." ]
python
train
39.25