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
saltstack/salt
salt/cloud/libcloudfuncs.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/libcloudfuncs.py#L519-L527
def conn_has_method(conn, method_name): ''' Find if the provided connection object has a specific method ''' if method_name in dir(conn): return True log.error('Method \'%s\' not yet supported!', method_name) return False
[ "def", "conn_has_method", "(", "conn", ",", "method_name", ")", ":", "if", "method_name", "in", "dir", "(", "conn", ")", ":", "return", "True", "log", ".", "error", "(", "'Method \\'%s\\' not yet supported!'", ",", "method_name", ")", "return", "False" ]
Find if the provided connection object has a specific method
[ "Find", "if", "the", "provided", "connection", "object", "has", "a", "specific", "method" ]
python
train
27.333333
nutechsoftware/alarmdecoder
alarmdecoder/devices/usb_device.py
https://github.com/nutechsoftware/alarmdecoder/blob/b0c014089e24455228cb4402cf30ba98157578cd/alarmdecoder/devices/usb_device.py#L358-L419
def read_line(self, timeout=0.0, purge_buffer=False): """ Reads a line from the device. :param timeout: read timeout :type timeout: float :param purge_buffer: Indicates whether to purge the buffer prior to reading. :type purge_buffer: bool ...
[ "def", "read_line", "(", "self", ",", "timeout", "=", "0.0", ",", "purge_buffer", "=", "False", ")", ":", "def", "timeout_event", "(", ")", ":", "\"\"\"Handles read timeout event\"\"\"", "timeout_event", ".", "reading", "=", "False", "timeout_event", ".", "readi...
Reads a line from the device. :param timeout: read timeout :type timeout: float :param purge_buffer: Indicates whether to purge the buffer prior to reading. :type purge_buffer: bool :returns: line that was read :raises: :py:class:`~alarmdeco...
[ "Reads", "a", "line", "from", "the", "device", "." ]
python
train
27.596774
materialsproject/pymatgen
pymatgen/ext/cod.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/ext/cod.py#L65-L88
def get_cod_ids(self, formula): """ Queries the COD for all cod ids associated with a formula. Requires mysql executable to be in the path. Args: formula (str): Formula. Returns: List of cod ids. """ # TODO: Remove dependency on external ...
[ "def", "get_cod_ids", "(", "self", ",", "formula", ")", ":", "# TODO: Remove dependency on external mysql call. MySQL-python package does not support Py3!", "# Standardize formula to the version used by COD.", "sql", "=", "'select file from data where formula=\"- %s -\"'", "%", "Composit...
Queries the COD for all cod ids associated with a formula. Requires mysql executable to be in the path. Args: formula (str): Formula. Returns: List of cod ids.
[ "Queries", "the", "COD", "for", "all", "cod", "ids", "associated", "with", "a", "formula", ".", "Requires", "mysql", "executable", "to", "be", "in", "the", "path", "." ]
python
train
30.708333
saltstack/salt
salt/modules/redismod.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L75-L86
def bgrewriteaof(host=None, port=None, db=None, password=None): ''' Asynchronously rewrite the append-only file CLI Example: .. code-block:: bash salt '*' redis.bgrewriteaof ''' server = _connect(host, port, db, password) return server.bgrewriteaof()
[ "def", "bgrewriteaof", "(", "host", "=", "None", ",", "port", "=", "None", ",", "db", "=", "None", ",", "password", "=", "None", ")", ":", "server", "=", "_connect", "(", "host", ",", "port", ",", "db", ",", "password", ")", "return", "server", "."...
Asynchronously rewrite the append-only file CLI Example: .. code-block:: bash salt '*' redis.bgrewriteaof
[ "Asynchronously", "rewrite", "the", "append", "-", "only", "file" ]
python
train
23.166667
reorx/torext
torext/script.py
https://github.com/reorx/torext/blob/84c4300ebc7fab0dbd11cf8b020bc7d4d1570171/torext/script.py#L175-L218
def print_usage(self, hint=None): """Usage format should be like: Lineno | Content 1 | Script description (__doc__) 2 | Usage: {script name} [COMMAND] [ARGUMENTS] 3 | \n 4 | Commands: 5 | cmd1 cmd1 description. ...
[ "def", "print_usage", "(", "self", ",", "hint", "=", "None", ")", ":", "buf", "=", "[", "]", "# Description", "if", "__doc__", ":", "buf", ".", "append", "(", "__doc__", ")", "# Usage", "script_name", "=", "sys", ".", "argv", "[", "0", "]", "buf", ...
Usage format should be like: Lineno | Content 1 | Script description (__doc__) 2 | Usage: {script name} [COMMAND] [ARGUMENTS] 3 | \n 4 | Commands: 5 | cmd1 cmd1 description. 6 | cmd2isverylong cmd2 description, a...
[ "Usage", "format", "should", "be", "like", ":", "Lineno", "|", "Content", "1", "|", "Script", "description", "(", "__doc__", ")", "2", "|", "Usage", ":", "{", "script", "name", "}", "[", "COMMAND", "]", "[", "ARGUMENTS", "]", "3", "|", "\\", "n", "...
python
train
31.681818
MIT-LCP/wfdb-python
wfdb/io/_signal.py
https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/io/_signal.py#L1798-L1824
def _infer_sig_len(file_name, fmt, n_sig, dir_name, pb_dir=None): """ Infer the length of a signal from a dat file. Parameters ---------- file_name : str Name of the dat file fmt : str WFDB fmt of the dat file n_sig : int Number of signals contained in the dat file ...
[ "def", "_infer_sig_len", "(", "file_name", ",", "fmt", ",", "n_sig", ",", "dir_name", ",", "pb_dir", "=", "None", ")", ":", "if", "pb_dir", "is", "None", ":", "file_size", "=", "os", ".", "path", ".", "getsize", "(", "os", ".", "path", ".", "join", ...
Infer the length of a signal from a dat file. Parameters ---------- file_name : str Name of the dat file fmt : str WFDB fmt of the dat file n_sig : int Number of signals contained in the dat file Notes ----- sig_len * n_sig * bytes_per_sample == file_size
[ "Infer", "the", "length", "of", "a", "signal", "from", "a", "dat", "file", "." ]
python
train
25.62963
tensorflow/probability
tensorflow_probability/python/optimizer/differential_evolution.py
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/differential_evolution.py#L120-L211
def one_step( objective_function, population, population_values=None, differential_weight=0.5, crossover_prob=0.9, seed=None, name=None): """Performs one step of the differential evolution algorithm. Args: objective_function: A Python callable that accepts a batch of possible ...
[ "def", "one_step", "(", "objective_function", ",", "population", ",", "population_values", "=", "None", ",", "differential_weight", "=", "0.5", ",", "crossover_prob", "=", "0.9", ",", "seed", "=", "None", ",", "name", "=", "None", ")", ":", "with", "tf", "...
Performs one step of the differential evolution algorithm. Args: objective_function: A Python callable that accepts a batch of possible solutions and returns the values of the objective function at those arguments as a rank 1 real `Tensor`. This specifies the function to be minimized. The inpu...
[ "Performs", "one", "step", "of", "the", "differential", "evolution", "algorithm", "." ]
python
test
48
SUNCAT-Center/CatHub
cathub/postgresql.py
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/postgresql.py#L224-L318
def create_user(self, user, table_privileges=['ALL PRIVILEGES'], schema_privileges=['ALL PRIVILEGES'], row_limit=50000): con = self.connection or self._connect() cur = con.cursor() cur.execute('CREATE SCHEMA {0};'.format(user)) # self._initialize(...
[ "def", "create_user", "(", "self", ",", "user", ",", "table_privileges", "=", "[", "'ALL PRIVILEGES'", "]", ",", "schema_privileges", "=", "[", "'ALL PRIVILEGES'", "]", ",", "row_limit", "=", "50000", ")", ":", "con", "=", "self", ".", "connection", "or", ...
Grant SELECT on public schema
[ "Grant", "SELECT", "on", "public", "schema" ]
python
train
38.442105
arteria/django-openinghours
openinghours/forms.py
https://github.com/arteria/django-openinghours/blob/6bad47509a14d65a3a5a08777455f4cc8b4961fa/openinghours/forms.py#L23-L31
def time_choices(): """Return digital time choices every half hour from 00:00 to 23:30.""" hours = list(range(0, 24)) times = [] for h in hours: hour = str(h).zfill(2) times.append(hour+':00') times.append(hour+':30') return list(zip(times, times))
[ "def", "time_choices", "(", ")", ":", "hours", "=", "list", "(", "range", "(", "0", ",", "24", ")", ")", "times", "=", "[", "]", "for", "h", "in", "hours", ":", "hour", "=", "str", "(", "h", ")", ".", "zfill", "(", "2", ")", "times", ".", "...
Return digital time choices every half hour from 00:00 to 23:30.
[ "Return", "digital", "time", "choices", "every", "half", "hour", "from", "00", ":", "00", "to", "23", ":", "30", "." ]
python
train
31.555556
rocky/python-uncompyle6
uncompyle6/semantics/helper.py
https://github.com/rocky/python-uncompyle6/blob/c5d7944e657f0ad05a0e2edd34e1acb27001abc0/uncompyle6/semantics/helper.py#L142-L162
def flatten_list(node): """ List of expressions may be nested in groups of 32 and 1024 items. flatten that out and return the list """ flat_elems = [] for elem in node: if elem == 'expr1024': for subelem in elem: assert subelem == 'expr32' for ...
[ "def", "flatten_list", "(", "node", ")", ":", "flat_elems", "=", "[", "]", "for", "elem", "in", "node", ":", "if", "elem", "==", "'expr1024'", ":", "for", "subelem", "in", "elem", ":", "assert", "subelem", "==", "'expr32'", "for", "subsubelem", "in", "...
List of expressions may be nested in groups of 32 and 1024 items. flatten that out and return the list
[ "List", "of", "expressions", "may", "be", "nested", "in", "groups", "of", "32", "and", "1024", "items", ".", "flatten", "that", "out", "and", "return", "the", "list" ]
python
train
29.619048
imtapps/ggeocoder
ggeocoder.py
https://github.com/imtapps/ggeocoder/blob/1db83d4fa635b09bc837bf00257f438f1c090bbe/ggeocoder.py#L251-L259
def _generate_signature(self, base_url, private_key): """ http://code.google.com/apis/maps/documentation/webservices/index.html#PythonSignatureExample """ url = urlparse.urlparse(base_url) url_to_sign = url.path + '?' + url.query decoded_key = base64.urlsafe_b64decode(pri...
[ "def", "_generate_signature", "(", "self", ",", "base_url", ",", "private_key", ")", ":", "url", "=", "urlparse", ".", "urlparse", "(", "base_url", ")", "url_to_sign", "=", "url", ".", "path", "+", "'?'", "+", "url", ".", "query", "decoded_key", "=", "ba...
http://code.google.com/apis/maps/documentation/webservices/index.html#PythonSignatureExample
[ "http", ":", "//", "code", ".", "google", ".", "com", "/", "apis", "/", "maps", "/", "documentation", "/", "webservices", "/", "index", ".", "html#PythonSignatureExample" ]
python
train
50
limix/glimix-core
glimix_core/lmm/_lmm_scan.py
https://github.com/limix/glimix-core/blob/cddd0994591d100499cc41c1f480ddd575e7a980/glimix_core/lmm/_lmm_scan.py#L267-L315
def scan(self, M): """ LML, fixed-effect sizes, and scale of the candidate set. Parameters ---------- M : array_like Fixed-effects set. Returns ------- lml : float Log of the marginal likelihood. effsizes0 : ndarray ...
[ "def", "scan", "(", "self", ",", "M", ")", ":", "from", "numpy_sugar", ".", "linalg", "import", "ddot", "from", "numpy_sugar", "import", "is_all_finite", "M", "=", "asarray", "(", "M", ",", "float", ")", "if", "M", ".", "shape", "[", "1", "]", "==", ...
LML, fixed-effect sizes, and scale of the candidate set. Parameters ---------- M : array_like Fixed-effects set. Returns ------- lml : float Log of the marginal likelihood. effsizes0 : ndarray Covariates fixed-effect sizes. ...
[ "LML", "fixed", "-", "effect", "sizes", "and", "scale", "of", "the", "candidate", "set", "." ]
python
valid
31.081633
viniciuschiele/flask-apidoc
flask_apidoc/apidoc.py
https://github.com/viniciuschiele/flask-apidoc/blob/5c3dfd9aae7780622e843bf7e95863264df3a488/flask_apidoc/apidoc.py#L85-L121
def __send_api_file(self, file_name): """ Send apidoc files from the apidoc folder to the browser. This method replaces all absolute urls in the file by the current url. :param file_name: the apidoc file. """ file_name = join(self.app.static_folder, file_name) ...
[ "def", "__send_api_file", "(", "self", ",", "file_name", ")", ":", "file_name", "=", "join", "(", "self", ".", "app", ".", "static_folder", ",", "file_name", ")", "with", "codecs", ".", "open", "(", "file_name", ",", "'r'", ",", "'utf-8'", ")", "as", "...
Send apidoc files from the apidoc folder to the browser. This method replaces all absolute urls in the file by the current url. :param file_name: the apidoc file.
[ "Send", "apidoc", "files", "from", "the", "apidoc", "folder", "to", "the", "browser", ".", "This", "method", "replaces", "all", "absolute", "urls", "in", "the", "file", "by", "the", "current", "url", ".", ":", "param", "file_name", ":", "the", "apidoc", ...
python
train
33.135135
bids-standard/pybids
bids/layout/layout.py
https://github.com/bids-standard/pybids/blob/30d924ce770622bda0e390d613a8da42a2a20c32/bids/layout/layout.py#L794-L798
def get_bval(self, path, **kwargs): """ Get bval file for passed path. """ result = self.get_nearest(path, extensions='bval', suffix='dwi', all_=True, **kwargs) return listify(result)[0]
[ "def", "get_bval", "(", "self", ",", "path", ",", "*", "*", "kwargs", ")", ":", "result", "=", "self", ".", "get_nearest", "(", "path", ",", "extensions", "=", "'bval'", ",", "suffix", "=", "'dwi'", ",", "all_", "=", "True", ",", "*", "*", "kwargs"...
Get bval file for passed path.
[ "Get", "bval", "file", "for", "passed", "path", "." ]
python
train
48
kelproject/pykube
pykube/objects.py
https://github.com/kelproject/pykube/blob/e8a46298a592ad9037587afb707ac75b3114eff9/pykube/objects.py#L138-L160
def object_factory(api, api_version, kind): """ Dynamically builds a Python class for the given Kubernetes object in an API. For example: api = pykube.HTTPClient(...) NetworkPolicy = pykube.object_factory(api, "networking.k8s.io/v1", "NetworkPolicy") This enables construction of any K...
[ "def", "object_factory", "(", "api", ",", "api_version", ",", "kind", ")", ":", "resource_list", "=", "api", ".", "resource_list", "(", "api_version", ")", "resource", "=", "next", "(", "(", "resource", "for", "resource", "in", "resource_list", "[", "\"resou...
Dynamically builds a Python class for the given Kubernetes object in an API. For example: api = pykube.HTTPClient(...) NetworkPolicy = pykube.object_factory(api, "networking.k8s.io/v1", "NetworkPolicy") This enables construction of any Kubernetes object kind without explicit support from ...
[ "Dynamically", "builds", "a", "Python", "class", "for", "the", "given", "Kubernetes", "object", "in", "an", "API", "." ]
python
train
39.565217
materialsproject/pymatgen
pymatgen/apps/battery/conversion_battery.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/apps/battery/conversion_battery.py#L250-L305
def get_summary_dict(self, print_subelectrodes=True): """ Args: print_subelectrodes: Also print data on all the possible subelectrodes Returns: a summary of this electrode"s properties in dictionary format """ d = {} framework_com...
[ "def", "get_summary_dict", "(", "self", ",", "print_subelectrodes", "=", "True", ")", ":", "d", "=", "{", "}", "framework_comp", "=", "Composition", "(", "{", "k", ":", "v", "for", "k", ",", "v", "in", "self", ".", "_composition", ".", "items", "(", ...
Args: print_subelectrodes: Also print data on all the possible subelectrodes Returns: a summary of this electrode"s properties in dictionary format
[ "Args", ":", "print_subelectrodes", ":", "Also", "print", "data", "on", "all", "the", "possible", "subelectrodes" ]
python
train
43.142857
log2timeline/plaso
plaso/storage/interface.py
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/storage/interface.py#L47-L66
def GetAttributeContainerByIndex(self, index): """Retrieves a specific serialized attribute container from the list. Args: index (int): attribute container index. Returns: bytes: serialized attribute container data or None if not available. Raises: IndexError: if the index is less t...
[ "def", "GetAttributeContainerByIndex", "(", "self", ",", "index", ")", ":", "if", "index", "<", "0", ":", "raise", "IndexError", "(", "'Unsupported negative index value: {0:d}.'", ".", "format", "(", "index", ")", ")", "if", "index", "<", "len", "(", "self", ...
Retrieves a specific serialized attribute container from the list. Args: index (int): attribute container index. Returns: bytes: serialized attribute container data or None if not available. Raises: IndexError: if the index is less than zero.
[ "Retrieves", "a", "specific", "serialized", "attribute", "container", "from", "the", "list", "." ]
python
train
25.45
manns/pyspread
pyspread/src/lib/vlc.py
https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/lib/vlc.py#L5052-L5067
def libvlc_video_set_callbacks(mp, lock, unlock, display, opaque): '''Set callbacks and private data to render decoded video to a custom area in memory. Use L{libvlc_video_set_format}() or L{libvlc_video_set_format_callbacks}() to configure the decoded format. @param mp: the media player. @param...
[ "def", "libvlc_video_set_callbacks", "(", "mp", ",", "lock", ",", "unlock", ",", "display", ",", "opaque", ")", ":", "f", "=", "_Cfunctions", ".", "get", "(", "'libvlc_video_set_callbacks'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_video_set_callbacks...
Set callbacks and private data to render decoded video to a custom area in memory. Use L{libvlc_video_set_format}() or L{libvlc_video_set_format_callbacks}() to configure the decoded format. @param mp: the media player. @param lock: callback to lock video memory (must not be NULL). @param unlock...
[ "Set", "callbacks", "and", "private", "data", "to", "render", "decoded", "video", "to", "a", "custom", "area", "in", "memory", ".", "Use", "L", "{", "libvlc_video_set_format", "}", "()", "or", "L", "{", "libvlc_video_set_format_callbacks", "}", "()", "to", "...
python
train
58.4375
ahwillia/tensortools
tensortools/data/random_tensor.py
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/data/random_tensor.py#L91-L136
def rand_ktensor(shape, rank, norm=None, random_state=None): """ Generates a random N-way tensor with rank R, where the entries are drawn from the standard uniform distribution in the interval [0.0,1]. Parameters ---------- shape : tuple shape of the tensor rank : integer r...
[ "def", "rand_ktensor", "(", "shape", ",", "rank", ",", "norm", "=", "None", ",", "random_state", "=", "None", ")", ":", "# Check input.", "rns", "=", "_check_random_state", "(", "random_state", ")", "# Randomize low-rank factor matrices i.i.d. uniform random elements.",...
Generates a random N-way tensor with rank R, where the entries are drawn from the standard uniform distribution in the interval [0.0,1]. Parameters ---------- shape : tuple shape of the tensor rank : integer rank of the tensor norm : float or None, optional (defaults: None) ...
[ "Generates", "a", "random", "N", "-", "way", "tensor", "with", "rank", "R", "where", "the", "entries", "are", "drawn", "from", "the", "standard", "uniform", "distribution", "in", "the", "interval", "[", "0", ".", "0", "1", "]", "." ]
python
train
32.956522
fake-name/ChromeController
ChromeController/Generator/Generated.py
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L5968-L5986
def Tracing_recordClockSyncMarker(self, syncId): """ Function path: Tracing.recordClockSyncMarker Domain: Tracing Method name: recordClockSyncMarker Parameters: Required arguments: 'syncId' (type: string) -> The ID of this clock sync marker No return value. Description: Record a clock ...
[ "def", "Tracing_recordClockSyncMarker", "(", "self", ",", "syncId", ")", ":", "assert", "isinstance", "(", "syncId", ",", "(", "str", ",", ")", ")", ",", "\"Argument 'syncId' must be of type '['str']'. Received type: '%s'\"", "%", "type", "(", "syncId", ")", "subdom...
Function path: Tracing.recordClockSyncMarker Domain: Tracing Method name: recordClockSyncMarker Parameters: Required arguments: 'syncId' (type: string) -> The ID of this clock sync marker No return value. Description: Record a clock sync marker in the trace.
[ "Function", "path", ":", "Tracing", ".", "recordClockSyncMarker", "Domain", ":", "Tracing", "Method", "name", ":", "recordClockSyncMarker", "Parameters", ":", "Required", "arguments", ":", "syncId", "(", "type", ":", "string", ")", "-", ">", "The", "ID", "of",...
python
train
30.736842
ambitioninc/python-logentries-api
logentries_api/resources.py
https://github.com/ambitioninc/python-logentries-api/blob/77ff1a7a2995d7ea2725b74e34c0f880f4ee23bc/logentries_api/resources.py#L402-L453
def update(self, hook): """ Update a hook :param hook: The data to update. Must include keys: * id (str) * name (str) * triggers (list of str) * sources (list of str) * groups (list of str) * actions (list of str) ...
[ "def", "update", "(", "self", ",", "hook", ")", ":", "data", "=", "{", "'id'", ":", "hook", "[", "'id'", "]", ",", "'name'", ":", "hook", "[", "'name'", "]", ",", "'triggers'", ":", "hook", "[", "'triggers'", "]", ",", "'sources'", ":", "hook", "...
Update a hook :param hook: The data to update. Must include keys: * id (str) * name (str) * triggers (list of str) * sources (list of str) * groups (list of str) * actions (list of str) :type hook: dict Example: ...
[ "Update", "a", "hook" ]
python
test
27.173077
dwwkelly/note
note/mongo_driver.py
https://github.com/dwwkelly/note/blob/b41d5fe1e4a3b67b50285168dd58f903bf219e6c/note/mongo_driver.py#L330-L369
def verify(self): """ :desc: Verifies the integrity of the database, specifically checks the values for unusedIDs and currentMax :returns: A boolean indicating whether the database is valid or not :rval: bool """ collec...
[ "def", "verify", "(", "self", ")", ":", "collections", "=", "self", ".", "get_data_collections", "(", ")", "allIDs", "=", "[", "]", "for", "coll", "in", "collections", ":", "IDs", "=", "self", ".", "noteDB", "[", "coll", "]", ".", "find", "(", "{", ...
:desc: Verifies the integrity of the database, specifically checks the values for unusedIDs and currentMax :returns: A boolean indicating whether the database is valid or not :rval: bool
[ ":", "desc", ":", "Verifies", "the", "integrity", "of", "the", "database", "specifically", "checks", "the", "values", "for", "unusedIDs", "and", "currentMax", ":", "returns", ":", "A", "boolean", "indicating", "whether", "the", "database", "is", "valid", "or",...
python
train
36.925
bcbio/bcbio-nextgen
bcbio/cwl/tool.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/tool.py#L34-L50
def _run_tool(cmd, use_container=True, work_dir=None, log_file=None): """Run with injection of bcbio path. Place at end for runs without containers to avoid overriding other bcbio installations. """ if isinstance(cmd, (list, tuple)): cmd = " ".join([str(x) for x in cmd]) cmd = utils.loc...
[ "def", "_run_tool", "(", "cmd", ",", "use_container", "=", "True", ",", "work_dir", "=", "None", ",", "log_file", "=", "None", ")", ":", "if", "isinstance", "(", "cmd", ",", "(", "list", ",", "tuple", ")", ")", ":", "cmd", "=", "\" \"", ".", "join"...
Run with injection of bcbio path. Place at end for runs without containers to avoid overriding other bcbio installations.
[ "Run", "with", "injection", "of", "bcbio", "path", "." ]
python
train
34.764706
miedzinski/google-oauth
google_oauth/service.py
https://github.com/miedzinski/google-oauth/blob/aef2e19d87281b1d8e42d6b158111e14e80128db/google_oauth/service.py#L99-L119
def from_pkcs12(cls, key, email, scopes, subject=None, passphrase=PKCS12_PASSPHRASE): """Alternate constructor intended for using .p12 files. Args: key (dict) - Parsed JSON with service account credentials. email (str) - Service account email. sco...
[ "def", "from_pkcs12", "(", "cls", ",", "key", ",", "email", ",", "scopes", ",", "subject", "=", "None", ",", "passphrase", "=", "PKCS12_PASSPHRASE", ")", ":", "key", "=", "OpenSSL", ".", "crypto", ".", "load_pkcs12", "(", "key", ",", "passphrase", ")", ...
Alternate constructor intended for using .p12 files. Args: key (dict) - Parsed JSON with service account credentials. email (str) - Service account email. scopes (Union[str, collections.Iterable[str]]) - List of permissions that the application requests. ...
[ "Alternate", "constructor", "intended", "for", "using", ".", "p12", "files", "." ]
python
train
47.285714
projectatomic/osbs-client
osbs/build/build_request.py
https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/build/build_request.py#L843-L871
def render_bump_release(self): """ If the bump_release plugin is present, configure it """ phase = 'prebuild_plugins' plugin = 'bump_release' if not self.dj.dock_json_has_plugin_conf(phase, plugin): return if self.spec.release.value: logge...
[ "def", "render_bump_release", "(", "self", ")", ":", "phase", "=", "'prebuild_plugins'", "plugin", "=", "'bump_release'", "if", "not", "self", ".", "dj", ".", "dock_json_has_plugin_conf", "(", "phase", ",", "plugin", ")", ":", "return", "if", "self", ".", "s...
If the bump_release plugin is present, configure it
[ "If", "the", "bump_release", "plugin", "is", "present", "configure", "it" ]
python
train
35.862069
buildbot/buildbot
worker/buildbot_worker/compat.py
https://github.com/buildbot/buildbot/blob/5df3cfae6d760557d99156633c32b1822a1e130c/worker/buildbot_worker/compat.py#L74-L87
def bytes2unicode(x, encoding='utf-8', errors='strict'): """ Convert a C{bytes} to a unicode string. @param x: a unicode string, of type C{unicode} on Python 2, or C{str} on Python 3. @param encoding: an optional codec, default: 'utf-8' @param errors: error handling scheme, default 's...
[ "def", "bytes2unicode", "(", "x", ",", "encoding", "=", "'utf-8'", ",", "errors", "=", "'strict'", ")", ":", "if", "isinstance", "(", "x", ",", "(", "text_type", ",", "type", "(", "None", ")", ")", ")", ":", "return", "x", "return", "text_type", "(",...
Convert a C{bytes} to a unicode string. @param x: a unicode string, of type C{unicode} on Python 2, or C{str} on Python 3. @param encoding: an optional codec, default: 'utf-8' @param errors: error handling scheme, default 'strict' @return: a unicode string of type C{unicode} on Python 2, ...
[ "Convert", "a", "C", "{", "bytes", "}", "to", "a", "unicode", "string", "." ]
python
train
37.5
disqus/nose-socket-whitelist
src/socketwhitelist/plugins.py
https://github.com/disqus/nose-socket-whitelist/blob/062f9bac079a01f74a94abda977c9a28ad472f39/src/socketwhitelist/plugins.py#L146-L182
def report(self): """ Performs rollups, prints report of sockets opened. """ aggregations = dict( (test, Counter().rollup(values)) for test, values in self.socket_warnings.items() ) total = sum( len(warnings) for warnings in...
[ "def", "report", "(", "self", ")", ":", "aggregations", "=", "dict", "(", "(", "test", ",", "Counter", "(", ")", ".", "rollup", "(", "values", ")", ")", "for", "test", ",", "values", "in", "self", ".", "socket_warnings", ".", "items", "(", ")", ")"...
Performs rollups, prints report of sockets opened.
[ "Performs", "rollups", "prints", "report", "of", "sockets", "opened", "." ]
python
train
32.108108
Esri/ArcREST
src/arcrest/ags/_imageservice.py
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/ags/_imageservice.py#L916-L1030
def measure(self,fromGeometry,toGeometry,measureOperation, geometryType="esriGeometryPoint",pixelSize=None,mosaicRule=None, linearUnit=None,angularUnit=None,areaUnit=None): """ The measure operation is performed on an image service resource. It lets a user measure...
[ "def", "measure", "(", "self", ",", "fromGeometry", ",", "toGeometry", ",", "measureOperation", ",", "geometryType", "=", "\"esriGeometryPoint\"", ",", "pixelSize", "=", "None", ",", "mosaicRule", "=", "None", ",", "linearUnit", "=", "None", ",", "angularUnit", ...
The measure operation is performed on an image service resource. It lets a user measure distance, direction, area, perimeter, and height from an image service. The result of this operation includes the name of the raster dataset being used, sensor name, and measured values. The measure ...
[ "The", "measure", "operation", "is", "performed", "on", "an", "image", "service", "resource", ".", "It", "lets", "a", "user", "measure", "distance", "direction", "area", "perimeter", "and", "height", "from", "an", "image", "service", ".", "The", "result", "o...
python
train
53
klmitch/bark
bark/format.py
https://github.com/klmitch/bark/blob/6e0e002d55f01fee27e3e45bb86e30af1bfeef36/bark/format.py#L118-L144
def set_conversion(self, idx): """ Adds the conversion to the format. :param idx: The ending index of the conversion name. """ # First, determine the name if self.conv_begin: name = self.format[self.conv_begin:idx] else: name = self.forma...
[ "def", "set_conversion", "(", "self", ",", "idx", ")", ":", "# First, determine the name", "if", "self", ".", "conv_begin", ":", "name", "=", "self", ".", "format", "[", "self", ".", "conv_begin", ":", "idx", "]", "else", ":", "name", "=", "self", ".", ...
Adds the conversion to the format. :param idx: The ending index of the conversion name.
[ "Adds", "the", "conversion", "to", "the", "format", "." ]
python
train
28.777778
quantopian/zipline
zipline/finance/position.py
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/position.py#L215-L225
def to_dict(self): """ Creates a dictionary representing the state of this position. Returns a dict object of the form: """ return { 'sid': self.asset, 'amount': self.amount, 'cost_basis': self.cost_basis, 'last_sale_price': self.la...
[ "def", "to_dict", "(", "self", ")", ":", "return", "{", "'sid'", ":", "self", ".", "asset", ",", "'amount'", ":", "self", ".", "amount", ",", "'cost_basis'", ":", "self", ".", "cost_basis", ",", "'last_sale_price'", ":", "self", ".", "last_sale_price", "...
Creates a dictionary representing the state of this position. Returns a dict object of the form:
[ "Creates", "a", "dictionary", "representing", "the", "state", "of", "this", "position", ".", "Returns", "a", "dict", "object", "of", "the", "form", ":" ]
python
train
30.272727
jmcgeheeiv/pyfakefs
pyfakefs/fake_filesystem.py
https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L4506-L4524
def fsync(self, file_des): """Perform fsync for a fake file (in other words, do nothing). Args: file_des: The file descriptor of the open file. Raises: OSError: file_des is an invalid file descriptor. TypeError: file_des is not an integer. """ ...
[ "def", "fsync", "(", "self", ",", "file_des", ")", ":", "# Throw an error if file_des isn't valid", "if", "0", "<=", "file_des", "<", "NR_STD_STREAMS", ":", "self", ".", "filesystem", ".", "raise_os_error", "(", "errno", ".", "EINVAL", ")", "file_object", "=", ...
Perform fsync for a fake file (in other words, do nothing). Args: file_des: The file descriptor of the open file. Raises: OSError: file_des is an invalid file descriptor. TypeError: file_des is not an integer.
[ "Perform", "fsync", "for", "a", "fake", "file", "(", "in", "other", "words", "do", "nothing", ")", "." ]
python
train
40.157895
onicagroup/runway
runway/commands/modules_command.py
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/commands/modules_command.py#L196-L219
def validate_account_credentials(deployment, context): """Exit if requested deployment account doesn't match credentials.""" boto_args = {'region_name': context.env_vars['AWS_DEFAULT_REGION']} for i in ['aws_access_key_id', 'aws_secret_access_key', 'aws_session_token']: if context.env_...
[ "def", "validate_account_credentials", "(", "deployment", ",", "context", ")", ":", "boto_args", "=", "{", "'region_name'", ":", "context", ".", "env_vars", "[", "'AWS_DEFAULT_REGION'", "]", "}", "for", "i", "in", "[", "'aws_access_key_id'", ",", "'aws_secret_acce...
Exit if requested deployment account doesn't match credentials.
[ "Exit", "if", "requested", "deployment", "account", "doesn", "t", "match", "credentials", "." ]
python
train
49.666667
jaredLunde/vital-tools
vital/tools/html.py
https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/tools/html.py#L38-L56
def remove_whitespace(s): """ Unsafely attempts to remove HTML whitespace. This is not an HTML parser which is why its considered 'unsafe', but it should work for most implementations. Just use on at your own risk. @s: #str -> HTML with whitespace removed, ignoring <pre>, script, t...
[ "def", "remove_whitespace", "(", "s", ")", ":", "ignores", "=", "{", "}", "for", "ignore", "in", "html_ignore_whitespace_re", ".", "finditer", "(", "s", ")", ":", "name", "=", "\"{}{}{}\"", ".", "format", "(", "r\"{}\"", ",", "uuid", ".", "uuid4", "(", ...
Unsafely attempts to remove HTML whitespace. This is not an HTML parser which is why its considered 'unsafe', but it should work for most implementations. Just use on at your own risk. @s: #str -> HTML with whitespace removed, ignoring <pre>, script, textarea and code tags
[ "Unsafely", "attempts", "to", "remove", "HTML", "whitespace", ".", "This", "is", "not", "an", "HTML", "parser", "which", "is", "why", "its", "considered", "unsafe", "but", "it", "should", "work", "for", "most", "implementations", ".", "Just", "use", "on", ...
python
train
35.894737
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py#L890-L906
def _SkipFieldMessage(tokenizer): """Skips over a field message. Args: tokenizer: A tokenizer to parse the field name and values. """ if tokenizer.TryConsume('<'): delimiter = '>' else: tokenizer.Consume('{') delimiter = '}' while not tokenizer.LookingAt('>') and not tokenizer.LookingAt('...
[ "def", "_SkipFieldMessage", "(", "tokenizer", ")", ":", "if", "tokenizer", ".", "TryConsume", "(", "'<'", ")", ":", "delimiter", "=", "'>'", "else", ":", "tokenizer", ".", "Consume", "(", "'{'", ")", "delimiter", "=", "'}'", "while", "not", "tokenizer", ...
Skips over a field message. Args: tokenizer: A tokenizer to parse the field name and values.
[ "Skips", "over", "a", "field", "message", "." ]
python
train
21.529412
sassoo/goldman
goldman/stores/base.py
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/stores/base.py#L24-L33
def get(self, key, bucket): """ Get a cached item by key If the cached item isn't found the return None. """ try: return self._cache[bucket][key] except (KeyError, TypeError): return None
[ "def", "get", "(", "self", ",", "key", ",", "bucket", ")", ":", "try", ":", "return", "self", ".", "_cache", "[", "bucket", "]", "[", "key", "]", "except", "(", "KeyError", ",", "TypeError", ")", ":", "return", "None" ]
Get a cached item by key If the cached item isn't found the return None.
[ "Get", "a", "cached", "item", "by", "key" ]
python
train
24.4
evhub/coconut
coconut/compiler/compiler.py
https://github.com/evhub/coconut/blob/ff97177344e7604e89a0a98a977a87ed2a56fc6d/coconut/compiler/compiler.py#L1033-L1082
def str_repl(self, inputstring, **kwargs): """Add back strings.""" out = [] comment = None string = None for i, c in enumerate(append_it(inputstring, None)): try: if comment is not None: if c is not None and c in nums: ...
[ "def", "str_repl", "(", "self", ",", "inputstring", ",", "*", "*", "kwargs", ")", ":", "out", "=", "[", "]", "comment", "=", "None", "string", "=", "None", "for", "i", ",", "c", "in", "enumerate", "(", "append_it", "(", "inputstring", ",", "None", ...
Add back strings.
[ "Add", "back", "strings", "." ]
python
train
39.62
PyCQA/astroid
astroid/brain/brain_namedtuple_enum.py
https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/brain/brain_namedtuple_enum.py#L297-L363
def infer_enum_class(node): """ Specific inference for enums. """ for basename in node.basenames: # TODO: doesn't handle subclasses yet. This implementation # is a hack to support enums. if basename not in ENUM_BASE_NAMES: continue if node.root().name == "enum": ...
[ "def", "infer_enum_class", "(", "node", ")", ":", "for", "basename", "in", "node", ".", "basenames", ":", "# TODO: doesn't handle subclasses yet. This implementation", "# is a hack to support enums.", "if", "basename", "not", "in", "ENUM_BASE_NAMES", ":", "continue", "if"...
Specific inference for enums.
[ "Specific", "inference", "for", "enums", "." ]
python
train
41.820896
wmayner/pyphi
pyphi/models/fmt.py
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/models/fmt.py#L252-L283
def fmt_partition(partition): """Format a |Bipartition|. The returned string looks like:: 0,1 ∅ ─── ✕ ─── 2 0,1 Args: partition (Bipartition): The partition in question. Returns: str: A human-readable string representation of the partition. """ ...
[ "def", "fmt_partition", "(", "partition", ")", ":", "if", "not", "partition", ":", "return", "''", "parts", "=", "[", "fmt_part", "(", "part", ",", "partition", ".", "node_labels", ")", ".", "split", "(", "'\\n'", ")", "for", "part", "in", "partition", ...
Format a |Bipartition|. The returned string looks like:: 0,1 ∅ ─── ✕ ─── 2 0,1 Args: partition (Bipartition): The partition in question. Returns: str: A human-readable string representation of the partition.
[ "Format", "a", "|Bipartition|", "." ]
python
train
26.0625
midasplatform/pydas
pydas/drivers.py
https://github.com/midasplatform/pydas/blob/e5f9e96e754fb2dc5da187b05e4abc77a9b2affd/pydas/drivers.py#L345-L360
def get_default_api_key(self, email, password): """ Get the default API key for a user. :param email: The email of the user. :type email: string :param password: The user's password. :type password: string :returns: API key to confirm that it was fetched successf...
[ "def", "get_default_api_key", "(", "self", ",", "email", ",", "password", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'email'", "]", "=", "email", "parameters", "[", "'password'", "]", "=", "password", "response", "=", "self", ".", ...
Get the default API key for a user. :param email: The email of the user. :type email: string :param password: The user's password. :type password: string :returns: API key to confirm that it was fetched successfully. :rtype: string
[ "Get", "the", "default", "API", "key", "for", "a", "user", "." ]
python
valid
34.875
okunishinishi/python-stringcase
stringcase.py
https://github.com/okunishinishi/python-stringcase/blob/700ad111be16b384aadaddcf8199f9390575c7b6/stringcase.py#L103-L116
def backslashcase(string): """Convert string into spinal case. Join punctuation with backslash. Args: string: String to convert. Returns: string: Spinal cased string. """ str1 = re.sub(r"_", r"\\", snakecase(string)) return str1
[ "def", "backslashcase", "(", "string", ")", ":", "str1", "=", "re", ".", "sub", "(", "r\"_\"", ",", "r\"\\\\\"", ",", "snakecase", "(", "string", ")", ")", "return", "str1" ]
Convert string into spinal case. Join punctuation with backslash. Args: string: String to convert. Returns: string: Spinal cased string.
[ "Convert", "string", "into", "spinal", "case", ".", "Join", "punctuation", "with", "backslash", "." ]
python
valid
18.785714
jaredLunde/redis_structures
redis_structures/__init__.py
https://github.com/jaredLunde/redis_structures/blob/b9cce5f5c85db5e12c292633ff8d04e3ae053294/redis_structures/__init__.py#L708-L712
def _bucket_key(self): """ Returns hash bucket key for the redis key """ return "{}.size.{}".format( self.prefix, (self._hashed_key//1000) if self._hashed_key > 1000 else self._hashed_key)
[ "def", "_bucket_key", "(", "self", ")", ":", "return", "\"{}.size.{}\"", ".", "format", "(", "self", ".", "prefix", ",", "(", "self", ".", "_hashed_key", "//", "1000", ")", "if", "self", ".", "_hashed_key", ">", "1000", "else", "self", ".", "_hashed_key"...
Returns hash bucket key for the redis key
[ "Returns", "hash", "bucket", "key", "for", "the", "redis", "key" ]
python
train
44.8
pgjones/quart
quart/wrappers/_base.py
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/wrappers/_base.py#L195-L204
def blueprint(self) -> Optional[str]: """Returns the blueprint the matched endpoint belongs to. This can be None if the request has not been matched or the endpoint is not in a blueprint. """ if self.endpoint is not None and '.' in self.endpoint: return self.endpoint...
[ "def", "blueprint", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "if", "self", ".", "endpoint", "is", "not", "None", "and", "'.'", "in", "self", ".", "endpoint", ":", "return", "self", ".", "endpoint", ".", "rsplit", "(", "'.'", ",", "...
Returns the blueprint the matched endpoint belongs to. This can be None if the request has not been matched or the endpoint is not in a blueprint.
[ "Returns", "the", "blueprint", "the", "matched", "endpoint", "belongs", "to", "." ]
python
train
36.7
exoscale/cs
cs/client.py
https://github.com/exoscale/cs/blob/3a0b05559c1f9f3c5bda34920d4497dfd8b9290a/cs/client.py#L334-L414
def _jobresult(self, jobid, json=True, headers=None): """Poll the async job result. To be run via in a Thread, the result is put within the result list which is a hack. """ failures = 0 total_time = self.job_timeout or 2**30 remaining = timedelta(seconds=total_t...
[ "def", "_jobresult", "(", "self", ",", "jobid", ",", "json", "=", "True", ",", "headers", "=", "None", ")", ":", "failures", "=", "0", "total_time", "=", "self", ".", "job_timeout", "or", "2", "**", "30", "remaining", "=", "timedelta", "(", "seconds", ...
Poll the async job result. To be run via in a Thread, the result is put within the result list which is a hack.
[ "Poll", "the", "async", "job", "result", "." ]
python
train
38.382716
mitsei/dlkit
dlkit/records/repository/basic/media_accessibility.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/records/repository/basic/media_accessibility.py#L71-L80
def get_alt_texts_metadata(self): """Gets the metadata for all alt_texts. return: (osid.Metadata) - metadata for the alt_texts *compliance: mandatory -- This method must be implemented.* """ metadata = dict(self._alt_texts_metadata) metadata.update({'existing_string_val...
[ "def", "get_alt_texts_metadata", "(", "self", ")", ":", "metadata", "=", "dict", "(", "self", ".", "_alt_texts_metadata", ")", "metadata", ".", "update", "(", "{", "'existing_string_values'", ":", "[", "t", "[", "'text'", "]", "for", "t", "in", "self", "."...
Gets the metadata for all alt_texts. return: (osid.Metadata) - metadata for the alt_texts *compliance: mandatory -- This method must be implemented.*
[ "Gets", "the", "metadata", "for", "all", "alt_texts", "." ]
python
train
42
spookey/photon
photon/util/files.py
https://github.com/spookey/photon/blob/57212a26ce713ab7723910ee49e3d0ba1697799f/photon/util/files.py#L8-L26
def read_file(filename): ''' Reads files :param filename: The full path of the file to read :returns: The content of the file as string (if `filename` exists) .. note:: If `filename`'s content is empty, ``None`` will also returned. To check if a file really exists ...
[ "def", "read_file", "(", "filename", ")", ":", "if", "filename", "and", "_path", ".", "exists", "(", "filename", ")", ":", "with", "open", "(", "filename", ",", "'r'", ")", "as", "f", ":", "return", "f", ".", "read", "(", ")" ]
Reads files :param filename: The full path of the file to read :returns: The content of the file as string (if `filename` exists) .. note:: If `filename`'s content is empty, ``None`` will also returned. To check if a file really exists use :func:`util.locations.search_loc...
[ "Reads", "files" ]
python
train
24.473684
markovmodel/msmtools
msmtools/estimation/sparse/effective_counts.py
https://github.com/markovmodel/msmtools/blob/54dc76dd2113a0e8f3d15d5316abab41402941be/msmtools/estimation/sparse/effective_counts.py#L38-L62
def _split_sequences_singletraj(dtraj, nstates, lag): """ splits the discrete trajectory into conditional sequences by starting state Parameters ---------- dtraj : int-iterable discrete trajectory nstates : int total number of discrete states lag : int lag time """ ...
[ "def", "_split_sequences_singletraj", "(", "dtraj", ",", "nstates", ",", "lag", ")", ":", "sall", "=", "[", "[", "]", "for", "_", "in", "range", "(", "nstates", ")", "]", "res_states", "=", "[", "]", "res_seqs", "=", "[", "]", "for", "t", "in", "ra...
splits the discrete trajectory into conditional sequences by starting state Parameters ---------- dtraj : int-iterable discrete trajectory nstates : int total number of discrete states lag : int lag time
[ "splits", "the", "discrete", "trajectory", "into", "conditional", "sequences", "by", "starting", "state" ]
python
train
25
rootpy/rootpy
rootpy/extern/shortuuid/__init__.py
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/extern/shortuuid/__init__.py#L39-L44
def encode(self, uuid, pad_length=22): """ Encodes a UUID into a string (LSB first) according to the alphabet If leftmost (MSB) bits 0, string might be shorter """ return self._num_to_string(uuid.int, pad_to_length=pad_length)
[ "def", "encode", "(", "self", ",", "uuid", ",", "pad_length", "=", "22", ")", ":", "return", "self", ".", "_num_to_string", "(", "uuid", ".", "int", ",", "pad_to_length", "=", "pad_length", ")" ]
Encodes a UUID into a string (LSB first) according to the alphabet If leftmost (MSB) bits 0, string might be shorter
[ "Encodes", "a", "UUID", "into", "a", "string", "(", "LSB", "first", ")", "according", "to", "the", "alphabet", "If", "leftmost", "(", "MSB", ")", "bits", "0", "string", "might", "be", "shorter" ]
python
train
43.5
opencobra/memote
memote/support/consistency.py
https://github.com/opencobra/memote/blob/276630fcd4449fb7b914186edfd38c239e7052df/memote/support/consistency.py#L400-L431
def find_stoichiometrically_balanced_cycles(model): u""" Find metabolic reactions in stoichiometrically balanced cycles (SBCs). Identify forward and reverse cycles by closing all exchanges and using FVA. Parameters ---------- model : cobra.Model The metabolic model under investigation....
[ "def", "find_stoichiometrically_balanced_cycles", "(", "model", ")", ":", "helpers", ".", "close_boundaries_sensibly", "(", "model", ")", "fva_result", "=", "flux_variability_analysis", "(", "model", ",", "loopless", "=", "False", ")", "return", "fva_result", ".", "...
u""" Find metabolic reactions in stoichiometrically balanced cycles (SBCs). Identify forward and reverse cycles by closing all exchanges and using FVA. Parameters ---------- model : cobra.Model The metabolic model under investigation. Notes ----- "SBCs are artifacts of metabol...
[ "u", "Find", "metabolic", "reactions", "in", "stoichiometrically", "balanced", "cycles", "(", "SBCs", ")", "." ]
python
train
35.625
gboeing/osmnx
osmnx/plot.py
https://github.com/gboeing/osmnx/blob/be59fd313bcb68af8fc79242c56194f1247e26e2/osmnx/plot.py#L183-L215
def get_edge_colors_by_attr(G, attr, num_bins=5, cmap='viridis', start=0, stop=1, na_color='none'): """ Get a list of edge colors by binning some continuous-variable attribute into quantiles. Parameters ---------- G : networkx multidigraph attr : string the name of the continuous-va...
[ "def", "get_edge_colors_by_attr", "(", "G", ",", "attr", ",", "num_bins", "=", "5", ",", "cmap", "=", "'viridis'", ",", "start", "=", "0", ",", "stop", "=", "1", ",", "na_color", "=", "'none'", ")", ":", "if", "num_bins", "is", "None", ":", "num_bins...
Get a list of edge colors by binning some continuous-variable attribute into quantiles. Parameters ---------- G : networkx multidigraph attr : string the name of the continuous-variable attribute num_bins : int how many quantiles cmap : string name of a colormap ...
[ "Get", "a", "list", "of", "edge", "colors", "by", "binning", "some", "continuous", "-", "variable", "attribute", "into", "quantiles", "." ]
python
train
31.757576
sony/nnabla
python/src/nnabla/parametric_functions.py
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/parametric_functions.py#L942-L1022
def binary_connect_convolution(inp, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, quantize_zero_to=1.0, w_init=None, wb_init=None, b_init=None, base_axis=1, fix_parameters=False,...
[ "def", "binary_connect_convolution", "(", "inp", ",", "outmaps", ",", "kernel", ",", "pad", "=", "None", ",", "stride", "=", "None", ",", "dilation", "=", "None", ",", "group", "=", "1", ",", "quantize_zero_to", "=", "1.0", ",", "w_init", "=", "None", ...
Binary Connect Convolution, multiplier-less inner-product. Binary Connect Convolution is the convolution function, except the definition of the inner product is modified. The input-output relation of this function is as follows: .. math:: y_{n, a, b} = \sum_{m} \sum_{i} \sum_{j} sign(w_{n, m,...
[ "Binary", "Connect", "Convolution", "multiplier", "-", "less", "inner", "-", "product", "." ]
python
train
58.160494
tensorflow/tensorboard
tensorboard/util/op_evaluator.py
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/util/op_evaluator.py#L70-L82
def _lazily_initialize(self): """Initialize the graph and session, if this has not yet been done.""" # TODO(nickfelt): remove on-demand imports once dep situation is fixed. import tensorflow.compat.v1 as tf with self._initialization_lock: if self._session: return graph = tf.Graph() ...
[ "def", "_lazily_initialize", "(", "self", ")", ":", "# TODO(nickfelt): remove on-demand imports once dep situation is fixed.", "import", "tensorflow", ".", "compat", ".", "v1", "as", "tf", "with", "self", ".", "_initialization_lock", ":", "if", "self", ".", "_session", ...
Initialize the graph and session, if this has not yet been done.
[ "Initialize", "the", "graph", "and", "session", "if", "this", "has", "not", "yet", "been", "done", "." ]
python
train
41.846154
ynop/audiomate
audiomate/processing/base.py
https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/processing/base.py#L358-L384
def _process_corpus(self, corpus, output_path, processing_func, frame_size=400, hop_size=160, sr=None): """ Utility function for processing a corpus with a separate processing function. """ feat_container = containers.FeatureContainer(output_path) feat_container.open() sampling_rate = -...
[ "def", "_process_corpus", "(", "self", ",", "corpus", ",", "output_path", ",", "processing_func", ",", "frame_size", "=", "400", ",", "hop_size", "=", "160", ",", "sr", "=", "None", ")", ":", "feat_container", "=", "containers", ".", "FeatureContainer", "(",...
Utility function for processing a corpus with a separate processing function.
[ "Utility", "function", "for", "processing", "a", "corpus", "with", "a", "separate", "processing", "function", "." ]
python
train
40.925926
wbond/asn1crypto
asn1crypto/crl.py
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/crl.py#L461-L480
def issuer_cert_urls(self): """ :return: A list of unicode strings that are URLs that should contain either an individual DER-encoded X.509 certificate, or a DER-encoded CMS message containing multiple certificates """ if self._issuer_cert_urls is Non...
[ "def", "issuer_cert_urls", "(", "self", ")", ":", "if", "self", ".", "_issuer_cert_urls", "is", "None", ":", "self", ".", "_issuer_cert_urls", "=", "[", "]", "if", "self", ".", "authority_information_access_value", ":", "for", "entry", "in", "self", ".", "au...
:return: A list of unicode strings that are URLs that should contain either an individual DER-encoded X.509 certificate, or a DER-encoded CMS message containing multiple certificates
[ ":", "return", ":", "A", "list", "of", "unicode", "strings", "that", "are", "URLs", "that", "should", "contain", "either", "an", "individual", "DER", "-", "encoded", "X", ".", "509", "certificate", "or", "a", "DER", "-", "encoded", "CMS", "message", "con...
python
train
45.8
nicolargo/glances
glances/exports/glances_csv.py
https://github.com/nicolargo/glances/blob/5bd4d587a736e0d2b03170b56926841d2a3eb7ee/glances/exports/glances_csv.py#L64-L98
def update(self, stats): """Update stats in the CSV output file.""" # Get the stats all_stats = stats.getAllExportsAsDict(plugin_list=self.plugins_to_export()) # Init data with timestamp (issue#708) if self.first_line: csv_header = ['timestamp'] csv_data = [t...
[ "def", "update", "(", "self", ",", "stats", ")", ":", "# Get the stats", "all_stats", "=", "stats", ".", "getAllExportsAsDict", "(", "plugin_list", "=", "self", ".", "plugins_to_export", "(", ")", ")", "# Init data with timestamp (issue#708)", "if", "self", ".", ...
Update stats in the CSV output file.
[ "Update", "stats", "in", "the", "CSV", "output", "file", "." ]
python
train
41.171429
wroberts/fsed
fsed/ahocorasick.py
https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/ahocorasick.py#L185-L193
def _reset_suffix_links(self): ''' Reset all suffix links in all nodes in this trie. ''' self._suffix_links_set = False for current, _parent in self.dfs(): current.suffix = None current.dict_suffix = None current.longest_prefix = None
[ "def", "_reset_suffix_links", "(", "self", ")", ":", "self", ".", "_suffix_links_set", "=", "False", "for", "current", ",", "_parent", "in", "self", ".", "dfs", "(", ")", ":", "current", ".", "suffix", "=", "None", "current", ".", "dict_suffix", "=", "No...
Reset all suffix links in all nodes in this trie.
[ "Reset", "all", "suffix", "links", "in", "all", "nodes", "in", "this", "trie", "." ]
python
train
33.555556
Alignak-monitoring/alignak
alignak/daemons/receiverdaemon.py
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/receiverdaemon.py#L244-L305
def push_external_commands_to_schedulers(self): """Push received external commands to the schedulers :return: None """ if not self.unprocessed_external_commands: return # Those are the global external commands commands_to_process = self.unprocessed_external_...
[ "def", "push_external_commands_to_schedulers", "(", "self", ")", ":", "if", "not", "self", ".", "unprocessed_external_commands", ":", "return", "# Those are the global external commands", "commands_to_process", "=", "self", ".", "unprocessed_external_commands", "self", ".", ...
Push received external commands to the schedulers :return: None
[ "Push", "received", "external", "commands", "to", "the", "schedulers" ]
python
train
46.548387
empymod/empymod
empymod/scripts/fdesign.py
https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/scripts/fdesign.py#L953-L962
def j1_2(a=1): r"""Hankel transform pair J1_2 ([Ande75]_).""" def lhs(x): return np.exp(-a*x) def rhs(b): return (np.sqrt(b**2 + a**2) - a)/(b*np.sqrt(b**2 + a**2)) return Ghosh('j1', lhs, rhs)
[ "def", "j1_2", "(", "a", "=", "1", ")", ":", "def", "lhs", "(", "x", ")", ":", "return", "np", ".", "exp", "(", "-", "a", "*", "x", ")", "def", "rhs", "(", "b", ")", ":", "return", "(", "np", ".", "sqrt", "(", "b", "**", "2", "+", "a", ...
r"""Hankel transform pair J1_2 ([Ande75]_).
[ "r", "Hankel", "transform", "pair", "J1_2", "(", "[", "Ande75", "]", "_", ")", "." ]
python
train
21.9
tensorflow/tensor2tensor
tensor2tensor/data_generators/wikisum/wikisum.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/wikisum.py#L382-L481
def produce_examples(shard_ids, wikis_dir, refs_dir, urls_dir, vocab_path, out_filepaths): """Produce examples from shard_ids to out_filepaths.""" # * Join the Wikipedia articles with their references # * Run Tf-idf to sort reference paragraphs # * Encode the Wikipedia and reference text wi...
[ "def", "produce_examples", "(", "shard_ids", ",", "wikis_dir", ",", "refs_dir", ",", "urls_dir", ",", "vocab_path", ",", "out_filepaths", ")", ":", "# * Join the Wikipedia articles with their references", "# * Run Tf-idf to sort reference paragraphs", "# * Encode the Wikipedia an...
Produce examples from shard_ids to out_filepaths.
[ "Produce", "examples", "from", "shard_ids", "to", "out_filepaths", "." ]
python
train
41.27
wavefrontHQ/python-client
wavefront_api_client/api/event_api.py
https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/api/event_api.py#L828-L849
def set_event_tags(self, id, **kwargs): # noqa: E501 """Set all tags associated with a specific event # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.set_even...
[ "def", "set_event_tags", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "set_event_tag...
Set all tags associated with a specific event # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.set_event_tags(id, async_req=True) >>> result = thread.get() ...
[ "Set", "all", "tags", "associated", "with", "a", "specific", "event", "#", "noqa", ":", "E501" ]
python
train
40.545455
pypa/pipenv
pipenv/patched/notpip/_internal/index.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/index.py#L450-L489
def _candidate_sort_key(self, candidate, ignore_compatibility=True): # type: (InstallationCandidate, bool) -> CandidateSortingKey """ Function used to generate link sort key for link tuples. The greater the return value, the more preferred it is. If not finding wheels, then sorte...
[ "def", "_candidate_sort_key", "(", "self", ",", "candidate", ",", "ignore_compatibility", "=", "True", ")", ":", "# type: (InstallationCandidate, bool) -> CandidateSortingKey", "support_num", "=", "len", "(", "self", ".", "valid_tags", ")", "build_tag", "=", "tuple", ...
Function used to generate link sort key for link tuples. The greater the return value, the more preferred it is. If not finding wheels, then sorted by version only. If finding wheels, then the sort order is by version, then: 1. existing installs 2. wheels ordered via Wheel.su...
[ "Function", "used", "to", "generate", "link", "sort", "key", "for", "link", "tuples", ".", "The", "greater", "the", "return", "value", "the", "more", "preferred", "it", "is", ".", "If", "not", "finding", "wheels", "then", "sorted", "by", "version", "only",...
python
train
49.3
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/DFReader.py
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/DFReader.py#L173-L179
def type_has_good_TimeMS(self, type): '''The TimeMS in some messages is not from *our* clock!''' if type.startswith('ACC'): return False; if type.startswith('GYR'): return False; return True
[ "def", "type_has_good_TimeMS", "(", "self", ",", "type", ")", ":", "if", "type", ".", "startswith", "(", "'ACC'", ")", ":", "return", "False", "if", "type", ".", "startswith", "(", "'GYR'", ")", ":", "return", "False", "return", "True" ]
The TimeMS in some messages is not from *our* clock!
[ "The", "TimeMS", "in", "some", "messages", "is", "not", "from", "*", "our", "*", "clock!" ]
python
train
34.285714
Neurita/boyle
scripts/filetree.py
https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/scripts/filetree.py#L20-L72
def copy(configfile='', destpath='', overwrite=False, sub_node=''): """Copies the files in the built file tree map to despath. :param configfile: string Path to the FileTreeMap config file :param destpath: string Path to the files destination :param overwrite: bool Overwrite files ...
[ "def", "copy", "(", "configfile", "=", "''", ",", "destpath", "=", "''", ",", "overwrite", "=", "False", ",", "sub_node", "=", "''", ")", ":", "log", ".", "info", "(", "'Running {0} {1} {2}'", ".", "format", "(", "os", ".", "path", ".", "basename", "...
Copies the files in the built file tree map to despath. :param configfile: string Path to the FileTreeMap config file :param destpath: string Path to the files destination :param overwrite: bool Overwrite files if they already exist. :param sub_node: string Tree map configura...
[ "Copies", "the", "files", "in", "the", "built", "file", "tree", "map", "to", "despath", "." ]
python
valid
30.075472
Nachtfeuer/pipeline
spline/components/tasks.py
https://github.com/Nachtfeuer/pipeline/blob/04ca18c4e95e4349532bb45b768206393e1f2c13/spline/components/tasks.py#L204-L211
def process_shells(self, shells): """Processing a list of shells.""" result = {'success': True, 'output': []} if self.parallel and len(shells) > 1: result = self.process_shells_parallel(shells) elif len(shells) > 0: result = self.process_shells_ordered(shells) ...
[ "def", "process_shells", "(", "self", ",", "shells", ")", ":", "result", "=", "{", "'success'", ":", "True", ",", "'output'", ":", "[", "]", "}", "if", "self", ".", "parallel", "and", "len", "(", "shells", ")", ">", "1", ":", "result", "=", "self",...
Processing a list of shells.
[ "Processing", "a", "list", "of", "shells", "." ]
python
train
41.375
codelv/enaml-native
src/enamlnative/android/http.py
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/http.py#L188-L204
def _default_body(self): """ If the body is not passed in by the user try to create one using the given data parameters. """ if not self.data: return "" if self.content_type == 'application/json': import json return json.dumps(self.data) ...
[ "def", "_default_body", "(", "self", ")", ":", "if", "not", "self", ".", "data", ":", "return", "\"\"", "if", "self", ".", "content_type", "==", "'application/json'", ":", "import", "json", "return", "json", ".", "dumps", "(", "self", ".", "data", ")", ...
If the body is not passed in by the user try to create one using the given data parameters.
[ "If", "the", "body", "is", "not", "passed", "in", "by", "the", "user", "try", "to", "create", "one", "using", "the", "given", "data", "parameters", "." ]
python
train
36.647059
floydhub/floyd-cli
floyd/cli/data.py
https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/data.py#L98-L109
def status(id): """ View status of all versions in a dataset. The command also accepts a specific dataset version. """ if id: data_source = get_data_object(id, use_data_config=False) print_data([data_source] if data_source else []) else: data_sources = DataClient().get_a...
[ "def", "status", "(", "id", ")", ":", "if", "id", ":", "data_source", "=", "get_data_object", "(", "id", ",", "use_data_config", "=", "False", ")", "print_data", "(", "[", "data_source", "]", "if", "data_source", "else", "[", "]", ")", "else", ":", "da...
View status of all versions in a dataset. The command also accepts a specific dataset version.
[ "View", "status", "of", "all", "versions", "in", "a", "dataset", "." ]
python
train
28.833333
foremast/foremast
src/foremast/utils/slack.py
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/utils/slack.py#L26-L40
def post_slack_message(message=None, channel=None, username=None, icon_emoji=None): """Format the message and post to the appropriate slack channel. Args: message (str): Message to post to slack channel (str): Desired channel. Must start with # """ LOG.debug('Slack Channel: %s\nSlack M...
[ "def", "post_slack_message", "(", "message", "=", "None", ",", "channel", "=", "None", ",", "username", "=", "None", ",", "icon_emoji", "=", "None", ")", ":", "LOG", ".", "debug", "(", "'Slack Channel: %s\\nSlack Message: %s'", ",", "channel", ",", "message", ...
Format the message and post to the appropriate slack channel. Args: message (str): Message to post to slack channel (str): Desired channel. Must start with #
[ "Format", "the", "message", "and", "post", "to", "the", "appropriate", "slack", "channel", "." ]
python
train
41.533333
helium/helium-python
helium/timeseries.py
https://github.com/helium/helium-python/blob/db73480b143da4fc48e95c4414bd69c576a3a390/helium/timeseries.py#L305-L333
def timeseries(): """Create a timeseries builder. Returns: A builder function which, given a class creates a timeseries relationship for that class. """ def method_builder(cls): method_doc = """Fetch the timeseries for this :class:`{0}`. Returns: The :cla...
[ "def", "timeseries", "(", ")", ":", "def", "method_builder", "(", "cls", ")", ":", "method_doc", "=", "\"\"\"Fetch the timeseries for this :class:`{0}`.\n\n Returns:\n\n The :class:`Timeseries` for this :class:`{0}`\n\n Keyword Args:\n\n **kwargs: The :c...
Create a timeseries builder. Returns: A builder function which, given a class creates a timeseries relationship for that class.
[ "Create", "a", "timeseries", "builder", "." ]
python
train
26.344828
asyncdef/eventemitter
eventemitter/emitter.py
https://github.com/asyncdef/eventemitter/blob/148b700c5846d8fdafc562d4326587da5447223f/eventemitter/emitter.py#L95-L121
def remove_listener(self, event, listener): """Remove a listener from the emitter. Args: event (str): The event name on which the listener is bound. listener: A reference to the same object given to add_listener. Returns: bool: True if a listener was removed...
[ "def", "remove_listener", "(", "self", ",", "event", ",", "listener", ")", ":", "with", "contextlib", ".", "suppress", "(", "ValueError", ")", ":", "self", ".", "_listeners", "[", "event", "]", ".", "remove", "(", "listener", ")", "return", "True", "with...
Remove a listener from the emitter. Args: event (str): The event name on which the listener is bound. listener: A reference to the same object given to add_listener. Returns: bool: True if a listener was removed else False. This method only removes one list...
[ "Remove", "a", "listener", "from", "the", "emitter", "." ]
python
valid
34.925926
spacetelescope/drizzlepac
drizzlepac/wfpc2Data.py
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/wfpc2Data.py#L58-L97
def find_DQ_extension(self): """ Return the suffix for the data quality extension and the name of the file which that DQ extension should be read from. """ dqfile = None # Look for additional file with DQ array, primarily for WFPC2 data indx = self._filename.find('.fits...
[ "def", "find_DQ_extension", "(", "self", ")", ":", "dqfile", "=", "None", "# Look for additional file with DQ array, primarily for WFPC2 data", "indx", "=", "self", ".", "_filename", ".", "find", "(", "'.fits'", ")", "if", "indx", ">", "3", ":", "suffix", "=", "...
Return the suffix for the data quality extension and the name of the file which that DQ extension should be read from.
[ "Return", "the", "suffix", "for", "the", "data", "quality", "extension", "and", "the", "name", "of", "the", "file", "which", "that", "DQ", "extension", "should", "be", "read", "from", "." ]
python
train
35.325
Azure/azure-sdk-for-python
azure-servicemanagement-legacy/azure/servicemanagement/schedulermanagementservice.py
https://github.com/Azure/azure-sdk-for-python/blob/d7306fde32f60a293a7567678692bdad31e4b667/azure-servicemanagement-legacy/azure/servicemanagement/schedulermanagementservice.py#L139-L156
def check_job_collection_name(self, cloud_service_id, job_collection_id): ''' The Check Name Availability operation checks if a new job collection with the given name may be created, or if it is unavailable. The result of the operation is a Boolean true or false. cloud_service_i...
[ "def", "check_job_collection_name", "(", "self", ",", "cloud_service_id", ",", "job_collection_id", ")", ":", "_validate_not_none", "(", "'cloud_service_id'", ",", "cloud_service_id", ")", "_validate_not_none", "(", "'job_collection_id'", ",", "job_collection_id", ")", "p...
The Check Name Availability operation checks if a new job collection with the given name may be created, or if it is unavailable. The result of the operation is a Boolean true or false. cloud_service_id: The cloud service id job_collection_id: The name of the job...
[ "The", "Check", "Name", "Availability", "operation", "checks", "if", "a", "new", "job", "collection", "with", "the", "given", "name", "may", "be", "created", "or", "if", "it", "is", "unavailable", ".", "The", "result", "of", "the", "operation", "is", "a", ...
python
test
45
OpenKMIP/PyKMIP
kmip/services/kmip_client.py
https://github.com/OpenKMIP/PyKMIP/blob/b51c5b044bd05f8c85a1d65d13a583a4d8fc1b0e/kmip/services/kmip_client.py#L345-L421
def rekey(self, uuid=None, offset=None, template_attribute=None, credential=None): """ Check object usage according to specific constraints. Args: uuid (string): The unique identifier of a managed cryptographic ...
[ "def", "rekey", "(", "self", ",", "uuid", "=", "None", ",", "offset", "=", "None", ",", "template_attribute", "=", "None", ",", "credential", "=", "None", ")", ":", "operation", "=", "Operation", "(", "OperationEnum", ".", "REKEY", ")", "request_payload", ...
Check object usage according to specific constraints. Args: uuid (string): The unique identifier of a managed cryptographic object that should be checked. Optional, defaults to None. offset (int): An integer specifying, in seconds, the difference between ...
[ "Check", "object", "usage", "according", "to", "specific", "constraints", "." ]
python
test
44.376623
ResidentMario/geoplot
geoplot/geoplot.py
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/geoplot.py#L2246-L2285
def _set_extent(ax, projection, extent, extrema): """ Sets the plot extent. Parameters ---------- ax : cartopy.GeoAxesSubplot instance The axis whose boundaries are being tweaked. projection : None or geoplot.crs instance The projection, if one is being used. extent : None o...
[ "def", "_set_extent", "(", "ax", ",", "projection", ",", "extent", ",", "extrema", ")", ":", "if", "extent", ":", "xmin", ",", "xmax", ",", "ymin", ",", "ymax", "=", "extent", "xmin", ",", "xmax", ",", "ymin", ",", "ymax", "=", "max", "(", "xmin", ...
Sets the plot extent. Parameters ---------- ax : cartopy.GeoAxesSubplot instance The axis whose boundaries are being tweaked. projection : None or geoplot.crs instance The projection, if one is being used. extent : None or (xmin, xmax, ymin, ymax) tuple A copy of the ``exten...
[ "Sets", "the", "plot", "extent", "." ]
python
train
41.35
ev3dev/ev3dev-lang-python
ev3dev2/sensor/lego.py
https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/sensor/lego.py#L799-L809
def distance(self, channel=1): """ Returns distance (0, 100) to the beacon on the given channel. Returns None when beacon is not found. """ self._ensure_mode(self.MODE_IR_SEEK) channel = self._normalize_channel(channel) ret_value = self.value((channel * 2) + 1) ...
[ "def", "distance", "(", "self", ",", "channel", "=", "1", ")", ":", "self", ".", "_ensure_mode", "(", "self", ".", "MODE_IR_SEEK", ")", "channel", "=", "self", ".", "_normalize_channel", "(", "channel", ")", "ret_value", "=", "self", ".", "value", "(", ...
Returns distance (0, 100) to the beacon on the given channel. Returns None when beacon is not found.
[ "Returns", "distance", "(", "0", "100", ")", "to", "the", "beacon", "on", "the", "given", "channel", ".", "Returns", "None", "when", "beacon", "is", "not", "found", "." ]
python
train
40
gwastro/pycbc
pycbc/frame/frame.py
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/frame/frame.py#L566-L581
def advance(self, blocksize): """Add blocksize seconds more to the buffer, push blocksize seconds from the beginning. Parameters ---------- blocksize: int The number of seconds to attempt to read from the channel """ ts = self._read_frame(blocksize) ...
[ "def", "advance", "(", "self", ",", "blocksize", ")", ":", "ts", "=", "self", ".", "_read_frame", "(", "blocksize", ")", "self", ".", "raw_buffer", ".", "roll", "(", "-", "len", "(", "ts", ")", ")", "self", ".", "raw_buffer", "[", "-", "len", "(", ...
Add blocksize seconds more to the buffer, push blocksize seconds from the beginning. Parameters ---------- blocksize: int The number of seconds to attempt to read from the channel
[ "Add", "blocksize", "seconds", "more", "to", "the", "buffer", "push", "blocksize", "seconds", "from", "the", "beginning", "." ]
python
train
30.4375
brocade/pynos
pynos/versions/ver_7/ver_7_1_0/yang/brocade_firmware.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_firmware.py#L420-L434
def firmware_download_input_protocol_type_sftp_protocol_sftp_password(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") firmware_download = ET.Element("firmware_download") config = firmware_download input = ET.SubElement(firmware_download, "input")...
[ "def", "firmware_download_input_protocol_type_sftp_protocol_sftp_password", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "firmware_download", "=", "ET", ".", "Element", "(", "\"firmware_download\"", ")"...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
45.266667
rbarrois/confutils
confutils/configfile.py
https://github.com/rbarrois/confutils/blob/26bbb3f31c09a99ee2104263a9e97d6d3fc8e4f4/confutils/configfile.py#L358-L364
def get_line(self, section, line): """Retrieve all lines compatible with a given line.""" try: section = self._get_section(section, create=False) except KeyError: return [] return section.find_lines(line)
[ "def", "get_line", "(", "self", ",", "section", ",", "line", ")", ":", "try", ":", "section", "=", "self", ".", "_get_section", "(", "section", ",", "create", "=", "False", ")", "except", "KeyError", ":", "return", "[", "]", "return", "section", ".", ...
Retrieve all lines compatible with a given line.
[ "Retrieve", "all", "lines", "compatible", "with", "a", "given", "line", "." ]
python
train
36.285714
cloudera/impyla
impala/hiveserver2.py
https://github.com/cloudera/impyla/blob/547fa2ba3b6151e2a98b3544301471a643212dc3/impala/hiveserver2.py#L458-L483
def fetchcbatch(self): '''Return a CBatch object of any data currently in the buffer or if no data currently in buffer then fetch a batch''' if not self._last_operation.is_columnar: raise NotSupportedError("Server does not support columnar " "fe...
[ "def", "fetchcbatch", "(", "self", ")", ":", "if", "not", "self", ".", "_last_operation", ".", "is_columnar", ":", "raise", "NotSupportedError", "(", "\"Server does not support columnar \"", "\"fetching\"", ")", "if", "not", "self", ".", "has_result_set", ":", "ra...
Return a CBatch object of any data currently in the buffer or if no data currently in buffer then fetch a batch
[ "Return", "a", "CBatch", "object", "of", "any", "data", "currently", "in", "the", "buffer", "or", "if", "no", "data", "currently", "in", "buffer", "then", "fetch", "a", "batch" ]
python
train
43.807692
Azure/azure-multiapi-storage-python
azure/multiapi/storage/v2016_05_31/file/fileservice.py
https://github.com/Azure/azure-multiapi-storage-python/blob/bd5482547f993c6eb56fd09070e15c2e9616e440/azure/multiapi/storage/v2016_05_31/file/fileservice.py#L1796-L1876
def get_file_to_path(self, share_name, directory_name, file_name, file_path, open_mode='wb', start_range=None, end_range=None, validate_content=False, progress_callback=None, max_connections=2, timeout=None): ''' Downloads a file...
[ "def", "get_file_to_path", "(", "self", ",", "share_name", ",", "directory_name", ",", "file_name", ",", "file_path", ",", "open_mode", "=", "'wb'", ",", "start_range", "=", "None", ",", "end_range", "=", "None", ",", "validate_content", "=", "False", ",", "...
Downloads a file to a file path, with automatic chunking and progress notifications. Returns an instance of File with properties and metadata. :param str share_name: Name of existing share. :param str directory_name: The path to the directory. :param str file_nam...
[ "Downloads", "a", "file", "to", "a", "file", "path", "with", "automatic", "chunking", "and", "progress", "notifications", ".", "Returns", "an", "instance", "of", "File", "with", "properties", "and", "metadata", "." ]
python
train
56.901235
yunojuno-archive/django-package-monitor
package_monitor/admin.py
https://github.com/yunojuno-archive/django-package-monitor/blob/534aa35ccfe187d2c55aeca0cb52b8278254e437/package_monitor/admin.py#L48-L72
def queryset(self, request, queryset): """Filter based on whether an update (of any sort) is available.""" if self.value() == '-1': return queryset.filter(latest_version__isnull=True) elif self.value() == '0': return ( queryset .filter( ...
[ "def", "queryset", "(", "self", ",", "request", ",", "queryset", ")", ":", "if", "self", ".", "value", "(", ")", "==", "'-1'", ":", "return", "queryset", ".", "filter", "(", "latest_version__isnull", "=", "True", ")", "elif", "self", ".", "value", "(",...
Filter based on whether an update (of any sort) is available.
[ "Filter", "based", "on", "whether", "an", "update", "(", "of", "any", "sort", ")", "is", "available", "." ]
python
train
33.72
CivicSpleen/ambry
ambry/bundle/concurrent.py
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/concurrent.py#L137-L151
def init_library(database_dsn, accounts_password, limited_run = False): """Child initializer, setup in Library.process_pool""" import os import signal # Have the child processes ignore the keyboard interrupt, and other signals. Instead, the parent will # catch these, and clean up the children. ...
[ "def", "init_library", "(", "database_dsn", ",", "accounts_password", ",", "limited_run", "=", "False", ")", ":", "import", "os", "import", "signal", "# Have the child processes ignore the keyboard interrupt, and other signals. Instead, the parent will", "# catch these, and clean u...
Child initializer, setup in Library.process_pool
[ "Child", "initializer", "setup", "in", "Library", ".", "process_pool" ]
python
train
39.666667
rytilahti/python-songpal
songpal/main.py
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L742-L745
async def mute(gc: GroupControl, mute): """(Un)mute group.""" click.echo("Muting group: %s" % mute) click.echo(await gc.set_mute(mute))
[ "async", "def", "mute", "(", "gc", ":", "GroupControl", ",", "mute", ")", ":", "click", ".", "echo", "(", "\"Muting group: %s\"", "%", "mute", ")", "click", ".", "echo", "(", "await", "gc", ".", "set_mute", "(", "mute", ")", ")" ]
(Un)mute group.
[ "(", "Un", ")", "mute", "group", "." ]
python
train
36
etingof/pysmi
pysmi/parser/smi.py
https://github.com/etingof/pysmi/blob/379a0a384c81875731be51a054bdacced6260fd8/pysmi/parser/smi.py#L659-L666
def p_enumItems(self, p): """enumItems : enumItems ',' enumItem | enumItem""" n = len(p) if n == 4: p[0] = p[1] + [p[3]] elif n == 2: p[0] = [p[1]]
[ "def", "p_enumItems", "(", "self", ",", "p", ")", ":", "n", "=", "len", "(", "p", ")", "if", "n", "==", "4", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "+", "[", "p", "[", "3", "]", "]", "elif", "n", "==", "2", ":", "p", "[", ...
enumItems : enumItems ',' enumItem | enumItem
[ "enumItems", ":", "enumItems", "enumItem", "|", "enumItem" ]
python
valid
27.125
lreis2415/PyGeoC
pygeoc/utils.py
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/utils.py#L345-L375
def rsr(obsvalues, # type: Union[numpy.ndarray, List[Union[float, int]]] simvalues # type: Union[numpy.ndarray, List[Union[float, int]]] ): # type: (...) -> Union[float, numpy.ScalarType] """Calculate RSR (RMSE-to-SD Ratio). Programmed according to equation (3) in ...
[ "def", "rsr", "(", "obsvalues", ",", "# type: Union[numpy.ndarray, List[Union[float, int]]]", "simvalues", "# type: Union[numpy.ndarray, List[Union[float, int]]]", ")", ":", "# type: (...) -> Union[float, numpy.ScalarType]", "if", "len", "(", "obsvalues", ")", "!=", "len", "(", ...
Calculate RSR (RMSE-to-SD Ratio). Programmed according to equation (3) in Moriasi et al. 2007. Model evalutaion guidelines for systematic quantification of accuracy in watershed simulations. Transactions of the ASABE 50(3): 885-900. Args: obsvalues: observe values array ...
[ "Calculate", "RSR", "(", "RMSE", "-", "to", "-", "SD", "Ratio", ")", "." ]
python
train
46
squaresLab/BugZoo
bugzoo/client/bug.py
https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/client/bug.py#L153-L170
def build(self, bug: Bug): """ Instructs the server to build the Docker image associated with a given bug. """ r = self.__api.post('bugs/{}/build'.format(bug.name)) if r.status_code == 204: return if r.status_code == 200: raise Exception("...
[ "def", "build", "(", "self", ",", "bug", ":", "Bug", ")", ":", "r", "=", "self", ".", "__api", ".", "post", "(", "'bugs/{}/build'", ".", "format", "(", "bug", ".", "name", ")", ")", "if", "r", ".", "status_code", "==", "204", ":", "return", "if",...
Instructs the server to build the Docker image associated with a given bug.
[ "Instructs", "the", "server", "to", "build", "the", "Docker", "image", "associated", "with", "a", "given", "bug", "." ]
python
train
35.222222
njharman/die
die/stats.py
https://github.com/njharman/die/blob/ad6b837fcf2415d1a7c7283f3b333ad435d0821d/die/stats.py#L60-L81
def do_run(self, count=1): '''Roll count dice, store results. Does all stats so might be slower than specific doFoo methods. But, it is proly faster than running each of those seperately to get same stats. Sets the following properties: - stats.bucket - stats.sum ...
[ "def", "do_run", "(", "self", ",", "count", "=", "1", ")", ":", "if", "not", "self", ".", "roll", ".", "summable", ":", "raise", "Exception", "(", "'Roll is not summable'", ")", "h", "=", "dict", "(", ")", "total", "=", "0", "for", "roll", "in", "s...
Roll count dice, store results. Does all stats so might be slower than specific doFoo methods. But, it is proly faster than running each of those seperately to get same stats. Sets the following properties: - stats.bucket - stats.sum - stats.avr :param cou...
[ "Roll", "count", "dice", "store", "results", ".", "Does", "all", "stats", "so", "might", "be", "slower", "than", "specific", "doFoo", "methods", ".", "But", "it", "is", "proly", "faster", "than", "running", "each", "of", "those", "seperately", "to", "get",...
python
train
31.681818
crytic/slither
slither/core/declarations/function.py
https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/declarations/function.py#L726-L747
def all_conditional_solidity_variables_read(self, include_loop=True): """ Return the Soldiity variables directly used in a condtion Use of the IR to filter index access Assumption: the solidity vars are used directly in the conditional node It won't work if the v...
[ "def", "all_conditional_solidity_variables_read", "(", "self", ",", "include_loop", "=", "True", ")", ":", "if", "include_loop", ":", "if", "self", ".", "_all_conditional_solidity_variables_read_with_loop", "is", "None", ":", "self", ".", "_all_conditional_solidity_variab...
Return the Soldiity variables directly used in a condtion Use of the IR to filter index access Assumption: the solidity vars are used directly in the conditional node It won't work if the variable is assigned to a temp variable
[ "Return", "the", "Soldiity", "variables", "directly", "used", "in", "a", "condtion" ]
python
train
60.818182
Guake/guake
guake/guake_app.py
https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/guake_app.py#L404-L421
def execute_command_by_uuid(self, tab_uuid, command): # TODO DBUS_ONLY """Execute the `command' in the tab whose terminal has the `tab_uuid' uuid """ if command[-1] != '\n': command += '\n' try: tab_uuid = uuid.UUID(tab_uuid) page_index, = ( ...
[ "def", "execute_command_by_uuid", "(", "self", ",", "tab_uuid", ",", "command", ")", ":", "# TODO DBUS_ONLY", "if", "command", "[", "-", "1", "]", "!=", "'\\n'", ":", "command", "+=", "'\\n'", "try", ":", "tab_uuid", "=", "uuid", ".", "UUID", "(", "tab_u...
Execute the `command' in the tab whose terminal has the `tab_uuid' uuid
[ "Execute", "the", "command", "in", "the", "tab", "whose", "terminal", "has", "the", "tab_uuid", "uuid" ]
python
train
37.277778
cloud9ers/gurumate
environment/lib/python2.7/site-packages/nose/plugins/manager.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/plugins/manager.py#L101-L111
def addPlugin(self, plugin, call): """Add plugin to my list of plugins to call, if it has the attribute I'm bound to. """ meth = getattr(plugin, call, None) if meth is not None: if call == 'loadTestsFromModule' and \ len(inspect.getargspec(meth)[0]...
[ "def", "addPlugin", "(", "self", ",", "plugin", ",", "call", ")", ":", "meth", "=", "getattr", "(", "plugin", ",", "call", ",", "None", ")", "if", "meth", "is", "not", "None", ":", "if", "call", "==", "'loadTestsFromModule'", "and", "len", "(", "insp...
Add plugin to my list of plugins to call, if it has the attribute I'm bound to.
[ "Add", "plugin", "to", "my", "list", "of", "plugins", "to", "call", "if", "it", "has", "the", "attribute", "I", "m", "bound", "to", "." ]
python
test
42.727273
JoelBender/bacpypes
py25/bacpypes/constructeddata.py
https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/constructeddata.py#L1301-L1374
def cast_out(self, klass): """Interpret the content as a particular class.""" if _debug: Any._debug("cast_out %r", klass) global _sequence_of_classes, _list_of_classes # check for a sequence element if (klass in _sequence_of_classes) or (klass in _list_of_classes): #...
[ "def", "cast_out", "(", "self", ",", "klass", ")", ":", "if", "_debug", ":", "Any", ".", "_debug", "(", "\"cast_out %r\"", ",", "klass", ")", "global", "_sequence_of_classes", ",", "_list_of_classes", "# check for a sequence element", "if", "(", "klass", "in", ...
Interpret the content as a particular class.
[ "Interpret", "the", "content", "as", "a", "particular", "class", "." ]
python
train
29.972973
basho/riak-python-client
riak/client/__init__.py
https://github.com/basho/riak-python-client/blob/91de13a16607cdf553d1a194e762734e3bec4231/riak/client/__init__.py#L37-L46
def default_encoder(obj): """ Default encoder for JSON datatypes, which returns UTF-8 encoded json instead of the default bloated backslash u XXXX escaped ASCII strings. """ if isinstance(obj, bytes): return json.dumps(bytes_to_str(obj), ensure_ascii=False).encode("...
[ "def", "default_encoder", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "bytes", ")", ":", "return", "json", ".", "dumps", "(", "bytes_to_str", "(", "obj", ")", ",", "ensure_ascii", "=", "False", ")", ".", "encode", "(", "\"utf-8\"", ")", ...
Default encoder for JSON datatypes, which returns UTF-8 encoded json instead of the default bloated backslash u XXXX escaped ASCII strings.
[ "Default", "encoder", "for", "JSON", "datatypes", "which", "returns", "UTF", "-", "8", "encoded", "json", "instead", "of", "the", "default", "bloated", "backslash", "u", "XXXX", "escaped", "ASCII", "strings", "." ]
python
train
39.5
jgrassler/mkdocs-pandoc
mkdocs_pandoc/filters/tables.py
https://github.com/jgrassler/mkdocs-pandoc/blob/11edfb90830325dca85bd0369bb8e2da8d6815b3/mkdocs_pandoc/filters/tables.py#L60-L169
def convert_table(self, block): """"Converts a table to grid table format""" lines_orig = block.split('\n') lines_orig.pop() # Remove extra newline at end of block widest_cell = [] # Will hold the width of the widest cell for each column widest_word = [] # Will hold the width of ...
[ "def", "convert_table", "(", "self", ",", "block", ")", ":", "lines_orig", "=", "block", ".", "split", "(", "'\\n'", ")", "lines_orig", ".", "pop", "(", ")", "# Remove extra newline at end of block", "widest_cell", "=", "[", "]", "# Will hold the width of the wide...
Converts a table to grid table format
[ "Converts", "a", "table", "to", "grid", "table", "format" ]
python
train
37.654545
johnbywater/eventsourcing
eventsourcing/utils/cipher/aes.py
https://github.com/johnbywater/eventsourcing/blob/de2c22c653fdccf2f5ee96faea74453ff1847e42/eventsourcing/utils/cipher/aes.py#L24-L49
def encrypt(self, plaintext): """Return ciphertext for given plaintext.""" # String to bytes. plainbytes = plaintext.encode('utf8') # Compress plaintext bytes. compressed = zlib.compress(plainbytes) # Construct AES-GCM cipher, with 96-bit nonce. cipher = AES.ne...
[ "def", "encrypt", "(", "self", ",", "plaintext", ")", ":", "# String to bytes.", "plainbytes", "=", "plaintext", ".", "encode", "(", "'utf8'", ")", "# Compress plaintext bytes.", "compressed", "=", "zlib", ".", "compress", "(", "plainbytes", ")", "# Construct AES-...
Return ciphertext for given plaintext.
[ "Return", "ciphertext", "for", "given", "plaintext", "." ]
python
train
28.307692
jobovy/galpy
galpy/df/quasiisothermaldf.py
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/df/quasiisothermaldf.py#L905-L968
def sigmaR2(self,R,z,nsigma=None,mc=False,nmc=10000, gl=True,ngl=_DEFAULTNGL,**kwargs): """ NAME: sigmaR2 PURPOSE: calculate sigma_R^2 by marginalizing over velocity INPUT: R - radius at which to calculate this (can be Quantity) ...
[ "def", "sigmaR2", "(", "self", ",", "R", ",", "z", ",", "nsigma", "=", "None", ",", "mc", "=", "False", ",", "nmc", "=", "10000", ",", "gl", "=", "True", ",", "ngl", "=", "_DEFAULTNGL", ",", "*", "*", "kwargs", ")", ":", "if", "mc", ":", "sur...
NAME: sigmaR2 PURPOSE: calculate sigma_R^2 by marginalizing over velocity INPUT: R - radius at which to calculate this (can be Quantity) z - height at which to calculate this (can be Quantity) OPTIONAL INPUT: nsigma - number of sigma...
[ "NAME", ":" ]
python
train
37.421875
carawarner/pantheon
pantheon/pantheons.py
https://github.com/carawarner/pantheon/blob/7e8718f4397eaa389fb3d5dc04fa01c7cb556512/pantheon/pantheons.py#L30-L59
def spawn(self, generations): """Grow this Pantheon by multiplying Gods.""" egg_donors = [god for god in self.gods.values() if god.chromosomes == 'XX'] sperm_donors = [god for god in self.gods.values() if god.chromosomes == 'XY'] for i in range(generations): print("\nGENERAT...
[ "def", "spawn", "(", "self", ",", "generations", ")", ":", "egg_donors", "=", "[", "god", "for", "god", "in", "self", ".", "gods", ".", "values", "(", ")", "if", "god", ".", "chromosomes", "==", "'XX'", "]", "sperm_donors", "=", "[", "god", "for", ...
Grow this Pantheon by multiplying Gods.
[ "Grow", "this", "Pantheon", "by", "multiplying", "Gods", "." ]
python
valid
40
odlgroup/odl
odl/operator/default_ops.py
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/operator/default_ops.py#L842-L847
def _call(self, x, out=None): """Return the constant vector or assign it to ``out``.""" if out is None: return self.range.element(copy(self.constant)) else: out.assign(self.constant)
[ "def", "_call", "(", "self", ",", "x", ",", "out", "=", "None", ")", ":", "if", "out", "is", "None", ":", "return", "self", ".", "range", ".", "element", "(", "copy", "(", "self", ".", "constant", ")", ")", "else", ":", "out", ".", "assign", "(...
Return the constant vector or assign it to ``out``.
[ "Return", "the", "constant", "vector", "or", "assign", "it", "to", "out", "." ]
python
train
37.5
tjvr/kurt
kurt/scratch14/objtable.py
https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/scratch14/objtable.py#L383-L443
def encode_network(root): """Yield ref-containing obj table entries from object network""" def fix_values(obj): if isinstance(obj, Container): obj.update((k, get_ref(v)) for (k, v) in obj.items() if k != 'class_name') fixed_obj = obj ...
[ "def", "encode_network", "(", "root", ")", ":", "def", "fix_values", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "Container", ")", ":", "obj", ".", "update", "(", "(", "k", ",", "get_ref", "(", "v", ")", ")", "for", "(", "k", ",", ...
Yield ref-containing obj table entries from object network
[ "Yield", "ref", "-", "containing", "obj", "table", "entries", "from", "object", "network" ]
python
train
29.655738
bapakode/OmMongo
ommongo/fields/document_field.py
https://github.com/bapakode/OmMongo/blob/52b5a5420516dc709f2d2eb065818c7973991ce3/ommongo/fields/document_field.py#L108-L114
def validate_wrap(self, value): ''' Checks that ``value`` is an instance of ``DocumentField.type``. if it is, then validation on its fields has already been done and no further validation is needed. ''' if not isinstance(value, self.type): self._fail_validatio...
[ "def", "validate_wrap", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "self", ".", "type", ")", ":", "self", ".", "_fail_validation_type", "(", "value", ",", "self", ".", "type", ")" ]
Checks that ``value`` is an instance of ``DocumentField.type``. if it is, then validation on its fields has already been done and no further validation is needed.
[ "Checks", "that", "value", "is", "an", "instance", "of", "DocumentField", ".", "type", ".", "if", "it", "is", "then", "validation", "on", "its", "fields", "has", "already", "been", "done", "and", "no", "further", "validation", "is", "needed", "." ]
python
train
48.285714
FPGAwars/apio
apio/commands/upload.py
https://github.com/FPGAwars/apio/blob/5c6310f11a061a760764c6b5847bfb431dc3d0bc/apio/commands/upload.py#L36-L52
def cli(ctx, board, serial_port, ftdi_id, sram, project_dir, verbose, verbose_yosys, verbose_arachne): """Upload the bitstream to the FPGA.""" drivers = Drivers() drivers.pre_upload() # Run scons exit_code = SCons(project_dir).upload({ 'board': board, 'verbose': { ...
[ "def", "cli", "(", "ctx", ",", "board", ",", "serial_port", ",", "ftdi_id", ",", "sram", ",", "project_dir", ",", "verbose", ",", "verbose_yosys", ",", "verbose_arachne", ")", ":", "drivers", "=", "Drivers", "(", ")", "drivers", ".", "pre_upload", "(", "...
Upload the bitstream to the FPGA.
[ "Upload", "the", "bitstream", "to", "the", "FPGA", "." ]
python
train
28.882353
mar10/wsgidav
wsgidav/util.py
https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/util.py#L274-L285
def dynamic_import_class(name): """Import a class from a module string, e.g. ``my.module.ClassName``.""" import importlib module_name, class_name = name.rsplit(".", 1) try: module = importlib.import_module(module_name) except Exception as e: _logger.exception("Dynamic import of {!r}...
[ "def", "dynamic_import_class", "(", "name", ")", ":", "import", "importlib", "module_name", ",", "class_name", "=", "name", ".", "rsplit", "(", "\".\"", ",", "1", ")", "try", ":", "module", "=", "importlib", ".", "import_module", "(", "module_name", ")", "...
Import a class from a module string, e.g. ``my.module.ClassName``.
[ "Import", "a", "class", "from", "a", "module", "string", "e", ".", "g", ".", "my", ".", "module", ".", "ClassName", "." ]
python
valid
34.75
arne-cl/discoursegraphs
src/discoursegraphs/discoursegraph.py
https://github.com/arne-cl/discoursegraphs/blob/842f0068a3190be2c75905754521b176b25a54fb/src/discoursegraphs/discoursegraph.py#L1327-L1365
def get_pointing_chains(docgraph, layer=None): """ returns a list of chained pointing relations (e.g. coreference chains) found in the given document graph. Parameters ---------- docgraph : DiscourseDocumentGraph a text with annotations, represented by a document graph layer : str o...
[ "def", "get_pointing_chains", "(", "docgraph", ",", "layer", "=", "None", ")", ":", "pointing_relations", "=", "select_edges_by", "(", "docgraph", ",", "layer", "=", "layer", ",", "edge_type", "=", "EdgeTypes", ".", "pointing_relation", ")", "# a markable can poin...
returns a list of chained pointing relations (e.g. coreference chains) found in the given document graph. Parameters ---------- docgraph : DiscourseDocumentGraph a text with annotations, represented by a document graph layer : str or None If layer is specifid, this function will onl...
[ "returns", "a", "list", "of", "chained", "pointing", "relations", "(", "e", ".", "g", ".", "coreference", "chains", ")", "found", "in", "the", "given", "document", "graph", "." ]
python
train
38.769231