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 |
|---|---|---|---|---|---|---|---|---|---|
wal-e/wal-e | wal_e/blobstore/file/calling_format.py | https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/blobstore/file/calling_format.py#L6-L12 | def remove_empty_dirs(path):
""" removes empty dirs under a given path """
for root, dirs, files in os.walk(path):
for d in dirs:
dir_path = os.path.join(root, d)
if not os.listdir(dir_path):
os.rmdir(dir_path) | [
"def",
"remove_empty_dirs",
"(",
"path",
")",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"for",
"d",
"in",
"dirs",
":",
"dir_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"d",
... | removes empty dirs under a given path | [
"removes",
"empty",
"dirs",
"under",
"a",
"given",
"path"
] | python | train | 37.142857 |
pyQode/pyqode.python | pyqode/python/modes/autoindent.py | https://github.com/pyQode/pyqode.python/blob/821e000ea2e2638a82ce095a559e69afd9bd4f38/pyqode/python/modes/autoindent.py#L301-L309 | def _at_block_start(tc, line):
"""
Improve QTextCursor.atBlockStart to ignore spaces
"""
if tc.atBlockStart():
return True
column = tc.columnNumber()
indentation = len(line) - len(line.lstrip())
return column <= indentation | [
"def",
"_at_block_start",
"(",
"tc",
",",
"line",
")",
":",
"if",
"tc",
".",
"atBlockStart",
"(",
")",
":",
"return",
"True",
"column",
"=",
"tc",
".",
"columnNumber",
"(",
")",
"indentation",
"=",
"len",
"(",
"line",
")",
"-",
"len",
"(",
"line",
... | Improve QTextCursor.atBlockStart to ignore spaces | [
"Improve",
"QTextCursor",
".",
"atBlockStart",
"to",
"ignore",
"spaces"
] | python | valid | 31.444444 |
OpenMath/py-openmath | openmath/helpers.py | https://github.com/OpenMath/py-openmath/blob/4906aa9ccf606f533675c28823772e07c30fd220/openmath/helpers.py#L237-L287 | def interpretAsOpenMath(x):
"""tries to convert a Python object into an OpenMath object
this is not a replacement for using a Converter for exporting Python objects
instead, it is used conveniently building OM objects in DSL embedded in Python
inparticular, it converts Python functions into OMBinding ob... | [
"def",
"interpretAsOpenMath",
"(",
"x",
")",
":",
"if",
"hasattr",
"(",
"x",
",",
"\"_ishelper\"",
")",
"and",
"x",
".",
"_ishelper",
":",
"# wrapped things in this class -> unwrap",
"return",
"x",
".",
"_toOM",
"(",
")",
"elif",
"isinstance",
"(",
"x",
",",... | tries to convert a Python object into an OpenMath object
this is not a replacement for using a Converter for exporting Python objects
instead, it is used conveniently building OM objects in DSL embedded in Python
inparticular, it converts Python functions into OMBinding objects using lambdaOM as the binder | [
"tries",
"to",
"convert",
"a",
"Python",
"object",
"into",
"an",
"OpenMath",
"object",
"this",
"is",
"not",
"a",
"replacement",
"for",
"using",
"a",
"Converter",
"for",
"exporting",
"Python",
"objects",
"instead",
"it",
"is",
"used",
"conveniently",
"building"... | python | test | 36.313725 |
PmagPy/PmagPy | pmagpy/pmag.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmag.py#L10562-L10570 | def adjust_all_to_360(dictionary):
"""
Take a dictionary and check each key/value pair.
If this key is of type: declination/longitude/azimuth/direction,
adjust it to be within 0-360 as required by the MagIC data model
"""
for key in dictionary:
dictionary[key] = adjust_to_360(dictionary[... | [
"def",
"adjust_all_to_360",
"(",
"dictionary",
")",
":",
"for",
"key",
"in",
"dictionary",
":",
"dictionary",
"[",
"key",
"]",
"=",
"adjust_to_360",
"(",
"dictionary",
"[",
"key",
"]",
",",
"key",
")",
"return",
"dictionary"
] | Take a dictionary and check each key/value pair.
If this key is of type: declination/longitude/azimuth/direction,
adjust it to be within 0-360 as required by the MagIC data model | [
"Take",
"a",
"dictionary",
"and",
"check",
"each",
"key",
"/",
"value",
"pair",
".",
"If",
"this",
"key",
"is",
"of",
"type",
":",
"declination",
"/",
"longitude",
"/",
"azimuth",
"/",
"direction",
"adjust",
"it",
"to",
"be",
"within",
"0",
"-",
"360",... | python | train | 38.222222 |
adaptive-learning/proso-apps | proso_common/views.py | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_common/views.py#L29-L43 | def show_one(request, post_process_fun, object_class, id, template='common_json.html'):
"""
Return object of the given type with the specified identifier.
GET parameters:
user:
identifier of the current user
stats:
turn on the enrichment of the objects by some statistics
h... | [
"def",
"show_one",
"(",
"request",
",",
"post_process_fun",
",",
"object_class",
",",
"id",
",",
"template",
"=",
"'common_json.html'",
")",
":",
"obj",
"=",
"get_object_or_404",
"(",
"object_class",
",",
"pk",
"=",
"id",
")",
"json",
"=",
"post_process_fun",
... | Return object of the given type with the specified identifier.
GET parameters:
user:
identifier of the current user
stats:
turn on the enrichment of the objects by some statistics
html
turn on the HTML version of the API | [
"Return",
"object",
"of",
"the",
"given",
"type",
"with",
"the",
"specified",
"identifier",
"."
] | python | train | 35.8 |
ZELLMECHANIK-DRESDEN/dclab | dclab/rtdc_dataset/core.py | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/core.py#L206-L213 | def features(self):
"""All available features"""
mycols = []
for col in dfn.feature_names:
if col in self:
mycols.append(col)
mycols.sort()
return mycols | [
"def",
"features",
"(",
"self",
")",
":",
"mycols",
"=",
"[",
"]",
"for",
"col",
"in",
"dfn",
".",
"feature_names",
":",
"if",
"col",
"in",
"self",
":",
"mycols",
".",
"append",
"(",
"col",
")",
"mycols",
".",
"sort",
"(",
")",
"return",
"mycols"
] | All available features | [
"All",
"available",
"features"
] | python | train | 26.75 |
bureaucratic-labs/models | b_labs_models/segmentation.py | https://github.com/bureaucratic-labs/models/blob/e674c622af883abd094293fb20c325742080577a/b_labs_models/segmentation.py#L76-L98 | def text2labels(text, sents):
'''
Marks all characters in given `text`, that doesn't exists within any
element of `sents` with `1` character, other characters (within sentences)
will be marked with `0`
Used in training process
>>> text = 'привет. меня зовут аня.'
>>> sents = ['привет.', 'мен... | [
"def",
"text2labels",
"(",
"text",
",",
"sents",
")",
":",
"labels",
"=",
"[",
"c",
"for",
"c",
"in",
"text",
"]",
"for",
"sent",
"in",
"sents",
":",
"start",
"=",
"text",
".",
"index",
"(",
"sent",
")",
"finish",
"=",
"start",
"+",
"len",
"(",
... | Marks all characters in given `text`, that doesn't exists within any
element of `sents` with `1` character, other characters (within sentences)
will be marked with `0`
Used in training process
>>> text = 'привет. меня зовут аня.'
>>> sents = ['привет.', 'меня зовут аня.']
>>> labels = text2label... | [
"Marks",
"all",
"characters",
"in",
"given",
"text",
"that",
"doesn",
"t",
"exists",
"within",
"any",
"element",
"of",
"sents",
"with",
"1",
"character",
"other",
"characters",
"(",
"within",
"sentences",
")",
"will",
"be",
"marked",
"with",
"0",
"Used",
"... | python | train | 34.478261 |
rupertford/melody | src/melody/search.py | https://github.com/rupertford/melody/blob/d50459880a87fdd1802c6893f6e12b52d51b3b91/src/melody/search.py#L121-L140 | def _recurse(self, inputs, output):
'''internal recursion routine called by the run method that generates
all input combinations'''
if inputs:
my_input = inputs[0]
name = my_input.name
if my_input.state:
my_options = my_input.options(self.state... | [
"def",
"_recurse",
"(",
"self",
",",
"inputs",
",",
"output",
")",
":",
"if",
"inputs",
":",
"my_input",
"=",
"inputs",
"[",
"0",
"]",
"name",
"=",
"my_input",
".",
"name",
"if",
"my_input",
".",
"state",
":",
"my_options",
"=",
"my_input",
".",
"opt... | internal recursion routine called by the run method that generates
all input combinations | [
"internal",
"recursion",
"routine",
"called",
"by",
"the",
"run",
"method",
"that",
"generates",
"all",
"input",
"combinations"
] | python | test | 38.6 |
spyder-ide/spyder-kernels | spyder_kernels/console/kernel.py | https://github.com/spyder-ide/spyder-kernels/blob/2c5b36cdb797b8aba77bc406ca96f5e079c4aaca/spyder_kernels/console/kernel.py#L274-L280 | def get_source(self, objtxt):
"""Get object source"""
from spyder_kernels.utils.dochelpers import getsource
obj, valid = self._eval(objtxt)
if valid:
return getsource(obj) | [
"def",
"get_source",
"(",
"self",
",",
"objtxt",
")",
":",
"from",
"spyder_kernels",
".",
"utils",
".",
"dochelpers",
"import",
"getsource",
"obj",
",",
"valid",
"=",
"self",
".",
"_eval",
"(",
"objtxt",
")",
"if",
"valid",
":",
"return",
"getsource",
"(... | Get object source | [
"Get",
"object",
"source"
] | python | train | 30 |
PlaidWeb/Publ | publ/category.py | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/category.py#L127-L131 | def description(self):
""" Get the textual description of the category """
if self._meta and self._meta.get_payload():
return utils.TrueCallableProxy(self._description)
return utils.CallableProxy(None) | [
"def",
"description",
"(",
"self",
")",
":",
"if",
"self",
".",
"_meta",
"and",
"self",
".",
"_meta",
".",
"get_payload",
"(",
")",
":",
"return",
"utils",
".",
"TrueCallableProxy",
"(",
"self",
".",
"_description",
")",
"return",
"utils",
".",
"Callable... | Get the textual description of the category | [
"Get",
"the",
"textual",
"description",
"of",
"the",
"category"
] | python | train | 46.6 |
dswah/pyGAM | pygam/links.py | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/links.py#L136-L149 | def gradient(self, mu, dist):
"""
derivative of the link function wrt mu
Parameters
----------
mu : array-like of legth n
dist : Distribution instance
Returns
-------
grad : np.array of length n
"""
return dist.levels/(mu*(dist.le... | [
"def",
"gradient",
"(",
"self",
",",
"mu",
",",
"dist",
")",
":",
"return",
"dist",
".",
"levels",
"/",
"(",
"mu",
"*",
"(",
"dist",
".",
"levels",
"-",
"mu",
")",
")"
] | derivative of the link function wrt mu
Parameters
----------
mu : array-like of legth n
dist : Distribution instance
Returns
-------
grad : np.array of length n | [
"derivative",
"of",
"the",
"link",
"function",
"wrt",
"mu"
] | python | train | 22.714286 |
ndokter/dsmr_parser | dsmr_parser/clients/serial_.py | https://github.com/ndokter/dsmr_parser/blob/c04b0a5add58ce70153eede1a87ca171876b61c7/dsmr_parser/clients/serial_.py#L51-L78 | def read(self, queue):
"""
Read complete DSMR telegram's from the serial interface and parse it
into CosemObject's and MbusObject's.
Instead of being a generator, values are pushed to provided queue for
asynchronous processing.
:rtype: None
"""
# create ... | [
"def",
"read",
"(",
"self",
",",
"queue",
")",
":",
"# create Serial StreamReader",
"conn",
"=",
"serial_asyncio",
".",
"open_serial_connection",
"(",
"*",
"*",
"self",
".",
"serial_settings",
")",
"reader",
",",
"_",
"=",
"yield",
"from",
"conn",
"while",
"... | Read complete DSMR telegram's from the serial interface and parse it
into CosemObject's and MbusObject's.
Instead of being a generator, values are pushed to provided queue for
asynchronous processing.
:rtype: None | [
"Read",
"complete",
"DSMR",
"telegram",
"s",
"from",
"the",
"serial",
"interface",
"and",
"parse",
"it",
"into",
"CosemObject",
"s",
"and",
"MbusObject",
"s",
"."
] | python | test | 37 |
unistra/django-rest-framework-fine-permissions | rest_framework_fine_permissions/management/commands/fine_permissions_load.py | https://github.com/unistra/django-rest-framework-fine-permissions/blob/71af5953648ef9f9bdfb64a4c0ed0ea62661fa61/rest_framework_fine_permissions/management/commands/fine_permissions_load.py#L26-L71 | def handle(self, *args, **options):
"""
dump fields permissions for a user
"""
def get_user(username):
try:
return User.objects.get(username=username)
except ObjectDoesNotExist as e:
raise CommandError("This user doesn't exist in t... | [
"def",
"handle",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"def",
"get_user",
"(",
"username",
")",
":",
"try",
":",
"return",
"User",
".",
"objects",
".",
"get",
"(",
"username",
"=",
"username",
")",
"except",
"ObjectDoesNo... | dump fields permissions for a user | [
"dump",
"fields",
"permissions",
"for",
"a",
"user"
] | python | train | 34.826087 |
davgeo/clear | clear/database.py | https://github.com/davgeo/clear/blob/5ec85d27efd28afddfcd4c3f44df17f0115a77aa/clear/database.py#L711-L715 | def PrintAllTables(self):
""" Prints contents of every table. """
goodlogging.Log.Info("DB", "Database contents:\n")
for table in self._tableDict.keys():
self._PrintDatabaseTable(table) | [
"def",
"PrintAllTables",
"(",
"self",
")",
":",
"goodlogging",
".",
"Log",
".",
"Info",
"(",
"\"DB\"",
",",
"\"Database contents:\\n\"",
")",
"for",
"table",
"in",
"self",
".",
"_tableDict",
".",
"keys",
"(",
")",
":",
"self",
".",
"_PrintDatabaseTable",
"... | Prints contents of every table. | [
"Prints",
"contents",
"of",
"every",
"table",
"."
] | python | train | 39.8 |
saltstack/salt | salt/states/snapper.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/snapper.py#L122-L131 | def _get_baseline_from_tag(config, tag):
'''
Returns the last created baseline snapshot marked with `tag`
'''
last_snapshot = None
for snapshot in __salt__['snapper.list_snapshots'](config):
if tag == snapshot['userdata'].get("baseline_tag"):
if not last_snapshot or last_snapshot... | [
"def",
"_get_baseline_from_tag",
"(",
"config",
",",
"tag",
")",
":",
"last_snapshot",
"=",
"None",
"for",
"snapshot",
"in",
"__salt__",
"[",
"'snapper.list_snapshots'",
"]",
"(",
"config",
")",
":",
"if",
"tag",
"==",
"snapshot",
"[",
"'userdata'",
"]",
"."... | Returns the last created baseline snapshot marked with `tag` | [
"Returns",
"the",
"last",
"created",
"baseline",
"snapshot",
"marked",
"with",
"tag"
] | python | train | 41.5 |
wind-python/windpowerlib | windpowerlib/wind_turbine_cluster.py | https://github.com/wind-python/windpowerlib/blob/421b316139743311b7cb68a69f6b53d2665f7e23/windpowerlib/wind_turbine_cluster.py#L114-L193 | def assign_power_curve(self, wake_losses_model='power_efficiency_curve',
smoothing=False, block_width=0.5,
standard_deviation_method='turbulence_intensity',
smoothing_order='wind_farm_power_curves',
turbulence_in... | [
"def",
"assign_power_curve",
"(",
"self",
",",
"wake_losses_model",
"=",
"'power_efficiency_curve'",
",",
"smoothing",
"=",
"False",
",",
"block_width",
"=",
"0.5",
",",
"standard_deviation_method",
"=",
"'turbulence_intensity'",
",",
"smoothing_order",
"=",
"'wind_farm... | r"""
Calculates the power curve of a wind turbine cluster.
The turbine cluster power curve is calculated by aggregating the wind
farm power curves of wind farms within the turbine cluster. Depending
on the parameters the power curves are smoothed (before or after the
aggregation... | [
"r",
"Calculates",
"the",
"power",
"curve",
"of",
"a",
"wind",
"turbine",
"cluster",
"."
] | python | train | 48.3 |
pgmpy/pgmpy | pgmpy/readwrite/XMLBIF.py | https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/readwrite/XMLBIF.py#L300-L332 | def get_states(self):
"""
Add outcome to variables of XMLBIF
Return
------
dict: dict of type {variable: outcome tags}
Examples
--------
>>> writer = XMLBIFWriter(model)
>>> writer.get_states()
{'dog-out': [<Element OUTCOME at 0x7ffbabfcd... | [
"def",
"get_states",
"(",
"self",
")",
":",
"outcome_tag",
"=",
"{",
"}",
"cpds",
"=",
"self",
".",
"model",
".",
"get_cpds",
"(",
")",
"for",
"cpd",
"in",
"cpds",
":",
"var",
"=",
"cpd",
".",
"variable",
"outcome_tag",
"[",
"var",
"]",
"=",
"[",
... | Add outcome to variables of XMLBIF
Return
------
dict: dict of type {variable: outcome tags}
Examples
--------
>>> writer = XMLBIFWriter(model)
>>> writer.get_states()
{'dog-out': [<Element OUTCOME at 0x7ffbabfcdec8>, <Element OUTCOME at 0x7ffbabfcdf08>]... | [
"Add",
"outcome",
"to",
"variables",
"of",
"XMLBIF"
] | python | train | 40.969697 |
alerta/alerta | alerta/commands.py | https://github.com/alerta/alerta/blob/6478d6addc217c96a4a6688fab841035bef134e1/alerta/commands.py#L78-L110 | def user(username, password, all):
"""Create admin users (BasicAuth only)."""
if current_app.config['AUTH_PROVIDER'] != 'basic':
raise click.UsageError('Not required for {} admin users'.format(current_app.config['AUTH_PROVIDER']))
if username and username not in current_app.config['ADMIN_USERS']:
... | [
"def",
"user",
"(",
"username",
",",
"password",
",",
"all",
")",
":",
"if",
"current_app",
".",
"config",
"[",
"'AUTH_PROVIDER'",
"]",
"!=",
"'basic'",
":",
"raise",
"click",
".",
"UsageError",
"(",
"'Not required for {} admin users'",
".",
"format",
"(",
"... | Create admin users (BasicAuth only). | [
"Create",
"admin",
"users",
"(",
"BasicAuth",
"only",
")",
"."
] | python | train | 36.484848 |
log2timeline/dfdatetime | dfdatetime/fake_time.py | https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/fake_time.py#L37-L53 | def _GetNormalizedTimestamp(self):
"""Retrieves the normalized timestamp.
Returns:
decimal.Decimal: normalized timestamp, which contains the number of
seconds since January 1, 1970 00:00:00 and a fraction of second used
for increased precision, or None if the normalized timestamp cann... | [
"def",
"_GetNormalizedTimestamp",
"(",
"self",
")",
":",
"if",
"self",
".",
"_normalized_timestamp",
"is",
"None",
":",
"if",
"self",
".",
"_number_of_seconds",
"is",
"not",
"None",
":",
"self",
".",
"_normalized_timestamp",
"=",
"(",
"decimal",
".",
"Decimal"... | Retrieves the normalized timestamp.
Returns:
decimal.Decimal: normalized timestamp, which contains the number of
seconds since January 1, 1970 00:00:00 and a fraction of second used
for increased precision, or None if the normalized timestamp cannot be
determined. | [
"Retrieves",
"the",
"normalized",
"timestamp",
"."
] | python | train | 40.235294 |
dailymuse/oz | oz/aws_cdn/__init__.py | https://github.com/dailymuse/oz/blob/4329f6a207dc9d2a8fbeb4d16d415dbe4570b5bd/oz/aws_cdn/__init__.py#L33-L35 | def set_cache_buster(redis, path, hash):
"""Sets the cache buster value for a given file path"""
redis.hset("cache-buster:{}:v3".format(oz.settings["s3_bucket"]), path, hash) | [
"def",
"set_cache_buster",
"(",
"redis",
",",
"path",
",",
"hash",
")",
":",
"redis",
".",
"hset",
"(",
"\"cache-buster:{}:v3\"",
".",
"format",
"(",
"oz",
".",
"settings",
"[",
"\"s3_bucket\"",
"]",
")",
",",
"path",
",",
"hash",
")"
] | Sets the cache buster value for a given file path | [
"Sets",
"the",
"cache",
"buster",
"value",
"for",
"a",
"given",
"file",
"path"
] | python | train | 60 |
inonit/drf-haystack | drf_haystack/serializers.py | https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/drf_haystack/serializers.py#L340-L360 | def get_narrow_url(self, instance):
"""
Return a link suitable for narrowing on the current item.
"""
text = instance[0]
request = self.context["request"]
query_params = request.GET.copy()
# Never keep the page query parameter in narrowing urls.
# It will... | [
"def",
"get_narrow_url",
"(",
"self",
",",
"instance",
")",
":",
"text",
"=",
"instance",
"[",
"0",
"]",
"request",
"=",
"self",
".",
"context",
"[",
"\"request\"",
"]",
"query_params",
"=",
"request",
".",
"GET",
".",
"copy",
"(",
")",
"# Never keep the... | Return a link suitable for narrowing on the current item. | [
"Return",
"a",
"link",
"suitable",
"for",
"narrowing",
"on",
"the",
"current",
"item",
"."
] | python | train | 48.761905 |
sphinx-gallery/sphinx-gallery | sphinx_gallery/scrapers.py | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/scrapers.py#L58-L101 | def matplotlib_scraper(block, block_vars, gallery_conf, **kwargs):
"""Scrape Matplotlib images.
Parameters
----------
block : tuple
A tuple containing the (label, content, line_number) of the block.
block_vars : dict
Dict of block variables.
gallery_conf : dict
Contains ... | [
"def",
"matplotlib_scraper",
"(",
"block",
",",
"block_vars",
",",
"gallery_conf",
",",
"*",
"*",
"kwargs",
")",
":",
"matplotlib",
",",
"plt",
"=",
"_import_matplotlib",
"(",
")",
"image_path_iterator",
"=",
"block_vars",
"[",
"'image_path_iterator'",
"]",
"ima... | Scrape Matplotlib images.
Parameters
----------
block : tuple
A tuple containing the (label, content, line_number) of the block.
block_vars : dict
Dict of block variables.
gallery_conf : dict
Contains the configuration of Sphinx-Gallery
**kwargs : dict
Additional... | [
"Scrape",
"Matplotlib",
"images",
"."
] | python | train | 41.681818 |
MIT-LCP/wfdb-python | wfdb/io/download.py | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/io/download.py#L352-L368 | def dl_full_file(url, save_file_name):
"""
Download a file. No checks are performed.
Parameters
----------
url : str
The url of the file to download
save_file_name : str
The name to save the file as
"""
response = requests.get(url)
with open(save_file_name, 'wb') as... | [
"def",
"dl_full_file",
"(",
"url",
",",
"save_file_name",
")",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
")",
"with",
"open",
"(",
"save_file_name",
",",
"'wb'",
")",
"as",
"writefile",
":",
"writefile",
".",
"write",
"(",
"response",
"."... | Download a file. No checks are performed.
Parameters
----------
url : str
The url of the file to download
save_file_name : str
The name to save the file as | [
"Download",
"a",
"file",
".",
"No",
"checks",
"are",
"performed",
"."
] | python | train | 21.705882 |
pypa/pipenv | pipenv/vendor/urllib3/connection.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/connection.py#L145-L170 | def _new_conn(self):
""" Establish a socket connection and set nodelay settings on it.
:return: New socket connection.
"""
extra_kw = {}
if self.source_address:
extra_kw['source_address'] = self.source_address
if self.socket_options:
extra_kw['so... | [
"def",
"_new_conn",
"(",
"self",
")",
":",
"extra_kw",
"=",
"{",
"}",
"if",
"self",
".",
"source_address",
":",
"extra_kw",
"[",
"'source_address'",
"]",
"=",
"self",
".",
"source_address",
"if",
"self",
".",
"socket_options",
":",
"extra_kw",
"[",
"'socke... | Establish a socket connection and set nodelay settings on it.
:return: New socket connection. | [
"Establish",
"a",
"socket",
"connection",
"and",
"set",
"nodelay",
"settings",
"on",
"it",
"."
] | python | train | 31.576923 |
pypa/pipenv | pipenv/vendor/click/_bashcomplete.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/_bashcomplete.py#L172-L191 | def get_user_autocompletions(ctx, args, incomplete, cmd_param):
"""
:param ctx: context associated with the parsed command
:param args: full list of args
:param incomplete: the incomplete text to autocomplete
:param cmd_param: command definition
:return: all the possible user-specified completio... | [
"def",
"get_user_autocompletions",
"(",
"ctx",
",",
"args",
",",
"incomplete",
",",
"cmd_param",
")",
":",
"results",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"cmd_param",
".",
"type",
",",
"Choice",
")",
":",
"# Choices don't support descriptions.",
"results",
... | :param ctx: context associated with the parsed command
:param args: full list of args
:param incomplete: the incomplete text to autocomplete
:param cmd_param: command definition
:return: all the possible user-specified completions for the param | [
":",
"param",
"ctx",
":",
"context",
"associated",
"with",
"the",
"parsed",
"command",
":",
"param",
"args",
":",
"full",
"list",
"of",
"args",
":",
"param",
"incomplete",
":",
"the",
"incomplete",
"text",
"to",
"autocomplete",
":",
"param",
"cmd_param",
"... | python | train | 46.4 |
bitesofcode/projexui | projexui/widgets/xorbquerywidget/xorbqueryentrywidget.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbquerywidget/xorbqueryentrywidget.py#L107-L124 | def assignEditor(self):
"""
Assigns the editor for this entry based on the plugin.
"""
plugin = self.currentPlugin()
column = self.currentColumn()
value = self.currentValue()
if not plugin:
self.setEditor(None)
return
... | [
"def",
"assignEditor",
"(",
"self",
")",
":",
"plugin",
"=",
"self",
".",
"currentPlugin",
"(",
")",
"column",
"=",
"self",
".",
"currentColumn",
"(",
")",
"value",
"=",
"self",
".",
"currentValue",
"(",
")",
"if",
"not",
"plugin",
":",
"self",
".",
... | Assigns the editor for this entry based on the plugin. | [
"Assigns",
"the",
"editor",
"for",
"this",
"entry",
"based",
"on",
"the",
"plugin",
"."
] | python | train | 31.666667 |
mailgun/talon | talon/signature/learning/helpers.py | https://github.com/mailgun/talon/blob/cdd84563dd329c4f887591807870d10015e0c7a7/talon/signature/learning/helpers.py#L127-L147 | def extract_names(sender):
"""Tries to extract sender's names from `From:` header.
It could extract not only the actual names but e.g.
the name of the company, parts of email, etc.
>>> extract_names('Sergey N. Obukhov <serobnic@mail.ru>')
['Sergey', 'Obukhov', 'serobnic']
>>> extract_names(''... | [
"def",
"extract_names",
"(",
"sender",
")",
":",
"sender",
"=",
"to_unicode",
"(",
"sender",
",",
"precise",
"=",
"True",
")",
"# Remove non-alphabetical characters",
"sender",
"=",
"\"\"",
".",
"join",
"(",
"[",
"char",
"if",
"char",
".",
"isalpha",
"(",
... | Tries to extract sender's names from `From:` header.
It could extract not only the actual names but e.g.
the name of the company, parts of email, etc.
>>> extract_names('Sergey N. Obukhov <serobnic@mail.ru>')
['Sergey', 'Obukhov', 'serobnic']
>>> extract_names('')
[] | [
"Tries",
"to",
"extract",
"sender",
"s",
"names",
"from",
"From",
":",
"header",
"."
] | python | train | 36.809524 |
redcap-tools/PyCap | redcap/project.py | https://github.com/redcap-tools/PyCap/blob/f44c9b62a4f62675aa609c06608663f37e12097e/redcap/project.py#L384-L420 | def filter(self, query, output_fields=None):
"""Query the database and return subject information for those
who match the query logic
Parameters
----------
query: Query or QueryGroup
Query(Group) object to process
output_fields: list
The fields de... | [
"def",
"filter",
"(",
"self",
",",
"query",
",",
"output_fields",
"=",
"None",
")",
":",
"query_keys",
"=",
"query",
".",
"fields",
"(",
")",
"if",
"not",
"set",
"(",
"query_keys",
")",
".",
"issubset",
"(",
"set",
"(",
"self",
".",
"field_names",
")... | Query the database and return subject information for those
who match the query logic
Parameters
----------
query: Query or QueryGroup
Query(Group) object to process
output_fields: list
The fields desired for matching subjects
Returns
---... | [
"Query",
"the",
"database",
"and",
"return",
"subject",
"information",
"for",
"those",
"who",
"match",
"the",
"query",
"logic"
] | python | train | 43.081081 |
konstantinstadler/pymrio | pymrio/core/mriosystem.py | https://github.com/konstantinstadler/pymrio/blob/d764aa0dd2150200e867a9713a98ddae203e12d4/pymrio/core/mriosystem.py#L83-L124 | def reset_full(self, force=False, _meta=None):
""" Remove all accounts which can be recalculated based on Z, Y, F, FY
Parameters
----------
force: boolean, optional
If True, reset to flows although the system can not be
recalculated. Default: False
_met... | [
"def",
"reset_full",
"(",
"self",
",",
"force",
"=",
"False",
",",
"_meta",
"=",
"None",
")",
":",
"# Attriubtes to keep must be defined in the init: __basic__",
"strwarn",
"=",
"None",
"for",
"df",
"in",
"self",
".",
"__basic__",
":",
"if",
"(",
"getattr",
"(... | Remove all accounts which can be recalculated based on Z, Y, F, FY
Parameters
----------
force: boolean, optional
If True, reset to flows although the system can not be
recalculated. Default: False
_meta: MRIOMetaData, optional
Metadata handler for ... | [
"Remove",
"all",
"accounts",
"which",
"can",
"be",
"recalculated",
"based",
"on",
"Z",
"Y",
"F",
"FY"
] | python | train | 35.880952 |
DataONEorg/d1_python | gmn/src/d1_gmn/app/did.py | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/did.py#L200-L204 | def is_unprocessed_local_replica(pid):
"""Is local replica with status "queued"."""
return d1_gmn.app.models.LocalReplica.objects.filter(
pid__did=pid, info__status__status='queued'
).exists() | [
"def",
"is_unprocessed_local_replica",
"(",
"pid",
")",
":",
"return",
"d1_gmn",
".",
"app",
".",
"models",
".",
"LocalReplica",
".",
"objects",
".",
"filter",
"(",
"pid__did",
"=",
"pid",
",",
"info__status__status",
"=",
"'queued'",
")",
".",
"exists",
"("... | Is local replica with status "queued". | [
"Is",
"local",
"replica",
"with",
"status",
"queued",
"."
] | python | train | 41.6 |
zabuldon/teslajsonpy | teslajsonpy/vehicle.py | https://github.com/zabuldon/teslajsonpy/blob/673ecdb5c9483160fb1b97e30e62f2c863761c39/teslajsonpy/vehicle.py#L59-L65 | def assumed_state(self):
# pylint: disable=protected-access
"""Return whether the data is from an online vehicle."""
return (not self._controller.car_online[self.id()] and
(self._controller._last_update_time[self.id()] -
self._controller._last_wake_up_time[self.i... | [
"def",
"assumed_state",
"(",
"self",
")",
":",
"# pylint: disable=protected-access",
"return",
"(",
"not",
"self",
".",
"_controller",
".",
"car_online",
"[",
"self",
".",
"id",
"(",
")",
"]",
"and",
"(",
"self",
".",
"_controller",
".",
"_last_update_time",
... | Return whether the data is from an online vehicle. | [
"Return",
"whether",
"the",
"data",
"is",
"from",
"an",
"online",
"vehicle",
"."
] | python | train | 53.142857 |
bsolomon1124/pyfinance | pyfinance/ols.py | https://github.com/bsolomon1124/pyfinance/blob/c95925209a809b4e648e79cbeaf7711d8e5ff1a6/pyfinance/ols.py#L421-L426 | def _std_err(self):
"""Standard error of the estimate (SEE). A scalar.
For standard errors of parameters, see _se_all, se_alpha, and se_beta.
"""
return np.sqrt(np.sum(np.square(self._resids), axis=1) / self._df_err) | [
"def",
"_std_err",
"(",
"self",
")",
":",
"return",
"np",
".",
"sqrt",
"(",
"np",
".",
"sum",
"(",
"np",
".",
"square",
"(",
"self",
".",
"_resids",
")",
",",
"axis",
"=",
"1",
")",
"/",
"self",
".",
"_df_err",
")"
] | Standard error of the estimate (SEE). A scalar.
For standard errors of parameters, see _se_all, se_alpha, and se_beta. | [
"Standard",
"error",
"of",
"the",
"estimate",
"(",
"SEE",
")",
".",
"A",
"scalar",
".",
"For",
"standard",
"errors",
"of",
"parameters",
"see",
"_se_all",
"se_alpha",
"and",
"se_beta",
"."
] | python | train | 41.666667 |
libChEBI/libChEBIpy | libchebipy/_parsers.py | https://github.com/libChEBI/libChEBIpy/blob/89f223a91f518619d5e3910070d283adcac1626e/libchebipy/_parsers.py#L91-L96 | def get_charge(chebi_id):
'''Returns charge'''
if len(__CHARGES) == 0:
__parse_chemical_data()
return __CHARGES[chebi_id] if chebi_id in __CHARGES else float('NaN') | [
"def",
"get_charge",
"(",
"chebi_id",
")",
":",
"if",
"len",
"(",
"__CHARGES",
")",
"==",
"0",
":",
"__parse_chemical_data",
"(",
")",
"return",
"__CHARGES",
"[",
"chebi_id",
"]",
"if",
"chebi_id",
"in",
"__CHARGES",
"else",
"float",
"(",
"'NaN'",
")"
] | Returns charge | [
"Returns",
"charge"
] | python | train | 30 |
RI-imaging/qpsphere | qpsphere/models/_bhfield/wrap.py | https://github.com/RI-imaging/qpsphere/blob/3cfa0e9fb8e81be8c820abbeccd47242e7972ac1/qpsphere/models/_bhfield/wrap.py#L224-L303 | def run_simulation(wdir, arp=True, **kwargs):
"""
Example
-------
100-nm silica sphere with 10-nm thick Ag coating,
embedded in water; arprec 20 digits; illuminated with YAG (1064nm);
scan xz plane (21x21, +-200nm)
bhfield-arp-db.exe mpdigit wl r_core r_coat
n_grid_x ... | [
"def",
"run_simulation",
"(",
"wdir",
",",
"arp",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"wdir",
"=",
"pathlib",
".",
"Path",
"(",
"wdir",
")",
"cmd",
"=",
"\"{pathbhfield} {mpdigit} {wl:f} {r_core:f} {r_coat:f} \"",
"+",
"\"{n_grid_x:d} {xspan_min:f} {xs... | Example
-------
100-nm silica sphere with 10-nm thick Ag coating,
embedded in water; arprec 20 digits; illuminated with YAG (1064nm);
scan xz plane (21x21, +-200nm)
bhfield-arp-db.exe mpdigit wl r_core r_coat
n_grid_x xspan_min xspan_max
n_grid_y yspan_... | [
"Example",
"-------",
"100",
"-",
"nm",
"silica",
"sphere",
"with",
"10",
"-",
"nm",
"thick",
"Ag",
"coating",
"embedded",
"in",
"water",
";",
"arprec",
"20",
"digits",
";",
"illuminated",
"with",
"YAG",
"(",
"1064nm",
")",
";",
"scan",
"xz",
"plane",
... | python | train | 34.0625 |
pydata/xarray | xarray/core/dataset.py | https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/core/dataset.py#L485-L520 | def load(self: T, **kwargs) -> T:
"""Manually trigger loading of this dataset's data from disk or a
remote source into memory and return this dataset.
Normally, it should not be necessary to call this method in user code,
because all xarray functions should either work on deferred data ... | [
"def",
"load",
"(",
"self",
":",
"T",
",",
"*",
"*",
"kwargs",
")",
"->",
"T",
":",
"# access .data to coerce everything to numpy or dask arrays",
"lazy_data",
"=",
"{",
"k",
":",
"v",
".",
"_data",
"for",
"k",
",",
"v",
"in",
"self",
".",
"variables",
"... | Manually trigger loading of this dataset's data from disk or a
remote source into memory and return this dataset.
Normally, it should not be necessary to call this method in user code,
because all xarray functions should either work on deferred data or
load data automatically. However, ... | [
"Manually",
"trigger",
"loading",
"of",
"this",
"dataset",
"s",
"data",
"from",
"disk",
"or",
"a",
"remote",
"source",
"into",
"memory",
"and",
"return",
"this",
"dataset",
"."
] | python | train | 35.75 |
jmcarp/flask-apispec | flask_apispec/annotations.py | https://github.com/jmcarp/flask-apispec/blob/d8cb658fa427f051568e58d6af201b8e9924c325/flask_apispec/annotations.py#L8-L38 | def use_kwargs(args, locations=None, inherit=None, apply=None, **kwargs):
"""Inject keyword arguments from the specified webargs arguments into the
decorated view function.
Usage:
.. code-block:: python
from marshmallow import fields
@use_kwargs({'name': fields.Str(), 'category': fie... | [
"def",
"use_kwargs",
"(",
"args",
",",
"locations",
"=",
"None",
",",
"inherit",
"=",
"None",
",",
"apply",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"update",
"(",
"{",
"'locations'",
":",
"locations",
"}",
")",
"def",
"wrapper"... | Inject keyword arguments from the specified webargs arguments into the
decorated view function.
Usage:
.. code-block:: python
from marshmallow import fields
@use_kwargs({'name': fields.Str(), 'category': fields.Str()})
def get_pets(**kwargs):
return Pet.query.filter_b... | [
"Inject",
"keyword",
"arguments",
"from",
"the",
"specified",
"webargs",
"arguments",
"into",
"the",
"decorated",
"view",
"function",
"."
] | python | train | 34.645161 |
sdispater/poetry | poetry/masonry/publishing/uploader.py | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/masonry/publishing/uploader.py#L256-L282 | def _register(self, session, url):
"""
Register a package to a repository.
"""
dist = self._poetry.file.parent / "dist"
file = dist / "{}-{}.tar.gz".format(
self._package.name, normalize_version(self._package.version.text)
)
if not file.exists():
... | [
"def",
"_register",
"(",
"self",
",",
"session",
",",
"url",
")",
":",
"dist",
"=",
"self",
".",
"_poetry",
".",
"file",
".",
"parent",
"/",
"\"dist\"",
"file",
"=",
"dist",
"/",
"\"{}-{}.tar.gz\"",
".",
"format",
"(",
"self",
".",
"_package",
".",
"... | Register a package to a repository. | [
"Register",
"a",
"package",
"to",
"a",
"repository",
"."
] | python | train | 29.518519 |
dlintott/gns3-converter | gns3converter/node.py | https://github.com/dlintott/gns3-converter/blob/acbc55da51de86388dc5b5f6da55809b3c86b7ca/gns3converter/node.py#L402-L410 | def set_description(self):
"""
Set the node description
"""
if self.device_info['type'] == 'Router':
self.node['description'] = '%s %s' % (self.device_info['type'],
self.device_info['model'])
else:
self.nod... | [
"def",
"set_description",
"(",
"self",
")",
":",
"if",
"self",
".",
"device_info",
"[",
"'type'",
"]",
"==",
"'Router'",
":",
"self",
".",
"node",
"[",
"'description'",
"]",
"=",
"'%s %s'",
"%",
"(",
"self",
".",
"device_info",
"[",
"'type'",
"]",
",",... | Set the node description | [
"Set",
"the",
"node",
"description"
] | python | train | 39.444444 |
loads/molotov | molotov/util.py | https://github.com/loads/molotov/blob/bd2c94e7f250e1fbb21940f02c68b4437655bc11/molotov/util.py#L203-L208 | def json_request(endpoint, verb='GET', session_options=None, **options):
"""Like :func:`molotov.request` but extracts json from the response.
"""
req = functools.partial(_request, endpoint, verb, session_options,
json=True, **options)
return _run_in_fresh_loop(req) | [
"def",
"json_request",
"(",
"endpoint",
",",
"verb",
"=",
"'GET'",
",",
"session_options",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"req",
"=",
"functools",
".",
"partial",
"(",
"_request",
",",
"endpoint",
",",
"verb",
",",
"session_options",
",... | Like :func:`molotov.request` but extracts json from the response. | [
"Like",
":",
"func",
":",
"molotov",
".",
"request",
"but",
"extracts",
"json",
"from",
"the",
"response",
"."
] | python | train | 50.666667 |
Jammy2211/PyAutoLens | autolens/lens/plane.py | https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/lens/plane.py#L490-L493 | def trace_to_next_plane(self):
"""Trace the positions to the next plane."""
return list(map(lambda positions, deflections: np.subtract(positions, deflections),
self.positions, self.deflections)) | [
"def",
"trace_to_next_plane",
"(",
"self",
")",
":",
"return",
"list",
"(",
"map",
"(",
"lambda",
"positions",
",",
"deflections",
":",
"np",
".",
"subtract",
"(",
"positions",
",",
"deflections",
")",
",",
"self",
".",
"positions",
",",
"self",
".",
"de... | Trace the positions to the next plane. | [
"Trace",
"the",
"positions",
"to",
"the",
"next",
"plane",
"."
] | python | valid | 57.75 |
EUDAT-B2SAFE/B2HANDLE | b2handle/handlesystemconnector.py | https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handlesystemconnector.py#L447-L482 | def check_if_username_exists(self, username):
'''
Check if the username handles exists.
:param username: The username, in the form index:prefix/suffix
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.GenericHandleError`... | [
"def",
"check_if_username_exists",
"(",
"self",
",",
"username",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'check_if_username_exists...'",
")",
"_",
",",
"handle",
"=",
"b2handle",
".",
"utilhandle",
".",
"remove_index_from_handle",
"(",
"username",
")",
"resp",
"... | Check if the username handles exists.
:param username: The username, in the form index:prefix/suffix
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.GenericHandleError`
:return: True. If it does not exist, an exception is rais... | [
"Check",
"if",
"the",
"username",
"handles",
"exists",
"."
] | python | train | 45.861111 |
Alignak-monitoring/alignak | alignak/objects/host.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/host.py#L319-L350 | def is_correct(self):
"""Check if this object configuration is correct ::
* Check our own specific properties
* Call our parent class is_correct checker
:return: True if the configuration is correct, otherwise False
:rtype: bool
"""
state = True
# Inter... | [
"def",
"is_correct",
"(",
"self",
")",
":",
"state",
"=",
"True",
"# Internal checks before executing inherited function...",
"cls",
"=",
"self",
".",
"__class__",
"if",
"hasattr",
"(",
"self",
",",
"'host_name'",
")",
":",
"for",
"char",
"in",
"cls",
".",
"il... | Check if this object configuration is correct ::
* Check our own specific properties
* Call our parent class is_correct checker
:return: True if the configuration is correct, otherwise False
:rtype: bool | [
"Check",
"if",
"this",
"object",
"configuration",
"is",
"correct",
"::"
] | python | train | 44.375 |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py#L597-L604 | def AddMethod(self, function, name=None):
"""
Adds the specified function as a method of this construction
environment with the specified name. If the name is omitted,
the default name is the name of the function itself.
"""
method = MethodWrapper(self, function, name)
... | [
"def",
"AddMethod",
"(",
"self",
",",
"function",
",",
"name",
"=",
"None",
")",
":",
"method",
"=",
"MethodWrapper",
"(",
"self",
",",
"function",
",",
"name",
")",
"self",
".",
"added_methods",
".",
"append",
"(",
"method",
")"
] | Adds the specified function as a method of this construction
environment with the specified name. If the name is omitted,
the default name is the name of the function itself. | [
"Adds",
"the",
"specified",
"function",
"as",
"a",
"method",
"of",
"this",
"construction",
"environment",
"with",
"the",
"specified",
"name",
".",
"If",
"the",
"name",
"is",
"omitted",
"the",
"default",
"name",
"is",
"the",
"name",
"of",
"the",
"function",
... | python | train | 44.125 |
gitpython-developers/smmap | smmap/mman.py | https://github.com/gitpython-developers/smmap/blob/48e9e30b0ef3c24ac7ed88e6e3bfa37dc945bf4c/smmap/mman.py#L225-L233 | def fd(self):
""":return: file descriptor used to create the underlying mapping.
**Note:** it is not required to be valid anymore
:raise ValueError: if the mapping was not created by a file descriptor"""
if isinstance(self._rlist.path_or_fd(), string_types()):
raise ValueErr... | [
"def",
"fd",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"_rlist",
".",
"path_or_fd",
"(",
")",
",",
"string_types",
"(",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"File descriptor queried although mapping was generated from path\"",
")",
"# ... | :return: file descriptor used to create the underlying mapping.
**Note:** it is not required to be valid anymore
:raise ValueError: if the mapping was not created by a file descriptor | [
":",
"return",
":",
"file",
"descriptor",
"used",
"to",
"create",
"the",
"underlying",
"mapping",
"."
] | python | train | 49.777778 |
FlorianRhiem/pyGLFW | glfw/__init__.py | https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L632-L646 | def get_version():
"""
Retrieves the version of the GLFW library.
Wrapper for:
void glfwGetVersion(int* major, int* minor, int* rev);
"""
major_value = ctypes.c_int(0)
major = ctypes.pointer(major_value)
minor_value = ctypes.c_int(0)
minor = ctypes.pointer(minor_value)
rev_v... | [
"def",
"get_version",
"(",
")",
":",
"major_value",
"=",
"ctypes",
".",
"c_int",
"(",
"0",
")",
"major",
"=",
"ctypes",
".",
"pointer",
"(",
"major_value",
")",
"minor_value",
"=",
"ctypes",
".",
"c_int",
"(",
"0",
")",
"minor",
"=",
"ctypes",
".",
"... | Retrieves the version of the GLFW library.
Wrapper for:
void glfwGetVersion(int* major, int* minor, int* rev); | [
"Retrieves",
"the",
"version",
"of",
"the",
"GLFW",
"library",
"."
] | python | train | 31.533333 |
django-dbbackup/django-dbbackup | dbbackup/management/commands/mediabackup.py | https://github.com/django-dbbackup/django-dbbackup/blob/77de209e2d5317e51510d0f888e085ee0c400d66/dbbackup/management/commands/mediabackup.py#L59-L68 | def _explore_storage(self):
"""Generator of all files contained in media storage."""
path = ''
dirs = [path]
while dirs:
path = dirs.pop()
subdirs, files = self.media_storage.listdir(path)
for media_filename in files:
yield os.path.join... | [
"def",
"_explore_storage",
"(",
"self",
")",
":",
"path",
"=",
"''",
"dirs",
"=",
"[",
"path",
"]",
"while",
"dirs",
":",
"path",
"=",
"dirs",
".",
"pop",
"(",
")",
"subdirs",
",",
"files",
"=",
"self",
".",
"media_storage",
".",
"listdir",
"(",
"p... | Generator of all files contained in media storage. | [
"Generator",
"of",
"all",
"files",
"contained",
"in",
"media",
"storage",
"."
] | python | train | 40.9 |
linuxsoftware/ls.joyous | ls/joyous/models/events.py | https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/events.py#L1003-L1026 | def status(self):
"""
The current status of the event (started, finished or pending).
"""
myNow = timezone.localtime(timezone=self.tz)
daysDelta = dt.timedelta(days=self.num_days - 1)
# NB: postponements can be created after the until date
# so ignore that
... | [
"def",
"status",
"(",
"self",
")",
":",
"myNow",
"=",
"timezone",
".",
"localtime",
"(",
"timezone",
"=",
"self",
".",
"tz",
")",
"daysDelta",
"=",
"dt",
".",
"timedelta",
"(",
"days",
"=",
"self",
".",
"num_days",
"-",
"1",
")",
"# NB: postponements c... | The current status of the event (started, finished or pending). | [
"The",
"current",
"status",
"of",
"the",
"event",
"(",
"started",
"finished",
"or",
"pending",
")",
"."
] | python | train | 46.5 |
aio-libs/aioredis | aioredis/commands/string.py | https://github.com/aio-libs/aioredis/blob/e8c33e39558d4cc91cf70dde490d8b330c97dc2e/aioredis/commands/string.py#L200-L212 | def setbit(self, key, offset, value):
"""Sets or clears the bit at offset in the string value stored at key.
:raises TypeError: if offset is not int
:raises ValueError: if offset is less than 0 or value is not 0 or 1
"""
if not isinstance(offset, int):
raise TypeErro... | [
"def",
"setbit",
"(",
"self",
",",
"key",
",",
"offset",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"offset",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"offset argument must be int\"",
")",
"if",
"offset",
"<",
"0",
":",
"raise",
... | Sets or clears the bit at offset in the string value stored at key.
:raises TypeError: if offset is not int
:raises ValueError: if offset is less than 0 or value is not 0 or 1 | [
"Sets",
"or",
"clears",
"the",
"bit",
"at",
"offset",
"in",
"the",
"string",
"value",
"stored",
"at",
"key",
"."
] | python | train | 45.076923 |
pywavefront/PyWavefront | pywavefront/material.py | https://github.com/pywavefront/PyWavefront/blob/39ee5186cb37750d4654d19ebe43f723ecd01e2f/pywavefront/material.py#L217-L220 | def parse_map_Ka(self):
"""Ambient map"""
Kd = os.path.join(self.dir, " ".join(self.values[1:]))
self.this_material.set_texture_ambient(Kd) | [
"def",
"parse_map_Ka",
"(",
"self",
")",
":",
"Kd",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"dir",
",",
"\" \"",
".",
"join",
"(",
"self",
".",
"values",
"[",
"1",
":",
"]",
")",
")",
"self",
".",
"this_material",
".",
"set_texture... | Ambient map | [
"Ambient",
"map"
] | python | train | 40 |
mitsei/dlkit | dlkit/json_/authorization/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/authorization/sessions.py#L3099-L3115 | def get_parent_vault_ids(self, vault_id):
"""Gets the parent ``Ids`` of the given vault.
arg: vault_id (osid.id.Id): a vault ``Id``
return: (osid.id.IdList) - the parent ``Ids`` of the vault
raise: NotFound - ``vault_id`` is not found
raise: NullArgument - ``vault_id`` is `... | [
"def",
"get_parent_vault_ids",
"(",
"self",
",",
"vault_id",
")",
":",
"# Implemented from template for",
"# osid.resource.BinHierarchySession.get_parent_bin_ids",
"if",
"self",
".",
"_catalog_session",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_catalog_session",
... | Gets the parent ``Ids`` of the given vault.
arg: vault_id (osid.id.Id): a vault ``Id``
return: (osid.id.IdList) - the parent ``Ids`` of the vault
raise: NotFound - ``vault_id`` is not found
raise: NullArgument - ``vault_id`` is ``null``
raise: OperationFailed - unable to c... | [
"Gets",
"the",
"parent",
"Ids",
"of",
"the",
"given",
"vault",
"."
] | python | train | 47.588235 |
numenta/htmresearch | projects/nik/nik_htm.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/nik/nik_htm.py#L284-L289 | def load(self, filename="temp.pkl"):
"""
Save TM in the filename specified above
"""
inputFile = open(filename, 'rb')
self.tm = cPickle.load(inputFile) | [
"def",
"load",
"(",
"self",
",",
"filename",
"=",
"\"temp.pkl\"",
")",
":",
"inputFile",
"=",
"open",
"(",
"filename",
",",
"'rb'",
")",
"self",
".",
"tm",
"=",
"cPickle",
".",
"load",
"(",
"inputFile",
")"
] | Save TM in the filename specified above | [
"Save",
"TM",
"in",
"the",
"filename",
"specified",
"above"
] | python | train | 27.666667 |
ambitioninc/rabbitmq-admin | rabbitmq_admin/api.py | https://github.com/ambitioninc/rabbitmq-admin/blob/ff65054115f19991da153f0e4f4e45e526545fea/rabbitmq_admin/api.py#L123-L132 | def list_connection_channels(self, name):
"""
List of all channels for a given connection.
:param name: The connection name
:type name: str
"""
return self._api_get('/api/connections/{0}/channels'.format(
urllib.parse.quote_plus(name)
)) | [
"def",
"list_connection_channels",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"_api_get",
"(",
"'/api/connections/{0}/channels'",
".",
"format",
"(",
"urllib",
".",
"parse",
".",
"quote_plus",
"(",
"name",
")",
")",
")"
] | List of all channels for a given connection.
:param name: The connection name
:type name: str | [
"List",
"of",
"all",
"channels",
"for",
"a",
"given",
"connection",
"."
] | python | train | 29.7 |
DataDog/integrations-core | tokumx/datadog_checks/tokumx/vendor/bson/__init__.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/tokumx/datadog_checks/tokumx/vendor/bson/__init__.py#L137-L155 | def _get_object(data, position, obj_end, opts, dummy):
"""Decode a BSON subdocument to opts.document_class or bson.dbref.DBRef."""
obj_size = _UNPACK_INT(data[position:position + 4])[0]
end = position + obj_size - 1
if data[end:position + obj_size] != b"\x00":
raise InvalidBSON("bad eoo")
if... | [
"def",
"_get_object",
"(",
"data",
",",
"position",
",",
"obj_end",
",",
"opts",
",",
"dummy",
")",
":",
"obj_size",
"=",
"_UNPACK_INT",
"(",
"data",
"[",
"position",
":",
"position",
"+",
"4",
"]",
")",
"[",
"0",
"]",
"end",
"=",
"position",
"+",
... | Decode a BSON subdocument to opts.document_class or bson.dbref.DBRef. | [
"Decode",
"a",
"BSON",
"subdocument",
"to",
"opts",
".",
"document_class",
"or",
"bson",
".",
"dbref",
".",
"DBRef",
"."
] | python | train | 40.842105 |
six8/corona-cipr | src/cipr/commands/core.py | https://github.com/six8/corona-cipr/blob/a2f45761080c874afa39bf95fd5c4467c8eae272/src/cipr/commands/core.py#L206-L264 | def build(env, ciprcfg, console):
"""
Build the current project for distribution
"""
os.putenv('CIPR_PACKAGES', env.package_dir)
os.putenv('CIPR_PROJECT', env.project_directory)
build_settings = path.join(env.project_directory, 'build.settings')
with open(build_settings, 'r') as f:
... | [
"def",
"build",
"(",
"env",
",",
"ciprcfg",
",",
"console",
")",
":",
"os",
".",
"putenv",
"(",
"'CIPR_PACKAGES'",
",",
"env",
".",
"package_dir",
")",
"os",
".",
"putenv",
"(",
"'CIPR_PROJECT'",
",",
"env",
".",
"project_directory",
")",
"build_settings",... | Build the current project for distribution | [
"Build",
"the",
"current",
"project",
"for",
"distribution"
] | python | train | 30.084746 |
MolSSI-BSE/basis_set_exchange | basis_set_exchange/lut.py | https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/lut.py#L198-L224 | def amchar_to_int(amchar, hij=False):
'''Convert an angular momentum integer to a character
The return value is a list of integers (to handle sp, spd, ... orbitals)
For example, converts 'p' to [1] and 'sp' to [0,1]
If hij is True, the ordering spdfghijkl is used. Otherwise, the
ordering will be ... | [
"def",
"amchar_to_int",
"(",
"amchar",
",",
"hij",
"=",
"False",
")",
":",
"if",
"hij",
":",
"amchar_map",
"=",
"_amchar_map_hij",
"else",
":",
"amchar_map",
"=",
"_amchar_map_hik",
"amchar_lower",
"=",
"amchar",
".",
"lower",
"(",
")",
"amint",
"=",
"[",
... | Convert an angular momentum integer to a character
The return value is a list of integers (to handle sp, spd, ... orbitals)
For example, converts 'p' to [1] and 'sp' to [0,1]
If hij is True, the ordering spdfghijkl is used. Otherwise, the
ordering will be spdfghikl (skipping j) | [
"Convert",
"an",
"angular",
"momentum",
"integer",
"to",
"a",
"character"
] | python | train | 25.037037 |
eaton-lab/toytree | toytree/Multitree.py | https://github.com/eaton-lab/toytree/blob/0347ed2098acc5f707fadf52a0ecd411a6d1859c/toytree/Multitree.py#L201-L280 | def draw_tree_grid(self,
nrows=None,
ncols=None,
start=0,
fixed_order=False,
shared_axis=False,
**kwargs):
"""
Draw a slice of x*y trees into a x,y grid non-overlapping.
Parameters:
-----------
x (int):
N... | [
"def",
"draw_tree_grid",
"(",
"self",
",",
"nrows",
"=",
"None",
",",
"ncols",
"=",
"None",
",",
"start",
"=",
"0",
",",
"fixed_order",
"=",
"False",
",",
"shared_axis",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# return nothing if tree is empty",
... | Draw a slice of x*y trees into a x,y grid non-overlapping.
Parameters:
-----------
x (int):
Number of grid cells in x dimension. Default=automatically set.
y (int):
Number of grid cells in y dimension. Default=automatically set.
start (int):
... | [
"Draw",
"a",
"slice",
"of",
"x",
"*",
"y",
"trees",
"into",
"a",
"x",
"y",
"grid",
"non",
"-",
"overlapping",
"."
] | python | train | 30.9375 |
hozn/coilmq | coilmq/start.py | https://github.com/hozn/coilmq/blob/76b7fcf347144b3a5746423a228bed121dc564b5/coilmq/start.py#L207-L216 | def main(config, host, port, logfile, debug, daemon, uid, gid, pidfile, umask, rundir):
"""
Main entry point for running a socket server from the commandline.
This method will read in options from the commandline and call the L{config.init_config} method
to get everything setup. Then, depending on whe... | [
"def",
"main",
"(",
"config",
",",
"host",
",",
"port",
",",
"logfile",
",",
"debug",
",",
"daemon",
",",
"uid",
",",
"gid",
",",
"pidfile",
",",
"umask",
",",
"rundir",
")",
":",
"_main",
"(",
"*",
"*",
"locals",
"(",
")",
")"
] | Main entry point for running a socket server from the commandline.
This method will read in options from the commandline and call the L{config.init_config} method
to get everything setup. Then, depending on whether deamon mode was specified or not,
the process may be forked (or not) and the server will b... | [
"Main",
"entry",
"point",
"for",
"running",
"a",
"socket",
"server",
"from",
"the",
"commandline",
"."
] | python | train | 45.2 |
saltstack/salt | salt/states/virt.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/virt.py#L187-L210 | def stopped(name, connection=None, username=None, password=None):
'''
Stops a VM by shutting it down nicely.
.. versionadded:: 2016.3.0
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
... | [
"def",
"stopped",
"(",
"name",
",",
"connection",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"return",
"_virt_call",
"(",
"name",
",",
"'shutdown'",
",",
"'stopped'",
",",
"\"Machine has been shut down\"",
",",
"connec... | Stops a VM by shutting it down nicely.
.. versionadded:: 2016.3.0
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
.. versionadded:: 2019.2.0
:param password: password to connect w... | [
"Stops",
"a",
"VM",
"by",
"shutting",
"it",
"down",
"nicely",
"."
] | python | train | 28.291667 |
kensho-technologies/graphql-compiler | graphql_compiler/compiler/emit_sql.py | https://github.com/kensho-technologies/graphql-compiler/blob/f6079c6d10f64932f6b3af309b79bcea2123ca8f/graphql_compiler/compiler/emit_sql.py#L75-L90 | def _create_table_and_update_context(node, context):
"""Create an aliased table for a SqlNode.
Updates the relevant Selectable global context.
Args:
node: SqlNode, the current node.
context: CompilationContext, global compilation state and metadata.
Returns:
Table, the newly a... | [
"def",
"_create_table_and_update_context",
"(",
"node",
",",
"context",
")",
":",
"schema_type_name",
"=",
"sql_context_helpers",
".",
"get_schema_type_name",
"(",
"node",
",",
"context",
")",
"table",
"=",
"context",
".",
"compiler_metadata",
".",
"get_table",
"(",... | Create an aliased table for a SqlNode.
Updates the relevant Selectable global context.
Args:
node: SqlNode, the current node.
context: CompilationContext, global compilation state and metadata.
Returns:
Table, the newly aliased SQLAlchemy table. | [
"Create",
"an",
"aliased",
"table",
"for",
"a",
"SqlNode",
"."
] | python | train | 35.5625 |
PaloAltoNetworks/pancloud | pancloud/directorysync.py | https://github.com/PaloAltoNetworks/pancloud/blob/c51e4c8aca3c988c60f062291007534edcb55285/pancloud/directorysync.py#L61-L86 | def attributes(self, **kwargs): # pragma: no cover
"""Retrieve the attribute configuration object.
Retrieves a mapping that identifies the custom directory
attributes configured for the Directory SyncService instance,
and the mapping of the custom attributes to standard directory
... | [
"def",
"attributes",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# pragma: no cover",
"path",
"=",
"\"/directory-sync-service/v1/attributes\"",
"r",
"=",
"self",
".",
"_httpclient",
".",
"request",
"(",
"method",
"=",
"\"GET\"",
",",
"path",
"=",
"path",
... | Retrieve the attribute configuration object.
Retrieves a mapping that identifies the custom directory
attributes configured for the Directory SyncService instance,
and the mapping of the custom attributes to standard directory
attributes.
Args:
**kwargs: Supported :... | [
"Retrieve",
"the",
"attribute",
"configuration",
"object",
"."
] | python | train | 30.730769 |
rocky/python-uncompyle6 | uncompyle6/semantics/fragments.py | https://github.com/rocky/python-uncompyle6/blob/c5d7944e657f0ad05a0e2edd34e1acb27001abc0/uncompyle6/semantics/fragments.py#L1858-L1884 | def code_deparse_around_offset(name, offset, co, out=StringIO(),
version=None, is_pypy=None,
debug_opts=DEFAULT_DEBUG_OPTS):
"""
Like deparse_code(), but given a function/module name and
offset, finds the node closest to offset. If offset is not... | [
"def",
"code_deparse_around_offset",
"(",
"name",
",",
"offset",
",",
"co",
",",
"out",
"=",
"StringIO",
"(",
")",
",",
"version",
"=",
"None",
",",
"is_pypy",
"=",
"None",
",",
"debug_opts",
"=",
"DEFAULT_DEBUG_OPTS",
")",
":",
"assert",
"iscode",
"(",
... | Like deparse_code(), but given a function/module name and
offset, finds the node closest to offset. If offset is not an instruction boundary,
we raise an IndexError. | [
"Like",
"deparse_code",
"()",
"but",
"given",
"a",
"function",
"/",
"module",
"name",
"and",
"offset",
"finds",
"the",
"node",
"closest",
"to",
"offset",
".",
"If",
"offset",
"is",
"not",
"an",
"instruction",
"boundary",
"we",
"raise",
"an",
"IndexError",
... | python | train | 36.740741 |
wonambi-python/wonambi | wonambi/trans/extern/dpss.py | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/extern/dpss.py#L8-L133 | def dpss_windows(N, NW, Kmax, interp_from=None, interp_kind='linear'):
"""
Returns the Discrete Prolate Spheroidal Sequences of orders [0,Kmax-1]
for a given frequency-spacing multiple NW and sequence length N.
Parameters
----------
N : int
sequence length
NW : float, unitless
... | [
"def",
"dpss_windows",
"(",
"N",
",",
"NW",
",",
"Kmax",
",",
"interp_from",
"=",
"None",
",",
"interp_kind",
"=",
"'linear'",
")",
":",
"Kmax",
"=",
"int",
"(",
"Kmax",
")",
"W",
"=",
"float",
"(",
"NW",
")",
"/",
"N",
"nidx",
"=",
"np",
".",
... | Returns the Discrete Prolate Spheroidal Sequences of orders [0,Kmax-1]
for a given frequency-spacing multiple NW and sequence length N.
Parameters
----------
N : int
sequence length
NW : float, unitless
standardized half bandwidth corresponding to 2NW = BW/f0 = BW*N*dt
but w... | [
"Returns",
"the",
"Discrete",
"Prolate",
"Spheroidal",
"Sequences",
"of",
"orders",
"[",
"0",
"Kmax",
"-",
"1",
"]",
"for",
"a",
"given",
"frequency",
"-",
"spacing",
"multiple",
"NW",
"and",
"sequence",
"length",
"N",
"."
] | python | train | 40.285714 |
numenta/nupic | src/nupic/regions/record_sensor.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/record_sensor.py#L507-L533 | def _convertNonNumericData(self, spatialOutput, temporalOutput, output):
"""
Converts all of the non-numeric fields from spatialOutput and temporalOutput
into their scalar equivalents and records them in the output dictionary.
:param spatialOutput: The results of topDownCompute() for the spatial input.... | [
"def",
"_convertNonNumericData",
"(",
"self",
",",
"spatialOutput",
",",
"temporalOutput",
",",
"output",
")",
":",
"encoders",
"=",
"self",
".",
"encoder",
".",
"getEncoderList",
"(",
")",
"types",
"=",
"self",
".",
"encoder",
".",
"getDecoderOutputFieldTypes",... | Converts all of the non-numeric fields from spatialOutput and temporalOutput
into their scalar equivalents and records them in the output dictionary.
:param spatialOutput: The results of topDownCompute() for the spatial input.
:param temporalOutput: The results of topDownCompute() for the temporal
in... | [
"Converts",
"all",
"of",
"the",
"non",
"-",
"numeric",
"fields",
"from",
"spatialOutput",
"and",
"temporalOutput",
"into",
"their",
"scalar",
"equivalents",
"and",
"records",
"them",
"in",
"the",
"output",
"dictionary",
"."
] | python | valid | 47.259259 |
ga4gh/ga4gh-server | ga4gh/server/datarepo.py | https://github.com/ga4gh/ga4gh-server/blob/1aa18922ef136db8604f6f098cb1732cba6f2a76/ga4gh/server/datarepo.py#L154-L160 | def getOntology(self, id_):
"""
Returns the ontology with the specified ID.
"""
if id_ not in self._ontologyIdMap:
raise exceptions.OntologyNotFoundException(id_)
return self._ontologyIdMap[id_] | [
"def",
"getOntology",
"(",
"self",
",",
"id_",
")",
":",
"if",
"id_",
"not",
"in",
"self",
".",
"_ontologyIdMap",
":",
"raise",
"exceptions",
".",
"OntologyNotFoundException",
"(",
"id_",
")",
"return",
"self",
".",
"_ontologyIdMap",
"[",
"id_",
"]"
] | Returns the ontology with the specified ID. | [
"Returns",
"the",
"ontology",
"with",
"the",
"specified",
"ID",
"."
] | python | train | 34.285714 |
aaugustin/websockets | src/websockets/headers.py | https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/headers.py#L354-L366 | def parse_subprotocol_item(
header: str, pos: int, header_name: str
) -> Tuple[Subprotocol, int]:
"""
Parse a subprotocol from ``header`` at the given position.
Return the subprotocol value and the new position.
Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs.
"""
... | [
"def",
"parse_subprotocol_item",
"(",
"header",
":",
"str",
",",
"pos",
":",
"int",
",",
"header_name",
":",
"str",
")",
"->",
"Tuple",
"[",
"Subprotocol",
",",
"int",
"]",
":",
"item",
",",
"pos",
"=",
"parse_token",
"(",
"header",
",",
"pos",
",",
... | Parse a subprotocol from ``header`` at the given position.
Return the subprotocol value and the new position.
Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs. | [
"Parse",
"a",
"subprotocol",
"from",
"header",
"at",
"the",
"given",
"position",
"."
] | python | train | 30.692308 |
fprimex/zdesk | zdesk/zdesk_api.py | https://github.com/fprimex/zdesk/blob/851611c13b4d530e9df31390b3ec709baf0a0188/zdesk/zdesk_api.py#L2586-L2590 | def organization_requests(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/requests#list-requests"
api_path = "/api/v2/organizations/{id}/requests.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | [
"def",
"organization_requests",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/organizations/{id}/requests.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"id",
"=",
"id",
")",
"return",
"self",
".",
"call",
... | https://developer.zendesk.com/rest_api/docs/core/requests#list-requests | [
"https",
":",
"//",
"developer",
".",
"zendesk",
".",
"com",
"/",
"rest_api",
"/",
"docs",
"/",
"core",
"/",
"requests#list",
"-",
"requests"
] | python | train | 54.6 |
getpelican/pelican-plugins | libravatar/libravatar.py | https://github.com/getpelican/pelican-plugins/blob/cfc7a3f224f1743063b034561f89a6a712d13587/libravatar/libravatar.py#L29-L61 | def add_libravatar (generator, metadata):
"""Article generator connector for the Libravatar plugin"""
missing = generator.settings.get ('LIBRAVATAR_MISSING')
size = generator.settings.get ('LIBRAVATAR_SIZE')
## Check the presence of the Email header
if 'email' not in metadata.keys ():
try:
... | [
"def",
"add_libravatar",
"(",
"generator",
",",
"metadata",
")",
":",
"missing",
"=",
"generator",
".",
"settings",
".",
"get",
"(",
"'LIBRAVATAR_MISSING'",
")",
"size",
"=",
"generator",
".",
"settings",
".",
"get",
"(",
"'LIBRAVATAR_SIZE'",
")",
"## Check th... | Article generator connector for the Libravatar plugin | [
"Article",
"generator",
"connector",
"for",
"the",
"Libravatar",
"plugin"
] | python | train | 33.545455 |
pywavefront/PyWavefront | pywavefront/mesh.py | https://github.com/pywavefront/PyWavefront/blob/39ee5186cb37750d4654d19ebe43f723ecd01e2f/pywavefront/mesh.py#L61-L66 | def add_material(self, material):
"""Add a material to the mesh, IF it's not already present."""
if self.has_material(material):
return
self.materials.append(material) | [
"def",
"add_material",
"(",
"self",
",",
"material",
")",
":",
"if",
"self",
".",
"has_material",
"(",
"material",
")",
":",
"return",
"self",
".",
"materials",
".",
"append",
"(",
"material",
")"
] | Add a material to the mesh, IF it's not already present. | [
"Add",
"a",
"material",
"to",
"the",
"mesh",
"IF",
"it",
"s",
"not",
"already",
"present",
"."
] | python | train | 33.166667 |
mapillary/mapillary_tools | mapillary_tools/exif_write.py | https://github.com/mapillary/mapillary_tools/blob/816785e90c589cae6e8e34a5530ce8417d29591c/mapillary_tools/exif_write.py#L57-L59 | def add_image_history(self, data):
"""Add arbitrary string to ImageHistory tag."""
self._ef['0th'][piexif.ImageIFD.ImageHistory] = json.dumps(data) | [
"def",
"add_image_history",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_ef",
"[",
"'0th'",
"]",
"[",
"piexif",
".",
"ImageIFD",
".",
"ImageHistory",
"]",
"=",
"json",
".",
"dumps",
"(",
"data",
")"
] | Add arbitrary string to ImageHistory tag. | [
"Add",
"arbitrary",
"string",
"to",
"ImageHistory",
"tag",
"."
] | python | train | 53.666667 |
luckydonald/pytgbot | code_generation/code_generator_template.py | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/code_generator_template.py#L52-L82 | def clazz(clazz, parent_clazz, description, link, params_string, init_super_args=None):
"""
Live template for pycharm:
y = clazz(clazz="$clazz$", parent_clazz="%parent$", description="$description$", link="$lnk$", params_string="$first_param$")
"""
variables_needed = []
variables_optional = []
... | [
"def",
"clazz",
"(",
"clazz",
",",
"parent_clazz",
",",
"description",
",",
"link",
",",
"params_string",
",",
"init_super_args",
"=",
"None",
")",
":",
"variables_needed",
"=",
"[",
"]",
"variables_optional",
"=",
"[",
"]",
"imports",
"=",
"set",
"(",
")"... | Live template for pycharm:
y = clazz(clazz="$clazz$", parent_clazz="%parent$", description="$description$", link="$lnk$", params_string="$first_param$") | [
"Live",
"template",
"for",
"pycharm",
":"
] | python | train | 38.967742 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/nose/util.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/util.py#L595-L626 | def transplant_func(func, module):
"""
Make a function imported from module A appear as if it is located
in module B.
>>> from pprint import pprint
>>> pprint.__module__
'pprint'
>>> pp = transplant_func(pprint, __name__)
>>> pp.__module__
'nose.util'
The original function is n... | [
"def",
"transplant_func",
"(",
"func",
",",
"module",
")",
":",
"from",
"nose",
".",
"tools",
"import",
"make_decorator",
"def",
"newfunc",
"(",
"*",
"arg",
",",
"*",
"*",
"kw",
")",
":",
"return",
"func",
"(",
"*",
"arg",
",",
"*",
"*",
"kw",
")",... | Make a function imported from module A appear as if it is located
in module B.
>>> from pprint import pprint
>>> pprint.__module__
'pprint'
>>> pp = transplant_func(pprint, __name__)
>>> pp.__module__
'nose.util'
The original function is not modified.
>>> pprint.__module__
'pp... | [
"Make",
"a",
"function",
"imported",
"from",
"module",
"A",
"appear",
"as",
"if",
"it",
"is",
"located",
"in",
"module",
"B",
"."
] | python | test | 21 |
common-workflow-language/cwltool | cwltool/utils.py | https://github.com/common-workflow-language/cwltool/blob/cb81b22abc52838823da9945f04d06739ab32fda/cwltool/utils.py#L233-L238 | def random_outdir(): # type: () -> Text
""" Return the random directory name chosen to use for tool / workflow output """
# compute this once and store it as a function attribute - each subsequent call will return the same value
if not hasattr(random_outdir, 'outdir'):
random_outdir.outdir = '/' + ... | [
"def",
"random_outdir",
"(",
")",
":",
"# type: () -> Text",
"# compute this once and store it as a function attribute - each subsequent call will return the same value",
"if",
"not",
"hasattr",
"(",
"random_outdir",
",",
"'outdir'",
")",
":",
"random_outdir",
".",
"outdir",
"=... | Return the random directory name chosen to use for tool / workflow output | [
"Return",
"the",
"random",
"directory",
"name",
"chosen",
"to",
"use",
"for",
"tool",
"/",
"workflow",
"output"
] | python | train | 72.666667 |
materialsproject/pymatgen | pymatgen/analysis/chemenv/coordination_environments/voronoi.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/chemenv/coordination_environments/voronoi.py#L750-L768 | def from_dict(cls, d):
"""
Reconstructs the VoronoiContainer object from a dict representation of the VoronoiContainer created using
the as_dict method.
:param d: dict representation of the VoronoiContainer object
:return: VoronoiContainer object
"""
structure = S... | [
"def",
"from_dict",
"(",
"cls",
",",
"d",
")",
":",
"structure",
"=",
"Structure",
".",
"from_dict",
"(",
"d",
"[",
"'structure'",
"]",
")",
"voronoi_list2",
"=",
"from_bson_voronoi_list2",
"(",
"d",
"[",
"'bson_nb_voro_list2'",
"]",
",",
"structure",
")",
... | Reconstructs the VoronoiContainer object from a dict representation of the VoronoiContainer created using
the as_dict method.
:param d: dict representation of the VoronoiContainer object
:return: VoronoiContainer object | [
"Reconstructs",
"the",
"VoronoiContainer",
"object",
"from",
"a",
"dict",
"representation",
"of",
"the",
"VoronoiContainer",
"created",
"using",
"the",
"as_dict",
"method",
".",
":",
"param",
"d",
":",
"dict",
"representation",
"of",
"the",
"VoronoiContainer",
"ob... | python | train | 60.736842 |
PythonicNinja/pydrill | pydrill/client/__init__.py | https://github.com/PythonicNinja/pydrill/blob/0713e78c84d44cd438018e4ba1588a8e242f78c4/pydrill/client/__init__.py#L193-L211 | def storage_update(self, name, config, timeout=10):
"""
Create or update a storage plugin configuration.
:param name: The name of the storage plugin configuration to create or update.
:param config: Overwrites the existing configuration if there is any, and therefore, must include all
... | [
"def",
"storage_update",
"(",
"self",
",",
"name",
",",
"config",
",",
"timeout",
"=",
"10",
")",
":",
"result",
"=",
"Result",
"(",
"*",
"self",
".",
"perform_request",
"(",
"*",
"*",
"{",
"'method'",
":",
"'POST'",
",",
"'url'",
":",
"'/storage/{0}.j... | Create or update a storage plugin configuration.
:param name: The name of the storage plugin configuration to create or update.
:param config: Overwrites the existing configuration if there is any, and therefore, must include all
required attributes and definitions.
:param timeout: int
... | [
"Create",
"or",
"update",
"a",
"storage",
"plugin",
"configuration",
"."
] | python | train | 36.842105 |
jgorset/django-respite | respite/utils/parsers.py | https://github.com/jgorset/django-respite/blob/719469d11baf91d05917bab1623bd82adc543546/respite/utils/parsers.py#L31-L62 | def parse_http_accept_header(header):
"""
Return a list of content types listed in the HTTP Accept header
ordered by quality.
:param header: A string describing the contents of the HTTP Accept header.
"""
components = [item.strip() for item in header.split(',')]
l = []
for component in... | [
"def",
"parse_http_accept_header",
"(",
"header",
")",
":",
"components",
"=",
"[",
"item",
".",
"strip",
"(",
")",
"for",
"item",
"in",
"header",
".",
"split",
"(",
"','",
")",
"]",
"l",
"=",
"[",
"]",
"for",
"component",
"in",
"components",
":",
"i... | Return a list of content types listed in the HTTP Accept header
ordered by quality.
:param header: A string describing the contents of the HTTP Accept header. | [
"Return",
"a",
"list",
"of",
"content",
"types",
"listed",
"in",
"the",
"HTTP",
"Accept",
"header",
"ordered",
"by",
"quality",
"."
] | python | train | 25.46875 |
MisterY/gnucash-portfolio | gnucash_portfolio/currencies.py | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/currencies.py#L132-L173 | def import_fx_rates(self, rates: List[PriceModel]):
""" Imports the given prices into database. Write operation! """
have_new_rates = False
base_currency = self.get_default_currency()
for rate in rates:
assert isinstance(rate, PriceModel)
currency = self.get_by... | [
"def",
"import_fx_rates",
"(",
"self",
",",
"rates",
":",
"List",
"[",
"PriceModel",
"]",
")",
":",
"have_new_rates",
"=",
"False",
"base_currency",
"=",
"self",
".",
"get_default_currency",
"(",
")",
"for",
"rate",
"in",
"rates",
":",
"assert",
"isinstance"... | Imports the given prices into database. Write operation! | [
"Imports",
"the",
"given",
"prices",
"into",
"database",
".",
"Write",
"operation!"
] | python | train | 40.738095 |
5monkeys/django-bananas | bananas/__init__.py | https://github.com/5monkeys/django-bananas/blob/cfd318c737f6c4580036c13d2acf32bca96654bf/bananas/__init__.py#L4-L24 | def get_version(version=None):
"""Derives a PEP386-compliant version number from VERSION."""
if version is None:
version = VERSION
assert len(version) == 5
assert version[3] in ("alpha", "beta", "rc", "final")
# Now build the two parts of the version number:
# main = X.Y[.Z]
# sub =... | [
"def",
"get_version",
"(",
"version",
"=",
"None",
")",
":",
"if",
"version",
"is",
"None",
":",
"version",
"=",
"VERSION",
"assert",
"len",
"(",
"version",
")",
"==",
"5",
"assert",
"version",
"[",
"3",
"]",
"in",
"(",
"\"alpha\"",
",",
"\"beta\"",
... | Derives a PEP386-compliant version number from VERSION. | [
"Derives",
"a",
"PEP386",
"-",
"compliant",
"version",
"number",
"from",
"VERSION",
"."
] | python | test | 31.238095 |
amperser/proselint | proselint/checks/mixed_metaphors/misc.py | https://github.com/amperser/proselint/blob/cb619ee4023cc7856f5fb96aec2a33a2c9f1a2e2/proselint/checks/mixed_metaphors/misc.py#L9-L27 | def check_bottleneck(text):
"""Avoid mixing metaphors about bottles and their necks.
source: Sir Ernest Gowers
source_url: http://bit.ly/1CQPH61
"""
err = "mixed_metaphors.misc.bottleneck"
msg = u"Mixed metaphor — bottles with big necks are easy to pass through."
list = [
"bigge... | [
"def",
"check_bottleneck",
"(",
"text",
")",
":",
"err",
"=",
"\"mixed_metaphors.misc.bottleneck\"",
"msg",
"=",
"u\"Mixed metaphor — bottles with big necks are easy to pass through.\"",
"list",
"=",
"[",
"\"biggest bottleneck\"",
",",
"\"big bottleneck\"",
",",
"\"large bottle... | Avoid mixing metaphors about bottles and their necks.
source: Sir Ernest Gowers
source_url: http://bit.ly/1CQPH61 | [
"Avoid",
"mixing",
"metaphors",
"about",
"bottles",
"and",
"their",
"necks",
"."
] | python | train | 29.526316 |
mohamedattahri/PyXMLi | pyxmli/__init__.py | https://github.com/mohamedattahri/PyXMLi/blob/a81a245be822d62f1a20c734ca14b42c786ae81e/pyxmli/__init__.py#L423-L441 | def to_xml(self, name="address"):
'''
Returns a DOM Element containing the XML representation of the
address.
@return:Element
'''
for n, v in {"street_address": self.street_address, "city": self.city,
"country": self.country}.items():
if i... | [
"def",
"to_xml",
"(",
"self",
",",
"name",
"=",
"\"address\"",
")",
":",
"for",
"n",
",",
"v",
"in",
"{",
"\"street_address\"",
":",
"self",
".",
"street_address",
",",
"\"city\"",
":",
"self",
".",
"city",
",",
"\"country\"",
":",
"self",
".",
"countr... | Returns a DOM Element containing the XML representation of the
address.
@return:Element | [
"Returns",
"a",
"DOM",
"Element",
"containing",
"the",
"XML",
"representation",
"of",
"the",
"address",
"."
] | python | train | 43 |
google/pyringe | pyringe/plugins/gdb_shell.py | https://github.com/google/pyringe/blob/76dff5d1ac29cd5e7bf32677654a83291a15ad8a/pyringe/plugins/gdb_shell.py#L38-L48 | def StartGdb(self):
"""Hands control over to a new gdb process."""
if self.inferior.is_running:
self.inferior.ShutDownGdb()
program_arg = 'program %d ' % self.inferior.pid
else:
program_arg = ''
os.system('gdb ' + program_arg + ' '.join(self.gdb_args))
reset_position = raw_input('R... | [
"def",
"StartGdb",
"(",
"self",
")",
":",
"if",
"self",
".",
"inferior",
".",
"is_running",
":",
"self",
".",
"inferior",
".",
"ShutDownGdb",
"(",
")",
"program_arg",
"=",
"'program %d '",
"%",
"self",
".",
"inferior",
".",
"pid",
"else",
":",
"program_a... | Hands control over to a new gdb process. | [
"Hands",
"control",
"over",
"to",
"a",
"new",
"gdb",
"process",
"."
] | python | train | 40.727273 |
improbable-research/keanu | keanu-python/keanu/vertex/generated.py | https://github.com/improbable-research/keanu/blob/73189a8f569078e156168e795f82c7366c59574b/keanu-python/keanu/vertex/generated.py#L393-L399 | def ArcSin(input_vertex: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
"""
Takes the inverse sin of a vertex, Arcsin(vertex)
:param input_vertex: the vertex
"""
return Double(context.jvm_view().ArcSinVertex, label, cast_to_double_vertex(input_vertex)) | [
"def",
"ArcSin",
"(",
"input_vertex",
":",
"vertex_constructor_param_types",
",",
"label",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"Vertex",
":",
"return",
"Double",
"(",
"context",
".",
"jvm_view",
"(",
")",
".",
"ArcSinVertex",
",",
"la... | Takes the inverse sin of a vertex, Arcsin(vertex)
:param input_vertex: the vertex | [
"Takes",
"the",
"inverse",
"sin",
"of",
"a",
"vertex",
"Arcsin",
"(",
"vertex",
")",
":",
"param",
"input_vertex",
":",
"the",
"vertex"
] | python | train | 42 |
tariqdaouda/pyGeno | pyGeno/tools/Stats.py | https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/Stats.py#L3-L11 | def kullback_leibler(p, q) :
"""Discrete Kullback-Leibler divergence D(P||Q)"""
p = np.asarray(p, dtype=np.float)
q = np.asarray(q, dtype=np.float)
if p.shape != q.shape :
raise ValueError("p and q must be of the same dimensions")
return np.sum(np.where(p > 0, np.log(p / q) * p, 0)) | [
"def",
"kullback_leibler",
"(",
"p",
",",
"q",
")",
":",
"p",
"=",
"np",
".",
"asarray",
"(",
"p",
",",
"dtype",
"=",
"np",
".",
"float",
")",
"q",
"=",
"np",
".",
"asarray",
"(",
"q",
",",
"dtype",
"=",
"np",
".",
"float",
")",
"if",
"p",
... | Discrete Kullback-Leibler divergence D(P||Q) | [
"Discrete",
"Kullback",
"-",
"Leibler",
"divergence",
"D",
"(",
"P||Q",
")"
] | python | train | 31.666667 |
saltstack/salt | salt/modules/boto3_elasticache.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_elasticache.py#L675-L687 | def delete_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Delete a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_security_group myelasticachesg
'''
return _delete_resource(name, name_param='Ca... | [
"def",
"delete_cache_security_group",
"(",
"name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"args",
")",
":",
"return",
"_delete_resource",
"(",
"name",
",",
"name_param",... | Delete a cache security group.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.delete_cache_security_group myelasticachesg | [
"Delete",
"a",
"cache",
"security",
"group",
"."
] | python | train | 39.230769 |
trailofbits/manticore | manticore/native/cpu/x86.py | https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L3205-L3212 | def JCXZ(cpu, target):
"""
Jumps short if CX register is 0.
:param cpu: current CPU.
:param target: destination operand.
"""
cpu.PC = Operators.ITEBV(cpu.address_bit_size, cpu.CX == 0, target.read(), cpu.PC) | [
"def",
"JCXZ",
"(",
"cpu",
",",
"target",
")",
":",
"cpu",
".",
"PC",
"=",
"Operators",
".",
"ITEBV",
"(",
"cpu",
".",
"address_bit_size",
",",
"cpu",
".",
"CX",
"==",
"0",
",",
"target",
".",
"read",
"(",
")",
",",
"cpu",
".",
"PC",
")"
] | Jumps short if CX register is 0.
:param cpu: current CPU.
:param target: destination operand. | [
"Jumps",
"short",
"if",
"CX",
"register",
"is",
"0",
"."
] | python | valid | 31.125 |
robin900/gspread-dataframe | gspread_dataframe.py | https://github.com/robin900/gspread-dataframe/blob/b64fef7ec196bfed69362aa35c593f448830a735/gspread_dataframe.py#L118-L135 | def get_as_dataframe(worksheet,
evaluate_formulas=False,
**options):
"""
Returns the worksheet contents as a DataFrame.
:param worksheet: the worksheet.
:param evaluate_formulas: if True, get the value of a cell after
formula evaluation; otherwise g... | [
"def",
"get_as_dataframe",
"(",
"worksheet",
",",
"evaluate_formulas",
"=",
"False",
",",
"*",
"*",
"options",
")",
":",
"all_values",
"=",
"_get_all_values",
"(",
"worksheet",
",",
"evaluate_formulas",
")",
"return",
"TextParser",
"(",
"all_values",
",",
"*",
... | Returns the worksheet contents as a DataFrame.
:param worksheet: the worksheet.
:param evaluate_formulas: if True, get the value of a cell after
formula evaluation; otherwise get the formula itself if present.
Defaults to False.
:param \*\*options: all the options for pandas.io.pars... | [
"Returns",
"the",
"worksheet",
"contents",
"as",
"a",
"DataFrame",
"."
] | python | train | 42.888889 |
eyeseast/python-tablefu | table_fu/formatting.py | https://github.com/eyeseast/python-tablefu/blob/d8761c1f87e3f89d9b89b0b6b9283fc4738b6676/table_fu/formatting.py#L163-L173 | def ratio(value, decimal_places=0, failure_string='N/A'):
"""
Converts a floating point value a X:1 ratio.
Number of decimal places set by the `precision` kwarg. Default is one.
"""
try:
f = float(value)
except ValueError:
return failure_string
return _saferound(f, decim... | [
"def",
"ratio",
"(",
"value",
",",
"decimal_places",
"=",
"0",
",",
"failure_string",
"=",
"'N/A'",
")",
":",
"try",
":",
"f",
"=",
"float",
"(",
"value",
")",
"except",
"ValueError",
":",
"return",
"failure_string",
"return",
"_saferound",
"(",
"f",
","... | Converts a floating point value a X:1 ratio.
Number of decimal places set by the `precision` kwarg. Default is one. | [
"Converts",
"a",
"floating",
"point",
"value",
"a",
"X",
":",
"1",
"ratio",
".",
"Number",
"of",
"decimal",
"places",
"set",
"by",
"the",
"precision",
"kwarg",
".",
"Default",
"is",
"one",
"."
] | python | train | 29.727273 |
klmitch/turnstile | turnstile/database.py | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/database.py#L126-L172 | def limit_update(db, key, limits):
"""
Safely updates the list of limits in the database.
:param db: The database handle.
:param key: The key the limits are stored under.
:param limits: A list or sequence of limit objects, each
understanding the dehydrate() method.
The limit... | [
"def",
"limit_update",
"(",
"db",
",",
"key",
",",
"limits",
")",
":",
"# Start by dehydrating all the limits",
"desired",
"=",
"[",
"msgpack",
".",
"dumps",
"(",
"l",
".",
"dehydrate",
"(",
")",
")",
"for",
"l",
"in",
"limits",
"]",
"desired_set",
"=",
... | Safely updates the list of limits in the database.
:param db: The database handle.
:param key: The key the limits are stored under.
:param limits: A list or sequence of limit objects, each
understanding the dehydrate() method.
The limits list currently in the database will be atomic... | [
"Safely",
"updates",
"the",
"list",
"of",
"limits",
"in",
"the",
"database",
"."
] | python | train | 31 |
python-rope/rope | rope/base/pyscopes.py | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/pyscopes.py#L22-L26 | def get_name(self, name):
"""Return name `PyName` defined in this scope"""
if name not in self.get_names():
raise exceptions.NameNotFoundError('name %s not found' % name)
return self.get_names()[name] | [
"def",
"get_name",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"get_names",
"(",
")",
":",
"raise",
"exceptions",
".",
"NameNotFoundError",
"(",
"'name %s not found'",
"%",
"name",
")",
"return",
"self",
".",
"get_names",
... | Return name `PyName` defined in this scope | [
"Return",
"name",
"PyName",
"defined",
"in",
"this",
"scope"
] | python | train | 46.4 |
klen/muffin-metrics | muffin_metrics.py | https://github.com/klen/muffin-metrics/blob/b62fc25172e3e1e9fc6dc6c8da3170935ee69f01/muffin_metrics.py#L111-L117 | def send(self, stat, value, backend=None):
"""Send stat to backend."""
client = yield from self.client(backend)
if not client:
return False
client.send(stat, value)
client.disconnect() | [
"def",
"send",
"(",
"self",
",",
"stat",
",",
"value",
",",
"backend",
"=",
"None",
")",
":",
"client",
"=",
"yield",
"from",
"self",
".",
"client",
"(",
"backend",
")",
"if",
"not",
"client",
":",
"return",
"False",
"client",
".",
"send",
"(",
"st... | Send stat to backend. | [
"Send",
"stat",
"to",
"backend",
"."
] | python | train | 32.857143 |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L1843-L1854 | def daffpa():
"""
Find the previous (backward) array in the current DAF.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/daffpa_c.html
:return: True if an array was found.
:rtype: bool
"""
found = ctypes.c_int()
libspice.daffpa_c(ctypes.byref(found))
return bool(found.value... | [
"def",
"daffpa",
"(",
")",
":",
"found",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"libspice",
".",
"daffpa_c",
"(",
"ctypes",
".",
"byref",
"(",
"found",
")",
")",
"return",
"bool",
"(",
"found",
".",
"value",
")"
] | Find the previous (backward) array in the current DAF.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/daffpa_c.html
:return: True if an array was found.
:rtype: bool | [
"Find",
"the",
"previous",
"(",
"backward",
")",
"array",
"in",
"the",
"current",
"DAF",
"."
] | python | train | 25.833333 |
Yelp/py_zipkin | py_zipkin/encoding/_decoders.py | https://github.com/Yelp/py_zipkin/blob/0944d9a3fb1f1798dbb276694aeed99f2b4283ba/py_zipkin/encoding/_decoders.py#L270-L288 | def _write_hex_long(self, data, pos, value):
"""
Writes an unsigned long value across a byte array.
:param data: the buffer to write the value to
:type data: bytearray
:param pos: the starting position
:type pos: int
:param value: the value to write
:type... | [
"def",
"_write_hex_long",
"(",
"self",
",",
"data",
",",
"pos",
",",
"value",
")",
":",
"self",
".",
"_write_hex_byte",
"(",
"data",
",",
"pos",
"+",
"0",
",",
"(",
"value",
">>",
"56",
")",
"&",
"0xff",
")",
"self",
".",
"_write_hex_byte",
"(",
"d... | Writes an unsigned long value across a byte array.
:param data: the buffer to write the value to
:type data: bytearray
:param pos: the starting position
:type pos: int
:param value: the value to write
:type value: unsigned long | [
"Writes",
"an",
"unsigned",
"long",
"value",
"across",
"a",
"byte",
"array",
"."
] | python | test | 45.210526 |
google/openhtf | openhtf/plugs/usb/filesync_service.py | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/filesync_service.py#L198-L203 | def recv(self, filename, dest_file, timeout=None):
"""Retrieve a file from the device into the file-like dest_file."""
transport = DataFilesyncTransport(self.stream)
transport.write_data('RECV', filename, timeout)
for data_msg in transport.read_until_done('DATA', timeout):
dest_file.write(data_msg... | [
"def",
"recv",
"(",
"self",
",",
"filename",
",",
"dest_file",
",",
"timeout",
"=",
"None",
")",
":",
"transport",
"=",
"DataFilesyncTransport",
"(",
"self",
".",
"stream",
")",
"transport",
".",
"write_data",
"(",
"'RECV'",
",",
"filename",
",",
"timeout"... | Retrieve a file from the device into the file-like dest_file. | [
"Retrieve",
"a",
"file",
"from",
"the",
"device",
"into",
"the",
"file",
"-",
"like",
"dest_file",
"."
] | python | train | 53.5 |
veeti/decent | decent/validators.py | https://github.com/veeti/decent/blob/07b11536953b9cf4402c65f241706ab717b90bff/decent/validators.py#L212-L231 | def Range(min=None, max=None, min_message="Must be at least {min}", max_message="Must be at most {max}"):
"""
Creates a validator that checks if the given numeric value is in the
specified range, inclusive.
Accepts values specified by ``numbers.Number`` only, excluding booleans.
The error messages... | [
"def",
"Range",
"(",
"min",
"=",
"None",
",",
"max",
"=",
"None",
",",
"min_message",
"=",
"\"Must be at least {min}\"",
",",
"max_message",
"=",
"\"Must be at most {max}\"",
")",
":",
"@",
"wraps",
"(",
"Range",
")",
"def",
"built",
"(",
"value",
")",
":"... | Creates a validator that checks if the given numeric value is in the
specified range, inclusive.
Accepts values specified by ``numbers.Number`` only, excluding booleans.
The error messages raised can be customized with ``min_message`` and
``max_message``. The ``min`` and ``max`` arguments are formatte... | [
"Creates",
"a",
"validator",
"that",
"checks",
"if",
"the",
"given",
"numeric",
"value",
"is",
"in",
"the",
"specified",
"range",
"inclusive",
"."
] | python | train | 41.8 |
edx/edx-submissions | submissions/api.py | https://github.com/edx/edx-submissions/blob/8d531ca25f7c2886dfcb1bb8febe0910e1433ca2/submissions/api.py#L759-L824 | def reset_score(student_id, course_id, item_id, clear_state=False, emit_signal=True):
"""
Reset scores for a specific student on a specific problem.
Note: this does *not* delete `Score` models from the database,
since these are immutable. It simply creates a new score with
the "reset" flag set to ... | [
"def",
"reset_score",
"(",
"student_id",
",",
"course_id",
",",
"item_id",
",",
"clear_state",
"=",
"False",
",",
"emit_signal",
"=",
"True",
")",
":",
"# Retrieve the student item",
"try",
":",
"student_item",
"=",
"StudentItem",
".",
"objects",
".",
"get",
"... | Reset scores for a specific student on a specific problem.
Note: this does *not* delete `Score` models from the database,
since these are immutable. It simply creates a new score with
the "reset" flag set to True.
Args:
student_id (unicode): The ID of the student for whom to reset scores.
... | [
"Reset",
"scores",
"for",
"a",
"specific",
"student",
"on",
"a",
"specific",
"problem",
"."
] | python | train | 37.151515 |
dcos/shakedown | shakedown/dcos/service.py | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/service.py#L540-L568 | def tasks_missing_predicate(
service_name,
old_task_ids,
task_predicate=None
):
""" Returns whether any of old_task_ids are no longer present
:param service_name: the service name
:type service_name: str
:param old_task_ids: list of original task ids as returned by g... | [
"def",
"tasks_missing_predicate",
"(",
"service_name",
",",
"old_task_ids",
",",
"task_predicate",
"=",
"None",
")",
":",
"try",
":",
"task_ids",
"=",
"get_service_task_ids",
"(",
"service_name",
",",
"task_predicate",
")",
"except",
"DCOSHTTPException",
":",
"print... | Returns whether any of old_task_ids are no longer present
:param service_name: the service name
:type service_name: str
:param old_task_ids: list of original task ids as returned by get_service_task_ids
:type old_task_ids: [str]
:param task_predicate: filter to use when searchin... | [
"Returns",
"whether",
"any",
"of",
"old_task_ids",
"are",
"no",
"longer",
"present"
] | python | train | 36.344828 |
census-instrumentation/opencensus-python | opencensus/trace/span.py | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/span.py#L163-L175 | def span(self, name='child_span'):
"""Create a child span for the current span and append it to the child
spans list.
:type name: str
:param name: (Optional) The name of the child span.
:rtype: :class: `~opencensus.trace.span.Span`
:returns: A child Span to be added to ... | [
"def",
"span",
"(",
"self",
",",
"name",
"=",
"'child_span'",
")",
":",
"child_span",
"=",
"Span",
"(",
"name",
",",
"parent_span",
"=",
"self",
")",
"self",
".",
"_child_spans",
".",
"append",
"(",
"child_span",
")",
"return",
"child_span"
] | Create a child span for the current span and append it to the child
spans list.
:type name: str
:param name: (Optional) The name of the child span.
:rtype: :class: `~opencensus.trace.span.Span`
:returns: A child Span to be added to the current span. | [
"Create",
"a",
"child",
"span",
"for",
"the",
"current",
"span",
"and",
"append",
"it",
"to",
"the",
"child",
"spans",
"list",
"."
] | python | train | 35.230769 |
zeth/inputs | inputs.py | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L2603-L2607 | def _get_data(self, read_size):
"""Get data from the character device."""
if NIX:
return super(Mouse, self)._get_data(read_size)
return self._pipe.recv_bytes() | [
"def",
"_get_data",
"(",
"self",
",",
"read_size",
")",
":",
"if",
"NIX",
":",
"return",
"super",
"(",
"Mouse",
",",
"self",
")",
".",
"_get_data",
"(",
"read_size",
")",
"return",
"self",
".",
"_pipe",
".",
"recv_bytes",
"(",
")"
] | Get data from the character device. | [
"Get",
"data",
"from",
"the",
"character",
"device",
"."
] | python | train | 38.2 |
vmware/pyvmomi | pyVmomi/SoapAdapter.py | https://github.com/vmware/pyvmomi/blob/3ffcb23bf77d757175c0d5216ba9a25345d824cd/pyVmomi/SoapAdapter.py#L272-L274 | def SerializeFaultDetail(self, val, info):
""" Serialize an object """
self._SerializeDataObject(val, info, ' xsi:typ="{1}"'.format(val._wsdlName), self.defaultNS) | [
"def",
"SerializeFaultDetail",
"(",
"self",
",",
"val",
",",
"info",
")",
":",
"self",
".",
"_SerializeDataObject",
"(",
"val",
",",
"info",
",",
"' xsi:typ=\"{1}\"'",
".",
"format",
"(",
"val",
".",
"_wsdlName",
")",
",",
"self",
".",
"defaultNS",
")"
] | Serialize an object | [
"Serialize",
"an",
"object"
] | python | train | 57.666667 |
dev-pipeline/dev-pipeline-git | lib/devpipeline_git/git.py | https://github.com/dev-pipeline/dev-pipeline-git/blob/b604f1f89402502b8ad858f4f834baa9467ef380/lib/devpipeline_git/git.py#L126-L134 | def update(self, repo_dir, **kwargs):
"""This function updates an existing checkout of source code."""
del kwargs
rev = self._args.get("revision")
if rev:
return [{"args": ["git", "checkout", rev], "cwd": repo_dir}] + _ff_command(
rev, repo_dir
)
... | [
"def",
"update",
"(",
"self",
",",
"repo_dir",
",",
"*",
"*",
"kwargs",
")",
":",
"del",
"kwargs",
"rev",
"=",
"self",
".",
"_args",
".",
"get",
"(",
"\"revision\"",
")",
"if",
"rev",
":",
"return",
"[",
"{",
"\"args\"",
":",
"[",
"\"git\"",
",",
... | This function updates an existing checkout of source code. | [
"This",
"function",
"updates",
"an",
"existing",
"checkout",
"of",
"source",
"code",
"."
] | python | train | 36.666667 |
materialsproject/pymatgen | pymatgen/analysis/gb/grain.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/gb/grain.py#L1172-L1247 | def enum_sigma_cubic(cutoff, r_axis):
"""
Find all possible sigma values and corresponding rotation angles
within a sigma value cutoff with known rotation axis in cubic system.
The algorithm for this code is from reference, Acta Cryst, A40,108(1984)
Args:
cutoff (inte... | [
"def",
"enum_sigma_cubic",
"(",
"cutoff",
",",
"r_axis",
")",
":",
"sigmas",
"=",
"{",
"}",
"# make sure gcd(r_axis)==1",
"if",
"reduce",
"(",
"gcd",
",",
"r_axis",
")",
"!=",
"1",
":",
"r_axis",
"=",
"[",
"int",
"(",
"round",
"(",
"x",
"/",
"reduce",
... | Find all possible sigma values and corresponding rotation angles
within a sigma value cutoff with known rotation axis in cubic system.
The algorithm for this code is from reference, Acta Cryst, A40,108(1984)
Args:
cutoff (integer): the cutoff of sigma values.
r_axis (list... | [
"Find",
"all",
"possible",
"sigma",
"values",
"and",
"corresponding",
"rotation",
"angles",
"within",
"a",
"sigma",
"value",
"cutoff",
"with",
"known",
"rotation",
"axis",
"in",
"cubic",
"system",
".",
"The",
"algorithm",
"for",
"this",
"code",
"is",
"from",
... | python | train | 47.907895 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.