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
cocaine/cocaine-tools
cocaine/tools/dispatch.py
https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L1407-L1416
def group_pop(name, app, **kwargs): """ Remove application from the specified routing group. """ ctx = Context(**kwargs) ctx.execute_action('group:app:remove', **{ 'storage': ctx.repo.create_secure_service('storage'), 'name': name, 'app': app, })
[ "def", "group_pop", "(", "name", ",", "app", ",", "*", "*", "kwargs", ")", ":", "ctx", "=", "Context", "(", "*", "*", "kwargs", ")", "ctx", ".", "execute_action", "(", "'group:app:remove'", ",", "*", "*", "{", "'storage'", ":", "ctx", ".", "repo", ...
Remove application from the specified routing group.
[ "Remove", "application", "from", "the", "specified", "routing", "group", "." ]
python
train
28.5
klahnakoski/pyLibrary
mo_math/vendor/strangman/stats.py
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_math/vendor/strangman/stats.py#L1559-L1573
def incr(l, cap): # to increment a list up to a max-list of 'cap' """ Simulate a counting system from an n-dimensional list. Usage: lincr(l,cap) l=list to increment, cap=max values for each list pos'n Returns: next set of values for list l, OR -1 (if overflow) """ l[0] = l[0] + 1 # e.g., [0,0,0]...
[ "def", "incr", "(", "l", ",", "cap", ")", ":", "# to increment a list up to a max-list of 'cap'", "l", "[", "0", "]", "=", "l", "[", "0", "]", "+", "1", "# e.g., [0,0,0] --> [2,4,3] (=cap)", "for", "i", "in", "range", "(", "len", "(", "l", ")", ")", ":",...
Simulate a counting system from an n-dimensional list. Usage: lincr(l,cap) l=list to increment, cap=max values for each list pos'n Returns: next set of values for list l, OR -1 (if overflow)
[ "Simulate", "a", "counting", "system", "from", "an", "n", "-", "dimensional", "list", "." ]
python
train
40.6
googleapis/google-cloud-python
logging/google/cloud/logging/logger.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/logger.py#L191-L209
def log_proto(self, message, client=None, **kw): """API call: log a protobuf message via a POST request See https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/list :type message: :class:`~google.protobuf.message.Message` :param message: The protobuf message to ...
[ "def", "log_proto", "(", "self", ",", "message", ",", "client", "=", "None", ",", "*", "*", "kw", ")", ":", "self", ".", "_do_log", "(", "client", ",", "ProtobufEntry", ",", "message", ",", "*", "*", "kw", ")" ]
API call: log a protobuf message via a POST request See https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/list :type message: :class:`~google.protobuf.message.Message` :param message: The protobuf message to be logged. :type client: :class:`~google.cloud.logg...
[ "API", "call", ":", "log", "a", "protobuf", "message", "via", "a", "POST", "request" ]
python
train
42.052632
secnot/rectpack
rectpack/packer.py
https://github.com/secnot/rectpack/blob/21d46be48fd453500ea49de699bc9eabc427bdf7/rectpack/packer.py#L423-L468
def _new_open_bin(self, remaining_rect): """ Extract the next bin where at least one of the rectangles in rem Arguments: remaining_rect (dict): rectangles not placed yet Returns: PackingAlgorithm: Initialized empty packing bin. None: No bin b...
[ "def", "_new_open_bin", "(", "self", ",", "remaining_rect", ")", ":", "factories_to_delete", "=", "set", "(", ")", "#", "new_bin", "=", "None", "for", "key", ",", "binfac", "in", "self", ".", "_empty_bins", ".", "items", "(", ")", ":", "# Only return the n...
Extract the next bin where at least one of the rectangles in rem Arguments: remaining_rect (dict): rectangles not placed yet Returns: PackingAlgorithm: Initialized empty packing bin. None: No bin big enough for the rectangle was found
[ "Extract", "the", "next", "bin", "where", "at", "least", "one", "of", "the", "rectangles", "in", "rem" ]
python
train
29.76087
taxpon/pymesh
pymesh/base.py
https://github.com/taxpon/pymesh/blob/a90b3b2ed1408d793f3b5208dd8087b08fb7c92e/pymesh/base.py#L33-L45
def set_initial_values(self): """Set initial values form existing self.data value :return: None """ self.normals = self.data['normals'] self.vectors = numpy.ones(( self.data['vectors'].shape[0], self.data['vectors'].shape[1], self.data['vectors...
[ "def", "set_initial_values", "(", "self", ")", ":", "self", ".", "normals", "=", "self", ".", "data", "[", "'normals'", "]", "self", ".", "vectors", "=", "numpy", ".", "ones", "(", "(", "self", ".", "data", "[", "'vectors'", "]", ".", "shape", "[", ...
Set initial values form existing self.data value :return: None
[ "Set", "initial", "values", "form", "existing", "self", ".", "data", "value", ":", "return", ":", "None" ]
python
train
34
openid/JWTConnect-Python-OidcService
src/oidcservice/oidc/end_session.py
https://github.com/openid/JWTConnect-Python-OidcService/blob/759ab7adef30a7e3b9d75475e2971433b9613788/src/oidcservice/oidc/end_session.py#L32-L53
def get_id_token_hint(self, request_args=None, **kwargs): """ Add id_token_hint to request :param request_args: :param kwargs: :return: """ request_args = self.multiple_extend_request_args( request_args, kwargs['state'], ['id_token'], ['au...
[ "def", "get_id_token_hint", "(", "self", ",", "request_args", "=", "None", ",", "*", "*", "kwargs", ")", ":", "request_args", "=", "self", ".", "multiple_extend_request_args", "(", "request_args", ",", "kwargs", "[", "'state'", "]", ",", "[", "'id_token'", "...
Add id_token_hint to request :param request_args: :param kwargs: :return:
[ "Add", "id_token_hint", "to", "request" ]
python
train
27.363636
pandas-dev/pandas
pandas/core/arrays/base.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/base.py#L479-L535
def shift( self, periods: int = 1, fill_value: object = None, ) -> ABCExtensionArray: """ Shift values by desired number. Newly introduced missing values are filled with ``self.dtype.na_value``. .. versionadded:: 0.24.0 Parameter...
[ "def", "shift", "(", "self", ",", "periods", ":", "int", "=", "1", ",", "fill_value", ":", "object", "=", "None", ",", ")", "->", "ABCExtensionArray", ":", "# Note: this implementation assumes that `self.dtype.na_value` can be", "# stored in an instance of your ExtensionA...
Shift values by desired number. Newly introduced missing values are filled with ``self.dtype.na_value``. .. versionadded:: 0.24.0 Parameters ---------- periods : int, default 1 The number of periods to shift. Negative values are allowed for shif...
[ "Shift", "values", "by", "desired", "number", "." ]
python
train
28.140351
pandas-dev/pandas
pandas/core/indexing.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexing.py#L2422-L2428
def _convert_key(self, key, is_setter=False): """ require integer args (and convert to label arguments) """ for a, i in zip(self.obj.axes, key): if not is_integer(i): raise ValueError("iAt based indexing can only have integer " "indexers") ...
[ "def", "_convert_key", "(", "self", ",", "key", ",", "is_setter", "=", "False", ")", ":", "for", "a", ",", "i", "in", "zip", "(", "self", ".", "obj", ".", "axes", ",", "key", ")", ":", "if", "not", "is_integer", "(", "i", ")", ":", "raise", "Va...
require integer args (and convert to label arguments)
[ "require", "integer", "args", "(", "and", "convert", "to", "label", "arguments", ")" ]
python
train
47
jsommers/switchyard
switchyard/syinit.py
https://github.com/jsommers/switchyard/blob/fdcb3869c937dcedbd6ea7a7822ebd412bf1e2b0/switchyard/syinit.py#L24-L39
def _parse_codeargs(argstr): ''' Parse and clean up argument to user code; separate *args from **kwargs. ''' args = [] kwargs = {} if isinstance(argstr, str): for a in argstr.split(): if '=' in a: k,attr = a.split('=') kwargs[k] = attr ...
[ "def", "_parse_codeargs", "(", "argstr", ")", ":", "args", "=", "[", "]", "kwargs", "=", "{", "}", "if", "isinstance", "(", "argstr", ",", "str", ")", ":", "for", "a", "in", "argstr", ".", "split", "(", ")", ":", "if", "'='", "in", "a", ":", "k...
Parse and clean up argument to user code; separate *args from **kwargs.
[ "Parse", "and", "clean", "up", "argument", "to", "user", "code", ";", "separate", "*", "args", "from", "**", "kwargs", "." ]
python
train
25.1875
binux/pyspider
pyspider/database/redis/taskdb.py
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/database/redis/taskdb.py#L118-L131
def status_count(self, project): ''' return a dict ''' pipe = self.redis.pipeline(transaction=False) for status in range(1, 5): pipe.scard(self._gen_status_key(project, status)) ret = pipe.execute() result = {} for status, count in enumerate(r...
[ "def", "status_count", "(", "self", ",", "project", ")", ":", "pipe", "=", "self", ".", "redis", ".", "pipeline", "(", "transaction", "=", "False", ")", "for", "status", "in", "range", "(", "1", ",", "5", ")", ":", "pipe", ".", "scard", "(", "self"...
return a dict
[ "return", "a", "dict" ]
python
train
28.714286
mathandy/svgpathtools
svgpathtools/path.py
https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/path.py#L1174-L1197
def intersect(self, other_seg, tol=1e-12): """Finds the intersections of two segments. returns a list of tuples (t1, t2) such that self.point(t1) == other_seg.point(t2). Note: This will fail if the two segments coincide for more than a finite collection of points.""" if i...
[ "def", "intersect", "(", "self", ",", "other_seg", ",", "tol", "=", "1e-12", ")", ":", "if", "isinstance", "(", "other_seg", ",", "Line", ")", ":", "return", "bezier_by_line_intersections", "(", "self", ",", "other_seg", ")", "elif", "(", "isinstance", "("...
Finds the intersections of two segments. returns a list of tuples (t1, t2) such that self.point(t1) == other_seg.point(t2). Note: This will fail if the two segments coincide for more than a finite collection of points.
[ "Finds", "the", "intersections", "of", "two", "segments", ".", "returns", "a", "list", "of", "tuples", "(", "t1", "t2", ")", "such", "that", "self", ".", "point", "(", "t1", ")", "==", "other_seg", ".", "point", "(", "t2", ")", ".", "Note", ":", "T...
python
train
49.5
coinbase/coinbase-python
coinbase/wallet/client.py
https://github.com/coinbase/coinbase-python/blob/497c28158f529e8c7d0228521b4386a890baf088/coinbase/wallet/client.py#L440-L448
def buy(self, account_id, **params): """https://developers.coinbase.com/api/v2#buy-bitcoin""" if 'amount' not in params and 'total' not in params: raise ValueError("Missing required parameter: 'amount' or 'total'") for required in ['currency', 'payment_method']: if requir...
[ "def", "buy", "(", "self", ",", "account_id", ",", "*", "*", "params", ")", ":", "if", "'amount'", "not", "in", "params", "and", "'total'", "not", "in", "params", ":", "raise", "ValueError", "(", "\"Missing required parameter: 'amount' or 'total'\"", ")", "for...
https://developers.coinbase.com/api/v2#buy-bitcoin
[ "https", ":", "//", "developers", ".", "coinbase", ".", "com", "/", "api", "/", "v2#buy", "-", "bitcoin" ]
python
train
60
MillionIntegrals/vel
vel/rl/env/classic_atari.py
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/env/classic_atari.py#L41-L52
def env_maker(environment_id): """ Create a relatively raw atari environment """ env = gym.make(environment_id) assert 'NoFrameskip' in env.spec.id # Wait for between 1 and 30 rounds doing nothing on start env = NoopResetEnv(env, noop_max=30) # Do the same action for k steps. Return max of las...
[ "def", "env_maker", "(", "environment_id", ")", ":", "env", "=", "gym", ".", "make", "(", "environment_id", ")", "assert", "'NoFrameskip'", "in", "env", ".", "spec", ".", "id", "# Wait for between 1 and 30 rounds doing nothing on start", "env", "=", "NoopResetEnv", ...
Create a relatively raw atari environment
[ "Create", "a", "relatively", "raw", "atari", "environment" ]
python
train
32.916667
CyberReboot/vent
vent/helpers/paths.py
https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/helpers/paths.py#L56-L66
def ensure_file(path): """ Checks if file exists, if fails, tries to create file """ try: exists = isfile(path) if not exists: with open(path, 'w+') as fname: fname.write('initialized') return (True, path) return (Tr...
[ "def", "ensure_file", "(", "path", ")", ":", "try", ":", "exists", "=", "isfile", "(", "path", ")", "if", "not", "exists", ":", "with", "open", "(", "path", ",", "'w+'", ")", "as", "fname", ":", "fname", ".", "write", "(", "'initialized'", ")", "re...
Checks if file exists, if fails, tries to create file
[ "Checks", "if", "file", "exists", "if", "fails", "tries", "to", "create", "file" ]
python
train
36.545455
gem/oq-engine
openquake/commands/plot.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/plot.py#L66-L89
def make_figure_hmaps(extractors, what): """ $ oq plot 'hmaps?kind=mean&imt=PGA' """ import matplotlib.pyplot as plt fig = plt.figure() ncalcs = len(extractors) for i, ex in enumerate(extractors): oq = ex.oqparam n_poes = len(oq.poes) sitecol = ex.get('sitecol') ...
[ "def", "make_figure_hmaps", "(", "extractors", ",", "what", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "fig", "=", "plt", ".", "figure", "(", ")", "ncalcs", "=", "len", "(", "extractors", ")", "for", "i", ",", "ex", "in", "enumerate"...
$ oq plot 'hmaps?kind=mean&imt=PGA'
[ "$", "oq", "plot", "hmaps?kind", "=", "mean&imt", "=", "PGA" ]
python
train
37
PagerDuty/pagerduty-api-python-client
pypd/models/entity.py
https://github.com/PagerDuty/pagerduty-api-python-client/blob/f420b34ca9b29689cc2ecc9adca6dc5d56ae7161/pypd/models/entity.py#L481-L487
def delete(cls, id, api_key=None, **kwargs): """Delete an entity from the server by ID.""" inst = cls(api_key=api_key) endpoint = '/'.join((cls.get_endpoint(), id)) inst.request('DELETE', endpoint=endpoint, query_params=kwargs) inst._is_deleted = True return True
[ "def", "delete", "(", "cls", ",", "id", ",", "api_key", "=", "None", ",", "*", "*", "kwargs", ")", ":", "inst", "=", "cls", "(", "api_key", "=", "api_key", ")", "endpoint", "=", "'/'", ".", "join", "(", "(", "cls", ".", "get_endpoint", "(", ")", ...
Delete an entity from the server by ID.
[ "Delete", "an", "entity", "from", "the", "server", "by", "ID", "." ]
python
train
43.571429
brunobord/tdaemon
tdaemon.py
https://github.com/brunobord/tdaemon/blob/733b5bddb4b12bc3db326a192ce5606f28768307/tdaemon.py#L224-L233
def loop(self): """Main loop daemon.""" while True: sleep(1) new_file_list = self.walk(self.file_path, {}) if new_file_list != self.file_list: if self.debug: self.diff_list(new_file_list, self.file_list) self.run_tes...
[ "def", "loop", "(", "self", ")", ":", "while", "True", ":", "sleep", "(", "1", ")", "new_file_list", "=", "self", ".", "walk", "(", "self", ".", "file_path", ",", "{", "}", ")", "if", "new_file_list", "!=", "self", ".", "file_list", ":", "if", "sel...
Main loop daemon.
[ "Main", "loop", "daemon", "." ]
python
train
36.2
DataDog/integrations-core
tokumx/datadog_checks/tokumx/vendor/pymongo/collection.py
https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/tokumx/datadog_checks/tokumx/vendor/pymongo/collection.py#L1610-L1626
def drop_indexes(self): """Drops all indexes on this collection. Can be used on non-existant collections or collections with no indexes. Raises OperationFailure on an error. .. note:: The :attr:`~pymongo.collection.Collection.write_concern` of this collection is automaticall...
[ "def", "drop_indexes", "(", "self", ")", ":", "self", ".", "__database", ".", "client", ".", "_purge_index", "(", "self", ".", "__database", ".", "name", ",", "self", ".", "__name", ")", "self", ".", "drop_index", "(", "\"*\"", ")" ]
Drops all indexes on this collection. Can be used on non-existant collections or collections with no indexes. Raises OperationFailure on an error. .. note:: The :attr:`~pymongo.collection.Collection.write_concern` of this collection is automatically applied to this operation when us...
[ "Drops", "all", "indexes", "on", "this", "collection", "." ]
python
train
38.176471
MIT-LCP/wfdb-python
wfdb/io/_signal.py
https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/io/_signal.py#L1237-L1340
def _blocks_to_samples(sig_data, n_samp, fmt): """ Convert uint8 blocks into signal samples for unaligned dat formats. Parameters ---------- sig_data : numpy array The uint8 data blocks. n_samp : int The number of samples contained in the bytes Returns ------- signa...
[ "def", "_blocks_to_samples", "(", "sig_data", ",", "n_samp", ",", "fmt", ")", ":", "if", "fmt", "==", "'212'", ":", "# Easier to process when dealing with whole blocks", "if", "n_samp", "%", "2", ":", "n_samp", "+=", "1", "added_samps", "=", "1", "sig_data", "...
Convert uint8 blocks into signal samples for unaligned dat formats. Parameters ---------- sig_data : numpy array The uint8 data blocks. n_samp : int The number of samples contained in the bytes Returns ------- signal : numpy array The numpy array of digital samples
[ "Convert", "uint8", "blocks", "into", "signal", "samples", "for", "unaligned", "dat", "formats", "." ]
python
train
38.480769
uuazed/numerapi
numerapi/numerapi.py
https://github.com/uuazed/numerapi/blob/fc9dcc53b32ede95bfda1ceeb62aec1d67d26697/numerapi/numerapi.py#L728-L777
def get_submission_filenames(self, tournament=None, round_num=None): """Get filenames of the submission of the user. Args: tournament (int): optionally filter by ID of the tournament round_num (int): optionally filter round number Returns: list: list of user...
[ "def", "get_submission_filenames", "(", "self", ",", "tournament", "=", "None", ",", "round_num", "=", "None", ")", ":", "query", "=", "'''\n query {\n user {\n submissions {\n filename\n selected\n round {...
Get filenames of the submission of the user. Args: tournament (int): optionally filter by ID of the tournament round_num (int): optionally filter round number Returns: list: list of user filenames (`dict`) Each filenames in the list as the following str...
[ "Get", "filenames", "of", "the", "submission", "of", "the", "user", "." ]
python
train
32.26
scott-griffiths/bitstring
bitstring.py
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L3553-L3611
def byteswap(self, fmt=None, start=None, end=None, repeat=True): """Change the endianness in-place. Return number of repeats of fmt done. fmt -- A compact structure string, an integer number of bytes or an iterable of integers. Defaults to 0, which byte reverses the whole ...
[ "def", "byteswap", "(", "self", ",", "fmt", "=", "None", ",", "start", "=", "None", ",", "end", "=", "None", ",", "repeat", "=", "True", ")", ":", "start", ",", "end", "=", "self", ".", "_validate_slice", "(", "start", ",", "end", ")", "if", "fmt...
Change the endianness in-place. Return number of repeats of fmt done. fmt -- A compact structure string, an integer number of bytes or an iterable of integers. Defaults to 0, which byte reverses the whole bitstring. start -- Start bit position, defaults to 0. end -...
[ "Change", "the", "endianness", "in", "-", "place", ".", "Return", "number", "of", "repeats", "of", "fmt", "done", "." ]
python
train
43.576271
materialsproject/pymatgen
pymatgen/core/structure.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/core/structure.py#L283-L300
def is_valid(self, tol: float = DISTANCE_TOLERANCE) -> bool: """ True if SiteCollection does not contain atoms that are too close together. Note that the distance definition is based on type of SiteCollection. Cartesian distances are used for non-periodic Molecules, while PBC is ...
[ "def", "is_valid", "(", "self", ",", "tol", ":", "float", "=", "DISTANCE_TOLERANCE", ")", "->", "bool", ":", "if", "len", "(", "self", ".", "sites", ")", "==", "1", ":", "return", "True", "all_dists", "=", "self", ".", "distance_matrix", "[", "np", "...
True if SiteCollection does not contain atoms that are too close together. Note that the distance definition is based on type of SiteCollection. Cartesian distances are used for non-periodic Molecules, while PBC is taken into account for periodic structures. Args: tol (float...
[ "True", "if", "SiteCollection", "does", "not", "contain", "atoms", "that", "are", "too", "close", "together", ".", "Note", "that", "the", "distance", "definition", "is", "based", "on", "type", "of", "SiteCollection", ".", "Cartesian", "distances", "are", "used...
python
train
40.722222
rigetti/pyquil
pyquil/api/_base_connection.py
https://github.com/rigetti/pyquil/blob/ec98e453084b0037d69d8c3245f6822a5422593d/pyquil/api/_base_connection.py#L52-L59
def post_json(session, url, json): """ Post JSON to the Forest endpoint. """ res = session.post(url, json=json) if res.status_code >= 400: raise parse_error(res) return res
[ "def", "post_json", "(", "session", ",", "url", ",", "json", ")", ":", "res", "=", "session", ".", "post", "(", "url", ",", "json", "=", "json", ")", "if", "res", ".", "status_code", ">=", "400", ":", "raise", "parse_error", "(", "res", ")", "retur...
Post JSON to the Forest endpoint.
[ "Post", "JSON", "to", "the", "Forest", "endpoint", "." ]
python
train
24.625
AkihikoITOH/capybara
capybara/virtualenv/lib/python2.7/site-packages/flask/blueprints.py
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/flask/blueprints.py#L337-L343
def app_context_processor(self, f): """Like :meth:`Flask.context_processor` but for a blueprint. Such a function is executed each request, even if outside of the blueprint. """ self.record_once(lambda s: s.app.template_context_processors .setdefault(None, []).append(f)) ...
[ "def", "app_context_processor", "(", "self", ",", "f", ")", ":", "self", ".", "record_once", "(", "lambda", "s", ":", "s", ".", "app", ".", "template_context_processors", ".", "setdefault", "(", "None", ",", "[", "]", ")", ".", "append", "(", "f", ")",...
Like :meth:`Flask.context_processor` but for a blueprint. Such a function is executed each request, even if outside of the blueprint.
[ "Like", ":", "meth", ":", "Flask", ".", "context_processor", "but", "for", "a", "blueprint", ".", "Such", "a", "function", "is", "executed", "each", "request", "even", "if", "outside", "of", "the", "blueprint", "." ]
python
test
46.571429
pmacosta/peng
peng/wave_functions.py
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L500-L562
def fft(wave, npoints=None, indep_min=None, indep_max=None): r""" Return the Fast Fourier Transform of a waveform. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :param npoints: Number of points to use in the transform. If **npoints** is less than the size of ...
[ "def", "fft", "(", "wave", ",", "npoints", "=", "None", ",", "indep_min", "=", "None", ",", "indep_max", "=", "None", ")", ":", "ret", "=", "copy", ".", "copy", "(", "wave", ")", "_bound_waveform", "(", "ret", ",", "indep_min", ",", "indep_max", ")",...
r""" Return the Fast Fourier Transform of a waveform. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :param npoints: Number of points to use in the transform. If **npoints** is less than the size of the independent variable vector the waveform ...
[ "r", "Return", "the", "Fast", "Fourier", "Transform", "of", "a", "waveform", "." ]
python
test
34.15873
SoftwareDefinedBuildings/XBOS
apps/Data_quality_analysis/Clean_Data.py
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/Data_quality_analysis/Clean_Data.py#L519-L541
def remove_missing(self, data, return_bool="any"): """ ??? Parameters ---------- data : pd.DataFrame() Input dataframe. return_bool : bool ??? Returns ------- pd.DataFrame() ??? """ ...
[ "def", "remove_missing", "(", "self", ",", "data", ",", "return_bool", "=", "\"any\"", ")", ":", "if", "return_bool", "==", "\"any\"", ":", "bool_sel", "=", "self", ".", "_find_missing", "(", "data", ",", "return_bool", "=", "\"any\"", ")", "elif", "return...
??? Parameters ---------- data : pd.DataFrame() Input dataframe. return_bool : bool ??? Returns ------- pd.DataFrame() ???
[ "???", "Parameters", "----------", "data", ":", "pd", ".", "DataFrame", "()", "Input", "dataframe", ".", "return_bool", ":", "bool", "???" ]
python
train
22.913043
JarryShaw/PyPCAPKit
src/protocols/application/httpv2.py
https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/application/httpv2.py#L254-L340
def _read_http_headers(self, size, kind, flag): """Read HTTP/2 HEADERS frames. Structure of HTTP/2 HEADERS frame [RFC 7540]: +-----------------------------------------------+ | Length (24) | +---------------+---------------+---------...
[ "def", "_read_http_headers", "(", "self", ",", "size", ",", "kind", ",", "flag", ")", ":", "_plen", "=", "0", "_elen", "=", "0", "_flag", "=", "dict", "(", "END_STREAM", "=", "False", ",", "# bit 0", "END_HEADERS", "=", "False", ",", "# bit 2", "PADDED...
Read HTTP/2 HEADERS frames. Structure of HTTP/2 HEADERS frame [RFC 7540]: +-----------------------------------------------+ | Length (24) | +---------------+---------------+---------------+ | Type (8) | Flags (8) | ...
[ "Read", "HTTP", "/", "2", "HEADERS", "frames", "." ]
python
train
43.954023
llazzaro/analyzerstrategies
analyzerstrategies/sma_portfolio_strategy.py
https://github.com/llazzaro/analyzerstrategies/blob/3c647802f582bf2f06c6793f282bee0d26514cd6/analyzerstrategies/sma_portfolio_strategy.py#L59-L66
def update(self, tickDict): ''' consume ticks ''' if not self.__trakers: self.__setUpTrakers() for security, tick in tickDict.items(): if security in self.__trakers: self.__trakers[security].tickUpdate(tick)
[ "def", "update", "(", "self", ",", "tickDict", ")", ":", "if", "not", "self", ".", "__trakers", ":", "self", ".", "__setUpTrakers", "(", ")", "for", "security", ",", "tick", "in", "tickDict", ".", "items", "(", ")", ":", "if", "security", "in", "self...
consume ticks
[ "consume", "ticks" ]
python
train
33.125
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L450-L468
def keystone_configure_api_version(self, sentry_relation_pairs, deployment, api_version): """Configure preferred-api-version of keystone in deployment and monitor provided list of relation objects for propagation before returning to caller. :...
[ "def", "keystone_configure_api_version", "(", "self", ",", "sentry_relation_pairs", ",", "deployment", ",", "api_version", ")", ":", "self", ".", "log", ".", "debug", "(", "\"Setting keystone preferred-api-version: '{}'\"", "\"\"", ".", "format", "(", "api_version", "...
Configure preferred-api-version of keystone in deployment and monitor provided list of relation objects for propagation before returning to caller. :param sentry_relation_pairs: list of sentry, relation tuples used for monitoring propagation of relati...
[ "Configure", "preferred", "-", "api", "-", "version", "of", "keystone", "in", "deployment", "and", "monitor", "provided", "list", "of", "relation", "objects", "for", "propagation", "before", "returning", "to", "caller", "." ]
python
train
51.842105
CI-WATER/gsshapy
gsshapy/orm/prj.py
https://github.com/CI-WATER/gsshapy/blob/00fd4af0fd65f1614d75a52fe950a04fb0867f4c/gsshapy/orm/prj.py#L1376-L1389
def centerLatLon(self): """ Get the center lat/lon of model """ # GET CENTROID FROM GSSHA GRID gssha_grid = self.getGrid() min_x, max_x, min_y, max_y = gssha_grid.bounds() x_ext, y_ext = transform(gssha_grid.proj, Proj(init='epsg:...
[ "def", "centerLatLon", "(", "self", ")", ":", "# GET CENTROID FROM GSSHA GRID", "gssha_grid", "=", "self", ".", "getGrid", "(", ")", "min_x", ",", "max_x", ",", "min_y", ",", "max_y", "=", "gssha_grid", ".", "bounds", "(", ")", "x_ext", ",", "y_ext", "=", ...
Get the center lat/lon of model
[ "Get", "the", "center", "lat", "/", "lon", "of", "model" ]
python
train
37.214286
ThreatConnect-Inc/tcex
tcex/tcex_playbook.py
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L461-L524
def read_embedded(self, data, parent_var_type): """Read method for "mixed" variable type. .. Note:: The ``read()`` method will automatically determine if the input is a variable or needs to be searched for embedded variables. There usually is no reason to call this m...
[ "def", "read_embedded", "(", "self", ",", "data", ",", "parent_var_type", ")", ":", "if", "data", "is", "None", ":", "return", "data", "# iterate all matching variables", "for", "var", "in", "(", "v", ".", "group", "(", "0", ")", "for", "v", "in", "re", ...
Read method for "mixed" variable type. .. Note:: The ``read()`` method will automatically determine if the input is a variable or needs to be searched for embedded variables. There usually is no reason to call this method directly. This method will automatically cov...
[ "Read", "method", "for", "mixed", "variable", "type", "." ]
python
train
35.625
widdowquinn/pyani
pyani/anib.py
https://github.com/widdowquinn/pyani/blob/2b24ec971401e04024bba896e4011984fe3f53f0/pyani/anib.py#L271-L286
def construct_makeblastdb_cmd( filename, outdir, blastdb_exe=pyani_config.MAKEBLASTDB_DEFAULT ): """Returns a single makeblastdb command. - filename - input filename - blastdb_exe - path to the makeblastdb executable """ title = os.path.splitext(os.path.split(filename)[-1])[0] outfilename =...
[ "def", "construct_makeblastdb_cmd", "(", "filename", ",", "outdir", ",", "blastdb_exe", "=", "pyani_config", ".", "MAKEBLASTDB_DEFAULT", ")", ":", "title", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "split", "(", "filename", ")", ...
Returns a single makeblastdb command. - filename - input filename - blastdb_exe - path to the makeblastdb executable
[ "Returns", "a", "single", "makeblastdb", "command", "." ]
python
train
32.6875
nvdv/vprof
vprof/memory_profiler.py
https://github.com/nvdv/vprof/blob/4c3ff78f8920ab10cb9c00b14143452aa09ff6bb/vprof/memory_profiler.py#L21-L33
def _remove_duplicates(objects): """Removes duplicate objects. http://www.peterbe.com/plog/uniqifiers-benchmark. """ seen, uniq = set(), [] for obj in objects: obj_id = id(obj) if obj_id in seen: continue seen.add(obj_id) uniq.append(obj) return uniq
[ "def", "_remove_duplicates", "(", "objects", ")", ":", "seen", ",", "uniq", "=", "set", "(", ")", ",", "[", "]", "for", "obj", "in", "objects", ":", "obj_id", "=", "id", "(", "obj", ")", "if", "obj_id", "in", "seen", ":", "continue", "seen", ".", ...
Removes duplicate objects. http://www.peterbe.com/plog/uniqifiers-benchmark.
[ "Removes", "duplicate", "objects", "." ]
python
test
23.615385
loli/medpy
bin/medpy_binary_resampling.py
https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/bin/medpy_binary_resampling.py#L118-L169
def shape_based_slice_interpolation(img, dim, nslices): """ Adds `nslices` slices between all slices of the binary image `img` along dimension `dim` respecting the original slice values to be situated in the middle of each slice. Extrapolation situations are handled by simple repeating. Interpo...
[ "def", "shape_based_slice_interpolation", "(", "img", ",", "dim", ",", "nslices", ")", ":", "# check arguments", "if", "not", "0", "==", "nslices", "%", "2", ":", "raise", "ValueError", "(", "'nslices must be an even number'", ")", "out", "=", "None", "slicer", ...
Adds `nslices` slices between all slices of the binary image `img` along dimension `dim` respecting the original slice values to be situated in the middle of each slice. Extrapolation situations are handled by simple repeating. Interpolation of new slices is performed using shape based interpolation. ...
[ "Adds", "nslices", "slices", "between", "all", "slices", "of", "the", "binary", "image", "img", "along", "dimension", "dim", "respecting", "the", "original", "slice", "values", "to", "be", "situated", "in", "the", "middle", "of", "each", "slice", ".", "Extra...
python
train
33.923077
jobovy/galpy
galpy/potential/FerrersPotential.py
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/potential/FerrersPotential.py#L229-L255
def _R2deriv(self,R,z,phi=0.,t=0.): """ NAME: _R2deriv PURPOSE: evaluate the second radial derivative for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPU...
[ "def", "_R2deriv", "(", "self", ",", "R", ",", "z", ",", "phi", "=", "0.", ",", "t", "=", "0.", ")", ":", "if", "not", "self", ".", "isNonAxi", ":", "phi", "=", "0.", "x", ",", "y", ",", "z", "=", "self", ".", "_compute_xyz", "(", "R", ",",...
NAME: _R2deriv PURPOSE: evaluate the second radial derivative for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: the second radial derivative
[ "NAME", ":", "_R2deriv", "PURPOSE", ":", "evaluate", "the", "second", "radial", "derivative", "for", "this", "potential", "INPUT", ":", "R", "-", "Galactocentric", "cylindrical", "radius", "z", "-", "vertical", "height", "phi", "-", "azimuth", "t", "-", "tim...
python
train
35
Sanic-Extensions/sanic-mongo
sanic_mongo/standalone/mongo_connection.py
https://github.com/Sanic-Extensions/sanic-mongo/blob/1521d3f01604da73ab5b89b0b7f8e9988d816c78/sanic_mongo/standalone/mongo_connection.py#L8-L24
def create_client(self,only_db=False): """返回连接的客户端 """ #database = parse_uri(self.uri).get("database") if self.ioloop: if only_db == False: client = AsyncIOMotorClient("/".join(self.uri.split("/")[:-1]), io_loop=self.ioloop) else: ...
[ "def", "create_client", "(", "self", ",", "only_db", "=", "False", ")", ":", "#database = parse_uri(self.uri).get(\"database\")", "if", "self", ".", "ioloop", ":", "if", "only_db", "==", "False", ":", "client", "=", "AsyncIOMotorClient", "(", "\"/\"", ".", "join...
返回连接的客户端
[ "返回连接的客户端" ]
python
train
34.352941
istresearch/scrapy-cluster
redis-monitor/redis_monitor.py
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/redis_monitor.py#L195-L216
def _process_failures(self, key): ''' Handles the retrying of the failed key ''' if self.settings['RETRY_FAILURES']: self.logger.debug("going to retry failure") # get the current failure count failkey = self._get_fail_key(key) current = sel...
[ "def", "_process_failures", "(", "self", ",", "key", ")", ":", "if", "self", ".", "settings", "[", "'RETRY_FAILURES'", "]", ":", "self", ".", "logger", ".", "debug", "(", "\"going to retry failure\"", ")", "# get the current failure count", "failkey", "=", "self...
Handles the retrying of the failed key
[ "Handles", "the", "retrying", "of", "the", "failed", "key" ]
python
train
39.409091
bykof/billomapy
billomapy/billomapy.py
https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L886-L895
def get_units_per_page(self, per_page=1000, page=1, params=None): """ Get units per page :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :param params: Search parameters. Default: {} :return: list """ return s...
[ "def", "get_units_per_page", "(", "self", ",", "per_page", "=", "1000", ",", "page", "=", "1", ",", "params", "=", "None", ")", ":", "return", "self", ".", "_get_resource_per_page", "(", "resource", "=", "UNITS", ",", "per_page", "=", "per_page", ",", "p...
Get units per page :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :param params: Search parameters. Default: {} :return: list
[ "Get", "units", "per", "page" ]
python
train
39.8
gholt/swiftly
swiftly/cli/put.py
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/put.py#L133-L154
def cli_put_account(context): """ Performs a PUT on the account. See :py:mod:`swiftly.cli.put` for context usage information. See :py:class:`CLIPut` for more information. """ body = None if context.input_: if context.input_ == '-': body = context.io_manager.get_stdin() ...
[ "def", "cli_put_account", "(", "context", ")", ":", "body", "=", "None", "if", "context", ".", "input_", ":", "if", "context", ".", "input_", "==", "'-'", ":", "body", "=", "context", ".", "io_manager", ".", "get_stdin", "(", ")", "else", ":", "body", ...
Performs a PUT on the account. See :py:mod:`swiftly.cli.put` for context usage information. See :py:class:`CLIPut` for more information.
[ "Performs", "a", "PUT", "on", "the", "account", "." ]
python
test
33.636364
bigchaindb/bigchaindb-driver
bigchaindb_driver/driver.py
https://github.com/bigchaindb/bigchaindb-driver/blob/c294a535f0696bd19483ae11a4882b74e6fc061e/bigchaindb_driver/driver.py#L278-L318
def get(self, *, asset_id, operation=None, headers=None): """Given an asset id, get its list of transactions (and optionally filter for only ``'CREATE'`` or ``'TRANSFER'`` transactions). Args: asset_id (str): Id of the asset. operation (str): The type of operatio...
[ "def", "get", "(", "self", ",", "*", ",", "asset_id", ",", "operation", "=", "None", ",", "headers", "=", "None", ")", ":", "return", "self", ".", "transport", ".", "forward_request", "(", "method", "=", "'GET'", ",", "path", "=", "self", ".", "path"...
Given an asset id, get its list of transactions (and optionally filter for only ``'CREATE'`` or ``'TRANSFER'`` transactions). Args: asset_id (str): Id of the asset. operation (str): The type of operation the transaction should be. Either ``'CREATE'`` or `...
[ "Given", "an", "asset", "id", "get", "its", "list", "of", "transactions", "(", "and", "optionally", "filter", "for", "only", "CREATE", "or", "TRANSFER", "transactions", ")", "." ]
python
train
41.926829
SBRG/ssbio
ssbio/protein/structure/structprop.py
https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/structure/structprop.py#L164-L205
def clean_structure(self, out_suffix='_clean', outdir=None, force_rerun=False, remove_atom_alt=True, keep_atom_alt_id='A',remove_atom_hydrogen=True, add_atom_occ=True, remove_res_hetero=True, keep_chemicals=None, keep_res_only=None, add_chain_id_i...
[ "def", "clean_structure", "(", "self", ",", "out_suffix", "=", "'_clean'", ",", "outdir", "=", "None", ",", "force_rerun", "=", "False", ",", "remove_atom_alt", "=", "True", ",", "keep_atom_alt_id", "=", "'A'", ",", "remove_atom_hydrogen", "=", "True", ",", ...
Clean the structure file associated with this structure, and save it as a new file. Returns the file path. Args: out_suffix (str): Suffix to append to original filename outdir (str): Path to output directory force_rerun (bool): If structure should be re-cleaned if a clean fi...
[ "Clean", "the", "structure", "file", "associated", "with", "this", "structure", "and", "save", "it", "as", "a", "new", "file", ".", "Returns", "the", "file", "path", "." ]
python
train
66.119048
skyfielders/python-skyfield
skyfield/units.py
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/units.py#L423-L439
def _interpret_angle(name, angle_object, angle_float, unit='degrees'): """Return an angle in radians from one of two arguments. It is common for Skyfield routines to accept both an argument like `alt` that takes an Angle object as well as an `alt_degrees` that can be given a bare float or a sexagesimal...
[ "def", "_interpret_angle", "(", "name", ",", "angle_object", ",", "angle_float", ",", "unit", "=", "'degrees'", ")", ":", "if", "angle_object", "is", "not", "None", ":", "if", "isinstance", "(", "angle_object", ",", "Angle", ")", ":", "return", "angle_object...
Return an angle in radians from one of two arguments. It is common for Skyfield routines to accept both an argument like `alt` that takes an Angle object as well as an `alt_degrees` that can be given a bare float or a sexagesimal tuple. A pair of such arguments can be passed to this routine for interp...
[ "Return", "an", "angle", "in", "radians", "from", "one", "of", "two", "arguments", "." ]
python
train
48.647059
openstack/python-monascaclient
monascaclient/v2_0/metrics.py
https://github.com/openstack/python-monascaclient/blob/03b07534145928eb2debad938da033c232dda105/monascaclient/v2_0/metrics.py#L23-L32
def create(self, **kwargs): """Create a metric.""" url_str = self.base_url if 'tenant_id' in kwargs: url_str = url_str + '?tenant_id=%s' % kwargs['tenant_id'] del kwargs['tenant_id'] data = kwargs['jsonbody'] if 'jsonbody' in kwargs else kwargs body = sel...
[ "def", "create", "(", "self", ",", "*", "*", "kwargs", ")", ":", "url_str", "=", "self", ".", "base_url", "if", "'tenant_id'", "in", "kwargs", ":", "url_str", "=", "url_str", "+", "'?tenant_id=%s'", "%", "kwargs", "[", "'tenant_id'", "]", "del", "kwargs"...
Create a metric.
[ "Create", "a", "metric", "." ]
python
train
37
apple/turicreate
src/unity/python/turicreate/util/_sframe_generation.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/util/_sframe_generation.py#L13-L71
def generate_random_sframe(num_rows, column_codes, random_seed = 0): """ Creates a random SFrame with `num_rows` rows and randomly generated column types determined by `column_codes`. The output SFrame is deterministic based on `random_seed`. `column_types` is a string with each character denoti...
[ "def", "generate_random_sframe", "(", "num_rows", ",", "column_codes", ",", "random_seed", "=", "0", ")", ":", "from", ".", ".", "extensions", "import", "_generate_random_sframe", "assert", "isinstance", "(", "column_codes", ",", "str", ")", "assert", "isinstance"...
Creates a random SFrame with `num_rows` rows and randomly generated column types determined by `column_codes`. The output SFrame is deterministic based on `random_seed`. `column_types` is a string with each character denoting one type of column, with the output SFrame having one column for each ...
[ "Creates", "a", "random", "SFrame", "with", "num_rows", "rows", "and", "randomly", "generated", "column", "types", "determined", "by", "column_codes", ".", "The", "output", "SFrame", "is", "deterministic", "based", "on", "random_seed", ".", "column_types", "is", ...
python
train
49.813559
ondryaso/pi-rc522
pirc522/rfid.py
https://github.com/ondryaso/pi-rc522/blob/9d9103e9701c105ba2348155e91f21ef338c4bd3/pirc522/rfid.py#L294-L319
def card_auth(self, auth_mode, block_address, key, uid): """ Authenticates to use specified block address. Tag must be selected using select_tag(uid) before auth. auth_mode -- RFID.auth_a or RFID.auth_b key -- list or tuple with six bytes key uid -- list or tuple with four bytes ...
[ "def", "card_auth", "(", "self", ",", "auth_mode", ",", "block_address", ",", "key", ",", "uid", ")", ":", "buf", "=", "[", "]", "buf", ".", "append", "(", "auth_mode", ")", "buf", ".", "append", "(", "block_address", ")", "for", "i", "in", "range", ...
Authenticates to use specified block address. Tag must be selected using select_tag(uid) before auth. auth_mode -- RFID.auth_a or RFID.auth_b key -- list or tuple with six bytes key uid -- list or tuple with four bytes tag ID Returns error state.
[ "Authenticates", "to", "use", "specified", "block", "address", ".", "Tag", "must", "be", "selected", "using", "select_tag", "(", "uid", ")", "before", "auth", ".", "auth_mode", "--", "RFID", ".", "auth_a", "or", "RFID", ".", "auth_b", "key", "--", "list", ...
python
train
29.961538
cathalgarvey/deadlock
deadlock/passwords/zxcvbn/scripts/build_keyboard_adjacency_graph.py
https://github.com/cathalgarvey/deadlock/blob/30099b476ff767611ce617150a0c574fc03fdf79/deadlock/passwords/zxcvbn/scripts/build_keyboard_adjacency_graph.py#L46-L50
def get_aligned_adjacent_coords(x, y): ''' returns the nine clockwise adjacent coordinates on a keypad, where each row is vertically aligned. ''' return [(x-1, y), (x-1, y-1), (x, y-1), (x+1, y-1), (x+1, y), (x+1, y+1), (x, y+1), (x-1, y+1)]
[ "def", "get_aligned_adjacent_coords", "(", "x", ",", "y", ")", ":", "return", "[", "(", "x", "-", "1", ",", "y", ")", ",", "(", "x", "-", "1", ",", "y", "-", "1", ")", ",", "(", "x", ",", "y", "-", "1", ")", ",", "(", "x", "+", "1", ","...
returns the nine clockwise adjacent coordinates on a keypad, where each row is vertically aligned.
[ "returns", "the", "nine", "clockwise", "adjacent", "coordinates", "on", "a", "keypad", "where", "each", "row", "is", "vertically", "aligned", "." ]
python
train
50.6
rootpy/rootpy
rootpy/extern/shortuuid/__init__.py
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/extern/shortuuid/__init__.py#L30-L37
def _string_to_int(self, string): """ Convert a string to a number, using the given alphabet.. """ number = 0 for char in string[::-1]: number = number * self._alpha_len + self._alphabet.index(char) return number
[ "def", "_string_to_int", "(", "self", ",", "string", ")", ":", "number", "=", "0", "for", "char", "in", "string", "[", ":", ":", "-", "1", "]", ":", "number", "=", "number", "*", "self", ".", "_alpha_len", "+", "self", ".", "_alphabet", ".", "index...
Convert a string to a number, using the given alphabet..
[ "Convert", "a", "string", "to", "a", "number", "using", "the", "given", "alphabet", ".." ]
python
train
33.125
halcy/Mastodon.py
mastodon/Mastodon.py
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2393-L2398
def stream_user(self, listener, run_async=False, timeout=__DEFAULT_STREAM_TIMEOUT, reconnect_async=False, reconnect_async_wait_sec=__DEFAULT_STREAM_RECONNECT_WAIT_SEC): """ Streams events that are relevant to the authorized user, i.e. home timeline and notifications. """ return s...
[ "def", "stream_user", "(", "self", ",", "listener", ",", "run_async", "=", "False", ",", "timeout", "=", "__DEFAULT_STREAM_TIMEOUT", ",", "reconnect_async", "=", "False", ",", "reconnect_async_wait_sec", "=", "__DEFAULT_STREAM_RECONNECT_WAIT_SEC", ")", ":", "return", ...
Streams events that are relevant to the authorized user, i.e. home timeline and notifications.
[ "Streams", "events", "that", "are", "relevant", "to", "the", "authorized", "user", "i", ".", "e", ".", "home", "timeline", "and", "notifications", "." ]
python
train
80.833333
i3visio/osrframework
osrframework/wrappers/twitter.py
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/wrappers/twitter.py#L131-L162
def do_usufy(self, query, **kwargs): """ Verifying a usufy query in this platform. This might be redefined in any class inheriting from Platform. Args: ----- query: The element to be searched. Return: ------- A list of elements to be app...
[ "def", "do_usufy", "(", "self", ",", "query", ",", "*", "*", "kwargs", ")", ":", "# Trying to interact with the API Wrapper", "try", ":", "self", ".", "wrapperAPI", "=", "TwitterAPIWrapper", "(", ")", "results", "=", "self", ".", "wrapperAPI", ".", "get_user",...
Verifying a usufy query in this platform. This might be redefined in any class inheriting from Platform. Args: ----- query: The element to be searched. Return: ------- A list of elements to be appended.
[ "Verifying", "a", "usufy", "query", "in", "this", "platform", "." ]
python
train
29.53125
timkpaine/pyEX
pyEX/marketdata/sse.py
https://github.com/timkpaine/pyEX/blob/91cf751dafdb208a0c8b5377945e5808b99f94ba/pyEX/marketdata/sse.py#L236-L248
def tradeBreaksSSE(symbols=None, on_data=None, token='', version=''): '''Trade report messages are sent when an order on the IEX Order Book is executed in whole or in part. DEEP sends a Trade report message for every individual fill. https://iexcloud.io/docs/api/#deep-trades Args: symbols (string)...
[ "def", "tradeBreaksSSE", "(", "symbols", "=", "None", ",", "on_data", "=", "None", ",", "token", "=", "''", ",", "version", "=", "''", ")", ":", "return", "_runSSE", "(", "'trade-breaks'", ",", "symbols", ",", "on_data", ",", "token", ",", "version", "...
Trade report messages are sent when an order on the IEX Order Book is executed in whole or in part. DEEP sends a Trade report message for every individual fill. https://iexcloud.io/docs/api/#deep-trades Args: symbols (string); Tickers to request on_data (function): Callback on data tok...
[ "Trade", "report", "messages", "are", "sent", "when", "an", "order", "on", "the", "IEX", "Order", "Book", "is", "executed", "in", "whole", "or", "in", "part", ".", "DEEP", "sends", "a", "Trade", "report", "message", "for", "every", "individual", "fill", ...
python
valid
40.461538
MediaFire/mediafire-python-open-sdk
examples/mediafire-cli.py
https://github.com/MediaFire/mediafire-python-open-sdk/blob/8f1f23db1b16f16e026f5c6777aec32d00baa05f/examples/mediafire-cli.py#L121-L126
def do_file_update_metadata(client, args): """Update file metadata""" client.update_file_metadata(args.uri, filename=args.filename, description=args.description, mtime=args.mtime, privacy=args.privacy) return True
[ "def", "do_file_update_metadata", "(", "client", ",", "args", ")", ":", "client", ".", "update_file_metadata", "(", "args", ".", "uri", ",", "filename", "=", "args", ".", "filename", ",", "description", "=", "args", ".", "description", ",", "mtime", "=", "...
Update file metadata
[ "Update", "file", "metadata" ]
python
train
47.333333
AndrewAnnex/SpiceyPy
spiceypy/spiceypy.py
https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L13028-L13051
def srfcss(code, bodstr, srflen=_default_len_out): """ Translate a surface ID code, together with a body string, to the corresponding surface name. If no such surface name exists, return a string representation of the surface ID code. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/...
[ "def", "srfcss", "(", "code", ",", "bodstr", ",", "srflen", "=", "_default_len_out", ")", ":", "code", "=", "ctypes", ".", "c_int", "(", "code", ")", "bodstr", "=", "stypes", ".", "stringToCharP", "(", "bodstr", ")", "srfstr", "=", "stypes", ".", "stri...
Translate a surface ID code, together with a body string, to the corresponding surface name. If no such surface name exists, return a string representation of the surface ID code. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/srfcss_c.html :param code: Integer surface ID code to ...
[ "Translate", "a", "surface", "ID", "code", "together", "with", "a", "body", "string", "to", "the", "corresponding", "surface", "name", ".", "If", "no", "such", "surface", "name", "exists", "return", "a", "string", "representation", "of", "the", "surface", "I...
python
train
39.708333
markuskiller/textblob-de
textblob_de/ext/_pattern/text/de/inflect.py
https://github.com/markuskiller/textblob-de/blob/1b427b2cdd7e5e9fd3697677a98358fae4aa6ad1/textblob_de/ext/_pattern/text/de/inflect.py#L568-L576
def grade(adjective, suffix=COMPARATIVE): """ Returns the comparative or superlative form of the given (inflected) adjective. """ b = predicative(adjective) # groß => großt, schön => schönst if suffix == SUPERLATIVE and b.endswith(("s", u"ß")): suffix = suffix[1:] # große => großere, sch...
[ "def", "grade", "(", "adjective", ",", "suffix", "=", "COMPARATIVE", ")", ":", "b", "=", "predicative", "(", "adjective", ")", "# groß => großt, schön => schönst", "if", "suffix", "==", "SUPERLATIVE", "and", "b", ".", "endswith", "(", "(", "\"s\"", ",", "u\"...
Returns the comparative or superlative form of the given (inflected) adjective.
[ "Returns", "the", "comparative", "or", "superlative", "form", "of", "the", "given", "(", "inflected", ")", "adjective", "." ]
python
train
43.222222
CloudGenix/sdk-python
cloudgenix/interactive.py
https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/interactive.py#L256-L360
def use_token(self, token=None): """ Function to use static AUTH_TOKEN as auth for the constructor instead of full login process. **Parameters:**: - **token**: Static AUTH_TOKEN **Returns:** Bool on success or failure. In addition the function will mutate the `cloudgenix.API...
[ "def", "use_token", "(", "self", ",", "token", "=", "None", ")", ":", "api_logger", ".", "info", "(", "'use_token function:'", ")", "# check token is a string.", "if", "not", "isinstance", "(", "token", ",", "(", "text_type", ",", "binary_type", ")", ")", ":...
Function to use static AUTH_TOKEN as auth for the constructor instead of full login process. **Parameters:**: - **token**: Static AUTH_TOKEN **Returns:** Bool on success or failure. In addition the function will mutate the `cloudgenix.API` constructor items as needed.
[ "Function", "to", "use", "static", "AUTH_TOKEN", "as", "auth", "for", "the", "constructor", "instead", "of", "full", "login", "process", "." ]
python
train
41.72381
Rapptz/discord.py
discord/message.py
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/message.py#L477-L564
def system_content(self): r"""A property that returns the content that is rendered regardless of the :attr:`Message.type`. In the case of :attr:`MessageType.default`\, this just returns the regular :attr:`Message.content`. Otherwise this returns an English message denoting the c...
[ "def", "system_content", "(", "self", ")", ":", "if", "self", ".", "type", "is", "MessageType", ".", "default", ":", "return", "self", ".", "content", "if", "self", ".", "type", "is", "MessageType", ".", "pins_add", ":", "return", "'{0.name} pinned a message...
r"""A property that returns the content that is rendered regardless of the :attr:`Message.type`. In the case of :attr:`MessageType.default`\, this just returns the regular :attr:`Message.content`. Otherwise this returns an English message denoting the contents of the system message.
[ "r", "A", "property", "that", "returns", "the", "content", "that", "is", "rendered", "regardless", "of", "the", ":", "attr", ":", "Message", ".", "type", "." ]
python
train
50.306818
has2k1/plotnine
plotnine/guides/guides.py
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/guides/guides.py#L85-L146
def build(self, plot): """ Build the guides Parameters ---------- plot : ggplot ggplot object being drawn Returns ------- box : matplotlib.offsetbox.Offsetbox | None A box that contains all the guides for the plot. If ...
[ "def", "build", "(", "self", ",", "plot", ")", ":", "get_property", "=", "plot", ".", "theme", ".", "themeables", ".", "property", "# by default, guide boxes are vertically aligned", "with", "suppress", "(", "KeyError", ")", ":", "self", ".", "box_direction", "=...
Build the guides Parameters ---------- plot : ggplot ggplot object being drawn Returns ------- box : matplotlib.offsetbox.Offsetbox | None A box that contains all the guides for the plot. If there are no guides, **None** is returned.
[ "Build", "the", "guides" ]
python
train
27.919355
aiogram/aiogram
aiogram/types/input_media.py
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/types/input_media.py#L328-L344
def attach_video(self, video: typing.Union[InputMediaVideo, base.InputFile], thumb: typing.Union[base.InputFile, base.String] = None, caption: base.String = None, width: base.Integer = None, height: base.Integer = None, duration: base.Integer = None): ...
[ "def", "attach_video", "(", "self", ",", "video", ":", "typing", ".", "Union", "[", "InputMediaVideo", ",", "base", ".", "InputFile", "]", ",", "thumb", ":", "typing", ".", "Union", "[", "base", ".", "InputFile", ",", "base", ".", "String", "]", "=", ...
Attach video :param video: :param caption: :param width: :param height: :param duration:
[ "Attach", "video" ]
python
train
40.882353
rwl/pylon
pylon/solver.py
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/solver.py#L444-L453
def _ref_bus_angle_constraint(self, buses, Va, xmin, xmax): """ Adds a constraint on the reference bus angles. """ refs = [bus._i for bus in buses if bus.type == REFERENCE] Varefs = array([b.v_angle for b in buses if b.type == REFERENCE]) xmin[Va.i1 - 1 + refs] = Varefs ...
[ "def", "_ref_bus_angle_constraint", "(", "self", ",", "buses", ",", "Va", ",", "xmin", ",", "xmax", ")", ":", "refs", "=", "[", "bus", ".", "_i", "for", "bus", "in", "buses", "if", "bus", ".", "type", "==", "REFERENCE", "]", "Varefs", "=", "array", ...
Adds a constraint on the reference bus angles.
[ "Adds", "a", "constraint", "on", "the", "reference", "bus", "angles", "." ]
python
train
36.9
flypenguin/python-cattleprod
cattleprod/__init__.py
https://github.com/flypenguin/python-cattleprod/blob/05043c91de78d211968db65413d3db4fd44c89e4/cattleprod/__init__.py#L55-L76
def poke(url, accesskey=None, secretkey=None, __method__='GET', **req_args): """ Poke the Rancher API. Returns a Rod object instance. Central starting point for the cattleprod package. :param url: The full Rancher URL to the API endpoint. :param accesskey: The rancher access key, optional. :para...
[ "def", "poke", "(", "url", ",", "accesskey", "=", "None", ",", "secretkey", "=", "None", ",", "__method__", "=", "'GET'", ",", "*", "*", "req_args", ")", ":", "if", "accesskey", "and", "secretkey", ":", "req_args", "[", "'auth'", "]", "=", "(", "acce...
Poke the Rancher API. Returns a Rod object instance. Central starting point for the cattleprod package. :param url: The full Rancher URL to the API endpoint. :param accesskey: The rancher access key, optional. :param secretkey: The rancher secret key, optional. :param __method__: Internal method, do...
[ "Poke", "the", "Rancher", "API", ".", "Returns", "a", "Rod", "object", "instance", ".", "Central", "starting", "point", "for", "the", "cattleprod", "package", ".", ":", "param", "url", ":", "The", "full", "Rancher", "URL", "to", "the", "API", "endpoint", ...
python
train
45.272727
ray-project/ray
python/ray/rllib/agents/mock.py
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/agents/mock.py#L108-L118
def _agent_import_failed(trace): """Returns dummy agent class for if PyTorch etc. is not installed.""" class _AgentImportFailed(Trainer): _name = "AgentImportFailed" _default_config = with_common_config({}) def _setup(self, config): raise ImportError(trace) return _Age...
[ "def", "_agent_import_failed", "(", "trace", ")", ":", "class", "_AgentImportFailed", "(", "Trainer", ")", ":", "_name", "=", "\"AgentImportFailed\"", "_default_config", "=", "with_common_config", "(", "{", "}", ")", "def", "_setup", "(", "self", ",", "config", ...
Returns dummy agent class for if PyTorch etc. is not installed.
[ "Returns", "dummy", "agent", "class", "for", "if", "PyTorch", "etc", ".", "is", "not", "installed", "." ]
python
train
29.454545
vertexproject/synapse
synapse/lib/types.py
https://github.com/vertexproject/synapse/blob/22e67c5a8f6d7caddbcf34b39ab1bd2d6c4a6e0b/synapse/lib/types.py#L252-L270
def norm(self, valu): ''' Normalize the value for a given type. Args: valu (obj): The value to normalize. Returns: ((obj,dict)): The normalized valu, info tuple. Notes: The info dictionary uses the following key conventions: ...
[ "def", "norm", "(", "self", ",", "valu", ")", ":", "func", "=", "self", ".", "_type_norms", ".", "get", "(", "type", "(", "valu", ")", ")", "if", "func", "is", "None", ":", "raise", "s_exc", ".", "NoSuchFunc", "(", "name", "=", "self", ".", "name...
Normalize the value for a given type. Args: valu (obj): The value to normalize. Returns: ((obj,dict)): The normalized valu, info tuple. Notes: The info dictionary uses the following key conventions: subs (dict): The normalized sub-fields as ...
[ "Normalize", "the", "value", "for", "a", "given", "type", "." ]
python
train
30.052632
mitsei/dlkit
dlkit/handcar/learning/managers.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/handcar/learning/managers.py#L2402-L2427
def get_objective_query_session(self, proxy): """Gets the ``OsidSession`` associated with the objective query service. :param proxy: a proxy :type proxy: ``osid.proxy.Proxy`` :return: an ``ObjectiveQuerySession`` :rtype: ``osid.learning.ObjectiveQuerySession`` :raise: ``...
[ "def", "get_objective_query_session", "(", "self", ",", "proxy", ")", ":", "if", "not", "self", ".", "supports_objective_query", "(", ")", ":", "raise", "Unimplemented", "(", ")", "try", ":", "from", ".", "import", "sessions", "except", "ImportError", ":", "...
Gets the ``OsidSession`` associated with the objective query service. :param proxy: a proxy :type proxy: ``osid.proxy.Proxy`` :return: an ``ObjectiveQuerySession`` :rtype: ``osid.learning.ObjectiveQuerySession`` :raise: ``NullArgument`` -- ``proxy`` is ``null`` :raise: `...
[ "Gets", "the", "OsidSession", "associated", "with", "the", "objective", "query", "service", "." ]
python
train
39.884615
manahl/arctic
arctic/store/metadata_store.py
https://github.com/manahl/arctic/blob/57e110b6e182dbab00e7e214dc26f7d9ec47c120/arctic/store/metadata_store.py#L275-L296
def pop(self, symbol): """ Delete current metadata of `symbol` Parameters ---------- symbol : `str` symbol name to delete Returns ------- Deleted metadata """ last_metadata = self.find_one({'symbol': symbol}, sort=[('start_tim...
[ "def", "pop", "(", "self", ",", "symbol", ")", ":", "last_metadata", "=", "self", ".", "find_one", "(", "{", "'symbol'", ":", "symbol", "}", ",", "sort", "=", "[", "(", "'start_time'", ",", "pymongo", ".", "DESCENDING", ")", "]", ")", "if", "last_met...
Delete current metadata of `symbol` Parameters ---------- symbol : `str` symbol name to delete Returns ------- Deleted metadata
[ "Delete", "current", "metadata", "of", "symbol" ]
python
train
34.5
9b/google-alerts
google_alerts/__init__.py
https://github.com/9b/google-alerts/blob/69a502cbcccf1bcafe963ed40d286441b0117e04/google_alerts/__init__.py#L339-L355
def create(self, term, options): """Create a monitor using passed configuration.""" if not self._state: raise InvalidState("State was not properly obtained from the app") options['action'] = 'CREATE' payload = self._build_payload(term, options) url = self.ALERTS_CREAT...
[ "def", "create", "(", "self", ",", "term", ",", "options", ")", ":", "if", "not", "self", ".", "_state", ":", "raise", "InvalidState", "(", "\"State was not properly obtained from the app\"", ")", "options", "[", "'action'", "]", "=", "'CREATE'", "payload", "=...
Create a monitor using passed configuration.
[ "Create", "a", "monitor", "using", "passed", "configuration", "." ]
python
train
48.588235
topic2k/pygcgen
pygcgen/reader.py
https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/reader.py#L63-L82
def parse(data): """ Parse the given ChangeLog data into a list of Hashes. @param [String] data File data from the ChangeLog.md @return [Array<Hash>] Parsed data, e.g. [{ 'version' => ..., 'url' => ..., 'date' => ..., 'content' => ...}, ...] """ sections = re.compile("^## .+$", re.MULTILINE).s...
[ "def", "parse", "(", "data", ")", ":", "sections", "=", "re", ".", "compile", "(", "\"^## .+$\"", ",", "re", ".", "MULTILINE", ")", ".", "split", "(", "data", ")", "headings", "=", "re", ".", "findall", "(", "\"^## .+?$\"", ",", "data", ",", "re", ...
Parse the given ChangeLog data into a list of Hashes. @param [String] data File data from the ChangeLog.md @return [Array<Hash>] Parsed data, e.g. [{ 'version' => ..., 'url' => ..., 'date' => ..., 'content' => ...}, ...]
[ "Parse", "the", "given", "ChangeLog", "data", "into", "a", "list", "of", "Hashes", "." ]
python
valid
28.2
fastai/fastai
fastai/gen_doc/gen_notebooks.py
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/gen_notebooks.py#L169-L173
def update_pos(pos_dict, start_key, nbr=2): "Update the `pos_dict` by moving all positions after `start_key` by `nbr`." for key,idx in pos_dict.items(): if str.lower(key) >= str.lower(start_key): pos_dict[key] += nbr return pos_dict
[ "def", "update_pos", "(", "pos_dict", ",", "start_key", ",", "nbr", "=", "2", ")", ":", "for", "key", ",", "idx", "in", "pos_dict", ".", "items", "(", ")", ":", "if", "str", ".", "lower", "(", "key", ")", ">=", "str", ".", "lower", "(", "start_ke...
Update the `pos_dict` by moving all positions after `start_key` by `nbr`.
[ "Update", "the", "pos_dict", "by", "moving", "all", "positions", "after", "start_key", "by", "nbr", "." ]
python
train
49.6
brainiak/brainiak
brainiak/isc.py
https://github.com/brainiak/brainiak/blob/408f12dec2ff56559a26873a848a09e4c8facfeb/brainiak/isc.py#L588-L642
def _threshold_nans(data, tolerate_nans): """Thresholds data based on proportion of subjects with NaNs Takes in data and a threshold value (float between 0.0 and 1.0) determining the permissible proportion of subjects with non-NaN values. For example, if threshold=.8, any voxel where >= 80% of subject...
[ "def", "_threshold_nans", "(", "data", ",", "tolerate_nans", ")", ":", "nans", "=", "np", ".", "all", "(", "np", ".", "any", "(", "np", ".", "isnan", "(", "data", ")", ",", "axis", "=", "0", ")", ",", "axis", "=", "1", ")", "# Check tolerate_nans i...
Thresholds data based on proportion of subjects with NaNs Takes in data and a threshold value (float between 0.0 and 1.0) determining the permissible proportion of subjects with non-NaN values. For example, if threshold=.8, any voxel where >= 80% of subjects have non-NaN values will be left unchanged, ...
[ "Thresholds", "data", "based", "on", "proportion", "of", "subjects", "with", "NaNs" ]
python
train
38.854545
lltk/lltk
lltk/scraping.py
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/scraping.py#L48-L57
def scrape(language, method, word, *args, **kwargs): ''' Uses custom scrapers and calls provided method. ''' scraper = Scrape(language, word) if hasattr(scraper, method): function = getattr(scraper, method) if callable(function): return function(*args, **kwargs) else: raise NotImplementedError('The method...
[ "def", "scrape", "(", "language", ",", "method", ",", "word", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "scraper", "=", "Scrape", "(", "language", ",", "word", ")", "if", "hasattr", "(", "scraper", ",", "method", ")", ":", "function", "=...
Uses custom scrapers and calls provided method.
[ "Uses", "custom", "scrapers", "and", "calls", "provided", "method", "." ]
python
train
35.7
kyan001/PyKyanToolKit
KyanToolKit.py
https://github.com/kyan001/PyKyanToolKit/blob/a3974fcd45ce41f743b4a3d42af961fedea8fda8/KyanToolKit.py#L214-L224
def readFile(cls, filepath): """Try different encoding to open a file in readonly mode""" for mode in ("utf-8", 'gbk', 'cp1252', 'windows-1252', 'latin-1'): try: with open(filepath, mode='r', encoding=mode) as f: content = f.read() cit....
[ "def", "readFile", "(", "cls", ",", "filepath", ")", ":", "for", "mode", "in", "(", "\"utf-8\"", ",", "'gbk'", ",", "'cp1252'", ",", "'windows-1252'", ",", "'latin-1'", ")", ":", "try", ":", "with", "open", "(", "filepath", ",", "mode", "=", "'r'", "...
Try different encoding to open a file in readonly mode
[ "Try", "different", "encoding", "to", "open", "a", "file", "in", "readonly", "mode" ]
python
train
44.818182
napalm-automation/napalm-logs
napalm_logs/server.py
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/server.py#L193-L215
def _identify_os(self, msg): ''' Using the prefix of the syslog message, we are able to identify the operating system and then continue parsing. ''' ret = [] for dev_os, data in self.compiled_prefixes.items(): # TODO Should we prevent attepmting to determine t...
[ "def", "_identify_os", "(", "self", ",", "msg", ")", ":", "ret", "=", "[", "]", "for", "dev_os", ",", "data", "in", "self", ".", "compiled_prefixes", ".", "items", "(", ")", ":", "# TODO Should we prevent attepmting to determine the OS for the blacklisted?", "# [m...
Using the prefix of the syslog message, we are able to identify the operating system and then continue parsing.
[ "Using", "the", "prefix", "of", "the", "syslog", "message", "we", "are", "able", "to", "identify", "the", "operating", "system", "and", "then", "continue", "parsing", "." ]
python
train
47.869565
saltstack/salt
salt/cli/support/__init__.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/support/__init__.py#L15-L22
def _render_profile(path, caller, runner): ''' Render profile as Jinja2. :param path: :return: ''' env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(path)), trim_blocks=False) return env.get_template(os.path.basename(path)).render(salt=caller, runners=runner).strip()
[ "def", "_render_profile", "(", "path", ",", "caller", ",", "runner", ")", ":", "env", "=", "jinja2", ".", "Environment", "(", "loader", "=", "jinja2", ".", "FileSystemLoader", "(", "os", ".", "path", ".", "dirname", "(", "path", ")", ")", ",", "trim_bl...
Render profile as Jinja2. :param path: :return:
[ "Render", "profile", "as", "Jinja2", ".", ":", "param", "path", ":", ":", "return", ":" ]
python
train
38.75
tensorflow/probability
experimental/no_u_turn_sampler/nuts.py
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/experimental/no_u_turn_sampler/nuts.py#L503-L507
def _log_joint(current_target_log_prob, current_momentum): """Log-joint probability given a state's log-probability and momentum.""" momentum_log_prob = -sum( [tf.reduce_sum(input_tensor=0.5 * (m**2.)) for m in current_momentum]) return current_target_log_prob + momentum_log_prob
[ "def", "_log_joint", "(", "current_target_log_prob", ",", "current_momentum", ")", ":", "momentum_log_prob", "=", "-", "sum", "(", "[", "tf", ".", "reduce_sum", "(", "input_tensor", "=", "0.5", "*", "(", "m", "**", "2.", ")", ")", "for", "m", "in", "curr...
Log-joint probability given a state's log-probability and momentum.
[ "Log", "-", "joint", "probability", "given", "a", "state", "s", "log", "-", "probability", "and", "momentum", "." ]
python
test
57.6
jcushman/pdfquery
pdfquery/pdfquery.py
https://github.com/jcushman/pdfquery/blob/f1c05d15e0c1b7c523a0971bc89b5610d8560f79/pdfquery/pdfquery.py#L456-L501
def get_tree(self, *page_numbers): """ Return lxml.etree.ElementTree for entire document, or page numbers given if any. """ cache_key = "_".join(map(str, _flatten(page_numbers))) tree = self._parse_tree_cacher.get(cache_key) if tree is None: ...
[ "def", "get_tree", "(", "self", ",", "*", "page_numbers", ")", ":", "cache_key", "=", "\"_\"", ".", "join", "(", "map", "(", "str", ",", "_flatten", "(", "page_numbers", ")", ")", ")", "tree", "=", "self", ".", "_parse_tree_cacher", ".", "get", "(", ...
Return lxml.etree.ElementTree for entire document, or page numbers given if any.
[ "Return", "lxml", ".", "etree", ".", "ElementTree", "for", "entire", "document", "or", "page", "numbers", "given", "if", "any", "." ]
python
train
44.673913
note35/sinon
sinon/lib/assertion.py
https://github.com/note35/sinon/blob/f1d551b679b393d64d926a8a279320904c38d0f5/sinon/lib/assertion.py#L185-L192
def neverCalledWithMatch(cls, spy, *args, **kwargs): #pylint: disable=invalid-name """ Checking the inspector is never called with partial SinonMatcher(args/kwargs) Args: SinonSpy, args/kwargs """ cls.__is_spy(spy) if not (spy.neverCalledWithMatch(*args, **kwargs)): ...
[ "def", "neverCalledWithMatch", "(", "cls", ",", "spy", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "#pylint: disable=invalid-name", "cls", ".", "__is_spy", "(", "spy", ")", "if", "not", "(", "spy", ".", "neverCalledWithMatch", "(", "*", "args", ...
Checking the inspector is never called with partial SinonMatcher(args/kwargs) Args: SinonSpy, args/kwargs
[ "Checking", "the", "inspector", "is", "never", "called", "with", "partial", "SinonMatcher", "(", "args", "/", "kwargs", ")", "Args", ":", "SinonSpy", "args", "/", "kwargs" ]
python
train
44.5
AndrewAnnex/SpiceyPy
spiceypy/spiceypy.py
https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L9891-L9905
def prsint(string): """ Parse a string as an integer, encapsulating error handling. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/prsint_c.html :param string: String representing an integer. :type string: str :return: Integer value obtained by parsing string. :rtype: int """ ...
[ "def", "prsint", "(", "string", ")", ":", "string", "=", "stypes", ".", "stringToCharP", "(", "string", ")", "intval", "=", "ctypes", ".", "c_int", "(", ")", "libspice", ".", "prsint_c", "(", "string", ",", "ctypes", ".", "byref", "(", "intval", ")", ...
Parse a string as an integer, encapsulating error handling. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/prsint_c.html :param string: String representing an integer. :type string: str :return: Integer value obtained by parsing string. :rtype: int
[ "Parse", "a", "string", "as", "an", "integer", "encapsulating", "error", "handling", "." ]
python
train
30.066667
inasafe/inasafe
safe/metadata/metadata_db_io.py
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata/metadata_db_io.py#L159-L195
def are_metadata_file_based(layer): """Check if metadata should be read/written to file or our metadata db. Determine which metadata lookup system to use (file base or cache db) based on the layer's provider type. True indicates we should use the datasource as a file and look for a meta...
[ "def", "are_metadata_file_based", "(", "layer", ")", ":", "try", ":", "provider_type", "=", "str", "(", "layer", ".", "providerType", "(", ")", ")", "except", "AttributeError", ":", "raise", "UnsupportedProviderError", "(", "'Could not determine type for provider: %s'...
Check if metadata should be read/written to file or our metadata db. Determine which metadata lookup system to use (file base or cache db) based on the layer's provider type. True indicates we should use the datasource as a file and look for a metadata file, False and we look in the met...
[ "Check", "if", "metadata", "should", "be", "read", "/", "written", "to", "file", "or", "our", "metadata", "db", "." ]
python
train
35.864865
jonathanslenders/textfsm
jtextfsm.py
https://github.com/jonathanslenders/textfsm/blob/cca5084512d14bc367205aceb34c938ac1c65daf/jtextfsm.py#L251-L291
def Parse(self, value): """Parse a 'Value' declaration. Args: value: String line from a template file, must begin with 'Value '. Raises: TextFSMTemplateError: Value declaration contains an error. """ value_line = value.split(' ') if len(value_line) < 3: raise TextFSMTemplat...
[ "def", "Parse", "(", "self", ",", "value", ")", ":", "value_line", "=", "value", ".", "split", "(", "' '", ")", "if", "len", "(", "value_line", ")", "<", "3", ":", "raise", "TextFSMTemplateError", "(", "'Expect at least 3 tokens on line.'", ")", "if", "not...
Parse a 'Value' declaration. Args: value: String line from a template file, must begin with 'Value '. Raises: TextFSMTemplateError: Value declaration contains an error.
[ "Parse", "a", "Value", "declaration", "." ]
python
train
31.707317
jrjparks/django-rest-framework-nested
rest_framework_nested/relations.py
https://github.com/jrjparks/django-rest-framework-nested/blob/8ab797281e11507b8142f342ad73ca48ef82565c/rest_framework_nested/relations.py#L15-L30
def get_object(self, view_name, view_args, view_kwargs): """ Return the object corresponding to a matched URL. Takes the matched URL conf arguments, and should return an object instance, or raise an `ObjectDoesNotExist` exception. """ lookup_value = view_kwargs.get(self....
[ "def", "get_object", "(", "self", ",", "view_name", ",", "view_args", ",", "view_kwargs", ")", ":", "lookup_value", "=", "view_kwargs", ".", "get", "(", "self", ".", "lookup_url_kwarg", ")", "parent_lookup_value", "=", "view_kwargs", ".", "get", "(", "self", ...
Return the object corresponding to a matched URL. Takes the matched URL conf arguments, and should return an object instance, or raise an `ObjectDoesNotExist` exception.
[ "Return", "the", "object", "corresponding", "to", "a", "matched", "URL", "." ]
python
train
42.5625
sdispater/poetry
poetry/console/commands/command.py
https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/console/commands/command.py#L79-L95
def register_logger(self, logger): """ Register a new logger. """ handler = CommandHandler(self) handler.setFormatter(CommandFormatter()) logger.handlers = [handler] logger.propagate = False output = self.output level = logging.WARNING if ...
[ "def", "register_logger", "(", "self", ",", "logger", ")", ":", "handler", "=", "CommandHandler", "(", "self", ")", "handler", ".", "setFormatter", "(", "CommandFormatter", "(", ")", ")", "logger", ".", "handlers", "=", "[", "handler", "]", "logger", ".", ...
Register a new logger.
[ "Register", "a", "new", "logger", "." ]
python
train
28.411765
tensorflow/cleverhans
cleverhans_tutorials/mnist_tutorial_keras.py
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans_tutorials/mnist_tutorial_keras.py#L30-L167
def mnist_tutorial(train_start=0, train_end=60000, test_start=0, test_end=10000, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE, learning_rate=LEARNING_RATE, testing=False, label_smoothing=0.1): """ MNIST CleverHans tutorial :param train_start: index of first t...
[ "def", "mnist_tutorial", "(", "train_start", "=", "0", ",", "train_end", "=", "60000", ",", "test_start", "=", "0", ",", "test_end", "=", "10000", ",", "nb_epochs", "=", "NB_EPOCHS", ",", "batch_size", "=", "BATCH_SIZE", ",", "learning_rate", "=", "LEARNING_...
MNIST CleverHans tutorial :param train_start: index of first training set example :param train_end: index of last training set example :param test_start: index of first test set example :param test_end: index of last test set example :param nb_epochs: number of epochs to train model :param batch_size: size ...
[ "MNIST", "CleverHans", "tutorial", ":", "param", "train_start", ":", "index", "of", "first", "training", "set", "example", ":", "param", "train_end", ":", "index", "of", "last", "training", "set", "example", ":", "param", "test_start", ":", "index", "of", "f...
python
train
38.376812
pywbem/pywbem
pywbem/mof_compiler.py
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/mof_compiler.py#L1604-L1616
def p_valueInitializer(p): """valueInitializer : identifier defaultValue ';' | qualifierList identifier defaultValue ';' """ if len(p) == 4: id_ = p[1] val = p[2] quals = [] else: quals = p[1] id_ = p[2] val = p[...
[ "def", "p_valueInitializer", "(", "p", ")", ":", "if", "len", "(", "p", ")", "==", "4", ":", "id_", "=", "p", "[", "1", "]", "val", "=", "p", "[", "2", "]", "quals", "=", "[", "]", "else", ":", "quals", "=", "p", "[", "1", "]", "id_", "="...
valueInitializer : identifier defaultValue ';' | qualifierList identifier defaultValue ';'
[ "valueInitializer", ":", "identifier", "defaultValue", ";", "|", "qualifierList", "identifier", "defaultValue", ";" ]
python
train
26.076923
fboender/ansible-cmdb
src/ansiblecmdb/parser.py
https://github.com/fboender/ansible-cmdb/blob/ebd960ac10684e8c9ec2b12751bba2c4c9504ab7/src/ansiblecmdb/parser.py#L402-L436
def _parse_group(self, group_name, group): """ Parse a group definition from a dynamic inventory. These are top-level elements which are not '_meta(data)'. """ if type(group) == dict: # Example: # { # "mgmt": { # "...
[ "def", "_parse_group", "(", "self", ",", "group_name", ",", "group", ")", ":", "if", "type", "(", "group", ")", "==", "dict", ":", "# Example:", "# {", "# \"mgmt\": {", "# \"hosts\": [ \"mgmt01\", \"mgmt02\" ],", "# \"vars\": {", "# \...
Parse a group definition from a dynamic inventory. These are top-level elements which are not '_meta(data)'.
[ "Parse", "a", "group", "definition", "from", "a", "dynamic", "inventory", ".", "These", "are", "top", "-", "level", "elements", "which", "are", "not", "_meta", "(", "data", ")", "." ]
python
train
40.085714
kubernetes-client/python
kubernetes/client/apis/batch_v1_api.py
https://github.com/kubernetes-client/python/blob/5e512ff564c244c50cab780d821542ed56aa965a/kubernetes/client/apis/batch_v1_api.py#L38-L61
def create_namespaced_job(self, namespace, body, **kwargs): """ create a Job This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_namespaced_job(namespace, body, async_req=True) >...
[ "def", "create_namespaced_job", "(", "self", ",", "namespace", ",", "body", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "...
create a Job This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_namespaced_job(namespace, body, async_req=True) >>> result = thread.get() :param async_req bool :param str names...
[ "create", "a", "Job", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "pass", "async_req", "=", "True", ">>>", "thread", "=", "api", ".", "create_namespa...
python
train
64.416667
pyviz/holoviews
holoviews/plotting/bokeh/raster.py
https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/plotting/bokeh/raster.py#L269-L281
def _init_glyph(self, plot, mapping, properties): """ Returns a Bokeh glyph object. """ properties = mpl_to_bokeh(properties) properties = dict(properties, **mapping) if 'xs' in mapping: renderer = plot.patches(**properties) else: renderer ...
[ "def", "_init_glyph", "(", "self", ",", "plot", ",", "mapping", ",", "properties", ")", ":", "properties", "=", "mpl_to_bokeh", "(", "properties", ")", "properties", "=", "dict", "(", "properties", ",", "*", "*", "mapping", ")", "if", "'xs'", "in", "mapp...
Returns a Bokeh glyph object.
[ "Returns", "a", "Bokeh", "glyph", "object", "." ]
python
train
38.615385
mnick/scikit-tensor
sktensor/dtensor.py
https://github.com/mnick/scikit-tensor/blob/fe517e9661a08164b8d30d2dddf7c96aeeabcf36/sktensor/dtensor.py#L103-L150
def unfold(self, mode): """ Unfolds a dense tensor in mode n. Parameters ---------- mode : int Mode in which tensor is unfolded Returns ------- unfolded_dtensor : unfolded_dtensor object Tensor unfolded along mode Example...
[ "def", "unfold", "(", "self", ",", "mode", ")", ":", "sz", "=", "array", "(", "self", ".", "shape", ")", "N", "=", "len", "(", "sz", ")", "order", "=", "(", "[", "mode", "]", ",", "from_to_without", "(", "N", "-", "1", ",", "-", "1", ",", "...
Unfolds a dense tensor in mode n. Parameters ---------- mode : int Mode in which tensor is unfolded Returns ------- unfolded_dtensor : unfolded_dtensor object Tensor unfolded along mode Examples -------- Create dense tens...
[ "Unfolds", "a", "dense", "tensor", "in", "mode", "n", "." ]
python
train
33.916667
Varkal/chuda
chuda/shell.py
https://github.com/Varkal/chuda/blob/0d93b716dede35231c21be97bcc19a656655983f/chuda/shell.py#L174-L203
def wait_for(self, pattern, timeout=None): """ Block until a pattern have been found in stdout and stderr Args: pattern(:class:`~re.Pattern`): The pattern to search timeout(int): Maximum number of second to wait. If None, wait infinitely Raises: Tim...
[ "def", "wait_for", "(", "self", ",", "pattern", ",", "timeout", "=", "None", ")", ":", "should_continue", "=", "True", "if", "self", ".", "block", ":", "raise", "TypeError", "(", "NON_BLOCKING_ERROR_MESSAGE", ")", "def", "stop", "(", "signum", ",", "frame"...
Block until a pattern have been found in stdout and stderr Args: pattern(:class:`~re.Pattern`): The pattern to search timeout(int): Maximum number of second to wait. If None, wait infinitely Raises: TimeoutError: When timeout is reach
[ "Block", "until", "a", "pattern", "have", "been", "found", "in", "stdout", "and", "stderr" ]
python
train
31.566667
NICTA/revrand
revrand/likelihoods.py
https://github.com/NICTA/revrand/blob/4c1881b6c1772d2b988518e49dde954f165acfb6/revrand/likelihoods.py#L523-L541
def cdf(self, y, f): r""" Cumulative density function of the likelihood. Parameters ---------- y: ndarray query quantiles, i.e.\ :math:`P(Y \leq y)`. f: ndarray latent function from the GLM prior (:math:`\mathbf{f} = \boldsymbol\Phi \...
[ "def", "cdf", "(", "self", ",", "y", ",", "f", ")", ":", "mu", "=", "np", ".", "exp", "(", "f", ")", "if", "self", ".", "tranfcn", "==", "'exp'", "else", "softplus", "(", "f", ")", "return", "poisson", ".", "cdf", "(", "y", ",", "mu", "=", ...
r""" Cumulative density function of the likelihood. Parameters ---------- y: ndarray query quantiles, i.e.\ :math:`P(Y \leq y)`. f: ndarray latent function from the GLM prior (:math:`\mathbf{f} = \boldsymbol\Phi \mathbf{w}`) Returns ...
[ "r", "Cumulative", "density", "function", "of", "the", "likelihood", "." ]
python
train
28.263158
eng-tools/sfsimodels
sfsimodels/sensors.py
https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/sensors.py#L85-L102
def get_mtype_and_number_from_code(si, sensor_code): """ Given a sensor sensor_code, get motion type and sensor number :param si: dict, sensor index json dictionary :param sensor_code: str, a sensor code (e.g. ACCX-UB1-L2C-M) :return: """ mtype_and_ory, x, y, z = sensor_code.split("-") ...
[ "def", "get_mtype_and_number_from_code", "(", "si", ",", "sensor_code", ")", ":", "mtype_and_ory", ",", "x", ",", "y", ",", "z", "=", "sensor_code", ".", "split", "(", "\"-\"", ")", "if", "mtype_and_ory", "[", "-", "1", "]", "in", "\"XYZ\"", "and", "\"AC...
Given a sensor sensor_code, get motion type and sensor number :param si: dict, sensor index json dictionary :param sensor_code: str, a sensor code (e.g. ACCX-UB1-L2C-M) :return:
[ "Given", "a", "sensor", "sensor_code", "get", "motion", "type", "and", "sensor", "number" ]
python
train
36.333333
SpriteLink/NIPAP
nipap-cli/nipap_cli/nipap_cli.py
https://github.com/SpriteLink/NIPAP/blob/f96069f11ab952d80b13cab06e0528f2d24b3de9/nipap-cli/nipap_cli/nipap_cli.py#L663-L684
def _prefix_from_opts(opts): """ Return a prefix based on options passed from command line Used by add_prefix() and add_prefix_from_pool() to avoid duplicate parsing """ p = Prefix() p.prefix = opts.get('prefix') p.type = opts.get('type') p.description = opts.get('description') ...
[ "def", "_prefix_from_opts", "(", "opts", ")", ":", "p", "=", "Prefix", "(", ")", "p", ".", "prefix", "=", "opts", ".", "get", "(", "'prefix'", ")", "p", ".", "type", "=", "opts", ".", "get", "(", "'type'", ")", "p", ".", "description", "=", "opts...
Return a prefix based on options passed from command line Used by add_prefix() and add_prefix_from_pool() to avoid duplicate parsing
[ "Return", "a", "prefix", "based", "on", "options", "passed", "from", "command", "line" ]
python
train
36.590909
ARMmbed/icetea
icetea_lib/tools/GenericProcess.py
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/GenericProcess.py#L167-L185
def _read_select_kqueue(k_queue): """ Read PIPES using BSD Kqueue """ npipes = len(NonBlockingStreamReader._streams) # Create list of kevent objects # pylint: disable=no-member kevents = [select.kevent(s.stream.fileno(), filter=sel...
[ "def", "_read_select_kqueue", "(", "k_queue", ")", ":", "npipes", "=", "len", "(", "NonBlockingStreamReader", ".", "_streams", ")", "# Create list of kevent objects", "# pylint: disable=no-member", "kevents", "=", "[", "select", ".", "kevent", "(", "s", ".", "stream...
Read PIPES using BSD Kqueue
[ "Read", "PIPES", "using", "BSD", "Kqueue" ]
python
train
47.894737
pyvisa/pyvisa-sim
pyvisa-sim/parser.py
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/parser.py#L82-L106
def _load(content_or_fp): """YAML Parse a file or str and check version. """ try: data = yaml.load(content_or_fp, Loader=yaml.loader.BaseLoader) except Exception as e: raise type(e)('Malformed yaml file:\n%r' % format_exc()) try: ver = data['spec'] except: raise ...
[ "def", "_load", "(", "content_or_fp", ")", ":", "try", ":", "data", "=", "yaml", ".", "load", "(", "content_or_fp", ",", "Loader", "=", "yaml", ".", "loader", ".", "BaseLoader", ")", "except", "Exception", "as", "e", ":", "raise", "type", "(", "e", "...
YAML Parse a file or str and check version.
[ "YAML", "Parse", "a", "file", "or", "str", "and", "check", "version", "." ]
python
train
31.72
MartinThoma/hwrt
hwrt/handwritten_data.py
https://github.com/MartinThoma/hwrt/blob/725c21a3d0f5a30b8492cbc184b3688ceb364e1c/hwrt/handwritten_data.py#L289-L297
def count_single_dots(self): """Count all strokes of this recording that have only a single dot. """ pointlist = self.get_pointlist() single_dots = 0 for stroke in pointlist: if len(stroke) == 1: single_dots += 1 return single_dots
[ "def", "count_single_dots", "(", "self", ")", ":", "pointlist", "=", "self", ".", "get_pointlist", "(", ")", "single_dots", "=", "0", "for", "stroke", "in", "pointlist", ":", "if", "len", "(", "stroke", ")", "==", "1", ":", "single_dots", "+=", "1", "r...
Count all strokes of this recording that have only a single dot.
[ "Count", "all", "strokes", "of", "this", "recording", "that", "have", "only", "a", "single", "dot", "." ]
python
train
33.222222
pgjones/quart
quart/wrappers/response.py
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/wrappers/response.py#L298-L335
async def make_conditional( self, request_range: Range, max_partial_size: Optional[int]=None, ) -> None: """Make the response conditional to the Arguments: request_range: The range as requested by the request. max_partial_size: The maximum...
[ "async", "def", "make_conditional", "(", "self", ",", "request_range", ":", "Range", ",", "max_partial_size", ":", "Optional", "[", "int", "]", "=", "None", ",", ")", "->", "None", ":", "self", ".", "accept_ranges", "=", "\"bytes\"", "# Advertise this ability"...
Make the response conditional to the Arguments: request_range: The range as requested by the request. max_partial_size: The maximum length the server is willing to serve in a single response. Defaults to unlimited.
[ "Make", "the", "response", "conditional", "to", "the" ]
python
train
41.263158
woolfson-group/isambard
isambard/ampal/protein.py
https://github.com/woolfson-group/isambard/blob/ebc33b48a28ad217e18f93b910dfba46e6e71e07/isambard/ampal/protein.py#L282-L297
def backbone(self): """Returns a new `Polymer` containing only the backbone atoms. Notes ----- Metadata is not currently preserved from the parent object. Sequence data is retained, but only the main chain atoms are retained. Returns ------- bb_poly : Po...
[ "def", "backbone", "(", "self", ")", ":", "bb_poly", "=", "Polypeptide", "(", "[", "x", ".", "backbone", "for", "x", "in", "self", ".", "_monomers", "]", ",", "self", ".", "id", ")", "return", "bb_poly" ]
Returns a new `Polymer` containing only the backbone atoms. Notes ----- Metadata is not currently preserved from the parent object. Sequence data is retained, but only the main chain atoms are retained. Returns ------- bb_poly : Polypeptide Polymer c...
[ "Returns", "a", "new", "Polymer", "containing", "only", "the", "backbone", "atoms", "." ]
python
train
32.375
corydodt/Crosscap
crosscap/openapi.py
https://github.com/corydodt/Crosscap/blob/388a2ec36b8aa85e8f1ed692bb6e43474ba76c8e/crosscap/openapi.py#L124-L138
def _orderedCleanDict(attrsObj): """ -> dict with false-values removed Also evaluates attr-instances for false-ness by looking at the values of their properties """ def _filt(k, v): if attr.has(v): return not not any(attr.astuple(v)) return not not v return attr.asd...
[ "def", "_orderedCleanDict", "(", "attrsObj", ")", ":", "def", "_filt", "(", "k", ",", "v", ")", ":", "if", "attr", ".", "has", "(", "v", ")", ":", "return", "not", "not", "any", "(", "attr", ".", "astuple", "(", "v", ")", ")", "return", "not", ...
-> dict with false-values removed Also evaluates attr-instances for false-ness by looking at the values of their properties
[ "-", ">", "dict", "with", "false", "-", "values", "removed" ]
python
train
26.533333
emin63/eyap
eyap/core/comments.py
https://github.com/emin63/eyap/blob/a610761973b478ca0e864e970be05ce29d5994a5/eyap/core/comments.py#L60-L65
def make_anchor_id(self): """Return string to use as URL anchor for this comment. """ result = re.sub( '[^a-zA-Z0-9_]', '_', self.user + '_' + self.timestamp) return result
[ "def", "make_anchor_id", "(", "self", ")", ":", "result", "=", "re", ".", "sub", "(", "'[^a-zA-Z0-9_]'", ",", "'_'", ",", "self", ".", "user", "+", "'_'", "+", "self", ".", "timestamp", ")", "return", "result" ]
Return string to use as URL anchor for this comment.
[ "Return", "string", "to", "use", "as", "URL", "anchor", "for", "this", "comment", "." ]
python
train
35.166667
django-haystack/pysolr
pysolr.py
https://github.com/django-haystack/pysolr/blob/ee28b39324fa21a99842d297e313c1759d8adbd2/pysolr.py#L150-L177
def unescape_html(text): """ Removes HTML or XML character references and entities from a text string. @param text The HTML (or XML) source text. @return The plain text, as a Unicode string, if necessary. Source: http://effbot.org/zone/re-sub.htm#unescape-html """ def fixup(m): tex...
[ "def", "unescape_html", "(", "text", ")", ":", "def", "fixup", "(", "m", ")", ":", "text", "=", "m", ".", "group", "(", "0", ")", "if", "text", "[", ":", "2", "]", "==", "\"&#\"", ":", "# character reference", "try", ":", "if", "text", "[", ":", ...
Removes HTML or XML character references and entities from a text string. @param text The HTML (or XML) source text. @return The plain text, as a Unicode string, if necessary. Source: http://effbot.org/zone/re-sub.htm#unescape-html
[ "Removes", "HTML", "or", "XML", "character", "references", "and", "entities", "from", "a", "text", "string", "." ]
python
train
31.428571
log2timeline/dfvfs
dfvfs/vfs/tar_file_entry.py
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/tar_file_entry.py#L130-L140
def _GetLink(self): """Retrieves the link. Returns: str: link. """ if self._link is None: if self._tar_info: self._link = self._tar_info.linkname return self._link
[ "def", "_GetLink", "(", "self", ")", ":", "if", "self", ".", "_link", "is", "None", ":", "if", "self", ".", "_tar_info", ":", "self", ".", "_link", "=", "self", ".", "_tar_info", ".", "linkname", "return", "self", ".", "_link" ]
Retrieves the link. Returns: str: link.
[ "Retrieves", "the", "link", "." ]
python
train
17.727273
shaypal5/pdutil
pdutil/iter/iter.py
https://github.com/shaypal5/pdutil/blob/231059634643af2558d22070f89767410978cf56/pdutil/iter/iter.py#L35-L64
def sub_dfs_by_num(df, num): """Get a generator yielding num consecutive sub-dataframes of the given df. Arguments --------- df : pandas.DataFrame The dataframe for which to get sub-dataframes. num : int The number of sub-dataframe to divide the given dataframe into. Returns ...
[ "def", "sub_dfs_by_num", "(", "df", ",", "num", ")", ":", "size", "=", "len", "(", "df", ")", "/", "float", "(", "num", ")", "for", "i", "in", "range", "(", "num", ")", ":", "yield", "df", ".", "iloc", "[", "int", "(", "round", "(", "size", "...
Get a generator yielding num consecutive sub-dataframes of the given df. Arguments --------- df : pandas.DataFrame The dataframe for which to get sub-dataframes. num : int The number of sub-dataframe to divide the given dataframe into. Returns ------- generator A ge...
[ "Get", "a", "generator", "yielding", "num", "consecutive", "sub", "-", "dataframes", "of", "the", "given", "df", "." ]
python
train
28.533333
uktrade/directory-validators
directory_validators/enrolment.py
https://github.com/uktrade/directory-validators/blob/e01f9d2aec683e34d978e4f67ed383ea2f9b85a0/directory_validators/enrolment.py#L43-L54
def email_domain_free(value): """ Confirms that the email address is not using a free service. @param {str} value @returns {None} @raises AssertionError """ domain = helpers.get_domain_from_email_address(value) if domain.lower() in free_domains: raise ValidationError(MESSAGE_US...
[ "def", "email_domain_free", "(", "value", ")", ":", "domain", "=", "helpers", ".", "get_domain_from_email_address", "(", "value", ")", "if", "domain", ".", "lower", "(", ")", "in", "free_domains", ":", "raise", "ValidationError", "(", "MESSAGE_USE_COMPANY_EMAIL", ...
Confirms that the email address is not using a free service. @param {str} value @returns {None} @raises AssertionError
[ "Confirms", "that", "the", "email", "address", "is", "not", "using", "a", "free", "service", ".", "@param", "{", "str", "}", "value", "@returns", "{", "None", "}", "@raises", "AssertionError" ]
python
train
27.083333