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
pywbem/pywbem
wbemcli.py
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/wbemcli.py#L3111-L3128
def _get_banner(): """Return a banner message for the interactive console.""" result = '' result += '\nPython %s' % _sys.version result += '\n\nWbemcli interactive shell' result += '\n%s' % _get_connection_info() # Give hint about exiting. Most people exit with 'quit()' which will # not re...
[ "def", "_get_banner", "(", ")", ":", "result", "=", "''", "result", "+=", "'\\nPython %s'", "%", "_sys", ".", "version", "result", "+=", "'\\n\\nWbemcli interactive shell'", "result", "+=", "'\\n%s'", "%", "_get_connection_info", "(", ")", "# Give hint about exiting...
Return a banner message for the interactive console.
[ "Return", "a", "banner", "message", "for", "the", "interactive", "console", "." ]
python
train
33.833333
secdev/scapy
scapy/sendrecv.py
https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/sendrecv.py#L687-L700
def sr1flood(x, promisc=None, filter=None, iface=None, nofilter=0, *args, **kargs): # noqa: E501 """Flood and receive packets at layer 3 and return only the first answer prn: function applied to packets received verbose: set verbosity level nofilter: put 1 to avoid use of BPF filters filter: provide a BPF ...
[ "def", "sr1flood", "(", "x", ",", "promisc", "=", "None", ",", "filter", "=", "None", ",", "iface", "=", "None", ",", "nofilter", "=", "0", ",", "*", "args", ",", "*", "*", "kargs", ")", ":", "# noqa: E501", "s", "=", "conf", ".", "L3socket", "("...
Flood and receive packets at layer 3 and return only the first answer prn: function applied to packets received verbose: set verbosity level nofilter: put 1 to avoid use of BPF filters filter: provide a BPF filter iface: listen answers only on the given interface
[ "Flood", "and", "receive", "packets", "at", "layer", "3", "and", "return", "only", "the", "first", "answer", "prn", ":", "function", "applied", "to", "packets", "received", "verbose", ":", "set", "verbosity", "level", "nofilter", ":", "put", "1", "to", "av...
python
train
43.285714
numenta/htmresearch
htmresearch/support/expsuite.py
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/expsuite.py#L492-L531
def expand_param_list(self, paramlist): """ expands the parameters list according to one of these schemes: grid: every list item is combined with every other list item list: every n-th list item of parameter lists are combined """ # for one single experiment, still wrap ...
[ "def", "expand_param_list", "(", "self", ",", "paramlist", ")", ":", "# for one single experiment, still wrap it in list", "if", "type", "(", "paramlist", ")", "==", "types", ".", "DictType", ":", "paramlist", "=", "[", "paramlist", "]", "# get all options that are it...
expands the parameters list according to one of these schemes: grid: every list item is combined with every other list item list: every n-th list item of parameter lists are combined
[ "expands", "the", "parameters", "list", "according", "to", "one", "of", "these", "schemes", ":", "grid", ":", "every", "list", "item", "is", "combined", "with", "every", "other", "list", "item", "list", ":", "every", "n", "-", "th", "list", "item", "of",...
python
train
53.375
davidaurelio/hashids-python
hashids.py
https://github.com/davidaurelio/hashids-python/blob/48f92cfd8427a0e434c9ced212fb93e641752db3/hashids.py#L111-L130
def _encode(values, salt, min_length, alphabet, separators, guards): """Helper function that does the hash building without argument checks.""" len_alphabet = len(alphabet) len_separators = len(separators) values_hash = sum(x % (i + 100) for i, x in enumerate(values)) encoded = lottery = alphabet[v...
[ "def", "_encode", "(", "values", ",", "salt", ",", "min_length", ",", "alphabet", ",", "separators", ",", "guards", ")", ":", "len_alphabet", "=", "len", "(", "alphabet", ")", "len_separators", "=", "len", "(", "separators", ")", "values_hash", "=", "sum",...
Helper function that does the hash building without argument checks.
[ "Helper", "function", "that", "does", "the", "hash", "building", "without", "argument", "checks", "." ]
python
train
41.4
markovmodel/PyEMMA
pyemma/util/types.py
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/types.py#L165-L178
def ensure_dtraj_list(dtrajs): r"""Makes sure that dtrajs is a list of discrete trajectories (array of int) """ if isinstance(dtrajs, list): # elements are ints? then wrap into a list if is_list_of_int(dtrajs): return [np.array(dtrajs, dtype=int)] else: for i...
[ "def", "ensure_dtraj_list", "(", "dtrajs", ")", ":", "if", "isinstance", "(", "dtrajs", ",", "list", ")", ":", "# elements are ints? then wrap into a list", "if", "is_list_of_int", "(", "dtrajs", ")", ":", "return", "[", "np", ".", "array", "(", "dtrajs", ",",...
r"""Makes sure that dtrajs is a list of discrete trajectories (array of int)
[ "r", "Makes", "sure", "that", "dtrajs", "is", "a", "list", "of", "discrete", "trajectories", "(", "array", "of", "int", ")" ]
python
train
32.714286
SFDO-Tooling/CumulusCI
cumulusci/core/config/BaseGlobalConfig.py
https://github.com/SFDO-Tooling/CumulusCI/blob/e19047921ca771a297e045f22f0bb201651bb6f7/cumulusci/core/config/BaseGlobalConfig.py#L51-L70
def _load_config(self): """ Loads the local configuration """ # load the global config with open(self.config_global_path, "r") as f_config: config = ordered_yaml_load(f_config) self.config_global = config # Load the local config if self.config_global_local_pa...
[ "def", "_load_config", "(", "self", ")", ":", "# load the global config", "with", "open", "(", "self", ".", "config_global_path", ",", "\"r\"", ")", "as", "f_config", ":", "config", "=", "ordered_yaml_load", "(", "f_config", ")", "self", ".", "config_global", ...
Loads the local configuration
[ "Loads", "the", "local", "configuration" ]
python
train
33.8
getfleety/coralillo
coralillo/core.py
https://github.com/getfleety/coralillo/blob/9cac101738a0fa7c1106f129604c00ef703370e1/coralillo/core.py#L68-L110
def validate(cls, **kwargs): ''' Validates the data received as keyword arguments whose name match this class attributes. ''' # errors can store multiple errors # obj is an instance in case validation succeeds # redis is needed for database validation errors = ValidationE...
[ "def", "validate", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "# errors can store multiple errors", "# obj is an instance in case validation succeeds", "# redis is needed for database validation", "errors", "=", "ValidationErrors", "(", ")", "obj", "=", "cls", "(", ")...
Validates the data received as keyword arguments whose name match this class attributes.
[ "Validates", "the", "data", "received", "as", "keyword", "arguments", "whose", "name", "match", "this", "class", "attributes", "." ]
python
train
30.116279
juju/python-libjuju
juju/client/_client5.py
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/_client5.py#L1258-L1271
async def DestroyController(self, destroy_models): ''' destroy_models : bool Returns -> None ''' # map input types to rpc msg _params = dict() msg = dict(type='Controller', request='DestroyController', version=5, ...
[ "async", "def", "DestroyController", "(", "self", ",", "destroy_models", ")", ":", "# map input types to rpc msg", "_params", "=", "dict", "(", ")", "msg", "=", "dict", "(", "type", "=", "'Controller'", ",", "request", "=", "'DestroyController'", ",", "version",...
destroy_models : bool Returns -> None
[ "destroy_models", ":", "bool", "Returns", "-", ">", "None" ]
python
train
31.142857
kensho-technologies/grift
grift/property_types.py
https://github.com/kensho-technologies/grift/blob/b8767d1604c1a0a25eace6cdd04b53b57afa9757/grift/property_types.py#L57-L61
def validate_member_type(self, value): """Validate each member of the list, if member_type exists""" if self.member_type: for item in value: self.member_type.validate(item)
[ "def", "validate_member_type", "(", "self", ",", "value", ")", ":", "if", "self", ".", "member_type", ":", "for", "item", "in", "value", ":", "self", ".", "member_type", ".", "validate", "(", "item", ")" ]
Validate each member of the list, if member_type exists
[ "Validate", "each", "member", "of", "the", "list", "if", "member_type", "exists" ]
python
train
42.4
blockstack/blockstack-core
blockstack/lib/queue.py
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/queue.py#L103-L143
def queuedb_findall(path, queue_id, name=None, offset=None, limit=None): """ Get all queued entries for a queue and a name. If name is None, then find all queue entries Return the rows on success (empty list if not found) Raise on error """ sql = "SELECT * FROM queue WHERE queue_id = ? ORDE...
[ "def", "queuedb_findall", "(", "path", ",", "queue_id", ",", "name", "=", "None", ",", "offset", "=", "None", ",", "limit", "=", "None", ")", ":", "sql", "=", "\"SELECT * FROM queue WHERE queue_id = ? ORDER BY rowid ASC\"", "args", "=", "(", "queue_id", ",", "...
Get all queued entries for a queue and a name. If name is None, then find all queue entries Return the rows on success (empty list if not found) Raise on error
[ "Get", "all", "queued", "entries", "for", "a", "queue", "and", "a", "name", ".", "If", "name", "is", "None", "then", "find", "all", "queue", "entries" ]
python
train
21.146341
ewels/MultiQC
multiqc/modules/bismark/bismark.py
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/bismark/bismark.py#L344-L366
def bismark_alignment_chart (self): """ Make the alignment plot """ # Specify the order of the different possible categories keys = OrderedDict() keys['aligned_reads'] = { 'color': '#2f7ed8', 'name': 'Aligned Uniquely' } keys['ambig_reads'] = { 'color': '#492970', 'name': ...
[ "def", "bismark_alignment_chart", "(", "self", ")", ":", "# Specify the order of the different possible categories", "keys", "=", "OrderedDict", "(", ")", "keys", "[", "'aligned_reads'", "]", "=", "{", "'color'", ":", "'#2f7ed8'", ",", "'name'", ":", "'Aligned Uniquel...
Make the alignment plot
[ "Make", "the", "alignment", "plot" ]
python
train
40.130435
django-userena-ce/django-userena-ce
userena/views.py
https://github.com/django-userena-ce/django-userena-ce/blob/2d8b745eed25128134e961ca96c270802e730256/userena/views.py#L393-L475
def signin(request, auth_form=AuthenticationForm, template_name='userena/signin_form.html', redirect_field_name=REDIRECT_FIELD_NAME, redirect_signin_function=signin_redirect, extra_context=None): """ Signin using email or username with password. Signs a user in by combining...
[ "def", "signin", "(", "request", ",", "auth_form", "=", "AuthenticationForm", ",", "template_name", "=", "'userena/signin_form.html'", ",", "redirect_field_name", "=", "REDIRECT_FIELD_NAME", ",", "redirect_signin_function", "=", "signin_redirect", ",", "extra_context", "=...
Signin using email or username with password. Signs a user in by combining email/username with password. If the combination is correct and the user :func:`is_active` the :func:`redirect_signin_function` is called with the arguments ``REDIRECT_FIELD_NAME`` and an instance of the :class:`User` who is is ...
[ "Signin", "using", "email", "or", "username", "with", "password", "." ]
python
train
43.301205
ellmetha/django-machina
machina/apps/forum_moderation/views.py
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_moderation/views.py#L257-L265
def update_type(self, request, *args, **kwargs): """ Updates the type of the considered topic and retirects the user to the success URL. """ self.object = self.get_object() success_url = self.get_success_url() self.object.type = self.target_type self.object.save() ...
[ "def", "update_type", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "object", "=", "self", ".", "get_object", "(", ")", "success_url", "=", "self", ".", "get_success_url", "(", ")", "self", ".", "objec...
Updates the type of the considered topic and retirects the user to the success URL.
[ "Updates", "the", "type", "of", "the", "considered", "topic", "and", "retirects", "the", "user", "to", "the", "success", "URL", "." ]
python
train
46
androguard/androguard
androguard/core/bytecodes/dvm.py
https://github.com/androguard/androguard/blob/984c0d981be2950cf0451e484f7b0d4d53bc4911/androguard/core/bytecodes/dvm.py#L7550-L7559
def show(self): """ Print with a pretty display the MapList object """ bytecode._Print("MAP_LIST SIZE", self.size) for i in self.map_item: if i.item != self: # FIXME this does not work for CodeItems! # as we do not have the method analy...
[ "def", "show", "(", "self", ")", ":", "bytecode", ".", "_Print", "(", "\"MAP_LIST SIZE\"", ",", "self", ".", "size", ")", "for", "i", "in", "self", ".", "map_item", ":", "if", "i", ".", "item", "!=", "self", ":", "# FIXME this does not work for CodeItems!"...
Print with a pretty display the MapList object
[ "Print", "with", "a", "pretty", "display", "the", "MapList", "object" ]
python
train
34.7
APSL/transmanager
transmanager/models.py
https://github.com/APSL/transmanager/blob/79157085840008e146b264521681913090197ed1/transmanager/models.py#L31-L44
def save(self, force_insert=False, force_update=False, using=None, update_fields=None): """ Overwrite of the save method in order that when setting the language as main we deactivate any other model selected as main before :param force_insert: :param force_update: :param...
[ "def", "save", "(", "self", ",", "force_insert", "=", "False", ",", "force_update", "=", "False", ",", "using", "=", "None", ",", "update_fields", "=", "None", ")", ":", "super", "(", ")", ".", "save", "(", "force_insert", ",", "force_update", ",", "us...
Overwrite of the save method in order that when setting the language as main we deactivate any other model selected as main before :param force_insert: :param force_update: :param using: :param update_fields: :return:
[ "Overwrite", "of", "the", "save", "method", "in", "order", "that", "when", "setting", "the", "language", "as", "main", "we", "deactivate", "any", "other", "model", "selected", "as", "main", "before" ]
python
train
39.785714
Kozea/cairocffi
cairocffi/surfaces.py
https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/surfaces.py#L1444-L1458
def ink_extents(self): """Measures the extents of the operations stored within the recording-surface. This is useful to compute the required size of an image surface (or equivalent) into which to replay the full sequence of drawing operations. :return: A ``(x, y, width, ...
[ "def", "ink_extents", "(", "self", ")", ":", "extents", "=", "ffi", ".", "new", "(", "'double[4]'", ")", "cairo", ".", "cairo_recording_surface_ink_extents", "(", "self", ".", "_pointer", ",", "extents", "+", "0", ",", "extents", "+", "1", ",", "extents", ...
Measures the extents of the operations stored within the recording-surface. This is useful to compute the required size of an image surface (or equivalent) into which to replay the full sequence of drawing operations. :return: A ``(x, y, width, height)`` tuple of floats.
[ "Measures", "the", "extents", "of", "the", "operations", "stored", "within", "the", "recording", "-", "surface", ".", "This", "is", "useful", "to", "compute", "the", "required", "size", "of", "an", "image", "surface", "(", "or", "equivalent", ")", "into", ...
python
train
38.2
ranaroussi/ezibpy
ezibpy/ezibpy.py
https://github.com/ranaroussi/ezibpy/blob/1a9d4bf52018abd2a01af7c991d7cf00cda53e0c/ezibpy/ezibpy.py#L1385-L1413
def contractDetails(self, contract_identifier): """ returns string from contract tuple """ if isinstance(contract_identifier, Contract): tickerId = self.tickerId(contract_identifier) else: if str(contract_identifier).isdigit(): tickerId = contract_identif...
[ "def", "contractDetails", "(", "self", ",", "contract_identifier", ")", ":", "if", "isinstance", "(", "contract_identifier", ",", "Contract", ")", ":", "tickerId", "=", "self", ".", "tickerId", "(", "contract_identifier", ")", "else", ":", "if", "str", "(", ...
returns string from contract tuple
[ "returns", "string", "from", "contract", "tuple" ]
python
train
48.896552
SKA-ScienceDataProcessor/integration-prototype
sip/execution_control/configuration_db/sip_config_db/scheduling/workflow_stage.py
https://github.com/SKA-ScienceDataProcessor/integration-prototype/blob/8c8006de6ad71dcd44114b0338780738079c87d4/sip/execution_control/configuration_db/sip_config_db/scheduling/workflow_stage.py#L130-L135
def _load_config(self): """Load the workflow stage config from the database.""" pb_key = SchedulingObject.get_key(PB_KEY, self._pb_id) stages = DB.get_hash_value(pb_key, 'workflow_stages') stages = ast.literal_eval(stages) return stages[self._index]
[ "def", "_load_config", "(", "self", ")", ":", "pb_key", "=", "SchedulingObject", ".", "get_key", "(", "PB_KEY", ",", "self", ".", "_pb_id", ")", "stages", "=", "DB", ".", "get_hash_value", "(", "pb_key", ",", "'workflow_stages'", ")", "stages", "=", "ast",...
Load the workflow stage config from the database.
[ "Load", "the", "workflow", "stage", "config", "from", "the", "database", "." ]
python
train
47.333333
a1ezzz/wasp-launcher
wasp_launcher/apps/log.py
https://github.com/a1ezzz/wasp-launcher/blob/38b476286fb422830207031935d3af1fe8da316d/wasp_launcher/apps/log.py#L54-L63
def stop(self): """ "Uninitialize" logger. Makes :attr:`wasp_launcher.apps.WAppsGlobals.log` logger unavailable :return: None """ if WAppsGlobals.log is not None and WLogApp.__log_handler__ is not None: WAppsGlobals.log.removeHandler(WLogApp.__log_handler__) WLogApp.__log_handler__ = None WAppsGlobals....
[ "def", "stop", "(", "self", ")", ":", "if", "WAppsGlobals", ".", "log", "is", "not", "None", "and", "WLogApp", ".", "__log_handler__", "is", "not", "None", ":", "WAppsGlobals", ".", "log", ".", "removeHandler", "(", "WLogApp", ".", "__log_handler__", ")", ...
"Uninitialize" logger. Makes :attr:`wasp_launcher.apps.WAppsGlobals.log` logger unavailable :return: None
[ "Uninitialize", "logger", ".", "Makes", ":", "attr", ":", "wasp_launcher", ".", "apps", ".", "WAppsGlobals", ".", "log", "logger", "unavailable" ]
python
train
32.1
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/filebrowser.py
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/filebrowser.py#L224-L235
def create_ver_browser(self, layout): """Create a version browser and insert it into the given layout :param layout: the layout to insert the browser into :type layout: QLayout :returns: the created browser :rtype: :class:`jukeboxcore.gui.widgets.browser.ComboBoxBrowser` ...
[ "def", "create_ver_browser", "(", "self", ",", "layout", ")", ":", "brws", "=", "ComboBoxBrowser", "(", "1", ",", "headers", "=", "[", "'Version:'", "]", ")", "layout", ".", "insertWidget", "(", "1", ",", "brws", ")", "return", "brws" ]
Create a version browser and insert it into the given layout :param layout: the layout to insert the browser into :type layout: QLayout :returns: the created browser :rtype: :class:`jukeboxcore.gui.widgets.browser.ComboBoxBrowser` :raises: None
[ "Create", "a", "version", "browser", "and", "insert", "it", "into", "the", "given", "layout" ]
python
train
37.333333
blockstack/virtualchain
virtualchain/lib/indexer.py
https://github.com/blockstack/virtualchain/blob/fcfc970064ca7dfcab26ebd3ab955870a763ea39/virtualchain/lib/indexer.py#L586-L629
def get_ops_hashes(cls, impl, working_dir, start_block_height=None, end_block_height=None): """ Read all consensus hashes into memory. They're write-once read-many, so no need to worry about cache-coherency. """ if (start_block_height is None and end_block_height is not None) or...
[ "def", "get_ops_hashes", "(", "cls", ",", "impl", ",", "working_dir", ",", "start_block_height", "=", "None", ",", "end_block_height", "=", "None", ")", ":", "if", "(", "start_block_height", "is", "None", "and", "end_block_height", "is", "not", "None", ")", ...
Read all consensus hashes into memory. They're write-once read-many, so no need to worry about cache-coherency.
[ "Read", "all", "consensus", "hashes", "into", "memory", ".", "They", "re", "write", "-", "once", "read", "-", "many", "so", "no", "need", "to", "worry", "about", "cache", "-", "coherency", "." ]
python
train
37.886364
inasafe/inasafe
safe/report/impact_report.py
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/impact_report.py#L116-L125
def organisation_logo(self, logo): """Set image that will be used as organisation logo in reports. :param logo: Path to the organisation logo image. :type logo: str """ if isinstance(logo, str) and os.path.exists(logo): self._organisation_logo = logo else: ...
[ "def", "organisation_logo", "(", "self", ",", "logo", ")", ":", "if", "isinstance", "(", "logo", ",", "str", ")", "and", "os", ".", "path", ".", "exists", "(", "logo", ")", ":", "self", ".", "_organisation_logo", "=", "logo", "else", ":", "self", "."...
Set image that will be used as organisation logo in reports. :param logo: Path to the organisation logo image. :type logo: str
[ "Set", "image", "that", "will", "be", "used", "as", "organisation", "logo", "in", "reports", "." ]
python
train
36.9
ecederstrand/exchangelib
exchangelib/autodiscover.py
https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/autodiscover.py#L173-L223
def discover(email, credentials): """ Performs the autodiscover dance and returns the primary SMTP address of the account and a Protocol on success. The autodiscover and EWS server might not be the same, so we use a different Protocol to do the autodiscover request, and return a hopefully-cached Protoco...
[ "def", "discover", "(", "email", ",", "credentials", ")", ":", "log", ".", "debug", "(", "'Attempting autodiscover on email %s'", ",", "email", ")", "if", "not", "isinstance", "(", "credentials", ",", "Credentials", ")", ":", "raise", "ValueError", "(", "\"'cr...
Performs the autodiscover dance and returns the primary SMTP address of the account and a Protocol on success. The autodiscover and EWS server might not be the same, so we use a different Protocol to do the autodiscover request, and return a hopefully-cached Protocol to the callee.
[ "Performs", "the", "autodiscover", "dance", "and", "returns", "the", "primary", "SMTP", "address", "of", "the", "account", "and", "a", "Protocol", "on", "success", ".", "The", "autodiscover", "and", "EWS", "server", "might", "not", "be", "the", "same", "so",...
python
train
63.254902
rocioar/flake8-django
flake8_django/checkers/issue.py
https://github.com/rocioar/flake8-django/blob/917f196e2518412bda6e841c1ed3de312004fc67/flake8_django/checkers/issue.py#L14-L19
def message(self): """ Return issue message. """ message = self.description.format(**self.parameters) return '{code} {message}'.format(code=self.code, message=message)
[ "def", "message", "(", "self", ")", ":", "message", "=", "self", ".", "description", ".", "format", "(", "*", "*", "self", ".", "parameters", ")", "return", "'{code} {message}'", ".", "format", "(", "code", "=", "self", ".", "code", ",", "message", "="...
Return issue message.
[ "Return", "issue", "message", "." ]
python
train
33.666667
allenai/allennlp
allennlp/modules/input_variational_dropout.py
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/input_variational_dropout.py#L13-L34
def forward(self, input_tensor): # pylint: disable=arguments-differ """ Apply dropout to input tensor. Parameters ---------- input_tensor: ``torch.FloatTensor`` A tensor of shape ``(batch_size, num_timesteps, embedding_dim)`` Returns ------- ...
[ "def", "forward", "(", "self", ",", "input_tensor", ")", ":", "# pylint: disable=arguments-differ", "ones", "=", "input_tensor", ".", "data", ".", "new_ones", "(", "input_tensor", ".", "shape", "[", "0", "]", ",", "input_tensor", ".", "shape", "[", "-", "1",...
Apply dropout to input tensor. Parameters ---------- input_tensor: ``torch.FloatTensor`` A tensor of shape ``(batch_size, num_timesteps, embedding_dim)`` Returns ------- output: ``torch.FloatTensor`` A tensor of shape ``(batch_size, num_timesteps...
[ "Apply", "dropout", "to", "input", "tensor", "." ]
python
train
36.727273
erdc/RAPIDpy
RAPIDpy/dataset.py
https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/dataset.py#L414-L532
def get_time_index_range(self, date_search_start=None, date_search_end=None, time_index_start=None, time_index_end=None, time_index=None): """ Generates a time...
[ "def", "get_time_index_range", "(", "self", ",", "date_search_start", "=", "None", ",", "date_search_end", "=", "None", ",", "time_index_start", "=", "None", ",", "time_index_end", "=", "None", ",", "time_index", "=", "None", ")", ":", "# get the range of time bas...
Generates a time index range based on time bounds given. This is useful for subset data extraction. Parameters ---------- date_search_start: :obj:`datetime.datetime`, optional This is a datetime object with the date of the minimum date for starting. date_...
[ "Generates", "a", "time", "index", "range", "based", "on", "time", "bounds", "given", ".", "This", "is", "useful", "for", "subset", "data", "extraction", "." ]
python
train
40.94958
bokeh/bokeh
bokeh/document/document.py
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L671-L678
def on_session_destroyed(self, *callbacks): ''' Provide callbacks to invoke when the session serving the Document is destroyed ''' for callback in callbacks: _check_callback(callback, ('session_context',)) self._session_destroyed_callbacks.add(callback)
[ "def", "on_session_destroyed", "(", "self", ",", "*", "callbacks", ")", ":", "for", "callback", "in", "callbacks", ":", "_check_callback", "(", "callback", ",", "(", "'session_context'", ",", ")", ")", "self", ".", "_session_destroyed_callbacks", ".", "add", "...
Provide callbacks to invoke when the session serving the Document is destroyed
[ "Provide", "callbacks", "to", "invoke", "when", "the", "session", "serving", "the", "Document", "is", "destroyed" ]
python
train
37.875
hydraplatform/hydra-base
hydra_base/lib/network.py
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/network.py#L874-L883
def _get_network_owners(network_id): """ Get all the nodes in a network """ owners_i = db.DBSession.query(NetworkOwner).filter( NetworkOwner.network_id==network_id).options(noload('network')).options(joinedload_all('user')).all() owners = [JSONObject(owner_i) for owner_i...
[ "def", "_get_network_owners", "(", "network_id", ")", ":", "owners_i", "=", "db", ".", "DBSession", ".", "query", "(", "NetworkOwner", ")", ".", "filter", "(", "NetworkOwner", ".", "network_id", "==", "network_id", ")", ".", "options", "(", "noload", "(", ...
Get all the nodes in a network
[ "Get", "all", "the", "nodes", "in", "a", "network" ]
python
train
34.3
ikalnytskyi/dooku
dooku/conf.py
https://github.com/ikalnytskyi/dooku/blob/77e6c82c9c41211c86ee36ae5e591d477945fedf/dooku/conf.py#L138-L148
def from_json(self, filename, encoding='utf-8', silent=False): """ Updates recursively the value in the the config from a JSON file. :param filename: (str) a filename of the JSON file :param encoding: (str) an encoding of the filename :param silent: (bool) fails silently if some...
[ "def", "from_json", "(", "self", ",", "filename", ",", "encoding", "=", "'utf-8'", ",", "silent", "=", "False", ")", ":", "self", ".", "from_file", "(", "json", ".", "load", ",", "filename", ",", "encoding", ",", "silent", ")" ]
Updates recursively the value in the the config from a JSON file. :param filename: (str) a filename of the JSON file :param encoding: (str) an encoding of the filename :param silent: (bool) fails silently if something wrong with json file .. versionadded:: 0.3.0
[ "Updates", "recursively", "the", "value", "in", "the", "the", "config", "from", "a", "JSON", "file", "." ]
python
train
40.272727
jmoiron/speedparser
speedparser/speedparser.py
https://github.com/jmoiron/speedparser/blob/e7e8d79daf73b35c9259695ad1e379476e1dfc77/speedparser/speedparser.py#L182-L186
def xpath(node, query, namespaces={}): """A safe xpath that only uses namespaces if available.""" if namespaces and 'None' not in namespaces: return node.xpath(query, namespaces=namespaces) return node.xpath(query)
[ "def", "xpath", "(", "node", ",", "query", ",", "namespaces", "=", "{", "}", ")", ":", "if", "namespaces", "and", "'None'", "not", "in", "namespaces", ":", "return", "node", ".", "xpath", "(", "query", ",", "namespaces", "=", "namespaces", ")", "return...
A safe xpath that only uses namespaces if available.
[ "A", "safe", "xpath", "that", "only", "uses", "namespaces", "if", "available", "." ]
python
train
46
kyuupichan/aiorpcX
aiorpcx/curio.py
https://github.com/kyuupichan/aiorpcX/blob/707c989ed1c67ac9a40cd20b0161b1ce1f4d7db0/aiorpcx/curio.py#L340-L359
def timeout_after(seconds, coro=None, *args): '''Execute the specified coroutine and return its result. However, issue a cancellation request to the calling task after seconds have elapsed. When this happens, a TaskTimeout exception is raised. If coro is None, the result of this function serves as...
[ "def", "timeout_after", "(", "seconds", ",", "coro", "=", "None", ",", "*", "args", ")", ":", "if", "coro", ":", "return", "_timeout_after_func", "(", "seconds", ",", "False", ",", "coro", ",", "args", ")", "return", "TimeoutAfter", "(", "seconds", ")" ]
Execute the specified coroutine and return its result. However, issue a cancellation request to the calling task after seconds have elapsed. When this happens, a TaskTimeout exception is raised. If coro is None, the result of this function serves as an asynchronous context manager that applies a timeo...
[ "Execute", "the", "specified", "coroutine", "and", "return", "its", "result", ".", "However", "issue", "a", "cancellation", "request", "to", "the", "calling", "task", "after", "seconds", "have", "elapsed", ".", "When", "this", "happens", "a", "TaskTimeout", "e...
python
train
42.2
jaywink/federation
federation/utils/network.py
https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/utils/network.py#L104-L113
def fetch_host_ip(host: str) -> str: """ Fetch ip by host """ try: ip = socket.gethostbyname(host) except socket.gaierror: return '' return ip
[ "def", "fetch_host_ip", "(", "host", ":", "str", ")", "->", "str", ":", "try", ":", "ip", "=", "socket", ".", "gethostbyname", "(", "host", ")", "except", "socket", ".", "gaierror", ":", "return", "''", "return", "ip" ]
Fetch ip by host
[ "Fetch", "ip", "by", "host" ]
python
train
17.4
deepmind/sonnet
sonnet/python/modules/scale_gradient.py
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/scale_gradient.py#L27-L61
def _scale_gradient_op(dtype): """Create an op that scales gradients using a Defun. The tensorflow Defun decorator creates an op and tensorflow caches these ops automatically according to `func_name`. Using a Defun decorator twice with the same `func_name` does not create a new op, instead the cached op is use...
[ "def", "_scale_gradient_op", "(", "dtype", ")", ":", "def", "scale_gradient_backward", "(", "op", ",", "grad", ")", ":", "scale", "=", "op", ".", "inputs", "[", "1", "]", "scaled_grad", "=", "grad", "*", "scale", "return", "scaled_grad", ",", "None", "# ...
Create an op that scales gradients using a Defun. The tensorflow Defun decorator creates an op and tensorflow caches these ops automatically according to `func_name`. Using a Defun decorator twice with the same `func_name` does not create a new op, instead the cached op is used. This method produces a new op ...
[ "Create", "an", "op", "that", "scales", "gradients", "using", "a", "Defun", "." ]
python
train
35.914286
QuantEcon/QuantEcon.py
quantecon/lss.py
https://github.com/QuantEcon/QuantEcon.py/blob/26a66c552f2a73967d7efb6e1f4b4c4985a12643/quantecon/lss.py#L20-L64
def simulate_linear_model(A, x0, v, ts_length): r""" This is a separate function for simulating a vector linear system of the form .. math:: x_{t+1} = A x_t + v_t given :math:`x_0` = x0 Here :math:`x_t` and :math:`v_t` are both n x 1 and :math:`A` is n x n. The purpose of separa...
[ "def", "simulate_linear_model", "(", "A", ",", "x0", ",", "v", ",", "ts_length", ")", ":", "A", "=", "np", ".", "asarray", "(", "A", ")", "n", "=", "A", ".", "shape", "[", "0", "]", "x", "=", "np", ".", "empty", "(", "(", "n", ",", "ts_length...
r""" This is a separate function for simulating a vector linear system of the form .. math:: x_{t+1} = A x_t + v_t given :math:`x_0` = x0 Here :math:`x_t` and :math:`v_t` are both n x 1 and :math:`A` is n x n. The purpose of separating this functionality out is to target it for ...
[ "r", "This", "is", "a", "separate", "function", "for", "simulating", "a", "vector", "linear", "system", "of", "the", "form" ]
python
train
27.888889
chrisspen/dtree
dtree.py
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L941-L950
def get_values(self, attr_name): """ Retrieves the unique set of values seen for the given attribute at this node. """ ret = list(self._attr_value_cdist[attr_name].keys()) \ + list(self._attr_value_counts[attr_name].keys()) \ + list(self._branches.keys()) ...
[ "def", "get_values", "(", "self", ",", "attr_name", ")", ":", "ret", "=", "list", "(", "self", ".", "_attr_value_cdist", "[", "attr_name", "]", ".", "keys", "(", ")", ")", "+", "list", "(", "self", ".", "_attr_value_counts", "[", "attr_name", "]", ".",...
Retrieves the unique set of values seen for the given attribute at this node.
[ "Retrieves", "the", "unique", "set", "of", "values", "seen", "for", "the", "given", "attribute", "at", "this", "node", "." ]
python
train
35.2
h2oai/h2o-3
h2o-py/h2o/automl/autoh2o.py
https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/h2o-py/h2o/automl/autoh2o.py#L443-L455
def download_pojo(self, path="", get_genmodel_jar=False, genmodel_name=""): """ Download the POJO for the leader model in AutoML to the directory specified by path. If path is an empty string, then dump the output to screen. :param path: An absolute path to the directory where POJO sh...
[ "def", "download_pojo", "(", "self", ",", "path", "=", "\"\"", ",", "get_genmodel_jar", "=", "False", ",", "genmodel_name", "=", "\"\"", ")", ":", "return", "h2o", ".", "download_pojo", "(", "self", ".", "leader", ",", "path", ",", "get_jar", "=", "get_g...
Download the POJO for the leader model in AutoML to the directory specified by path. If path is an empty string, then dump the output to screen. :param path: An absolute path to the directory where POJO should be saved. :param get_genmodel_jar: if True, then also download h2o-genmodel.jar and...
[ "Download", "the", "POJO", "for", "the", "leader", "model", "in", "AutoML", "to", "the", "directory", "specified", "by", "path", "." ]
python
test
50.307692
fabioz/PyDev.Debugger
_pydevd_bundle/pydevd_api.py
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydevd_bundle/pydevd_api.py#L181-L186
def request_get_variable(self, py_db, seq, thread_id, frame_id, scope, attrs): ''' :param scope: 'FRAME' or 'GLOBAL' ''' int_cmd = InternalGetVariable(seq, thread_id, frame_id, scope, attrs) py_db.post_internal_command(int_cmd, thread_id)
[ "def", "request_get_variable", "(", "self", ",", "py_db", ",", "seq", ",", "thread_id", ",", "frame_id", ",", "scope", ",", "attrs", ")", ":", "int_cmd", "=", "InternalGetVariable", "(", "seq", ",", "thread_id", ",", "frame_id", ",", "scope", ",", "attrs",...
:param scope: 'FRAME' or 'GLOBAL'
[ ":", "param", "scope", ":", "FRAME", "or", "GLOBAL" ]
python
train
45.5
twisted/txaws
txaws/ec2/client.py
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/ec2/client.py#L583-L624
def instance(self, instance_data, reservation): """Parse instance data out of an XML payload. @param instance_data: An XML node containing instance data. @param reservation: The L{Reservation} associated with the instance. @return: An L{Instance}. TODO: reason, platform, monito...
[ "def", "instance", "(", "self", ",", "instance_data", ",", "reservation", ")", ":", "for", "group_data", "in", "instance_data", ".", "find", "(", "\"groupSet\"", ")", ":", "group_id", "=", "group_data", ".", "findtext", "(", "\"groupId\"", ")", "group_name", ...
Parse instance data out of an XML payload. @param instance_data: An XML node containing instance data. @param reservation: The L{Reservation} associated with the instance. @return: An L{Instance}. TODO: reason, platform, monitoring, subnetId, vpcId, privateIpAddress, ipAd...
[ "Parse", "instance", "data", "out", "of", "an", "XML", "payload", "." ]
python
train
51.857143
StagPython/StagPy
stagpy/stagyydata.py
https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/stagyydata.py#L530-L557
def scale(self, data, unit): """Scales quantity to obtain dimensionful quantity. Args: data (numpy.array): the quantity that should be scaled. dim (str): the dimension of data as defined in phyvars. Return: (float, str): scaling factor and unit string. ...
[ "def", "scale", "(", "self", ",", "data", ",", "unit", ")", ":", "if", "self", ".", "par", "[", "'switches'", "]", "[", "'dimensional_units'", "]", "or", "not", "conf", ".", "scaling", ".", "dimensional", "or", "unit", "==", "'1'", ":", "return", "da...
Scales quantity to obtain dimensionful quantity. Args: data (numpy.array): the quantity that should be scaled. dim (str): the dimension of data as defined in phyvars. Return: (float, str): scaling factor and unit string. Other Parameters: conf.sca...
[ "Scales", "quantity", "to", "obtain", "dimensionful", "quantity", "." ]
python
train
40
boto/s3transfer
s3transfer/utils.py
https://github.com/boto/s3transfer/blob/2aead638c8385d8ae0b1756b2de17e8fad45fffa/s3transfer/utils.py#L562-L576
def acquire(self, tag, blocking=True): """Acquire the semaphore :param tag: A tag identifying what is acquiring the semaphore. Note that this is not really needed to directly use this class but is needed for API compatibility with the SlidingWindowSemaphore implement...
[ "def", "acquire", "(", "self", ",", "tag", ",", "blocking", "=", "True", ")", ":", "logger", ".", "debug", "(", "\"Acquiring %s\"", ",", "tag", ")", "if", "not", "self", ".", "_semaphore", ".", "acquire", "(", "blocking", ")", ":", "raise", "NoResource...
Acquire the semaphore :param tag: A tag identifying what is acquiring the semaphore. Note that this is not really needed to directly use this class but is needed for API compatibility with the SlidingWindowSemaphore implementation. :param block: If True, block until ...
[ "Acquire", "the", "semaphore" ]
python
test
47.2
MacHu-GWU/single_file_module-project
sfm/obj_file_io.py
https://github.com/MacHu-GWU/single_file_module-project/blob/01f7a6b250853bebfd73de275895bf274325cfc1/sfm/obj_file_io.py#L216-L230
def load_func(serializer_type): """A decorator for ``_load(loader_func=loader_func, **kwargs)`` """ def outer_wrapper(loader_func): def wrapper(*args, **kwargs): return _load( *args, loader_func=loader_func, serializer_type=serializer_type, ...
[ "def", "load_func", "(", "serializer_type", ")", ":", "def", "outer_wrapper", "(", "loader_func", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_load", "(", "*", "args", ",", "loader_func", "=", "loader_func"...
A decorator for ``_load(loader_func=loader_func, **kwargs)``
[ "A", "decorator", "for", "_load", "(", "loader_func", "=", "loader_func", "**", "kwargs", ")" ]
python
train
25.333333
IdentityPython/SATOSA
src/satosa/frontends/saml2.py
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/frontends/saml2.py#L621-L635
def handle_authn_request(self, context, binding_in): """ Loads approved endpoints dynamically See super class satosa.frontends.saml2.SAMLFrontend#handle_authn_request :type context: satosa.context.Context :type binding_in: str :rtype: satosa.response.Response """...
[ "def", "handle_authn_request", "(", "self", ",", "context", ",", "binding_in", ")", ":", "target_entity_id", "=", "context", ".", "target_entity_id_from_path", "(", ")", "target_entity_id", "=", "urlsafe_b64decode", "(", "target_entity_id", ")", ".", "decode", "(", ...
Loads approved endpoints dynamically See super class satosa.frontends.saml2.SAMLFrontend#handle_authn_request :type context: satosa.context.Context :type binding_in: str :rtype: satosa.response.Response
[ "Loads", "approved", "endpoints", "dynamically", "See", "super", "class", "satosa", ".", "frontends", ".", "saml2", ".", "SAMLFrontend#handle_authn_request" ]
python
train
42.6
cjdrake/pyeda
pyeda/boolalg/boolfunc.py
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/boolfunc.py#L238-L247
def point2term(point, conj=False): """Convert *point* into a min/max term. If *conj* is ``False``, return a minterm. Otherwise, return a maxterm. """ if conj: return tuple(~v if val else v for v, val in point.items()) else: return tuple(v if val else ~v for v, val in point.items...
[ "def", "point2term", "(", "point", ",", "conj", "=", "False", ")", ":", "if", "conj", ":", "return", "tuple", "(", "~", "v", "if", "val", "else", "v", "for", "v", ",", "val", "in", "point", ".", "items", "(", ")", ")", "else", ":", "return", "t...
Convert *point* into a min/max term. If *conj* is ``False``, return a minterm. Otherwise, return a maxterm.
[ "Convert", "*", "point", "*", "into", "a", "min", "/", "max", "term", "." ]
python
train
31.4
chatfirst/chatfirst
chatfirst/client.py
https://github.com/chatfirst/chatfirst/blob/11e023fc372e034dfd3417b61b67759ef8c37ad6/chatfirst/client.py#L123-L136
def broadcast(self, bot, channel_type, text): """ Use this method to broadcast text message to all users of bot. :param bot: bot that will push user :type bot: Bot :param channel_type: one of [telegram, facebook, slack] :type channel_type: str :param text: text m...
[ "def", "broadcast", "(", "self", ",", "bot", ",", "channel_type", ",", "text", ")", ":", "self", ".", "client", ".", "broadcast", ".", "__getattr__", "(", "bot", ".", "name", ")", ".", "__call__", "(", "_method", "=", "\"POST\"", ",", "_params", "=", ...
Use this method to broadcast text message to all users of bot. :param bot: bot that will push user :type bot: Bot :param channel_type: one of [telegram, facebook, slack] :type channel_type: str :param text: text message :type text: str
[ "Use", "this", "method", "to", "broadcast", "text", "message", "to", "all", "users", "of", "bot", "." ]
python
train
42.857143
etal/biocma
biocma/cma.py
https://github.com/etal/biocma/blob/eac0c57eb83a9498e53ccdeb9cbc3fe21a5826a7/biocma/cma.py#L392-L417
def seqrecord2sequence(record, qlen, index): """Convert a Biopython SeqRecord to a esbglib.cma block. Indels (gaps, casing) must have already been handled in the record. """ # aligned_len = sum(map(str.isupper, str(record.seq))) # assert qlen == aligned_len, ( # "Aligned sequence length...
[ "def", "seqrecord2sequence", "(", "record", ",", "qlen", ",", "index", ")", ":", "# aligned_len = sum(map(str.isupper, str(record.seq)))", "# assert qlen == aligned_len, (", "# \"Aligned sequence length %s, query %s\\n%s\"", "# % (aligned_len, qlen, str(record)))", "descr...
Convert a Biopython SeqRecord to a esbglib.cma block. Indels (gaps, casing) must have already been handled in the record.
[ "Convert", "a", "Biopython", "SeqRecord", "to", "a", "esbglib", ".", "cma", "block", "." ]
python
train
34.769231
inveniosoftware-attic/invenio-utils
invenio_utils/filedownload.py
https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/filedownload.py#L253-L295
def download_local_file(filename, download_to_file): """ Copies a local file to Invenio's temporary directory. @param filename: the name of the file to copy @type filename: string @param download_to_file: the path to save the file to @type download_to_file: string @return: the path of the...
[ "def", "download_local_file", "(", "filename", ",", "download_to_file", ")", ":", "# Try to copy.", "try", ":", "path", "=", "urllib2", ".", "urlparse", ".", "urlsplit", "(", "urllib", ".", "unquote", "(", "filename", ")", ")", "[", "2", "]", "if", "os", ...
Copies a local file to Invenio's temporary directory. @param filename: the name of the file to copy @type filename: string @param download_to_file: the path to save the file to @type download_to_file: string @return: the path of the temporary file created @rtype: string @raise StandardErr...
[ "Copies", "a", "local", "file", "to", "Invenio", "s", "temporary", "directory", "." ]
python
train
37.186047
lacava/few
few/few.py
https://github.com/lacava/few/blob/5c72044425e9a5d73b8dc2cbb9b96e873dcb5b4a/few/few.py#L448-L467
def predict(self, testing_features): """predict on a holdout data set.""" # print("best_inds:",self._best_inds) # print("best estimator size:",self._best_estimator.coef_.shape) if self.clean: testing_features = self.impute_data(testing_features) if self._best_inds: ...
[ "def", "predict", "(", "self", ",", "testing_features", ")", ":", "# print(\"best_inds:\",self._best_inds)", "# print(\"best estimator size:\",self._best_estimator.coef_.shape)", "if", "self", ".", "clean", ":", "testing_features", "=", "self", ".", "impute_data", "(", "tes...
predict on a holdout data set.
[ "predict", "on", "a", "holdout", "data", "set", "." ]
python
train
46.75
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_dataflash_logger.py
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_dataflash_logger.py#L98-L114
def start_new_log(self): '''open a new dataflash log, reset state''' filename = self.new_log_filepath() self.block_cnt = 0 self.logfile = open(filename, 'w+b') print("DFLogger: logging started (%s)" % (filename)) self.prev_cnt = 0 self.download = 0 self.p...
[ "def", "start_new_log", "(", "self", ")", ":", "filename", "=", "self", ".", "new_log_filepath", "(", ")", "self", ".", "block_cnt", "=", "0", "self", ".", "logfile", "=", "open", "(", "filename", ",", "'w+b'", ")", "print", "(", "\"DFLogger: logging start...
open a new dataflash log, reset state
[ "open", "a", "new", "dataflash", "log", "reset", "state" ]
python
train
34.411765
inveniosoftware/invenio-iiif
invenio_iiif/utils.py
https://github.com/inveniosoftware/invenio-iiif/blob/e4f2f93eaabdc8e2efea81c239ab76d481191959/invenio_iiif/utils.py#L18-L32
def iiif_image_key(obj): """Generate the IIIF image key.""" if isinstance(obj, ObjectVersion): bucket_id = obj.bucket_id version_id = obj.version_id key = obj.key else: bucket_id = obj.get('bucket') version_id = obj.get('version_id') key = obj.get('key') r...
[ "def", "iiif_image_key", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "ObjectVersion", ")", ":", "bucket_id", "=", "obj", ".", "bucket_id", "version_id", "=", "obj", ".", "version_id", "key", "=", "obj", ".", "key", "else", ":", "bucket_id"...
Generate the IIIF image key.
[ "Generate", "the", "IIIF", "image", "key", "." ]
python
train
25.933333
HacKanCuBa/passphrase-py
passphrase/random.py
https://github.com/HacKanCuBa/passphrase-py/blob/219d6374338ed9a1475b4f09b0d85212376f11e0/passphrase/random.py#L35-L49
def randbytes(nbytes: int) -> bytes: r"""Return a random byte string containing *nbytes* bytes. Raises ValueError if nbytes <= 0, and TypeError if it's not an integer. >>> randbytes(16) #doctest:+SKIP b'\\xebr\\x17D*t\\xae\\xd4\\xe3S\\xb6\\xe2\\xebP1\\x8b' """ if not isinstance(nbytes, int):...
[ "def", "randbytes", "(", "nbytes", ":", "int", ")", "->", "bytes", ":", "if", "not", "isinstance", "(", "nbytes", ",", "int", ")", ":", "raise", "TypeError", "(", "'number of bytes shoud be an integer'", ")", "if", "nbytes", "<=", "0", ":", "raise", "Value...
r"""Return a random byte string containing *nbytes* bytes. Raises ValueError if nbytes <= 0, and TypeError if it's not an integer. >>> randbytes(16) #doctest:+SKIP b'\\xebr\\x17D*t\\xae\\xd4\\xe3S\\xb6\\xe2\\xebP1\\x8b'
[ "r", "Return", "a", "random", "byte", "string", "containing", "*", "nbytes", "*", "bytes", "." ]
python
train
32.533333
mrcagney/make_gtfs
make_gtfs/main.py
https://github.com/mrcagney/make_gtfs/blob/37b6f88e03bac708c2e85d6f4b6d48a0c92e4a59/make_gtfs/main.py#L268-L384
def build_stop_times(pfeed, routes, shapes, stops, trips, buffer=cs.BUFFER): """ Given a ProtoFeed and its corresponding routes (DataFrame), shapes (DataFrame), stops (DataFrame), trips (DataFrame), return DataFrame representing ``stop_times.txt``. Includes the optional ``shape_dist_traveled`` colum...
[ "def", "build_stop_times", "(", "pfeed", ",", "routes", ",", "shapes", ",", "stops", ",", "trips", ",", "buffer", "=", "cs", ".", "BUFFER", ")", ":", "# Get the table of trips and add frequency and service window details", "routes", "=", "(", "routes", ".", "filte...
Given a ProtoFeed and its corresponding routes (DataFrame), shapes (DataFrame), stops (DataFrame), trips (DataFrame), return DataFrame representing ``stop_times.txt``. Includes the optional ``shape_dist_traveled`` column. Don't make stop times for trips with no nearby stops.
[ "Given", "a", "ProtoFeed", "and", "its", "corresponding", "routes", "(", "DataFrame", ")", "shapes", "(", "DataFrame", ")", "stops", "(", "DataFrame", ")", "trips", "(", "DataFrame", ")", "return", "DataFrame", "representing", "stop_times", ".", "txt", ".", ...
python
train
40.735043
opendatateam/udata
udata/core/user/commands.py
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/user/commands.py#L78-L84
def set_admin(email): '''Set an user as administrator''' user = datastore.get_user(email) log.info('Adding admin role to user %s (%s)', user.fullname, user.email) role = datastore.find_or_create_role('admin') datastore.add_role_to_user(user, role) success('User %s (%s) is now administrator' % (u...
[ "def", "set_admin", "(", "email", ")", ":", "user", "=", "datastore", ".", "get_user", "(", "email", ")", "log", ".", "info", "(", "'Adding admin role to user %s (%s)'", ",", "user", ".", "fullname", ",", "user", ".", "email", ")", "role", "=", "datastore"...
Set an user as administrator
[ "Set", "an", "user", "as", "administrator" ]
python
train
48.571429
mikicz/arca
arca/backend/docker.py
https://github.com/mikicz/arca/blob/e67fdc00be473ecf8ec16d024e1a3f2c47ca882c/arca/backend/docker.py#L153-L161
def get_python_version(self) -> str: """ Returns either the specified version from settings or platform.python_version() """ if self.python_version is None: python_version = platform.python_version() else: python_version = self.python_version return pytho...
[ "def", "get_python_version", "(", "self", ")", "->", "str", ":", "if", "self", ".", "python_version", "is", "None", ":", "python_version", "=", "platform", ".", "python_version", "(", ")", "else", ":", "python_version", "=", "self", ".", "python_version", "r...
Returns either the specified version from settings or platform.python_version()
[ "Returns", "either", "the", "specified", "version", "from", "settings", "or", "platform", ".", "python_version", "()" ]
python
train
35.666667
ninuxorg/nodeshot
nodeshot/networking/net/models/interface.py
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/net/models/interface.py#L38-L52
def save(self, *args, **kwargs): """ Custom save method does the following: * save shortcuts if HSTORE is enabled """ if 'node' not in self.shortcuts: self.shortcuts['node'] = self.device.node if 'user' not in self.shortcuts and self.device.node.user: ...
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "'node'", "not", "in", "self", ".", "shortcuts", ":", "self", ".", "shortcuts", "[", "'node'", "]", "=", "self", ".", "device", ".", "node", "if", "'user'", "n...
Custom save method does the following: * save shortcuts if HSTORE is enabled
[ "Custom", "save", "method", "does", "the", "following", ":", "*", "save", "shortcuts", "if", "HSTORE", "is", "enabled" ]
python
train
38.2
noahbenson/pimms
pimms/calculation.py
https://github.com/noahbenson/pimms/blob/9051b86d6b858a7a13511b72c48dc21bc903dab2/pimms/calculation.py#L495-L503
def _cache(cpath, arg): ''' IMap._cache(cpath, arg) is an internally-called method that saves the dict of arguments to cache files in the given cpath directory. ''' if not os.path.isdir(cpath): os.makedirs(cpath) for (k,v) in six.iteritems(arg): save(os.path...
[ "def", "_cache", "(", "cpath", ",", "arg", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "cpath", ")", ":", "os", ".", "makedirs", "(", "cpath", ")", "for", "(", "k", ",", "v", ")", "in", "six", ".", "iteritems", "(", "arg", ")...
IMap._cache(cpath, arg) is an internally-called method that saves the dict of arguments to cache files in the given cpath directory.
[ "IMap", ".", "_cache", "(", "cpath", "arg", ")", "is", "an", "internally", "-", "called", "method", "that", "saves", "the", "dict", "of", "arguments", "to", "cache", "files", "in", "the", "given", "cpath", "directory", "." ]
python
train
44.444444
paramiko/paramiko
paramiko/kex_gss.py
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/kex_gss.py#L590-L638
def _parse_kexgss_complete(self, m): """ Parse the SSH2_MSG_KEXGSS_COMPLETE message (client mode). :param `Message` m: The content of the SSH2_MSG_KEXGSS_COMPLETE message """ if self.transport.host_key is None: self.transport.host_key = NullHostKey() self.f =...
[ "def", "_parse_kexgss_complete", "(", "self", ",", "m", ")", ":", "if", "self", ".", "transport", ".", "host_key", "is", "None", ":", "self", ".", "transport", ".", "host_key", "=", "NullHostKey", "(", ")", "self", ".", "f", "=", "m", ".", "get_mpint",...
Parse the SSH2_MSG_KEXGSS_COMPLETE message (client mode). :param `Message` m: The content of the SSH2_MSG_KEXGSS_COMPLETE message
[ "Parse", "the", "SSH2_MSG_KEXGSS_COMPLETE", "message", "(", "client", "mode", ")", "." ]
python
train
37.122449
jobovy/galpy
galpy/util/bovy_plot.py
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/util/bovy_plot.py#L809-L1043
def scatterplot(x,y,*args,**kwargs): """ NAME: scatterplot PURPOSE: make a 'smart' scatterplot that is a density plot in high-density regions and a regular scatterplot for outliers INPUT: x, y xlabel - (raw string!) x-axis label, LaTeX math mode, no $s needed ...
[ "def", "scatterplot", "(", "x", ",", "y", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "xlabel", "=", "kwargs", ".", "pop", "(", "'xlabel'", ",", "None", ")", "ylabel", "=", "kwargs", ".", "pop", "(", "'ylabel'", ",", "None", ")", "if", ...
NAME: scatterplot PURPOSE: make a 'smart' scatterplot that is a density plot in high-density regions and a regular scatterplot for outliers INPUT: x, y xlabel - (raw string!) x-axis label, LaTeX math mode, no $s needed ylabel - (raw string!) y-axis label, LaTeX m...
[ "NAME", ":" ]
python
train
39.459574
KE-works/pykechain
pykechain/models/scope.py
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/scope.py#L170-L177
def service_execution(self, *args, **kwargs): """Retrieve a single service execution belonging to this scope. See :class:`pykechain.Client.service_execution` for available parameters. .. versionadded:: 1.13 """ return self._client.service_execution(*args, scope=self.id, **kwarg...
[ "def", "service_execution", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_client", ".", "service_execution", "(", "*", "args", ",", "scope", "=", "self", ".", "id", ",", "*", "*", "kwargs", ")" ]
Retrieve a single service execution belonging to this scope. See :class:`pykechain.Client.service_execution` for available parameters. .. versionadded:: 1.13
[ "Retrieve", "a", "single", "service", "execution", "belonging", "to", "this", "scope", "." ]
python
train
39.375
saltstack/salt
salt/states/openvswitch_port.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/openvswitch_port.py#L274-L339
def absent(name, bridge=None): ''' Ensures that the named port exists on bridge, eventually deletes it. If bridge is not set, port is removed from whatever bridge contains it. Args: name: The name of the port. bridge: The name of the bridge. ''' ret = {'name': name, 'changes':...
[ "def", "absent", "(", "name", ",", "bridge", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "False", ",", "'comment'", ":", "''", "}", "bridge_exists", "=", "False", "if", "brid...
Ensures that the named port exists on bridge, eventually deletes it. If bridge is not set, port is removed from whatever bridge contains it. Args: name: The name of the port. bridge: The name of the bridge.
[ "Ensures", "that", "the", "named", "port", "exists", "on", "bridge", "eventually", "deletes", "it", ".", "If", "bridge", "is", "not", "set", "port", "is", "removed", "from", "whatever", "bridge", "contains", "it", "." ]
python
train
36.939394
jayclassless/tidypy
src/tidypy/collector.py
https://github.com/jayclassless/tidypy/blob/3c3497ca377fbbe937103b77b02b326c860c748f/src/tidypy/collector.py#L76-L86
def get_issues(self, sortby=None): """ Retrieves the issues in the collection. :param sortby: the properties to sort the issues by :type sortby: list(str) :rtype: list(tidypy.Issue) """ self._ensure_cleaned_issues() return self._sort_issues(self._cleaned...
[ "def", "get_issues", "(", "self", ",", "sortby", "=", "None", ")", ":", "self", ".", "_ensure_cleaned_issues", "(", ")", "return", "self", ".", "_sort_issues", "(", "self", ".", "_cleaned_issues", ",", "sortby", ")" ]
Retrieves the issues in the collection. :param sortby: the properties to sort the issues by :type sortby: list(str) :rtype: list(tidypy.Issue)
[ "Retrieves", "the", "issues", "in", "the", "collection", "." ]
python
valid
29.636364
etcher-be/emiz
emiz/weather/custom_metar/custom_metar.py
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/weather/custom_metar/custom_metar.py#L27-L60
def get_metar( metar: typing.Union[str, 'CustomMetar'] ) -> typing.Tuple[typing.Union[str, None], typing.Union['CustomMetar', None]]: """ Builds a CustomMetar object from a CustomMetar object (returns it), an ICAO code or a METAR string Args: metar: CustomMetar objec...
[ "def", "get_metar", "(", "metar", ":", "typing", ".", "Union", "[", "str", ",", "'CustomMetar'", "]", ")", "->", "typing", ".", "Tuple", "[", "typing", ".", "Union", "[", "str", ",", "None", "]", ",", "typing", ".", "Union", "[", "'CustomMetar'", ","...
Builds a CustomMetar object from a CustomMetar object (returns it), an ICAO code or a METAR string Args: metar: CustomMetar object, ICAO string or METAR string Returns: CustomMetar object
[ "Builds", "a", "CustomMetar", "object", "from", "a", "CustomMetar", "object", "(", "returns", "it", ")", "an", "ICAO", "code", "or", "a", "METAR", "string" ]
python
train
36.647059
aws/sagemaker-python-sdk
src/sagemaker/local/utils.py
https://github.com/aws/sagemaker-python-sdk/blob/a9e724c7d3f5572b68c3903548c792a59d99799a/src/sagemaker/local/utils.py#L43-L68
def move_to_destination(source, destination, job_name, sagemaker_session): """move source to destination. Can handle uploading to S3 Args: source (str): root directory to move destination (str): file:// or s3:// URI that source will be moved to. job_name (str): SageMaker job name. ...
[ "def", "move_to_destination", "(", "source", ",", "destination", ",", "job_name", ",", "sagemaker_session", ")", ":", "parsed_uri", "=", "urlparse", "(", "destination", ")", "if", "parsed_uri", ".", "scheme", "==", "'file'", ":", "recursive_copy", "(", "source",...
move source to destination. Can handle uploading to S3 Args: source (str): root directory to move destination (str): file:// or s3:// URI that source will be moved to. job_name (str): SageMaker job name. sagemaker_session (sagemaker.Session): a sagemaker_session to interact with S3 ...
[ "move", "source", "to", "destination", ".", "Can", "handle", "uploading", "to", "S3" ]
python
train
38.384615
biolink/ontobio
ontobio/golr/golr_associations.py
https://github.com/biolink/ontobio/blob/4e512a7831cfe6bc1b32f2c3be2ba41bc5cf7345/ontobio/golr/golr_associations.py#L167-L212
def pivot_query_as_matrix(facet=None, facet_pivot_fields=None, **kwargs): """ Pivot query """ if facet_pivot_fields is None: facet_pivot_fields = [] logging.info("Additional args: {}".format(kwargs)) fp = search_associations(rows=0, facet_fields=[facet], ...
[ "def", "pivot_query_as_matrix", "(", "facet", "=", "None", ",", "facet_pivot_fields", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "facet_pivot_fields", "is", "None", ":", "facet_pivot_fields", "=", "[", "]", "logging", ".", "info", "(", "\"Addition...
Pivot query
[ "Pivot", "query" ]
python
train
27.326087
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/color/color_array.py
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/color/color_array.py#L338-L355
def darker(self, dv=0.1, copy=True): """Produce a darker color (if possible) Parameters ---------- dv : float Amount to decrease the color value by. copy : bool If False, operation will be carried out in-place. Returns ------- col...
[ "def", "darker", "(", "self", ",", "dv", "=", "0.1", ",", "copy", "=", "True", ")", ":", "color", "=", "self", ".", "copy", "(", ")", "if", "copy", "else", "self", "color", ".", "value", "-=", "dv", "return", "color" ]
Produce a darker color (if possible) Parameters ---------- dv : float Amount to decrease the color value by. copy : bool If False, operation will be carried out in-place. Returns ------- color : instance of ColorArray The dark...
[ "Produce", "a", "darker", "color", "(", "if", "possible", ")" ]
python
train
25.944444
nschloe/orthopy
orthopy/line_segment/tools.py
https://github.com/nschloe/orthopy/blob/64713d0533b0af042810a7535fff411b8e0aea9e/orthopy/line_segment/tools.py#L8-L39
def clenshaw(a, alpha, beta, t): """Clenshaw's algorithm for evaluating S(t) = \\sum a_k P_k(alpha, beta)(t) where P_k(alpha, beta) is the kth orthogonal polynomial defined by the recurrence coefficients alpha, beta. See <https://en.wikipedia.org/wiki/Clenshaw_algorithm> for details. """ ...
[ "def", "clenshaw", "(", "a", ",", "alpha", ",", "beta", ",", "t", ")", ":", "n", "=", "len", "(", "alpha", ")", "assert", "len", "(", "beta", ")", "==", "n", "assert", "len", "(", "a", ")", "==", "n", "+", "1", "try", ":", "b", "=", "numpy"...
Clenshaw's algorithm for evaluating S(t) = \\sum a_k P_k(alpha, beta)(t) where P_k(alpha, beta) is the kth orthogonal polynomial defined by the recurrence coefficients alpha, beta. See <https://en.wikipedia.org/wiki/Clenshaw_algorithm> for details.
[ "Clenshaw", "s", "algorithm", "for", "evaluating" ]
python
train
27.21875
ArchiveTeam/wpull
wpull/protocol/ftp/ls/listing.py
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/ftp/ls/listing.py#L57-L66
def parse(self, lines): '''Parse the lines.''' if self.type == 'msdos': return self.parse_msdos(lines) elif self.type == 'unix': return self.parse_unix(lines) elif self.type == 'nlst': return self.parse_nlst(lines) else: raise Unkno...
[ "def", "parse", "(", "self", ",", "lines", ")", ":", "if", "self", ".", "type", "==", "'msdos'", ":", "return", "self", ".", "parse_msdos", "(", "lines", ")", "elif", "self", ".", "type", "==", "'unix'", ":", "return", "self", ".", "parse_unix", "(",...
Parse the lines.
[ "Parse", "the", "lines", "." ]
python
train
35.4
visualfabriq/bquery
bquery/benchmarks/bench_groupby.py
https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/benchmarks/bench_groupby.py#L29-L39
def ctime(message=None): "Counts the time spent in some context" global t_elapsed t_elapsed = 0.0 print('\n') t = time.time() yield if message: print(message + ": ", end='') t_elapsed = time.time() - t print(round(t_elapsed, 4), "sec")
[ "def", "ctime", "(", "message", "=", "None", ")", ":", "global", "t_elapsed", "t_elapsed", "=", "0.0", "print", "(", "'\\n'", ")", "t", "=", "time", ".", "time", "(", ")", "yield", "if", "message", ":", "print", "(", "message", "+", "\": \"", ",", ...
Counts the time spent in some context
[ "Counts", "the", "time", "spent", "in", "some", "context" ]
python
train
24.545455
jmbhughes/suvi-trainer
scripts/fetch_hek_labeled.py
https://github.com/jmbhughes/suvi-trainer/blob/3d89894a4a037286221974c7eb5634d229b4f5d4/scripts/fetch_hek_labeled.py#L85-L114
def main(): """ fetches hek data and makes thematic maps as requested """ args = get_args() config = Config(args.config) # Load dates if os.path.isfile(args.dates): with open(args.dates) as f: dates = [dateparser.parse(line.split(" ")[0]) for line in f.readlines()] e...
[ "def", "main", "(", ")", ":", "args", "=", "get_args", "(", ")", "config", "=", "Config", "(", "args", ".", "config", ")", "# Load dates", "if", "os", ".", "path", ".", "isfile", "(", "args", ".", "dates", ")", ":", "with", "open", "(", "args", "...
fetches hek data and makes thematic maps as requested
[ "fetches", "hek", "data", "and", "makes", "thematic", "maps", "as", "requested" ]
python
train
37.1
crytic/slither
slither/detectors/shadowing/builtin_symbols.py
https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/detectors/shadowing/builtin_symbols.py#L114-L152
def _detect(self): """ Detect shadowing of built-in symbols Recursively visit the calls Returns: list: {'vuln', 'filename,'contract','func', 'shadow'} """ results = [] for contract in self.contracts: shadows = self.detect_builtin_shadowing_defin...
[ "def", "_detect", "(", "self", ")", ":", "results", "=", "[", "]", "for", "contract", "in", "self", ".", "contracts", ":", "shadows", "=", "self", ".", "detect_builtin_shadowing_definitions", "(", "contract", ")", "if", "shadows", ":", "for", "shadow", "in...
Detect shadowing of built-in symbols Recursively visit the calls Returns: list: {'vuln', 'filename,'contract','func', 'shadow'}
[ "Detect", "shadowing", "of", "built", "-", "in", "symbols" ]
python
train
47.230769
blockstack/virtualchain
virtualchain/lib/blockchain/bitcoin_blockchain/keys.py
https://github.com/blockstack/virtualchain/blob/fcfc970064ca7dfcab26ebd3ab955870a763ea39/virtualchain/lib/blockchain/bitcoin_blockchain/keys.py#L473-L484
def btc_is_p2wsh_address( address ): """ Is the given address a p2wsh address? """ wver, whash = segwit_addr_decode(address) if whash is None: return False if len(whash) != 32: return False return True
[ "def", "btc_is_p2wsh_address", "(", "address", ")", ":", "wver", ",", "whash", "=", "segwit_addr_decode", "(", "address", ")", "if", "whash", "is", "None", ":", "return", "False", "if", "len", "(", "whash", ")", "!=", "32", ":", "return", "False", "retur...
Is the given address a p2wsh address?
[ "Is", "the", "given", "address", "a", "p2wsh", "address?" ]
python
train
20
openpaperwork/paperwork-backend
paperwork_backend/img/page.py
https://github.com/openpaperwork/paperwork-backend/blob/114b831e94e039e68b339751fd18250877abad76/paperwork_backend/img/page.py#L129-L136
def __get_img(self): """ Returns an image object corresponding to the page """ with self.fs.open(self.__img_path, 'rb') as fd: img = PIL.Image.open(fd) img.load() return img
[ "def", "__get_img", "(", "self", ")", ":", "with", "self", ".", "fs", ".", "open", "(", "self", ".", "__img_path", ",", "'rb'", ")", "as", "fd", ":", "img", "=", "PIL", ".", "Image", ".", "open", "(", "fd", ")", "img", ".", "load", "(", ")", ...
Returns an image object corresponding to the page
[ "Returns", "an", "image", "object", "corresponding", "to", "the", "page" ]
python
train
29.25
rosenbrockc/fortpy
fortpy/parsers/docstring.py
https://github.com/rosenbrockc/fortpy/blob/1ed0757c52d549e41d9d44bdea68cb89529293a5/fortpy/parsers/docstring.py#L9-L25
def _update_globals(kids, xmlglobals): """Updates the specified 'xmlglobals' dictionary with the specific *and* supported global tag definitions. """ for child in kids: key = child.tag.lower() if key != "defaults": if key not in xmlglobals: xmlglobals[key] = {...
[ "def", "_update_globals", "(", "kids", ",", "xmlglobals", ")", ":", "for", "child", "in", "kids", ":", "key", "=", "child", ".", "tag", ".", "lower", "(", ")", "if", "key", "!=", "\"defaults\"", ":", "if", "key", "not", "in", "xmlglobals", ":", "xmlg...
Updates the specified 'xmlglobals' dictionary with the specific *and* supported global tag definitions.
[ "Updates", "the", "specified", "xmlglobals", "dictionary", "with", "the", "specific", "*", "and", "*", "supported", "global", "tag", "definitions", "." ]
python
train
40.470588
numenta/nupic
src/nupic/data/aggregator.py
https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/data/aggregator.py#L114-L129
def _filterRecord(filterList, record): """ Takes a record and returns true if record meets filter criteria, false otherwise """ for (fieldIdx, fp, params) in filterList: x = dict() x['value'] = record[fieldIdx] x['acceptValues'] = params['acceptValues'] x['min'] = params['min'] x['max'] = p...
[ "def", "_filterRecord", "(", "filterList", ",", "record", ")", ":", "for", "(", "fieldIdx", ",", "fp", ",", "params", ")", "in", "filterList", ":", "x", "=", "dict", "(", ")", "x", "[", "'value'", "]", "=", "record", "[", "fieldIdx", "]", "x", "[",...
Takes a record and returns true if record meets filter criteria, false otherwise
[ "Takes", "a", "record", "and", "returns", "true", "if", "record", "meets", "filter", "criteria", "false", "otherwise" ]
python
valid
27.625
google/grr
grr/server/grr_response_server/gui/wsgiapp.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/gui/wsgiapp.py#L162-L181
def LogAccessWrapper(func): """Decorator that ensures that HTTP access is logged.""" def Wrapper(request, *args, **kwargs): """Wrapping function.""" try: response = func(request, *args, **kwargs) server_logging.LOGGER.LogHttpAdminUIAccess(request, response) except Exception: # pylint: disa...
[ "def", "LogAccessWrapper", "(", "func", ")", ":", "def", "Wrapper", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Wrapping function.\"\"\"", "try", ":", "response", "=", "func", "(", "request", ",", "*", "args", ",", "*", ...
Decorator that ensures that HTTP access is logged.
[ "Decorator", "that", "ensures", "that", "HTTP", "access", "is", "logged", "." ]
python
train
37.25
twidi/django-extended-choices
extended_choices/helpers.py
https://github.com/twidi/django-extended-choices/blob/bb310c5da4d53685c69173541172e4b813a6afb2/extended_choices/helpers.py#L306-L329
def _get_choice_attribute(self, value): """Get a choice attribute for the given value. Parameters ---------- value: ? The value for which we want a choice attribute. Returns ------- An instance of a class based on ``ChoiceAttributeMixin`` for the giv...
[ "def", "_get_choice_attribute", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "raise", "ValueError", "(", "'Using `None` in a `Choices` object is not supported. You may '", "'use an empty string.'", ")", "return", "create_choice_attribute", "(", "...
Get a choice attribute for the given value. Parameters ---------- value: ? The value for which we want a choice attribute. Returns ------- An instance of a class based on ``ChoiceAttributeMixin`` for the given value. Raises ------ Va...
[ "Get", "a", "choice", "attribute", "for", "the", "given", "value", "." ]
python
train
28.958333
HazyResearch/fonduer
src/fonduer/candidates/models/span_mention.py
https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/candidates/models/span_mention.py#L123-L138
def get_attrib_tokens(self, a="words"): """Get the tokens of sentence attribute *a*. Intuitively, like calling:: span.a :param a: The attribute to get tokens for. :type a: str :return: The tokens of sentence attribute defined by *a* for the span. :rtype: l...
[ "def", "get_attrib_tokens", "(", "self", ",", "a", "=", "\"words\"", ")", ":", "return", "self", ".", "sentence", ".", "__getattribute__", "(", "a", ")", "[", "self", ".", "get_word_start_index", "(", ")", ":", "self", ".", "get_word_end_index", "(", ")", ...
Get the tokens of sentence attribute *a*. Intuitively, like calling:: span.a :param a: The attribute to get tokens for. :type a: str :return: The tokens of sentence attribute defined by *a* for the span. :rtype: list
[ "Get", "the", "tokens", "of", "sentence", "attribute", "*", "a", "*", "." ]
python
train
28.25
SmileyChris/django-countries
django_countries/fields.py
https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/fields.py#L337-L353
def deconstruct(self): """ Remove choices from deconstructed field, as this is the country list and not user editable. Not including the ``blank_label`` property, as this isn't database related. """ name, path, args, kwargs = super(CountryField, self).deconstruct...
[ "def", "deconstruct", "(", "self", ")", ":", "name", ",", "path", ",", "args", ",", "kwargs", "=", "super", "(", "CountryField", ",", "self", ")", ".", "deconstruct", "(", ")", "kwargs", ".", "pop", "(", "\"choices\"", ")", "if", "self", ".", "multip...
Remove choices from deconstructed field, as this is the country list and not user editable. Not including the ``blank_label`` property, as this isn't database related.
[ "Remove", "choices", "from", "deconstructed", "field", "as", "this", "is", "the", "country", "list", "and", "not", "user", "editable", "." ]
python
train
41.117647
common-workflow-language/cwltool
cwltool/secrets.py
https://github.com/common-workflow-language/cwltool/blob/cb81b22abc52838823da9945f04d06739ab32fda/cwltool/secrets.py#L15-L28
def add(self, value): # type: (Text) -> Text """ Add the given value to the store. Returns a placeholder value to use until the real value is needed. """ if not isinstance(value, string_types): raise Exception("Secret store only accepts strings") if value n...
[ "def", "add", "(", "self", ",", "value", ")", ":", "# type: (Text) -> Text", "if", "not", "isinstance", "(", "value", ",", "string_types", ")", ":", "raise", "Exception", "(", "\"Secret store only accepts strings\"", ")", "if", "value", "not", "in", "self", "....
Add the given value to the store. Returns a placeholder value to use until the real value is needed.
[ "Add", "the", "given", "value", "to", "the", "store", "." ]
python
train
34.642857
pkgw/pwkit
pwkit/synphot.py
https://github.com/pkgw/pwkit/blob/d40957a1c3d2ea34e7ceac2267ee9635135f2793/pwkit/synphot.py#L930-L943
def _load_data(self, band): """From the WISE All-Sky Explanatory Supplement, IV.4.h.i.1, and Jarrett+ 2011. These are relative response per erg and so can be integrated directly against F_nu spectra. Wavelengths are in micron, uncertainties are in parts per thousand. """ ...
[ "def", "_load_data", "(", "self", ",", "band", ")", ":", "# `band` should be 1, 2, 3, or 4.", "df", "=", "bandpass_data_frame", "(", "'filter_wise_'", "+", "str", "(", "band", ")", "+", "'.dat'", ",", "'wlen resp uncert'", ")", "df", ".", "wlen", "*=", "1e4", ...
From the WISE All-Sky Explanatory Supplement, IV.4.h.i.1, and Jarrett+ 2011. These are relative response per erg and so can be integrated directly against F_nu spectra. Wavelengths are in micron, uncertainties are in parts per thousand.
[ "From", "the", "WISE", "All", "-", "Sky", "Explanatory", "Supplement", "IV", ".", "4", ".", "h", ".", "i", ".", "1", "and", "Jarrett", "+", "2011", ".", "These", "are", "relative", "response", "per", "erg", "and", "so", "can", "be", "integrated", "di...
python
train
47.571429
StackStorm/pybind
pybind/slxos/v17r_1_01a/ipv6_acl/ipv6/access_list/extended/seq/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17r_1_01a/ipv6_acl/ipv6/access_list/extended/seq/__init__.py#L239-L260
def _set_src_host_any_sip(self, v, load=False): """ Setter method for src_host_any_sip, mapped from YANG variable /ipv6_acl/ipv6/access_list/extended/seq/src_host_any_sip (union) If this variable is read-only (config: false) in the source YANG file, then _set_src_host_any_sip is considered as a private ...
[ "def", "_set_src_host_any_sip", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", ...
Setter method for src_host_any_sip, mapped from YANG variable /ipv6_acl/ipv6/access_list/extended/seq/src_host_any_sip (union) If this variable is read-only (config: false) in the source YANG file, then _set_src_host_any_sip is considered as a private method. Backends looking to populate this variable shoul...
[ "Setter", "method", "for", "src_host_any_sip", "mapped", "from", "YANG", "variable", "/", "ipv6_acl", "/", "ipv6", "/", "access_list", "/", "extended", "/", "seq", "/", "src_host_any_sip", "(", "union", ")", "If", "this", "variable", "is", "read", "-", "only...
python
train
124.727273
Azure/azure-sdk-for-python
azure-servicemanagement-legacy/azure/servicemanagement/servicemanagementclient.py
https://github.com/Azure/azure-sdk-for-python/blob/d7306fde32f60a293a7567678692bdad31e4b667/azure-servicemanagement-legacy/azure/servicemanagement/servicemanagementclient.py#L135-L148
def set_proxy(self, host, port, user=None, password=None): ''' Sets the proxy server host and port for the HTTP CONNECT Tunnelling. host: Address of the proxy. Ex: '192.168.0.100' port: Port of the proxy. Ex: 6000 user: User for proxy authoriz...
[ "def", "set_proxy", "(", "self", ",", "host", ",", "port", ",", "user", "=", "None", ",", "password", "=", "None", ")", ":", "self", ".", "_httpclient", ".", "set_proxy", "(", "host", ",", "port", ",", "user", ",", "password", ")" ]
Sets the proxy server host and port for the HTTP CONNECT Tunnelling. host: Address of the proxy. Ex: '192.168.0.100' port: Port of the proxy. Ex: 6000 user: User for proxy authorization. password: Password for proxy authorization.
[ "Sets", "the", "proxy", "server", "host", "and", "port", "for", "the", "HTTP", "CONNECT", "Tunnelling", "." ]
python
test
32.285714
deepmind/pysc2
pysc2/bin/gen_actions.py
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/bin/gen_actions.py#L127-L157
def generate_py_abilities(data): """Generate the list of functions in actions.py.""" def print_action(func_id, name, func, ab_id, general_id): args = [func_id, '"%s"' % name, func, ab_id] if general_id: args.append(general_id) print(" Function.ability(%s)," % ", ".join(str(v) for v in args)) ...
[ "def", "generate_py_abilities", "(", "data", ")", ":", "def", "print_action", "(", "func_id", ",", "name", ",", "func", ",", "ab_id", ",", "general_id", ")", ":", "args", "=", "[", "func_id", ",", "'\"%s\"'", "%", "name", ",", "func", ",", "ab_id", "]"...
Generate the list of functions in actions.py.
[ "Generate", "the", "list", "of", "functions", "in", "actions", ".", "py", "." ]
python
train
47.096774
chrisrink10/basilisp
src/basilisp/lang/set.py
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/set.py#L134-L136
def s(*members: T, meta=None) -> Set[T]: """Creates a new set from members.""" return Set(pset(members), meta=meta)
[ "def", "s", "(", "*", "members", ":", "T", ",", "meta", "=", "None", ")", "->", "Set", "[", "T", "]", ":", "return", "Set", "(", "pset", "(", "members", ")", ",", "meta", "=", "meta", ")" ]
Creates a new set from members.
[ "Creates", "a", "new", "set", "from", "members", "." ]
python
test
40.333333
lemieuxl/pyGenClean
pyGenClean/run_data_clean_up.py
https://github.com/lemieuxl/pyGenClean/blob/6173a48ccc0cf3a3bd711b1f2a1fa16248b8bf55/pyGenClean/run_data_clean_up.py#L1903-L2153
def run_find_related_samples(in_prefix, in_type, out_prefix, base_dir, options): """Runs step9 (find related samples). :param in_prefix: the prefix of the input files. :param in_type: the type of the input files. :param out_prefix: the output prefix. :param base_dir: th...
[ "def", "run_find_related_samples", "(", "in_prefix", ",", "in_type", ",", "out_prefix", ",", "base_dir", ",", "options", ")", ":", "# Creating the output directory", "os", ".", "mkdir", "(", "out_prefix", ")", "# We know we need bfile", "required_type", "=", "\"bfile\...
Runs step9 (find related samples). :param in_prefix: the prefix of the input files. :param in_type: the type of the input files. :param out_prefix: the output prefix. :param base_dir: the output directory. :param options: the options needed. :type in_prefix: str :type in_type: str :typ...
[ "Runs", "step9", "(", "find", "related", "samples", ")", "." ]
python
train
39.525896
aaren/notedown
notedown/notedown.py
https://github.com/aaren/notedown/blob/1e920c7e4ecbe47420c12eed3d5bcae735121222/notedown/notedown.py#L648-L679
def get_caption_comments(content): """Retrieve an id and a caption from a code cell. If the code cell content begins with a commented block that looks like ## fig:id # multi-line or single-line # caption then the 'fig:id' and the caption will be returned. The '#' are stripped. """...
[ "def", "get_caption_comments", "(", "content", ")", ":", "if", "not", "content", ".", "startswith", "(", "'## fig:'", ")", ":", "return", "None", ",", "None", "content", "=", "content", ".", "splitlines", "(", ")", "id", "=", "content", "[", "0", "]", ...
Retrieve an id and a caption from a code cell. If the code cell content begins with a commented block that looks like ## fig:id # multi-line or single-line # caption then the 'fig:id' and the caption will be returned. The '#' are stripped.
[ "Retrieve", "an", "id", "and", "a", "caption", "from", "a", "code", "cell", "." ]
python
train
24.59375
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_cmdlong.py
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_cmdlong.py#L126-L149
def cmd_condition_yaw(self, args): '''yaw angle angular_speed angle_mode''' if ( len(args) != 3): print("Usage: yaw ANGLE ANGULAR_SPEED MODE:[0 absolute / 1 relative]") return if (len(args) == 3): angle = float(args[0]) angular_speed = float(args[...
[ "def", "cmd_condition_yaw", "(", "self", ",", "args", ")", ":", "if", "(", "len", "(", "args", ")", "!=", "3", ")", ":", "print", "(", "\"Usage: yaw ANGLE ANGULAR_SPEED MODE:[0 absolute / 1 relative]\"", ")", "return", "if", "(", "len", "(", "args", ")", "==...
yaw angle angular_speed angle_mode
[ "yaw", "angle", "angular_speed", "angle_mode" ]
python
train
39.791667
datastax/python-driver
cassandra/cluster.py
https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L2197-L2237
def execute(self, query, parameters=None, timeout=_NOT_SET, trace=False, custom_payload=None, execution_profile=EXEC_PROFILE_DEFAULT, paging_state=None, host=None): """ Execute the given query and synchronously wait for the response. If an error is encountered wh...
[ "def", "execute", "(", "self", ",", "query", ",", "parameters", "=", "None", ",", "timeout", "=", "_NOT_SET", ",", "trace", "=", "False", ",", "custom_payload", "=", "None", ",", "execution_profile", "=", "EXEC_PROFILE_DEFAULT", ",", "paging_state", "=", "No...
Execute the given query and synchronously wait for the response. If an error is encountered while executing the query, an Exception will be raised. `query` may be a query string or an instance of :class:`cassandra.query.Statement`. `parameters` may be a sequence or dict of parameters ...
[ "Execute", "the", "given", "query", "and", "synchronously", "wait", "for", "the", "response", "." ]
python
train
55.073171
src-d/modelforge
modelforge/slogging.py
https://github.com/src-d/modelforge/blob/4f73c2bf0318261ac01bc8b6c0d4250a5d303418/modelforge/slogging.py#L71-L94
def getMessage(self): """ Return the message for this LogRecord. Return the message for this LogRecord after merging any user-supplied \ arguments with the message. """ if isinstance(self.msg, numpy.ndarray): msg = self.array2string(self.msg) else: ...
[ "def", "getMessage", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "msg", ",", "numpy", ".", "ndarray", ")", ":", "msg", "=", "self", ".", "array2string", "(", "self", ".", "msg", ")", "else", ":", "msg", "=", "str", "(", "self", "...
Return the message for this LogRecord. Return the message for this LogRecord after merging any user-supplied \ arguments with the message.
[ "Return", "the", "message", "for", "this", "LogRecord", "." ]
python
train
40.791667
StackStorm/pybind
pybind/nos/v6_0_2f/zoning/defined_configuration/cfg/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v6_0_2f/zoning/defined_configuration/cfg/__init__.py#L131-L152
def _set_member_zone(self, v, load=False): """ Setter method for member_zone, mapped from YANG variable /zoning/defined_configuration/cfg/member_zone (list) If this variable is read-only (config: false) in the source YANG file, then _set_member_zone is considered as a private method. Backends lookin...
[ "def", "_set_member_zone", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "ba...
Setter method for member_zone, mapped from YANG variable /zoning/defined_configuration/cfg/member_zone (list) If this variable is read-only (config: false) in the source YANG file, then _set_member_zone is considered as a private method. Backends looking to populate this variable should do so via callin...
[ "Setter", "method", "for", "member_zone", "mapped", "from", "YANG", "variable", "/", "zoning", "/", "defined_configuration", "/", "cfg", "/", "member_zone", "(", "list", ")", "If", "this", "variable", "is", "read", "-", "only", "(", "config", ":", "false", ...
python
train
130.681818
intelsdi-x/snap-plugin-lib-py
snap_plugin/v1/collector_proxy.py
https://github.com/intelsdi-x/snap-plugin-lib-py/blob/8da5d00ac5f9d2b48a7239563ac7788209891ca4/snap_plugin/v1/collector_proxy.py#L36-L48
def CollectMetrics(self, request, context): """Dispatches the request to the plugins collect method""" LOG.debug("CollectMetrics called") try: metrics_to_collect = [] for metric in request.metrics: metrics_to_collect.append(Metric(pb=metric)) m...
[ "def", "CollectMetrics", "(", "self", ",", "request", ",", "context", ")", ":", "LOG", ".", "debug", "(", "\"CollectMetrics called\"", ")", "try", ":", "metrics_to_collect", "=", "[", "]", "for", "metric", "in", "request", ".", "metrics", ":", "metrics_to_co...
Dispatches the request to the plugins collect method
[ "Dispatches", "the", "request", "to", "the", "plugins", "collect", "method" ]
python
train
48.692308
leancloud/python-sdk
leancloud/push.py
https://github.com/leancloud/python-sdk/blob/fea3240257ce65e6a32c7312a5cee1f94a51a587/leancloud/push.py#L34-L82
def send(data, channels=None, push_time=None, expiration_time=None, expiration_interval=None, where=None, cql=None): """ 发送推送消息。返回结果为此条推送对应的 _Notification 表中的对象,但是如果需要使用其中的数据,需要调用 fetch() 方法将数据同步至本地。 :param channels: 需要推送的频道 :type channels: list or tuple :param push_time: 推送的时间 :type push_time:...
[ "def", "send", "(", "data", ",", "channels", "=", "None", ",", "push_time", "=", "None", ",", "expiration_time", "=", "None", ",", "expiration_interval", "=", "None", ",", "where", "=", "None", ",", "cql", "=", "None", ")", ":", "if", "expiration_interva...
发送推送消息。返回结果为此条推送对应的 _Notification 表中的对象,但是如果需要使用其中的数据,需要调用 fetch() 方法将数据同步至本地。 :param channels: 需要推送的频道 :type channels: list or tuple :param push_time: 推送的时间 :type push_time: datetime :param expiration_time: 消息过期的绝对日期时间 :type expiration_time: datetime :param expiration_interval: 消息过期的相对时间,从...
[ "发送推送消息。返回结果为此条推送对应的", "_Notification", "表中的对象,但是如果需要使用其中的数据,需要调用", "fetch", "()", "方法将数据同步至本地。" ]
python
train
34.918367
lowandrew/OLCTools
accessoryFunctions/resistance.py
https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/accessoryFunctions/resistance.py#L12-L36
def classes(targetpath): """ Uses .tfa files included in the ResFinder database to determine the resistance class of gene matches :param targetpath: Path to database files :return: Dictionary of resistance class: gene set """ # Initialise dictionary to store results ...
[ "def", "classes", "(", "targetpath", ")", ":", "# Initialise dictionary to store results", "resistance_dict", "=", "dict", "(", ")", "# Find all the .tfa files in the folder", "resistance_files", "=", "sorted", "(", "glob", "(", "os", ".", "path", ".", "join", "(", ...
Uses .tfa files included in the ResFinder database to determine the resistance class of gene matches :param targetpath: Path to database files :return: Dictionary of resistance class: gene set
[ "Uses", ".", "tfa", "files", "included", "in", "the", "ResFinder", "database", "to", "determine", "the", "resistance", "class", "of", "gene", "matches", ":", "param", "targetpath", ":", "Path", "to", "database", "files", ":", "return", ":", "Dictionary", "of...
python
train
49.92
HPENetworking/PYHPEIMC
pyhpeimc/plat/system.py
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/system.py#L397-L439
def modify_ssh_template(auth, url, ssh_template, template_name= None, template_id = None): """ Function takes input of a dictionry containing the required key/value pair for the modification of a ssh template. :param auth: :param url: :param ssh_template: Human readable label which is the name ...
[ "def", "modify_ssh_template", "(", "auth", ",", "url", ",", "ssh_template", ",", "template_name", "=", "None", ",", "template_id", "=", "None", ")", ":", "if", "template_name", "is", "None", ":", "template_name", "=", "ssh_template", "[", "'name'", "]", "if"...
Function takes input of a dictionry containing the required key/value pair for the modification of a ssh template. :param auth: :param url: :param ssh_template: Human readable label which is the name of the specific ssh template :param template_id Internal IMC number which designates the specific s...
[ "Function", "takes", "input", "of", "a", "dictionry", "containing", "the", "required", "key", "/", "value", "pair", "for", "the", "modification", "of", "a", "ssh", "template", "." ]
python
train
37.55814
gwastro/pycbc
pycbc/conversions.py
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/conversions.py#L498-L503
def secondary_xi(mass1, mass2, spin1x, spin1y, spin2x, spin2y): """Returns the effective precession spin argument for the smaller mass. """ spinx = secondary_spin(mass1, mass2, spin1x, spin2x) spiny = secondary_spin(mass1, mass2, spin1y, spin2y) return xi2_from_mass1_mass2_spin2x_spin2y(mass1, mass2...
[ "def", "secondary_xi", "(", "mass1", ",", "mass2", ",", "spin1x", ",", "spin1y", ",", "spin2x", ",", "spin2y", ")", ":", "spinx", "=", "secondary_spin", "(", "mass1", ",", "mass2", ",", "spin1x", ",", "spin2x", ")", "spiny", "=", "secondary_spin", "(", ...
Returns the effective precession spin argument for the smaller mass.
[ "Returns", "the", "effective", "precession", "spin", "argument", "for", "the", "smaller", "mass", "." ]
python
train
55
ankeshanand/py-gfycat
gfycat/client.py
https://github.com/ankeshanand/py-gfycat/blob/74759a88fc59db1c5b270331b24442bc5f4c38e9/gfycat/client.py#L41-L69
def upload_from_file(self, filename): """ Upload a local file to Gfycat """ key = str(uuid.uuid4())[:8] form = [('key', key), ('acl', ACL), ('AWSAccessKeyId', AWS_ACCESS_KEY_ID), ('success_action_status', SUCCESS_ACTION_STATUS), ...
[ "def", "upload_from_file", "(", "self", ",", "filename", ")", ":", "key", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "[", ":", "8", "]", "form", "=", "[", "(", "'key'", ",", "key", ")", ",", "(", "'acl'", ",", "ACL", ")", ",", "(",...
Upload a local file to Gfycat
[ "Upload", "a", "local", "file", "to", "Gfycat" ]
python
train
32.758621
mabuchilab/QNET
src/qnet/algebra/pattern_matching/__init__.py
https://github.com/mabuchilab/QNET/blob/cc20d26dad78691d34c67173e5cd67dcac94208a/src/qnet/algebra/pattern_matching/__init__.py#L83-L97
def update(self, *others): """Update dict with entries from `other` If `other` has an attribute ``success=False`` and ``reason``, those attributes are copied as well """ for other in others: for key, val in other.items(): self[key] = val t...
[ "def", "update", "(", "self", ",", "*", "others", ")", ":", "for", "other", "in", "others", ":", "for", "key", ",", "val", "in", "other", ".", "items", "(", ")", ":", "self", "[", "key", "]", "=", "val", "try", ":", "if", "not", "other", ".", ...
Update dict with entries from `other` If `other` has an attribute ``success=False`` and ``reason``, those attributes are copied as well
[ "Update", "dict", "with", "entries", "from", "other" ]
python
train
32.733333
MacHu-GWU/pathlib_mate-project
pathlib_mate/mate_tool_box.py
https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/mate_tool_box.py#L118-L137
def print_big_dir_and_big_file(self, top_n=5): """Print ``top_n`` big dir and ``top_n`` big file in each dir. """ self.assert_is_dir_and_exists() size_table1 = sorted( [(p, p.dirsize) for p in self.select_dir(recursive=False)], key=lambda x: x[1], rev...
[ "def", "print_big_dir_and_big_file", "(", "self", ",", "top_n", "=", "5", ")", ":", "self", ".", "assert_is_dir_and_exists", "(", ")", "size_table1", "=", "sorted", "(", "[", "(", "p", ",", "p", ".", "dirsize", ")", "for", "p", "in", "self", ".", "sele...
Print ``top_n`` big dir and ``top_n`` big file in each dir.
[ "Print", "top_n", "big", "dir", "and", "top_n", "big", "file", "in", "each", "dir", "." ]
python
valid
39.35
invinst/ResponseBot
responsebot/responsebot_client.py
https://github.com/invinst/ResponseBot/blob/a6b1a431a343007f7ae55a193e432a61af22253f/responsebot/responsebot_client.py#L82-L95
def retweet(self, id): """ Retweet a tweet. :param id: ID of the tweet in question :return: True if success, False otherwise """ try: self._client.retweet(id=id) return True except TweepError as e: if e.api_code == TWITTER_PAGE...
[ "def", "retweet", "(", "self", ",", "id", ")", ":", "try", ":", "self", ".", "_client", ".", "retweet", "(", "id", "=", "id", ")", "return", "True", "except", "TweepError", "as", "e", ":", "if", "e", ".", "api_code", "==", "TWITTER_PAGE_DOES_NOT_EXISTS...
Retweet a tweet. :param id: ID of the tweet in question :return: True if success, False otherwise
[ "Retweet", "a", "tweet", "." ]
python
train
26.928571
google/grr
grr/server/grr_response_server/sequential_collection.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/sequential_collection.py#L406-L410
def AddAsMessage(self, rdfvalue_in, source, mutation_pool=None): """Helper method to add rdfvalues as GrrMessages for testing.""" self.Add( rdf_flows.GrrMessage(payload=rdfvalue_in, source=source), mutation_pool=mutation_pool)
[ "def", "AddAsMessage", "(", "self", ",", "rdfvalue_in", ",", "source", ",", "mutation_pool", "=", "None", ")", ":", "self", ".", "Add", "(", "rdf_flows", ".", "GrrMessage", "(", "payload", "=", "rdfvalue_in", ",", "source", "=", "source", ")", ",", "muta...
Helper method to add rdfvalues as GrrMessages for testing.
[ "Helper", "method", "to", "add", "rdfvalues", "as", "GrrMessages", "for", "testing", "." ]
python
train
49.2
briancappello/flask-unchained
flask_unchained/bundles/security/commands/users.py
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/commands/users.py#L168-L179
def add_role_to_user(user, role): """ Add a role to a user. """ user = _query_to_user(user) role = _query_to_role(role) if click.confirm(f'Are you sure you want to add {role!r} to {user!r}?'): user.roles.append(role) user_manager.save(user, commit=True) click.echo(f'Succe...
[ "def", "add_role_to_user", "(", "user", ",", "role", ")", ":", "user", "=", "_query_to_user", "(", "user", ")", "role", "=", "_query_to_role", "(", "role", ")", "if", "click", ".", "confirm", "(", "f'Are you sure you want to add {role!r} to {user!r}?'", ")", ":"...
Add a role to a user.
[ "Add", "a", "role", "to", "a", "user", "." ]
python
train
32.333333