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 |
|---|---|---|---|---|---|---|---|---|---|
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py#L792-L807 | def DocbookXInclude(env, target, source, *args, **kw):
"""
A pseudo-Builder, for resolving XIncludes in a separate processing step.
"""
# Init list of targets/sources
target, source = __extend_targets_sources(target, source)
# Setup builder
__builder = __select_builder(__xinclude_lxml_build... | [
"def",
"DocbookXInclude",
"(",
"env",
",",
"target",
",",
"source",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"# Init list of targets/sources",
"target",
",",
"source",
"=",
"__extend_targets_sources",
"(",
"target",
",",
"source",
")",
"# Setup builder... | A pseudo-Builder, for resolving XIncludes in a separate processing step. | [
"A",
"pseudo",
"-",
"Builder",
"for",
"resolving",
"XIncludes",
"in",
"a",
"separate",
"processing",
"step",
"."
] | python | train | 32.75 |
etcher-be/emiz | emiz/avwx/translate.py | https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/translate.py#L144-L161 | def temperature(temp: Number, unit: str = 'C') -> str:
"""
Formats a temperature element into a string with both C and F values
Used for both Temp and Dew
Ex: 34°C (93°F)
"""
unit = unit.upper()
if not (temp and unit in ('C', 'F')):
return ''
if unit == 'C':
converted =... | [
"def",
"temperature",
"(",
"temp",
":",
"Number",
",",
"unit",
":",
"str",
"=",
"'C'",
")",
"->",
"str",
":",
"unit",
"=",
"unit",
".",
"upper",
"(",
")",
"if",
"not",
"(",
"temp",
"and",
"unit",
"in",
"(",
"'C'",
",",
"'F'",
")",
")",
":",
"... | Formats a temperature element into a string with both C and F values
Used for both Temp and Dew
Ex: 34°C (93°F) | [
"Formats",
"a",
"temperature",
"element",
"into",
"a",
"string",
"with",
"both",
"C",
"and",
"F",
"values"
] | python | train | 32.166667 |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/checkers/_namespace.py | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/checkers/_namespace.py#L33-L47 | def serialize_text(self):
'''Returns a serialized form of the Namepace.
All the elements in the namespace are sorted by
URI, joined to the associated prefix with a colon and
separated with spaces.
:return: bytes
'''
if self._uri_to_prefix is None or len(self._uri... | [
"def",
"serialize_text",
"(",
"self",
")",
":",
"if",
"self",
".",
"_uri_to_prefix",
"is",
"None",
"or",
"len",
"(",
"self",
".",
"_uri_to_prefix",
")",
"==",
"0",
":",
"return",
"b''",
"od",
"=",
"collections",
".",
"OrderedDict",
"(",
"sorted",
"(",
... | Returns a serialized form of the Namepace.
All the elements in the namespace are sorted by
URI, joined to the associated prefix with a colon and
separated with spaces.
:return: bytes | [
"Returns",
"a",
"serialized",
"form",
"of",
"the",
"Namepace",
"."
] | python | train | 36.8 |
kensho-technologies/graphql-compiler | graphql_compiler/compiler/ir_lowering_match/utils.py | https://github.com/kensho-technologies/graphql-compiler/blob/f6079c6d10f64932f6b3af309b79bcea2123ca8f/graphql_compiler/compiler/ir_lowering_match/utils.py#L287-L334 | def get_all_rooted_subtrees_as_lists(self, start_location=None):
"""Return a list of all rooted subtrees (each as a list of Location objects)."""
if start_location is not None and start_location not in self._location_to_children:
raise AssertionError(u'Received invalid start_location {} that... | [
"def",
"get_all_rooted_subtrees_as_lists",
"(",
"self",
",",
"start_location",
"=",
"None",
")",
":",
"if",
"start_location",
"is",
"not",
"None",
"and",
"start_location",
"not",
"in",
"self",
".",
"_location_to_children",
":",
"raise",
"AssertionError",
"(",
"u'R... | Return a list of all rooted subtrees (each as a list of Location objects). | [
"Return",
"a",
"list",
"of",
"all",
"rooted",
"subtrees",
"(",
"each",
"as",
"a",
"list",
"of",
"Location",
"objects",
")",
"."
] | python | train | 49.270833 |
amzn/ion-python | amazon/ion/reader_text.py | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L1222-L1302 | def _symbol_or_keyword_handler(c, ctx, is_field_name=False):
"""Handles the start of an unquoted text token.
This may be an operator (if in an s-expression), an identifier symbol, or a keyword.
"""
in_sexp = ctx.container.ion_type is IonType.SEXP
if c not in _IDENTIFIER_STARTS:
if in_sexp a... | [
"def",
"_symbol_or_keyword_handler",
"(",
"c",
",",
"ctx",
",",
"is_field_name",
"=",
"False",
")",
":",
"in_sexp",
"=",
"ctx",
".",
"container",
".",
"ion_type",
"is",
"IonType",
".",
"SEXP",
"if",
"c",
"not",
"in",
"_IDENTIFIER_STARTS",
":",
"if",
"in_se... | Handles the start of an unquoted text token.
This may be an operator (if in an s-expression), an identifier symbol, or a keyword. | [
"Handles",
"the",
"start",
"of",
"an",
"unquoted",
"text",
"token",
"."
] | python | train | 45.901235 |
apache/incubator-mxnet | python/mxnet/symbol/register.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/symbol/register.py#L199-L209 | def _make_symbol_function(handle, name, func_name):
"""Create a symbol function by handle and function name."""
code, doc_str = _generate_symbol_function_code(handle, name, func_name)
local = {}
exec(code, None, local) # pylint: disable=exec-used
symbol_function = local[func_name]
symbol_funct... | [
"def",
"_make_symbol_function",
"(",
"handle",
",",
"name",
",",
"func_name",
")",
":",
"code",
",",
"doc_str",
"=",
"_generate_symbol_function_code",
"(",
"handle",
",",
"name",
",",
"func_name",
")",
"local",
"=",
"{",
"}",
"exec",
"(",
"code",
",",
"Non... | Create a symbol function by handle and function name. | [
"Create",
"a",
"symbol",
"function",
"by",
"handle",
"and",
"function",
"name",
"."
] | python | train | 40.636364 |
Pelagicore/qface | qface/helper/generic.py | https://github.com/Pelagicore/qface/blob/7f60e91e3a91a7cb04cfacbc9ce80f43df444853/qface/helper/generic.py#L26-L30 | def hash(symbol, hash_type='sha1'):
""" create a hash code from symbol """
code = hashlib.new(hash_type)
code.update(str(symbol).encode('utf-8'))
return code.hexdigest() | [
"def",
"hash",
"(",
"symbol",
",",
"hash_type",
"=",
"'sha1'",
")",
":",
"code",
"=",
"hashlib",
".",
"new",
"(",
"hash_type",
")",
"code",
".",
"update",
"(",
"str",
"(",
"symbol",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"return",
"code",
".... | create a hash code from symbol | [
"create",
"a",
"hash",
"code",
"from",
"symbol"
] | python | train | 36.2 |
python-rope/rope | rope/base/prefs.py | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/prefs.py#L14-L22 | def add(self, key, value):
"""Add an entry to a list preference
Add `value` to the list of entries for the `key` preference.
"""
if not key in self.prefs:
self.prefs[key] = []
self.prefs[key].append(value) | [
"def",
"add",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"not",
"key",
"in",
"self",
".",
"prefs",
":",
"self",
".",
"prefs",
"[",
"key",
"]",
"=",
"[",
"]",
"self",
".",
"prefs",
"[",
"key",
"]",
".",
"append",
"(",
"value",
")"
... | Add an entry to a list preference
Add `value` to the list of entries for the `key` preference. | [
"Add",
"an",
"entry",
"to",
"a",
"list",
"preference"
] | python | train | 27.888889 |
globality-corp/flake8-logging-format | logging_format/visitor.py | https://github.com/globality-corp/flake8-logging-format/blob/3c6ce53d0ff1ec369799cff0ed6d048343252e40/logging_format/visitor.py#L127-L142 | def visit_Dict(self, node):
"""
Process dict arguments.
"""
if self.should_check_whitelist(node):
for key in node.keys:
if key.s in self.whitelist or key.s.startswith("debug_"):
continue
self.violations.append((self.current... | [
"def",
"visit_Dict",
"(",
"self",
",",
"node",
")",
":",
"if",
"self",
".",
"should_check_whitelist",
"(",
"node",
")",
":",
"for",
"key",
"in",
"node",
".",
"keys",
":",
"if",
"key",
".",
"s",
"in",
"self",
".",
"whitelist",
"or",
"key",
".",
"s",... | Process dict arguments. | [
"Process",
"dict",
"arguments",
"."
] | python | test | 34.4375 |
pallets/werkzeug | src/werkzeug/wrappers/etag.py | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/wrappers/etag.py#L236-L239 | def add_etag(self, overwrite=False, weak=False):
"""Add an etag for the current response if there is none yet."""
if overwrite or "etag" not in self.headers:
self.set_etag(generate_etag(self.get_data()), weak) | [
"def",
"add_etag",
"(",
"self",
",",
"overwrite",
"=",
"False",
",",
"weak",
"=",
"False",
")",
":",
"if",
"overwrite",
"or",
"\"etag\"",
"not",
"in",
"self",
".",
"headers",
":",
"self",
".",
"set_etag",
"(",
"generate_etag",
"(",
"self",
".",
"get_da... | Add an etag for the current response if there is none yet. | [
"Add",
"an",
"etag",
"for",
"the",
"current",
"response",
"if",
"there",
"is",
"none",
"yet",
"."
] | python | train | 58.5 |
filepreviews/filepreviews-python | filepreviews/__main__.py | https://github.com/filepreviews/filepreviews-python/blob/11be871a07438e3ab5d87ab1f2c163bbac4d4570/filepreviews/__main__.py#L30-L58 | def generate(ctx, url, *args, **kwargs):
"""
Generate preview for URL.
"""
file_previews = ctx.obj['file_previews']
options = {}
metadata = kwargs['metadata']
width = kwargs['width']
height = kwargs['height']
output_format = kwargs['format']
if metadata:
options['metada... | [
"def",
"generate",
"(",
"ctx",
",",
"url",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"file_previews",
"=",
"ctx",
".",
"obj",
"[",
"'file_previews'",
"]",
"options",
"=",
"{",
"}",
"metadata",
"=",
"kwargs",
"[",
"'metadata'",
"]",
"width"... | Generate preview for URL. | [
"Generate",
"preview",
"for",
"URL",
"."
] | python | test | 22.586207 |
google/dotty | efilter/dispatch.py | https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/dispatch.py#L71-L82 | def _class_dispatch(args, kwargs):
"""See 'class_multimethod'."""
_ = kwargs
if not args:
raise ValueError(
"Multimethods must be passed at least one positional arg.")
if not isinstance(args[0], type):
raise TypeError(
"class_multimethod must be called with a typ... | [
"def",
"_class_dispatch",
"(",
"args",
",",
"kwargs",
")",
":",
"_",
"=",
"kwargs",
"if",
"not",
"args",
":",
"raise",
"ValueError",
"(",
"\"Multimethods must be passed at least one positional arg.\"",
")",
"if",
"not",
"isinstance",
"(",
"args",
"[",
"0",
"]",
... | See 'class_multimethod'. | [
"See",
"class_multimethod",
"."
] | python | train | 28.916667 |
numenta/nupic | src/nupic/algorithms/fdrutilities.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/fdrutilities.py#L1006-L1053 | def averageOnTime(vectors, numSamples=None):
"""
Returns the average on-time, averaged over all on-time runs.
Parameters:
-----------------------------------------------
vectors: the vectors for which the onTime is calculated. Row 0
contains the outputs from time step 0, row 1 fr... | [
"def",
"averageOnTime",
"(",
"vectors",
",",
"numSamples",
"=",
"None",
")",
":",
"# Special case given a 1 dimensional vector: it represents a single column",
"if",
"vectors",
".",
"ndim",
"==",
"1",
":",
"vectors",
".",
"shape",
"=",
"(",
"-",
"1",
",",
"1",
"... | Returns the average on-time, averaged over all on-time runs.
Parameters:
-----------------------------------------------
vectors: the vectors for which the onTime is calculated. Row 0
contains the outputs from time step 0, row 1 from time step
1, etc.
numSamples... | [
"Returns",
"the",
"average",
"on",
"-",
"time",
"averaged",
"over",
"all",
"on",
"-",
"time",
"runs",
"."
] | python | valid | 32.270833 |
ecederstrand/exchangelib | exchangelib/items.py | https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/items.py#L444-L460 | def detach(self, attachments):
"""Remove an attachment, or a list of attachments, from this item. If the item has already been saved, the
attachments will be deleted on the server immediately. If the item has not yet been saved, the attachments will
simply not be created on the server the item i... | [
"def",
"detach",
"(",
"self",
",",
"attachments",
")",
":",
"if",
"not",
"is_iterable",
"(",
"attachments",
",",
"generators_allowed",
"=",
"True",
")",
":",
"attachments",
"=",
"[",
"attachments",
"]",
"for",
"a",
"in",
"attachments",
":",
"if",
"a",
".... | Remove an attachment, or a list of attachments, from this item. If the item has already been saved, the
attachments will be deleted on the server immediately. If the item has not yet been saved, the attachments will
simply not be created on the server the item is saved.
Removing attachments fro... | [
"Remove",
"an",
"attachment",
"or",
"a",
"list",
"of",
"attachments",
"from",
"this",
"item",
".",
"If",
"the",
"item",
"has",
"already",
"been",
"saved",
"the",
"attachments",
"will",
"be",
"deleted",
"on",
"the",
"server",
"immediately",
".",
"If",
"the"... | python | train | 51.941176 |
tanghaibao/goatools | goatools/go_enrichment.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/go_enrichment.py#L482-L486 | def prt_tsv(self, prt, goea_results, **kws):
"""Write tab-separated table data"""
prt_flds = kws.get('prt_flds', self.get_prtflds_default(goea_results))
tsv_data = MgrNtGOEAs(goea_results).get_goea_nts_prt(prt_flds, **kws)
RPT.prt_tsv(prt, tsv_data, **kws) | [
"def",
"prt_tsv",
"(",
"self",
",",
"prt",
",",
"goea_results",
",",
"*",
"*",
"kws",
")",
":",
"prt_flds",
"=",
"kws",
".",
"get",
"(",
"'prt_flds'",
",",
"self",
".",
"get_prtflds_default",
"(",
"goea_results",
")",
")",
"tsv_data",
"=",
"MgrNtGOEAs",
... | Write tab-separated table data | [
"Write",
"tab",
"-",
"separated",
"table",
"data"
] | python | train | 56.8 |
duniter/duniter-python-api | duniterpy/key/signing_key.py | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/key/signing_key.py#L196-L212 | def from_wif_or_ewif_hex(wif_hex: str, password: Optional[str] = None) -> SigningKeyType:
"""
Return SigningKey instance from Duniter WIF or EWIF in hexadecimal format
:param wif_hex: WIF or EWIF string in hexadecimal format
:param password: Password of EWIF encrypted seed
"""
... | [
"def",
"from_wif_or_ewif_hex",
"(",
"wif_hex",
":",
"str",
",",
"password",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"SigningKeyType",
":",
"wif_bytes",
"=",
"Base58Encoder",
".",
"decode",
"(",
"wif_hex",
")",
"fi",
"=",
"wif_bytes",
"[",... | Return SigningKey instance from Duniter WIF or EWIF in hexadecimal format
:param wif_hex: WIF or EWIF string in hexadecimal format
:param password: Password of EWIF encrypted seed | [
"Return",
"SigningKey",
"instance",
"from",
"Duniter",
"WIF",
"or",
"EWIF",
"in",
"hexadecimal",
"format"
] | python | train | 38.647059 |
bitesofcode/projexui | projexui/xapplication.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/xapplication.py#L492-L505 | def unregisterWalkthrough(self, walkthrough):
"""
Unregisters the inputed walkthrough from the application walkthroug
list.
:param walkthrough | <XWalkthrough>
"""
if type(walkthrough) in (str, unicode):
walkthrough = self.findWalkthrough... | [
"def",
"unregisterWalkthrough",
"(",
"self",
",",
"walkthrough",
")",
":",
"if",
"type",
"(",
"walkthrough",
")",
"in",
"(",
"str",
",",
"unicode",
")",
":",
"walkthrough",
"=",
"self",
".",
"findWalkthrough",
"(",
"walkthrough",
")",
"try",
":",
"self",
... | Unregisters the inputed walkthrough from the application walkthroug
list.
:param walkthrough | <XWalkthrough> | [
"Unregisters",
"the",
"inputed",
"walkthrough",
"from",
"the",
"application",
"walkthroug",
"list",
".",
":",
"param",
"walkthrough",
"|",
"<XWalkthrough",
">"
] | python | train | 31 |
Chilipp/psy-simple | psy_simple/widgets/texts.py | https://github.com/Chilipp/psy-simple/blob/7d916406a6d3c3c27c0b7102f98fef07a4da0a61/psy_simple/widgets/texts.py#L420-L437 | def refresh(self):
"""Refresh the widgets from the current font"""
font = self.current_font
# refresh btn_bold
self.btn_bold.blockSignals(True)
self.btn_bold.setChecked(font.weight() > 50)
self.btn_bold.blockSignals(False)
# refresh btn_italic
self.btn_i... | [
"def",
"refresh",
"(",
"self",
")",
":",
"font",
"=",
"self",
".",
"current_font",
"# refresh btn_bold",
"self",
".",
"btn_bold",
".",
"blockSignals",
"(",
"True",
")",
"self",
".",
"btn_bold",
".",
"setChecked",
"(",
"font",
".",
"weight",
"(",
")",
">"... | Refresh the widgets from the current font | [
"Refresh",
"the",
"widgets",
"from",
"the",
"current",
"font"
] | python | train | 32.333333 |
Dallinger/Dallinger | dallinger/experiment_server/experiment_server.py | https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment_server/experiment_server.py#L535-L548 | def should_show_thanks_page_to(participant):
"""In the context of the /ad route, should the participant be shown
the thanks.html page instead of ad.html?
"""
if participant is None:
return False
status = participant.status
marked_done = participant.end_time is not None
ready_for_exte... | [
"def",
"should_show_thanks_page_to",
"(",
"participant",
")",
":",
"if",
"participant",
"is",
"None",
":",
"return",
"False",
"status",
"=",
"participant",
".",
"status",
"marked_done",
"=",
"participant",
".",
"end_time",
"is",
"not",
"None",
"ready_for_external_... | In the context of the /ad route, should the participant be shown
the thanks.html page instead of ad.html? | [
"In",
"the",
"context",
"of",
"the",
"/",
"ad",
"route",
"should",
"the",
"participant",
"be",
"shown",
"the",
"thanks",
".",
"html",
"page",
"instead",
"of",
"ad",
".",
"html?"
] | python | train | 37.285714 |
wummel/dosage | dosagelib/scraper.py | https://github.com/wummel/dosage/blob/a0109c3a46219f280e6e5e77183674e40da0f304/dosagelib/scraper.py#L318-L335 | def language(cls):
"""
Return language of the comic as a human-readable language name instead
of a 2-character ISO639-1 code.
"""
lang = 'Unknown (%s)' % cls.lang
if pycountry is None:
if cls.lang in languages.Languages:
lang = languages.Langua... | [
"def",
"language",
"(",
"cls",
")",
":",
"lang",
"=",
"'Unknown (%s)'",
"%",
"cls",
".",
"lang",
"if",
"pycountry",
"is",
"None",
":",
"if",
"cls",
".",
"lang",
"in",
"languages",
".",
"Languages",
":",
"lang",
"=",
"languages",
".",
"Languages",
"[",
... | Return language of the comic as a human-readable language name instead
of a 2-character ISO639-1 code. | [
"Return",
"language",
"of",
"the",
"comic",
"as",
"a",
"human",
"-",
"readable",
"language",
"name",
"instead",
"of",
"a",
"2",
"-",
"character",
"ISO639",
"-",
"1",
"code",
"."
] | python | train | 34.888889 |
datadotworld/data.world-py | datadotworld/client/_swagger/apis/download_api.py | https://github.com/datadotworld/data.world-py/blob/ffaeb115f358731ab0b805b0c43b7ff2e3cf0a77/datadotworld/client/_swagger/apis/download_api.py#L43-L68 | def download_dataset(self, owner, id, **kwargs):
"""
Download dataset
This endpoint will return a .zip containing all files within the dataset as originally uploaded. If you are interested retrieving clean data extracted from those files by data.world, check out `GET:/sql` and `GET:/sparql`.
... | [
"def",
"download_dataset",
"(",
"self",
",",
"owner",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"download_dat... | Download dataset
This endpoint will return a .zip containing all files within the dataset as originally uploaded. If you are interested retrieving clean data extracted from those files by data.world, check out `GET:/sql` and `GET:/sparql`.
This method makes a synchronous HTTP request by default. To ma... | [
"Download",
"dataset",
"This",
"endpoint",
"will",
"return",
"a",
".",
"zip",
"containing",
"all",
"files",
"within",
"the",
"dataset",
"as",
"originally",
"uploaded",
".",
"If",
"you",
"are",
"interested",
"retrieving",
"clean",
"data",
"extracted",
"from",
"... | python | train | 67.846154 |
sassoftware/saspy | saspy/sasbase.py | https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L705-L731 | def datasets(self, libref: str = '') -> str:
"""
This method is used to query a libref. The results show information about the libref including members.
:param libref: the libref to query
:return:
"""
code = "proc datasets"
if libref:
code += " dd=" + ... | [
"def",
"datasets",
"(",
"self",
",",
"libref",
":",
"str",
"=",
"''",
")",
"->",
"str",
":",
"code",
"=",
"\"proc datasets\"",
"if",
"libref",
":",
"code",
"+=",
"\" dd=\"",
"+",
"libref",
"code",
"+=",
"\"; quit;\"",
"if",
"self",
".",
"nosub",
":",
... | This method is used to query a libref. The results show information about the libref including members.
:param libref: the libref to query
:return: | [
"This",
"method",
"is",
"used",
"to",
"query",
"a",
"libref",
".",
"The",
"results",
"show",
"information",
"about",
"the",
"libref",
"including",
"members",
"."
] | python | train | 31.592593 |
pyblish/pyblish-qml | pyblish_qml/util.py | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/util.py#L217-L232 | def format_text(text):
"""Remove newlines, but preserve paragraphs"""
result = ""
for paragraph in text.split("\n\n"):
result += " ".join(paragraph.split()) + "\n\n"
result = result.rstrip("\n") # Remove last newlines
# converting links to HTML
pattern = r"(https?:\/\/(?:w{1,3}.)?[^\s... | [
"def",
"format_text",
"(",
"text",
")",
":",
"result",
"=",
"\"\"",
"for",
"paragraph",
"in",
"text",
".",
"split",
"(",
"\"\\n\\n\"",
")",
":",
"result",
"+=",
"\" \"",
".",
"join",
"(",
"paragraph",
".",
"split",
"(",
")",
")",
"+",
"\"\\n\\n\"",
"... | Remove newlines, but preserve paragraphs | [
"Remove",
"newlines",
"but",
"preserve",
"paragraphs"
] | python | train | 33.4375 |
brutasse/graphite-api | graphite_api/functions.py | https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L1013-L1028 | def scaleToSeconds(requestContext, seriesList, seconds):
"""
Takes one metric or a wildcard seriesList and returns "value per seconds"
where seconds is a last argument to this functions.
Useful in conjunction with derivative or integral function if you want
to normalize its result to a known resolu... | [
"def",
"scaleToSeconds",
"(",
"requestContext",
",",
"seriesList",
",",
"seconds",
")",
":",
"for",
"series",
"in",
"seriesList",
":",
"series",
".",
"name",
"=",
"\"scaleToSeconds(%s,%d)\"",
"%",
"(",
"series",
".",
"name",
",",
"seconds",
")",
"series",
".... | Takes one metric or a wildcard seriesList and returns "value per seconds"
where seconds is a last argument to this functions.
Useful in conjunction with derivative or integral function if you want
to normalize its result to a known resolution for arbitrary retentions | [
"Takes",
"one",
"metric",
"or",
"a",
"wildcard",
"seriesList",
"and",
"returns",
"value",
"per",
"seconds",
"where",
"seconds",
"is",
"a",
"last",
"argument",
"to",
"this",
"functions",
"."
] | python | train | 40.3125 |
FutunnOpen/futuquant | futuquant/trade/trade_response_handler.py | https://github.com/FutunnOpen/futuquant/blob/1512b321845f92ec9c578ce2689aa4e8482669e4/futuquant/trade/trade_response_handler.py#L51-L58 | def on_recv_rsp(self, rsp_pb):
"""receive response callback function"""
ret_code, msg, _= SubAccPush.unpack_rsp(rsp_pb)
if self._notify_obj is not None:
self._notify_obj.on_async_sub_acc_push(ret_code, msg)
return ret_code, msg | [
"def",
"on_recv_rsp",
"(",
"self",
",",
"rsp_pb",
")",
":",
"ret_code",
",",
"msg",
",",
"_",
"=",
"SubAccPush",
".",
"unpack_rsp",
"(",
"rsp_pb",
")",
"if",
"self",
".",
"_notify_obj",
"is",
"not",
"None",
":",
"self",
".",
"_notify_obj",
".",
"on_asy... | receive response callback function | [
"receive",
"response",
"callback",
"function"
] | python | train | 33.25 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/futures.py | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/futures.py#L508-L524 | def notify_done(self, error=False, run_done_callbacks=True):
''' if error clear all sessions otherwise check to see if all other sessions are complete
then run the done callbacks
'''
if error:
for _session in self._sessions.values():
_session.set_done()
... | [
"def",
"notify_done",
"(",
"self",
",",
"error",
"=",
"False",
",",
"run_done_callbacks",
"=",
"True",
")",
":",
"if",
"error",
":",
"for",
"_session",
"in",
"self",
".",
"_sessions",
".",
"values",
"(",
")",
":",
"_session",
".",
"set_done",
"(",
")",... | if error clear all sessions otherwise check to see if all other sessions are complete
then run the done callbacks | [
"if",
"error",
"clear",
"all",
"sessions",
"otherwise",
"check",
"to",
"see",
"if",
"all",
"other",
"sessions",
"are",
"complete",
"then",
"run",
"the",
"done",
"callbacks"
] | python | train | 36.411765 |
markovmodel/PyEMMA | pyemma/plots/networks.py | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/plots/networks.py#L133-L281 | def plot_network(
self, state_sizes=None, state_scale=1.0, state_colors='#ff5500', state_labels='auto',
arrow_scale=1.0, arrow_curvature=1.0, arrow_labels='weights', arrow_label_format='%10.2f',
max_width=12, max_height=12, figpadding=0.2, xticks=False, yticks=False, show_frame=False,
**... | [
"def",
"plot_network",
"(",
"self",
",",
"state_sizes",
"=",
"None",
",",
"state_scale",
"=",
"1.0",
",",
"state_colors",
"=",
"'#ff5500'",
",",
"state_labels",
"=",
"'auto'",
",",
"arrow_scale",
"=",
"1.0",
",",
"arrow_curvature",
"=",
"1.0",
",",
"arrow_la... | Draws a network using discs and curved arrows.
The thicknesses and labels of the arrows are taken from the off-diagonal matrix elements
in A. | [
"Draws",
"a",
"network",
"using",
"discs",
"and",
"curved",
"arrows",
"."
] | python | train | 41.986577 |
chriso/timeseries | timeseries/lazy_import.py | https://github.com/chriso/timeseries/blob/8b81e6cfd955a7cf75a421dfdb71b3f9e53be64d/timeseries/lazy_import.py#L10-L20 | def numpy():
'''Lazily import the numpy module'''
if LazyImport.numpy_module is None:
try:
LazyImport.numpy_module = __import__('numpypy')
except ImportError:
try:
LazyImport.numpy_module = __import__('numpy')
ex... | [
"def",
"numpy",
"(",
")",
":",
"if",
"LazyImport",
".",
"numpy_module",
"is",
"None",
":",
"try",
":",
"LazyImport",
".",
"numpy_module",
"=",
"__import__",
"(",
"'numpypy'",
")",
"except",
"ImportError",
":",
"try",
":",
"LazyImport",
".",
"numpy_module",
... | Lazily import the numpy module | [
"Lazily",
"import",
"the",
"numpy",
"module"
] | python | train | 39.636364 |
oriontvv/pyaspeller | pyaspeller/speller.py | https://github.com/oriontvv/pyaspeller/blob/9a76d1f1fb00c7eabfa006f8e0f145f764c7a8d6/pyaspeller/speller.py#L152-L157 | def config_path(self, value):
"""Set config_path"""
self._config_path = value or ''
if not isinstance(self._config_path, str):
raise BadArgumentError("config_path must be string: {}".format(
self._config_path)) | [
"def",
"config_path",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_config_path",
"=",
"value",
"or",
"''",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_config_path",
",",
"str",
")",
":",
"raise",
"BadArgumentError",
"(",
"\"config_path must be stri... | Set config_path | [
"Set",
"config_path"
] | python | test | 42.833333 |
securestate/termineter | lib/termineter/options.py | https://github.com/securestate/termineter/blob/d657d25d97c7739e650b951c396404e857e56625/lib/termineter/options.py#L193-L198 | def get_missing_options(self):
"""
Get a list of options that are required, but with default values
of None.
"""
return [option.name for option in self._options.values() if option.required and option.value is None] | [
"def",
"get_missing_options",
"(",
"self",
")",
":",
"return",
"[",
"option",
".",
"name",
"for",
"option",
"in",
"self",
".",
"_options",
".",
"values",
"(",
")",
"if",
"option",
".",
"required",
"and",
"option",
".",
"value",
"is",
"None",
"]"
] | Get a list of options that are required, but with default values
of None. | [
"Get",
"a",
"list",
"of",
"options",
"that",
"are",
"required",
"but",
"with",
"default",
"values",
"of",
"None",
"."
] | python | train | 36.5 |
senaite/senaite.core | bika/lims/exportimport/instruments/nuclisens/easyq.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/exportimport/instruments/nuclisens/easyq.py#L47-L67 | def xlsx_to_csv(self, infile, worksheet=0, delimiter=","):
""" Convert xlsx to easier format first, since we want to use the
convenience of the CSV library
"""
wb = load_workbook(self.getInputFile())
sheet = wb.worksheets[worksheet]
buffer = StringIO()
# extract ... | [
"def",
"xlsx_to_csv",
"(",
"self",
",",
"infile",
",",
"worksheet",
"=",
"0",
",",
"delimiter",
"=",
"\",\"",
")",
":",
"wb",
"=",
"load_workbook",
"(",
"self",
".",
"getInputFile",
"(",
")",
")",
"sheet",
"=",
"wb",
".",
"worksheets",
"[",
"worksheet"... | Convert xlsx to easier format first, since we want to use the
convenience of the CSV library | [
"Convert",
"xlsx",
"to",
"easier",
"format",
"first",
"since",
"we",
"want",
"to",
"use",
"the",
"convenience",
"of",
"the",
"CSV",
"library"
] | python | train | 35.238095 |
user-cont/colin | colin/core/fmf_extension.py | https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/fmf_extension.py#L80-L85 | def search(self, name):
""" Search node with given name based on regexp, basic method (find) uses equality"""
for node in self.climb():
if re.search(name, node.name):
return node
return None | [
"def",
"search",
"(",
"self",
",",
"name",
")",
":",
"for",
"node",
"in",
"self",
".",
"climb",
"(",
")",
":",
"if",
"re",
".",
"search",
"(",
"name",
",",
"node",
".",
"name",
")",
":",
"return",
"node",
"return",
"None"
] | Search node with given name based on regexp, basic method (find) uses equality | [
"Search",
"node",
"with",
"given",
"name",
"based",
"on",
"regexp",
"basic",
"method",
"(",
"find",
")",
"uses",
"equality"
] | python | train | 39.5 |
tehmaze/natural | natural/date.py | https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/date.py#L41-L53 | def _total_seconds(t):
'''
Takes a `datetime.timedelta` object and returns the delta in seconds.
>>> _total_seconds(datetime.timedelta(23, 42, 123456))
1987242
>>> _total_seconds(datetime.timedelta(23, 42, 654321))
1987243
'''
return sum([
int(t.days * 86400 + t.seconds),
... | [
"def",
"_total_seconds",
"(",
"t",
")",
":",
"return",
"sum",
"(",
"[",
"int",
"(",
"t",
".",
"days",
"*",
"86400",
"+",
"t",
".",
"seconds",
")",
",",
"int",
"(",
"round",
"(",
"t",
".",
"microseconds",
"/",
"1000000.0",
")",
")",
"]",
")"
] | Takes a `datetime.timedelta` object and returns the delta in seconds.
>>> _total_seconds(datetime.timedelta(23, 42, 123456))
1987242
>>> _total_seconds(datetime.timedelta(23, 42, 654321))
1987243 | [
"Takes",
"a",
"datetime",
".",
"timedelta",
"object",
"and",
"returns",
"the",
"delta",
"in",
"seconds",
"."
] | python | train | 27.307692 |
timothyb0912/pylogit | pylogit/bootstrap.py | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/bootstrap.py#L737-L788 | def calc_abc_interval(self,
conf_percentage,
init_vals,
epsilon=0.001,
**fit_kwargs):
"""
Calculates Approximate Bootstrap Confidence Intervals for one's model.
Parameters
----------
... | [
"def",
"calc_abc_interval",
"(",
"self",
",",
"conf_percentage",
",",
"init_vals",
",",
"epsilon",
"=",
"0.001",
",",
"*",
"*",
"fit_kwargs",
")",
":",
"print",
"(",
"\"Calculating Approximate Bootstrap Confidence (ABC) Intervals\"",
")",
"print",
"(",
"time",
".",
... | Calculates Approximate Bootstrap Confidence Intervals for one's model.
Parameters
----------
conf_percentage : scalar in the interval (0.0, 100.0).
Denotes the confidence-level for the returned endpoints. For
instance, to calculate a 95% confidence interval, pass `95`.
... | [
"Calculates",
"Approximate",
"Bootstrap",
"Confidence",
"Intervals",
"for",
"one",
"s",
"model",
"."
] | python | train | 47.057692 |
saltstack/salt | salt/returners/local_cache.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/local_cache.py#L374-L387 | def get_jids():
'''
Return a dict mapping all job ids to job information
'''
ret = {}
for jid, job, _, _ in _walk_through(_job_dir()):
ret[jid] = salt.utils.jid.format_jid_instance(jid, job)
if __opts__.get('job_cache_store_endtime'):
endtime = get_endtime(jid)
... | [
"def",
"get_jids",
"(",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"jid",
",",
"job",
",",
"_",
",",
"_",
"in",
"_walk_through",
"(",
"_job_dir",
"(",
")",
")",
":",
"ret",
"[",
"jid",
"]",
"=",
"salt",
".",
"utils",
".",
"jid",
".",
"format_jid_in... | Return a dict mapping all job ids to job information | [
"Return",
"a",
"dict",
"mapping",
"all",
"job",
"ids",
"to",
"job",
"information"
] | python | train | 27.357143 |
YosaiProject/yosai | yosai/core/mgt/mgt.py | https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/mgt/mgt.py#L910-L925 | def get_remembered_identity(self, subject_context):
"""
Using the specified subject context map intended to build a ``Subject``
instance, returns any previously remembered identifiers for the subject
for automatic identity association (aka 'Remember Me').
"""
rmm = self.r... | [
"def",
"get_remembered_identity",
"(",
"self",
",",
"subject_context",
")",
":",
"rmm",
"=",
"self",
".",
"remember_me_manager",
"if",
"rmm",
"is",
"not",
"None",
":",
"try",
":",
"return",
"rmm",
".",
"get_remembered_identifiers",
"(",
"subject_context",
")",
... | Using the specified subject context map intended to build a ``Subject``
instance, returns any previously remembered identifiers for the subject
for automatic identity association (aka 'Remember Me'). | [
"Using",
"the",
"specified",
"subject",
"context",
"map",
"intended",
"to",
"build",
"a",
"Subject",
"instance",
"returns",
"any",
"previously",
"remembered",
"identifiers",
"for",
"the",
"subject",
"for",
"automatic",
"identity",
"association",
"(",
"aka",
"Remem... | python | train | 47.1875 |
wandb/client | wandb/vendor/prompt_toolkit/buffer.py | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/buffer.py#L1092-L1116 | def validate(self):
"""
Returns `True` if valid.
"""
# Don't call the validator again, if it was already called for the
# current input.
if self.validation_state != ValidationState.UNKNOWN:
return self.validation_state == ValidationState.VALID
# Valid... | [
"def",
"validate",
"(",
"self",
")",
":",
"# Don't call the validator again, if it was already called for the",
"# current input.",
"if",
"self",
".",
"validation_state",
"!=",
"ValidationState",
".",
"UNKNOWN",
":",
"return",
"self",
".",
"validation_state",
"==",
"Valid... | Returns `True` if valid. | [
"Returns",
"True",
"if",
"valid",
"."
] | python | train | 37.52 |
assemblerflow/flowcraft | flowcraft/generator/pipeline_parser.py | https://github.com/assemblerflow/flowcraft/blob/fc3f4bddded1efc76006600016dc71a06dd908c0/flowcraft/generator/pipeline_parser.py#L341-L447 | def parse_pipeline(pipeline_str):
"""Parses a pipeline string into a list of dictionaries with the connections
between processes
Parameters
----------
pipeline_str : str
String with the definition of the pipeline, e.g.::
'processA processB processC(ProcessD | ProcessE)'
Re... | [
"def",
"parse_pipeline",
"(",
"pipeline_str",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"pipeline_str",
")",
":",
"logger",
".",
"debug",
"(",
"\"Found pipeline file: {}\"",
".",
"format",
"(",
"pipeline_str",
")",
")",
"with",
"open",
"(",
"p... | Parses a pipeline string into a list of dictionaries with the connections
between processes
Parameters
----------
pipeline_str : str
String with the definition of the pipeline, e.g.::
'processA processB processC(ProcessD | ProcessE)'
Returns
-------
pipeline_links : li... | [
"Parses",
"a",
"pipeline",
"string",
"into",
"a",
"list",
"of",
"dictionaries",
"with",
"the",
"connections",
"between",
"processes"
] | python | test | 40.009346 |
sassoo/goldman | goldman/queryparams/filter.py | https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/queryparams/filter.py#L172-L182 | def _validate_field(param, fields):
""" Ensure the field exists on the model """
if '/' not in param.field and param.field not in fields:
raise InvalidQueryParams(**{
'detail': 'The filter query param of "%s" is not possible. The '
'resource requested does not have a "... | [
"def",
"_validate_field",
"(",
"param",
",",
"fields",
")",
":",
"if",
"'/'",
"not",
"in",
"param",
".",
"field",
"and",
"param",
".",
"field",
"not",
"in",
"fields",
":",
"raise",
"InvalidQueryParams",
"(",
"*",
"*",
"{",
"'detail'",
":",
"'The filter q... | Ensure the field exists on the model | [
"Ensure",
"the",
"field",
"exists",
"on",
"the",
"model"
] | python | train | 43.272727 |
hobson/pug-dj | pug/dj/miner/views.py | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/miner/views.py#L411-L452 | def follow_double_underscores(obj, field_name=None, excel_dialect=True, eval_python=False, index_error_value=None):
'''Like getattr(obj, field_name) only follows model relationships through "__" or "." as link separators
>>> from django.contrib.auth.models import Permission
>>> import math
>>> p = Perm... | [
"def",
"follow_double_underscores",
"(",
"obj",
",",
"field_name",
"=",
"None",
",",
"excel_dialect",
"=",
"True",
",",
"eval_python",
"=",
"False",
",",
"index_error_value",
"=",
"None",
")",
":",
"if",
"not",
"obj",
":",
"return",
"obj",
"if",
"isinstance"... | Like getattr(obj, field_name) only follows model relationships through "__" or "." as link separators
>>> from django.contrib.auth.models import Permission
>>> import math
>>> p = Permission.objects.all()[0]
>>> follow_double_underscores(p, 'content_type__name') == p.content_type.name
True
>>> ... | [
"Like",
"getattr",
"(",
"obj",
"field_name",
")",
"only",
"follows",
"model",
"relationships",
"through",
"__",
"or",
".",
"as",
"link",
"separators"
] | python | train | 47.333333 |
saltstack/salt | salt/engines/libvirt_events.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L285-L291 | def _domain_event_watchdog_cb(conn, domain, action, opaque):
'''
Domain watchdog events handler
'''
_salt_send_domain_event(opaque, conn, domain, opaque['event'], {
'action': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_WATCHDOG_', action)
}) | [
"def",
"_domain_event_watchdog_cb",
"(",
"conn",
",",
"domain",
",",
"action",
",",
"opaque",
")",
":",
"_salt_send_domain_event",
"(",
"opaque",
",",
"conn",
",",
"domain",
",",
"opaque",
"[",
"'event'",
"]",
",",
"{",
"'action'",
":",
"_get_libvirt_enum_stri... | Domain watchdog events handler | [
"Domain",
"watchdog",
"events",
"handler"
] | python | train | 37.428571 |
maaku/python-bitcoin | bitcoin/tools.py | https://github.com/maaku/python-bitcoin/blob/1b80c284170fd3f547cc45f4700ce169f3f99641/bitcoin/tools.py#L34-L57 | def compress_amount(n):
"""\
Compress 64-bit integer values, preferring a smaller size for whole
numbers (base-10), so as to achieve run-length encoding gains on real-
world data. The basic algorithm:
* If the amount is 0, return 0
* Divide the amount (in base units) evenly by the larges... | [
"def",
"compress_amount",
"(",
"n",
")",
":",
"if",
"not",
"n",
":",
"return",
"0",
"e",
"=",
"0",
"while",
"(",
"n",
"%",
"10",
")",
"==",
"0",
"and",
"e",
"<",
"9",
":",
"n",
"=",
"n",
"//",
"10",
"e",
"=",
"e",
"+",
"1",
"if",
"e",
"... | \
Compress 64-bit integer values, preferring a smaller size for whole
numbers (base-10), so as to achieve run-length encoding gains on real-
world data. The basic algorithm:
* If the amount is 0, return 0
* Divide the amount (in base units) evenly by the largest power of 10
possibl... | [
"\\",
"Compress",
"64",
"-",
"bit",
"integer",
"values",
"preferring",
"a",
"smaller",
"size",
"for",
"whole",
"numbers",
"(",
"base",
"-",
"10",
")",
"so",
"as",
"to",
"achieve",
"run",
"-",
"length",
"encoding",
"gains",
"on",
"real",
"-",
"world",
"... | python | train | 40.083333 |
numenta/nupic | src/nupic/regions/knn_classifier_region.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/knn_classifier_region.py#L605-L619 | def _initEphemerals(self):
"""
Initialize attributes that are not saved with the checkpoint.
"""
self._firstComputeCall = True
self._accuracy = None
self._protoScores = None
self._categoryDistances = None
self._knn = knn_classifier.KNNClassifier(**self.knnParams)
for x in ('_partit... | [
"def",
"_initEphemerals",
"(",
"self",
")",
":",
"self",
".",
"_firstComputeCall",
"=",
"True",
"self",
".",
"_accuracy",
"=",
"None",
"self",
".",
"_protoScores",
"=",
"None",
"self",
".",
"_categoryDistances",
"=",
"None",
"self",
".",
"_knn",
"=",
"knn_... | Initialize attributes that are not saved with the checkpoint. | [
"Initialize",
"attributes",
"that",
"are",
"not",
"saved",
"with",
"the",
"checkpoint",
"."
] | python | valid | 30 |
RockFeng0/rtsf-http | httpdriver/actions.py | https://github.com/RockFeng0/rtsf-http/blob/3280cc9a01b0c92c52d699b0ebc29e55e62611a0/httpdriver/actions.py#L227-L245 | def DyStrData(cls,name, regx, index = 0):
''' set dynamic value from the string data of response
@param name: glob parameter name
@param regx: re._pattern_type
e.g.
DyStrData("a",re.compile('123'))
'''
text = Markup(cls.__trackinfo["response_body"... | [
"def",
"DyStrData",
"(",
"cls",
",",
"name",
",",
"regx",
",",
"index",
"=",
"0",
")",
":",
"text",
"=",
"Markup",
"(",
"cls",
".",
"__trackinfo",
"[",
"\"response_body\"",
"]",
")",
".",
"unescape",
"(",
")",
"if",
"not",
"text",
":",
"return",
"i... | set dynamic value from the string data of response
@param name: glob parameter name
@param regx: re._pattern_type
e.g.
DyStrData("a",re.compile('123')) | [
"set",
"dynamic",
"value",
"from",
"the",
"string",
"data",
"of",
"response"
] | python | train | 37.105263 |
bloomreach/s4cmd | s4cmd.py | https://github.com/bloomreach/s4cmd/blob/bb51075bf43703e7cd95aa39288cf7732ec13a6d/s4cmd.py#L1208-L1223 | def conditional(self, result, obj):
'''Check all file item with given conditions.'''
fileonly = (self.opt.last_modified_before is not None) or (self.opt.last_modified_after is not None)
if obj['is_dir']:
if not fileonly:
result.append(obj)
return
if (self.opt.last_modified_before i... | [
"def",
"conditional",
"(",
"self",
",",
"result",
",",
"obj",
")",
":",
"fileonly",
"=",
"(",
"self",
".",
"opt",
".",
"last_modified_before",
"is",
"not",
"None",
")",
"or",
"(",
"self",
".",
"opt",
".",
"last_modified_after",
"is",
"not",
"None",
")"... | Check all file item with given conditions. | [
"Check",
"all",
"file",
"item",
"with",
"given",
"conditions",
"."
] | python | test | 33.375 |
pachyderm/python-pachyderm | src/python_pachyderm/pfs_client.py | https://github.com/pachyderm/python-pachyderm/blob/1c58cf91d30e03716a4f45213989e890f7b8a78c/src/python_pachyderm/pfs_client.py#L290-L361 | def put_file_bytes(self, commit, path, value, delimiter=proto.NONE,
target_file_datums=0, target_file_bytes=0, overwrite_index=None):
"""
Uploads a binary bytes array as file(s) in a certain path.
Params:
* commit: A tuple, string, or Commit object representing th... | [
"def",
"put_file_bytes",
"(",
"self",
",",
"commit",
",",
"path",
",",
"value",
",",
"delimiter",
"=",
"proto",
".",
"NONE",
",",
"target_file_datums",
"=",
"0",
",",
"target_file_bytes",
"=",
"0",
",",
"overwrite_index",
"=",
"None",
")",
":",
"overwrite_... | Uploads a binary bytes array as file(s) in a certain path.
Params:
* commit: A tuple, string, or Commit object representing the commit.
* path: Path in the repo the file(s) will be written to.
* value: The file contents as bytes, represented as a file-like
object, bytestring, or... | [
"Uploads",
"a",
"binary",
"bytes",
"array",
"as",
"file",
"(",
"s",
")",
"in",
"a",
"certain",
"path",
"."
] | python | train | 47.097222 |
h2non/pook | pook/response.py | https://github.com/h2non/pook/blob/e64094e41e4d89d98d2d29af7608ef27dc50cf19/pook/response.py#L148-L161 | def body(self, body):
"""
Defines response body data.
Arguments:
body (str|bytes): response body to use.
Returns:
self: ``pook.Response`` current instance.
"""
if isinstance(body, bytes):
body = body.decode('utf-8')
self._bod... | [
"def",
"body",
"(",
"self",
",",
"body",
")",
":",
"if",
"isinstance",
"(",
"body",
",",
"bytes",
")",
":",
"body",
"=",
"body",
".",
"decode",
"(",
"'utf-8'",
")",
"self",
".",
"_body",
"=",
"body"
] | Defines response body data.
Arguments:
body (str|bytes): response body to use.
Returns:
self: ``pook.Response`` current instance. | [
"Defines",
"response",
"body",
"data",
"."
] | python | test | 22.5 |
h2oai/h2o-3 | h2o-py/h2o/estimators/glm.py | https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/h2o-py/h2o/estimators/glm.py#L879-L898 | def makeGLMModel(model, coefs, threshold=.5):
"""
Create a custom GLM model using the given coefficients.
Needs to be passed source model trained on the dataset to extract the dataset information from.
:param model: source model, used for extracting dataset information
:param c... | [
"def",
"makeGLMModel",
"(",
"model",
",",
"coefs",
",",
"threshold",
"=",
".5",
")",
":",
"model_json",
"=",
"h2o",
".",
"api",
"(",
"\"POST /3/MakeGLMModel\"",
",",
"data",
"=",
"{",
"\"model\"",
":",
"model",
".",
"_model_json",
"[",
"\"model_id\"",
"]",... | Create a custom GLM model using the given coefficients.
Needs to be passed source model trained on the dataset to extract the dataset information from.
:param model: source model, used for extracting dataset information
:param coefs: dictionary containing model coefficients
:param thre... | [
"Create",
"a",
"custom",
"GLM",
"model",
"using",
"the",
"given",
"coefficients",
"."
] | python | test | 43.35 |
barrust/pyspellchecker | spellchecker/spellchecker.py | https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L350-L359 | def items(self):
""" Iterator over the words in the dictionary
Yields:
str: The next word in the dictionary
int: The number of instances in the dictionary
Note:
This is the same as `dict.items()` """
for word in self._dictionary.ke... | [
"def",
"items",
"(",
"self",
")",
":",
"for",
"word",
"in",
"self",
".",
"_dictionary",
".",
"keys",
"(",
")",
":",
"yield",
"word",
",",
"self",
".",
"_dictionary",
"[",
"word",
"]"
] | Iterator over the words in the dictionary
Yields:
str: The next word in the dictionary
int: The number of instances in the dictionary
Note:
This is the same as `dict.items()` | [
"Iterator",
"over",
"the",
"words",
"in",
"the",
"dictionary"
] | python | train | 36.3 |
Qiskit/qiskit-api-py | IBMQuantumExperience/IBMQuantumExperience.py | https://github.com/Qiskit/qiskit-api-py/blob/2ab240110fb7e653254e44c4833f3643e8ae7f0f/IBMQuantumExperience/IBMQuantumExperience.py#L996-L1012 | def available_backend_simulators(self, access_token=None, user_id=None):
"""
Get the backend simulators available to use in the QX Platform
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id... | [
"def",
"available_backend_simulators",
"(",
"self",
",",
"access_token",
"=",
"None",
",",
"user_id",
"=",
"None",
")",
":",
"if",
"access_token",
":",
"self",
".",
"req",
".",
"credential",
".",
"set_token",
"(",
"access_token",
")",
"if",
"user_id",
":",
... | Get the backend simulators available to use in the QX Platform | [
"Get",
"the",
"backend",
"simulators",
"available",
"to",
"use",
"in",
"the",
"QX",
"Platform"
] | python | train | 41.647059 |
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#L143-L155 | def _make_git(config_info):
"""This function initializes and Git SCM tool object."""
git_args = {}
def _add_value(value, key):
args_key, args_value = _GIT_ARG_FNS[key](value)
git_args[args_key] = args_value
devpipeline_core.toolsupport.args_builder("git", config_info, _GIT_ARGS, _add_v... | [
"def",
"_make_git",
"(",
"config_info",
")",
":",
"git_args",
"=",
"{",
"}",
"def",
"_add_value",
"(",
"value",
",",
"key",
")",
":",
"args_key",
",",
"args_value",
"=",
"_GIT_ARG_FNS",
"[",
"key",
"]",
"(",
"value",
")",
"git_args",
"[",
"args_key",
"... | This function initializes and Git SCM tool object. | [
"This",
"function",
"initializes",
"and",
"Git",
"SCM",
"tool",
"object",
"."
] | python | train | 38.538462 |
tensorflow/tensor2tensor | tensor2tensor/data_generators/wikisum/utils.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/utils.py#L118-L127 | def wet_records(wet_filepath):
"""Generate WETRecords from filepath."""
if wet_filepath.endswith('.gz'):
fopen = gzip.open
else:
fopen = tf.gfile.GFile
with fopen(wet_filepath) as f:
for record in wet_records_from_file_obj(f):
yield record | [
"def",
"wet_records",
"(",
"wet_filepath",
")",
":",
"if",
"wet_filepath",
".",
"endswith",
"(",
"'.gz'",
")",
":",
"fopen",
"=",
"gzip",
".",
"open",
"else",
":",
"fopen",
"=",
"tf",
".",
"gfile",
".",
"GFile",
"with",
"fopen",
"(",
"wet_filepath",
")... | Generate WETRecords from filepath. | [
"Generate",
"WETRecords",
"from",
"filepath",
"."
] | python | train | 25.7 |
totalgood/nlpia | src/nlpia/loaders.py | https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L1320-L1346 | def isglove(filepath):
""" Get the first word vector in a GloVE file and return its dimensionality or False if not a vector
>>> isglove(os.path.join(DATA_PATH, 'cats_and_dogs.txt'))
False
"""
with ensure_open(filepath, 'r') as f:
header_line = f.readline()
vector_line = f.readline(... | [
"def",
"isglove",
"(",
"filepath",
")",
":",
"with",
"ensure_open",
"(",
"filepath",
",",
"'r'",
")",
"as",
"f",
":",
"header_line",
"=",
"f",
".",
"readline",
"(",
")",
"vector_line",
"=",
"f",
".",
"readline",
"(",
")",
"try",
":",
"num_vectors",
"... | Get the first word vector in a GloVE file and return its dimensionality or False if not a vector
>>> isglove(os.path.join(DATA_PATH, 'cats_and_dogs.txt'))
False | [
"Get",
"the",
"first",
"word",
"vector",
"in",
"a",
"GloVE",
"file",
"and",
"return",
"its",
"dimensionality",
"or",
"False",
"if",
"not",
"a",
"vector"
] | python | train | 28.518519 |
numenta/nupic | src/nupic/swarming/dummy_model_runner.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/dummy_model_runner.py#L352-L390 | def _computModelDelay(self):
""" Computes the amount of time (if any) to delay the run of this model.
This can be determined by two mutually exclusive parameters:
delay and sleepModelRange.
'delay' specifies the number of seconds a model should be delayed. If a list
is specified, the appropriate am... | [
"def",
"_computModelDelay",
"(",
"self",
")",
":",
"# 'delay' and 'sleepModelRange' are mutually exclusive",
"if",
"self",
".",
"_params",
"[",
"'delay'",
"]",
"is",
"not",
"None",
"and",
"self",
".",
"_params",
"[",
"'sleepModelRange'",
"]",
"is",
"not",
"None",
... | Computes the amount of time (if any) to delay the run of this model.
This can be determined by two mutually exclusive parameters:
delay and sleepModelRange.
'delay' specifies the number of seconds a model should be delayed. If a list
is specified, the appropriate amount of delay is determined by using ... | [
"Computes",
"the",
"amount",
"of",
"time",
"(",
"if",
"any",
")",
"to",
"delay",
"the",
"run",
"of",
"this",
"model",
".",
"This",
"can",
"be",
"determined",
"by",
"two",
"mutually",
"exclusive",
"parameters",
":",
"delay",
"and",
"sleepModelRange",
"."
] | python | valid | 40.487179 |
feliperyan/EinsteinVisionPython | EinsteinVision/EinsteinVision.py | https://github.com/feliperyan/EinsteinVisionPython/blob/c761c46c7dc5fe8bbe7b15a6e1166a3585ed3cfb/EinsteinVision/EinsteinVision.py#L367-L379 | def save_parsed_data_to_csv(self, output_filename='output.csv'):
""" Outputs a csv file in accordance with parse_rectlabel_app_output method. This csv file is meant to accompany a set of pictures files
in the creation of an Object Detection dataset.
:param output_filename string, default... | [
"def",
"save_parsed_data_to_csv",
"(",
"self",
",",
"output_filename",
"=",
"'output.csv'",
")",
":",
"result",
"=",
"self",
".",
"parse_rectlabel_app_output",
"(",
")",
"ff",
"=",
"open",
"(",
"output_filename",
",",
"'w'",
",",
"encoding",
"=",
"'utf8'",
")"... | Outputs a csv file in accordance with parse_rectlabel_app_output method. This csv file is meant to accompany a set of pictures files
in the creation of an Object Detection dataset.
:param output_filename string, default makes sense, but for your convenience. | [
"Outputs",
"a",
"csv",
"file",
"in",
"accordance",
"with",
"parse_rectlabel_app_output",
"method",
".",
"This",
"csv",
"file",
"is",
"meant",
"to",
"accompany",
"a",
"set",
"of",
"pictures",
"files",
"in",
"the",
"creation",
"of",
"an",
"Object",
"Detection",
... | python | train | 42.384615 |
LISE-B26/pylabcontrol | build/lib/pylabcontrol/src/core/scripts.py | https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/src/core/scripts.py#L198-L209 | def log(self, string):
"""
appends input string to log file and sends it to log function (self.log_function)
Returns:
"""
self.log_data.append(string)
if self.log_function is None:
print(string)
else:
self.log_function(string) | [
"def",
"log",
"(",
"self",
",",
"string",
")",
":",
"self",
".",
"log_data",
".",
"append",
"(",
"string",
")",
"if",
"self",
".",
"log_function",
"is",
"None",
":",
"print",
"(",
"string",
")",
"else",
":",
"self",
".",
"log_function",
"(",
"string"... | appends input string to log file and sends it to log function (self.log_function)
Returns: | [
"appends",
"input",
"string",
"to",
"log",
"file",
"and",
"sends",
"it",
"to",
"log",
"function",
"(",
"self",
".",
"log_function",
")",
"Returns",
":"
] | python | train | 24.75 |
gumblex/zhconv | zhconv/zhconv.py | https://github.com/gumblex/zhconv/blob/925c0f9494f3439bc05526e7e89bb5f0ab3d185e/zhconv/zhconv.py#L449-L475 | def main():
"""
Simple stdin/stdout interface.
"""
if len(sys.argv) == 2 and sys.argv[1] in Locales:
locale = sys.argv[1]
convertfunc = convert
elif len(sys.argv) == 3 and sys.argv[1] == '-w' and sys.argv[2] in Locales:
locale = sys.argv[2]
convertfunc = convert_for_m... | [
"def",
"main",
"(",
")",
":",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
"==",
"2",
"and",
"sys",
".",
"argv",
"[",
"1",
"]",
"in",
"Locales",
":",
"locale",
"=",
"sys",
".",
"argv",
"[",
"1",
"]",
"convertfunc",
"=",
"convert",
"elif",
"len",
... | Simple stdin/stdout interface. | [
"Simple",
"stdin",
"/",
"stdout",
"interface",
"."
] | python | train | 31.555556 |
biocore/burrito | burrito/util.py | https://github.com/biocore/burrito/blob/3b1dcc560431cc2b7a4856b99aafe36d32082356/burrito/util.py#L332-L346 | def _input_as_multiline_string(self, data):
"""Write a multiline string to a temp file and return the filename.
data: a multiline string to be written to a file.
* Note: the result will be the filename as a FilePath object
(which is a string subclass).
"""
f... | [
"def",
"_input_as_multiline_string",
"(",
"self",
",",
"data",
")",
":",
"filename",
"=",
"self",
".",
"_input_filename",
"=",
"FilePath",
"(",
"self",
".",
"getTmpFilename",
"(",
"self",
".",
"TmpDir",
")",
")",
"data_file",
"=",
"open",
"(",
"filename",
... | Write a multiline string to a temp file and return the filename.
data: a multiline string to be written to a file.
* Note: the result will be the filename as a FilePath object
(which is a string subclass). | [
"Write",
"a",
"multiline",
"string",
"to",
"a",
"temp",
"file",
"and",
"return",
"the",
"filename",
"."
] | python | train | 34.333333 |
dpkp/kafka-python | kafka/metrics/metrics.py | https://github.com/dpkp/kafka-python/blob/f6a8a38937688ea2cc5dc13d3d1039493be5c9b5/kafka/metrics/metrics.py#L218-L222 | def add_reporter(self, reporter):
"""Add a MetricReporter"""
with self._lock:
reporter.init(list(self.metrics.values()))
self._reporters.append(reporter) | [
"def",
"add_reporter",
"(",
"self",
",",
"reporter",
")",
":",
"with",
"self",
".",
"_lock",
":",
"reporter",
".",
"init",
"(",
"list",
"(",
"self",
".",
"metrics",
".",
"values",
"(",
")",
")",
")",
"self",
".",
"_reporters",
".",
"append",
"(",
"... | Add a MetricReporter | [
"Add",
"a",
"MetricReporter"
] | python | train | 37.8 |
mitsei/dlkit | dlkit/json_/assessment/mixins.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/assessment/mixins.py#L421-L436 | def _get_question_map(self, question_id):
"""get question map from questions matching question_id
This can make sense of both Section assigned Ids or normal Question/Item Ids
"""
if question_id.get_authority() == ASSESSMENT_AUTHORITY:
key = '_id'
match_value = O... | [
"def",
"_get_question_map",
"(",
"self",
",",
"question_id",
")",
":",
"if",
"question_id",
".",
"get_authority",
"(",
")",
"==",
"ASSESSMENT_AUTHORITY",
":",
"key",
"=",
"'_id'",
"match_value",
"=",
"ObjectId",
"(",
"question_id",
".",
"get_identifier",
"(",
... | get question map from questions matching question_id
This can make sense of both Section assigned Ids or normal Question/Item Ids | [
"get",
"question",
"map",
"from",
"questions",
"matching",
"question_id"
] | python | train | 37.625 |
pantsbuild/pants | src/python/pants/backend/python/tasks/python_binary_create.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/python/tasks/python_binary_create.py#L105-L159 | def _create_binary(self, binary_tgt, results_dir):
"""Create a .pex file for the specified binary target."""
# Note that we rebuild a chroot from scratch, instead of using the REQUIREMENTS_PEX
# and PYTHON_SOURCES products, because those products are already-built pexes, and there's
# no easy way to mer... | [
"def",
"_create_binary",
"(",
"self",
",",
"binary_tgt",
",",
"results_dir",
")",
":",
"# Note that we rebuild a chroot from scratch, instead of using the REQUIREMENTS_PEX",
"# and PYTHON_SOURCES products, because those products are already-built pexes, and there's",
"# no easy way to merge ... | Create a .pex file for the specified binary target. | [
"Create",
"a",
".",
"pex",
"file",
"for",
"the",
"specified",
"binary",
"target",
"."
] | python | train | 49.309091 |
Erotemic/utool | utool/util_hash.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_hash.py#L766-L806 | def convert_hexstr_to_bigbase(hexstr, alphabet=ALPHABET, bigbase=BIGBASE):
r"""
Packs a long hexstr into a shorter length string with a larger base
Ignore:
# Determine the length savings with lossless conversion
import sympy as sy
consts = dict(hexbase=16, hexlen=256, bigbase=27)
... | [
"def",
"convert_hexstr_to_bigbase",
"(",
"hexstr",
",",
"alphabet",
"=",
"ALPHABET",
",",
"bigbase",
"=",
"BIGBASE",
")",
":",
"x",
"=",
"int",
"(",
"hexstr",
",",
"16",
")",
"# first convert to base 16",
"if",
"x",
"==",
"0",
":",
"return",
"'0'",
"sign",... | r"""
Packs a long hexstr into a shorter length string with a larger base
Ignore:
# Determine the length savings with lossless conversion
import sympy as sy
consts = dict(hexbase=16, hexlen=256, bigbase=27)
symbols = sy.symbols('hexbase, hexlen, bigbase, newlen')
haexbase... | [
"r",
"Packs",
"a",
"long",
"hexstr",
"into",
"a",
"shorter",
"length",
"string",
"with",
"a",
"larger",
"base"
] | python | train | 32.146341 |
OSSOS/MOP | src/jjk/preproc/MOPplot.py | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPplot.py#L803-L881 | def save_pointings(self):
"""Print the currently defined FOVs"""
import tkFileDialog
f=tkFileDialog.asksaveasfile()
i=0
if self.pointing_format.get()=='CFHT PH':
f.write("""<?xml version = "1.0"?>
<!DOCTYPE ASTRO SYSTEM "http://vizier.u-strasbg.fr/xml/astrores.dtd">
<ASTRO ... | [
"def",
"save_pointings",
"(",
"self",
")",
":",
"import",
"tkFileDialog",
"f",
"=",
"tkFileDialog",
".",
"asksaveasfile",
"(",
")",
"i",
"=",
"0",
"if",
"self",
".",
"pointing_format",
".",
"get",
"(",
")",
"==",
"'CFHT PH'",
":",
"f",
".",
"write",
"(... | Print the currently defined FOVs | [
"Print",
"the",
"currently",
"defined",
"FOVs"
] | python | train | 37.759494 |
xguse/table_enforcer | table_enforcer/utils/validate/decorators.py | https://github.com/xguse/table_enforcer/blob/f3137839574bf8ea933a14ea16a8acba45e3e0c3/table_enforcer/utils/validate/decorators.py#L5-L20 | def minmax(low, high):
"""Test that the data items fall within range: low <= x <= high."""
def decorator(function):
"""Decorate a function with args."""
@functools.wraps(function)
def wrapper(*args, **kwargs):
"""Wrap the function."""
series = function(*args, **kw... | [
"def",
"minmax",
"(",
"low",
",",
"high",
")",
":",
"def",
"decorator",
"(",
"function",
")",
":",
"\"\"\"Decorate a function with args.\"\"\"",
"@",
"functools",
".",
"wraps",
"(",
"function",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwarg... | Test that the data items fall within range: low <= x <= high. | [
"Test",
"that",
"the",
"data",
"items",
"fall",
"within",
"range",
":",
"low",
"<",
"=",
"x",
"<",
"=",
"high",
"."
] | python | train | 29.1875 |
google/pyringe | pyringe/payload/libpython.py | https://github.com/google/pyringe/blob/76dff5d1ac29cd5e7bf32677654a83291a15ad8a/pyringe/payload/libpython.py#L1185-L1194 | def get_index(self):
'''Calculate index of frame, starting at 0 for the newest frame within
this thread'''
index = 0
# Go down until you reach the newest frame:
iter_frame = self
while iter_frame.newer():
index += 1
iter_frame = iter_frame.newer()
... | [
"def",
"get_index",
"(",
"self",
")",
":",
"index",
"=",
"0",
"# Go down until you reach the newest frame:",
"iter_frame",
"=",
"self",
"while",
"iter_frame",
".",
"newer",
"(",
")",
":",
"index",
"+=",
"1",
"iter_frame",
"=",
"iter_frame",
".",
"newer",
"(",
... | Calculate index of frame, starting at 0 for the newest frame within
this thread | [
"Calculate",
"index",
"of",
"frame",
"starting",
"at",
"0",
"for",
"the",
"newest",
"frame",
"within",
"this",
"thread"
] | python | train | 33.1 |
spacetelescope/stsci.tools | lib/stsci/tools/editpar.py | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/editpar.py#L1688-L1693 | def _pushMessages(self):
""" Internal callback used to make sure the msg list keeps moving. """
# This continues to get itself called until no msgs are left in list.
self.showStatus('')
if len(self._statusMsgsToShow) > 0:
self.top.after(200, self._pushMessages) | [
"def",
"_pushMessages",
"(",
"self",
")",
":",
"# This continues to get itself called until no msgs are left in list.",
"self",
".",
"showStatus",
"(",
"''",
")",
"if",
"len",
"(",
"self",
".",
"_statusMsgsToShow",
")",
">",
"0",
":",
"self",
".",
"top",
".",
"a... | Internal callback used to make sure the msg list keeps moving. | [
"Internal",
"callback",
"used",
"to",
"make",
"sure",
"the",
"msg",
"list",
"keeps",
"moving",
"."
] | python | train | 50 |
klen/zeta-library | zetalibrary/scss/__init__.py | https://github.com/klen/zeta-library/blob/b76f89000f467e10ddcc94aded3f6c6bf4a0e5bd/zetalibrary/scss/__init__.py#L1307-L1317 | def _do_else(self, rule, p_selectors, p_parents, p_children, scope, media, c_lineno, c_property, c_codestr, code, name):
"""
Implements @else
"""
if '@if' not in rule[OPTIONS]:
log.error("@else with no @if (%s", rule[INDEX][rule[LINENO]])
val = rule[OPTIONS].pop('@if'... | [
"def",
"_do_else",
"(",
"self",
",",
"rule",
",",
"p_selectors",
",",
"p_parents",
",",
"p_children",
",",
"scope",
",",
"media",
",",
"c_lineno",
",",
"c_property",
",",
"c_codestr",
",",
"code",
",",
"name",
")",
":",
"if",
"'@if'",
"not",
"in",
"rul... | Implements @else | [
"Implements"
] | python | train | 43.727273 |
BlueBrain/NeuroM | examples/radius_of_gyration.py | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/examples/radius_of_gyration.py#L74-L82 | def radius_of_gyration(neurite):
'''Calculate and return radius of gyration of a given neurite.'''
centre_mass = neurite_centre_of_mass(neurite)
sum_sqr_distance = 0
N = 0
dist_sqr = [distance_sqr(centre_mass, s) for s in nm.iter_segments(neurite)]
sum_sqr_distance = np.sum(dist_sqr)
N = len... | [
"def",
"radius_of_gyration",
"(",
"neurite",
")",
":",
"centre_mass",
"=",
"neurite_centre_of_mass",
"(",
"neurite",
")",
"sum_sqr_distance",
"=",
"0",
"N",
"=",
"0",
"dist_sqr",
"=",
"[",
"distance_sqr",
"(",
"centre_mass",
",",
"s",
")",
"for",
"s",
"in",
... | Calculate and return radius of gyration of a given neurite. | [
"Calculate",
"and",
"return",
"radius",
"of",
"gyration",
"of",
"a",
"given",
"neurite",
"."
] | python | train | 40.333333 |
apache/incubator-heron | third_party/python/cpplint/cpplint.py | https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L5479-L5498 | def ExpectingFunctionArgs(clean_lines, linenum):
"""Checks whether where function type arguments are expected.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if the line at 'linenum' is inside something that expects arguments
... | [
"def",
"ExpectingFunctionArgs",
"(",
"clean_lines",
",",
"linenum",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"return",
"(",
"Match",
"(",
"r'^\\s*MOCK_(CONST_)?METHOD\\d+(_T)?\\('",
",",
"line",
")",
"or",
"(",
"linenum",
">=",
... | Checks whether where function type arguments are expected.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if the line at 'linenum' is inside something that expects arguments
of function types. | [
"Checks",
"whether",
"where",
"function",
"type",
"arguments",
"are",
"expected",
"."
] | python | valid | 40.5 |
linkedin/naarad | src/naarad/reporting/diff.py | https://github.com/linkedin/naarad/blob/261e2c0760fd6a6b0ee59064180bd8e3674311fe/src/naarad/reporting/diff.py#L313-L368 | def generate(self):
"""
Generate a diff report from the reports specified.
:return: True/False : return status of whether the diff report generation succeeded.
"""
if (self.discover(CONSTANTS.STATS_CSV_LIST_FILE) and self.discover(CONSTANTS.PLOTS_CSV_LIST_FILE) and self.discover(CONSTANTS.CDF_PLOTS_... | [
"def",
"generate",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"discover",
"(",
"CONSTANTS",
".",
"STATS_CSV_LIST_FILE",
")",
"and",
"self",
".",
"discover",
"(",
"CONSTANTS",
".",
"PLOTS_CSV_LIST_FILE",
")",
"and",
"self",
".",
"discover",
"(",
"CONSTA... | Generate a diff report from the reports specified.
:return: True/False : return status of whether the diff report generation succeeded. | [
"Generate",
"a",
"diff",
"report",
"from",
"the",
"reports",
"specified",
".",
":",
"return",
":",
"True",
"/",
"False",
":",
"return",
"status",
"of",
"whether",
"the",
"diff",
"report",
"generation",
"succeeded",
"."
] | python | valid | 57.732143 |
albert12132/templar | templar/api/publish.py | https://github.com/albert12132/templar/blob/39851c89730ab69e5c73d0a46adca2a44ecc4165/templar/api/publish.py#L18-L104 | def publish(config, source=None, template=None, destination=None, jinja_env=None, no_write=False):
"""Given a config, performs an end-to-end publishing pipeline and returns the result:
linking -> compiling -> templating -> writing
NOTE: at most one of source and template can be None. If both are None,... | [
"def",
"publish",
"(",
"config",
",",
"source",
"=",
"None",
",",
"template",
"=",
"None",
",",
"destination",
"=",
"None",
",",
"jinja_env",
"=",
"None",
",",
"no_write",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"config",
",",
"Config",... | Given a config, performs an end-to-end publishing pipeline and returns the result:
linking -> compiling -> templating -> writing
NOTE: at most one of source and template can be None. If both are None, the publisher
effectively has nothing to do; an exception is raised.
PARAMETERS:
config ... | [
"Given",
"a",
"config",
"performs",
"an",
"end",
"-",
"to",
"-",
"end",
"publishing",
"pipeline",
"and",
"returns",
"the",
"result",
":"
] | python | train | 47.850575 |
cdeboever3/cdpybio | cdpybio/star.py | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/star.py#L535-L547 | def _total_jxn_counts(fns):
"""Count the total unique coverage junction for junctions in a set of
SJ.out.tab files."""
df = pd.read_table(fns[0], header=None, names=COLUMN_NAMES)
df.index = (df.chrom + ':' + df.start.astype(int).astype(str) + '-' +
df.end.astype(int).astype(str))
cou... | [
"def",
"_total_jxn_counts",
"(",
"fns",
")",
":",
"df",
"=",
"pd",
".",
"read_table",
"(",
"fns",
"[",
"0",
"]",
",",
"header",
"=",
"None",
",",
"names",
"=",
"COLUMN_NAMES",
")",
"df",
".",
"index",
"=",
"(",
"df",
".",
"chrom",
"+",
"':'",
"+"... | Count the total unique coverage junction for junctions in a set of
SJ.out.tab files. | [
"Count",
"the",
"total",
"unique",
"coverage",
"junction",
"for",
"junctions",
"in",
"a",
"set",
"of",
"SJ",
".",
"out",
".",
"tab",
"files",
"."
] | python | train | 49.307692 |
inveniosoftware/invenio-files-rest | invenio_files_rest/models.py | https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L1186-L1201 | def get_versions(cls, bucket, key, desc=True):
"""Fetch all versions of a specific object.
:param bucket: The bucket (instance or id) to get the object from.
:param key: Key of object.
:param desc: Sort results desc if True, asc otherwise.
:returns: The query to execute to fetch... | [
"def",
"get_versions",
"(",
"cls",
",",
"bucket",
",",
"key",
",",
"desc",
"=",
"True",
")",
":",
"filters",
"=",
"[",
"cls",
".",
"bucket_id",
"==",
"as_bucket_id",
"(",
"bucket",
")",
",",
"cls",
".",
"key",
"==",
"key",
",",
"]",
"order",
"=",
... | Fetch all versions of a specific object.
:param bucket: The bucket (instance or id) to get the object from.
:param key: Key of object.
:param desc: Sort results desc if True, asc otherwise.
:returns: The query to execute to fetch all versions. | [
"Fetch",
"all",
"versions",
"of",
"a",
"specific",
"object",
"."
] | python | train | 35.9375 |
riga/law | law/patches.py | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/patches.py#L123-L136 | def patch_cmdline_parser():
"""
Patches the ``luigi.cmdline_parser.CmdlineParser`` to store the original command line arguments
for later processing in the :py:class:`law.config.Config`.
"""
# store original functions
_init = luigi.cmdline_parser.CmdlineParser.__init__
# patch init
def ... | [
"def",
"patch_cmdline_parser",
"(",
")",
":",
"# store original functions",
"_init",
"=",
"luigi",
".",
"cmdline_parser",
".",
"CmdlineParser",
".",
"__init__",
"# patch init",
"def",
"__init__",
"(",
"self",
",",
"cmdline_args",
")",
":",
"_init",
"(",
"self",
... | Patches the ``luigi.cmdline_parser.CmdlineParser`` to store the original command line arguments
for later processing in the :py:class:`law.config.Config`. | [
"Patches",
"the",
"luigi",
".",
"cmdline_parser",
".",
"CmdlineParser",
"to",
"store",
"the",
"original",
"command",
"line",
"arguments",
"for",
"later",
"processing",
"in",
"the",
":",
"py",
":",
"class",
":",
"law",
".",
"config",
".",
"Config",
"."
] | python | train | 33.642857 |
paksu/pytelegraf | telegraf/protocol.py | https://github.com/paksu/pytelegraf/blob/a5a326bd99902768be2bf10da7dde2dfa165c013/telegraf/protocol.py#L46-L58 | def get_output_tags(self):
"""
Return an escaped string of comma separated tag_name: tag_value pairs
Tags should be sorted by key before being sent for best performance. The sort should
match that from the Go bytes. Compare function (http://golang.org/pkg/bytes/#Compare).
"""
... | [
"def",
"get_output_tags",
"(",
"self",
")",
":",
"# Sort the tags in lexicographically by tag name",
"sorted_tags",
"=",
"sorted",
"(",
"self",
".",
"tags",
".",
"items",
"(",
")",
")",
"# Finally render, escape and return the tag string",
"return",
"u\",\"",
".",
"join... | Return an escaped string of comma separated tag_name: tag_value pairs
Tags should be sorted by key before being sent for best performance. The sort should
match that from the Go bytes. Compare function (http://golang.org/pkg/bytes/#Compare). | [
"Return",
"an",
"escaped",
"string",
"of",
"comma",
"separated",
"tag_name",
":",
"tag_value",
"pairs"
] | python | train | 44.230769 |
datadesk/django-bakery | bakery/management/commands/build.py | https://github.com/datadesk/django-bakery/blob/e2feb13a66552a388fbcfaaacdd504bba08d3c69/bakery/management/commands/build.py#L170-L211 | def build_static(self, *args, **options):
"""
Builds the static files directory as well as robots.txt and favicon.ico
"""
logger.debug("Building static directory")
if self.verbosity > 1:
self.stdout.write("Building static directory")
management.call_command(
... | [
"def",
"build_static",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"logger",
".",
"debug",
"(",
"\"Building static directory\"",
")",
"if",
"self",
".",
"verbosity",
">",
"1",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"\"Bui... | Builds the static files directory as well as robots.txt and favicon.ico | [
"Builds",
"the",
"static",
"files",
"directory",
"as",
"well",
"as",
"robots",
".",
"txt",
"and",
"favicon",
".",
"ico"
] | python | train | 45.214286 |
pantsbuild/pants | src/python/pants/pantsd/service/pants_service.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/pantsd/service/pants_service.py#L182-L188 | def mark_pausing(self):
"""Requests that the service move to the Paused state, without waiting for it to do so.
Raises if the service is not currently in the Running state.
"""
with self._lock:
self._set_state(self._PAUSING, self._RUNNING) | [
"def",
"mark_pausing",
"(",
"self",
")",
":",
"with",
"self",
".",
"_lock",
":",
"self",
".",
"_set_state",
"(",
"self",
".",
"_PAUSING",
",",
"self",
".",
"_RUNNING",
")"
] | Requests that the service move to the Paused state, without waiting for it to do so.
Raises if the service is not currently in the Running state. | [
"Requests",
"that",
"the",
"service",
"move",
"to",
"the",
"Paused",
"state",
"without",
"waiting",
"for",
"it",
"to",
"do",
"so",
"."
] | python | train | 36.571429 |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/dvipdf.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/dvipdf.py#L82-L91 | def PDFEmitter(target, source, env):
"""Strips any .aux or .log files from the input source list.
These are created by the TeX Builder that in all likelihood was
used to generate the .dvi file we're using as input, and we only
care about the .dvi file.
"""
def strip_suffixes(n):
return n... | [
"def",
"PDFEmitter",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"def",
"strip_suffixes",
"(",
"n",
")",
":",
"return",
"not",
"SCons",
".",
"Util",
".",
"splitext",
"(",
"str",
"(",
"n",
")",
")",
"[",
"1",
"]",
"in",
"[",
"'.aux'",
",",... | Strips any .aux or .log files from the input source list.
These are created by the TeX Builder that in all likelihood was
used to generate the .dvi file we're using as input, and we only
care about the .dvi file. | [
"Strips",
"any",
".",
"aux",
"or",
".",
"log",
"files",
"from",
"the",
"input",
"source",
"list",
".",
"These",
"are",
"created",
"by",
"the",
"TeX",
"Builder",
"that",
"in",
"all",
"likelihood",
"was",
"used",
"to",
"generate",
"the",
".",
"dvi",
"fil... | python | train | 45.2 |
aiven/pghoard | pghoard/pghoard.py | https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/pghoard.py#L311-L340 | def check_backup_count_and_state(self, site):
"""Look up basebackups from the object store, prune any extra
backups and return the datetime of the latest backup."""
basebackups = self.get_remote_basebackups_info(site)
self.log.debug("Found %r basebackups", basebackups)
if baseba... | [
"def",
"check_backup_count_and_state",
"(",
"self",
",",
"site",
")",
":",
"basebackups",
"=",
"self",
".",
"get_remote_basebackups_info",
"(",
"site",
")",
"self",
".",
"log",
".",
"debug",
"(",
"\"Found %r basebackups\"",
",",
"basebackups",
")",
"if",
"baseba... | Look up basebackups from the object store, prune any extra
backups and return the datetime of the latest backup. | [
"Look",
"up",
"basebackups",
"from",
"the",
"object",
"store",
"prune",
"any",
"extra",
"backups",
"and",
"return",
"the",
"datetime",
"of",
"the",
"latest",
"backup",
"."
] | python | train | 51.566667 |
sanskrit-coders/indic_transliteration | indic_transliteration/sanscript/schemes/roman.py | https://github.com/sanskrit-coders/indic_transliteration/blob/b7c5166a275c15a612fbb96fd3d765bc9004b299/indic_transliteration/sanscript/schemes/roman.py#L30-L38 | def get_standard_form(self, data):
"""Roman schemes define multiple representations of the same devanAgarI character. This method gets a library-standard representation.
data : a text in the given scheme.
"""
if self.synonym_map is None:
return data
from indi... | [
"def",
"get_standard_form",
"(",
"self",
",",
"data",
")",
":",
"if",
"self",
".",
"synonym_map",
"is",
"None",
":",
"return",
"data",
"from",
"indic_transliteration",
"import",
"sanscript",
"return",
"sanscript",
".",
"transliterate",
"(",
"data",
"=",
"sansc... | Roman schemes define multiple representations of the same devanAgarI character. This method gets a library-standard representation.
data : a text in the given scheme. | [
"Roman",
"schemes",
"define",
"multiple",
"representations",
"of",
"the",
"same",
"devanAgarI",
"character",
".",
"This",
"method",
"gets",
"a",
"library",
"-",
"standard",
"representation",
".",
"data",
":",
"a",
"text",
"in",
"the",
"given",
"scheme",
"."
] | python | valid | 56.888889 |
mattlong/hermes | hermes/chatroom.py | https://github.com/mattlong/hermes/blob/63a5afcafe90ca99aeb44edeee9ed6f90baae431/hermes/chatroom.py#L78-L100 | def invite_user(self, new_member, inviter=None, roster=None):
"""Invites a new member to the chatroom"""
roster = roster or self.client.getRoster()
jid = new_member['JID']
logger.info('roster %s %s' % (jid, roster.getSubscription(jid)))
if jid in roster.keys() and roster.getSubs... | [
"def",
"invite_user",
"(",
"self",
",",
"new_member",
",",
"inviter",
"=",
"None",
",",
"roster",
"=",
"None",
")",
":",
"roster",
"=",
"roster",
"or",
"self",
".",
"client",
".",
"getRoster",
"(",
")",
"jid",
"=",
"new_member",
"[",
"'JID'",
"]",
"l... | Invites a new member to the chatroom | [
"Invites",
"a",
"new",
"member",
"to",
"the",
"chatroom"
] | python | train | 49 |
wise-team/python-social-auth-steemconnect | steemconnect/backends.py | https://github.com/wise-team/python-social-auth-steemconnect/blob/087299895bceab587b30740c38fce8d5dbecddb7/steemconnect/backends.py#L41-L53 | def get_user_details(self, response):
"""Return user details from GitHub account"""
account = response['account']
metadata = json.loads(account.get('json_metadata') or '{}')
account['json_metadata'] = metadata
return {
'id': account['id'],
'username': ac... | [
"def",
"get_user_details",
"(",
"self",
",",
"response",
")",
":",
"account",
"=",
"response",
"[",
"'account'",
"]",
"metadata",
"=",
"json",
".",
"loads",
"(",
"account",
".",
"get",
"(",
"'json_metadata'",
")",
"or",
"'{}'",
")",
"account",
"[",
"'jso... | Return user details from GitHub account | [
"Return",
"user",
"details",
"from",
"GitHub",
"account"
] | python | train | 33 |
bunq/sdk_python | bunq/sdk/model/generated/object_.py | https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/object_.py#L4302-L4335 | def get_referenced_object(self):
"""
:rtype: core.BunqModel
:raise: BunqException
"""
if self._BillingInvoice is not None:
return self._BillingInvoice
if self._DraftPayment is not None:
return self._DraftPayment
if self._MasterCardAction... | [
"def",
"get_referenced_object",
"(",
"self",
")",
":",
"if",
"self",
".",
"_BillingInvoice",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_BillingInvoice",
"if",
"self",
".",
"_DraftPayment",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_DraftPayme... | :rtype: core.BunqModel
:raise: BunqException | [
":",
"rtype",
":",
"core",
".",
"BunqModel",
":",
"raise",
":",
"BunqException"
] | python | train | 27 |
pantsbuild/pants | src/python/pants/base/exiter.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/exiter.py#L83-L90 | def exit_and_fail(self, msg=None, out=None):
"""Exits the runtime with a nonzero exit code, indicating failure.
:param msg: A string message to print to stderr or another custom file desciptor before exiting.
(Optional)
:param out: The file descriptor to emit `msg` to. (Optional)
"""
... | [
"def",
"exit_and_fail",
"(",
"self",
",",
"msg",
"=",
"None",
",",
"out",
"=",
"None",
")",
":",
"self",
".",
"exit",
"(",
"result",
"=",
"PANTS_FAILED_EXIT_CODE",
",",
"msg",
"=",
"msg",
",",
"out",
"=",
"out",
")"
] | Exits the runtime with a nonzero exit code, indicating failure.
:param msg: A string message to print to stderr or another custom file desciptor before exiting.
(Optional)
:param out: The file descriptor to emit `msg` to. (Optional) | [
"Exits",
"the",
"runtime",
"with",
"a",
"nonzero",
"exit",
"code",
"indicating",
"failure",
"."
] | python | train | 46.625 |
twilio/twilio-python | twilio/rest/autopilot/v1/assistant/style_sheet.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/autopilot/v1/assistant/style_sheet.py#L202-L212 | def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: StyleSheetContext for this StyleSheetInstance
:rtype: twilio.rest.autopilot.v1.assistant.style_sh... | [
"def",
"_proxy",
"(",
"self",
")",
":",
"if",
"self",
".",
"_context",
"is",
"None",
":",
"self",
".",
"_context",
"=",
"StyleSheetContext",
"(",
"self",
".",
"_version",
",",
"assistant_sid",
"=",
"self",
".",
"_solution",
"[",
"'assistant_sid'",
"]",
"... | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: StyleSheetContext for this StyleSheetInstance
:rtype: twilio.rest.autopilot.v1.assistant.style_sheet.StyleSheetContext | [
"Generate",
"an",
"instance",
"context",
"for",
"the",
"instance",
"the",
"context",
"is",
"capable",
"of",
"performing",
"various",
"actions",
".",
"All",
"instance",
"actions",
"are",
"proxied",
"to",
"the",
"context"
] | python | train | 46.909091 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/process.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L1897-L1920 | def read_structure(self, lpBaseAddress, stype):
"""
Reads a ctypes structure from the memory of the process.
@see: L{read}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin reading.
@type stype: class ctypes.Structure or a subclass.
@para... | [
"def",
"read_structure",
"(",
"self",
",",
"lpBaseAddress",
",",
"stype",
")",
":",
"if",
"type",
"(",
"lpBaseAddress",
")",
"not",
"in",
"(",
"type",
"(",
"0",
")",
",",
"type",
"(",
"long",
"(",
"0",
")",
")",
")",
":",
"lpBaseAddress",
"=",
"cty... | Reads a ctypes structure from the memory of the process.
@see: L{read}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin reading.
@type stype: class ctypes.Structure or a subclass.
@param stype: Structure definition.
@rtype: int
@return... | [
"Reads",
"a",
"ctypes",
"structure",
"from",
"the",
"memory",
"of",
"the",
"process",
"."
] | python | train | 36.208333 |
inveniosoftware/invenio-pages | invenio_pages/models.py | https://github.com/inveniosoftware/invenio-pages/blob/8d544d72fb4c22b7134c521f435add0abed42544/invenio_pages/models.py#L71-L81 | def validate_template_name(self, key, value):
"""Validate template name.
:param key: The template path.
:param value: The template name.
:raises ValueError: If template name is wrong.
"""
if value not in dict(current_app.config['PAGES_TEMPLATES']):
raise Valu... | [
"def",
"validate_template_name",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"value",
"not",
"in",
"dict",
"(",
"current_app",
".",
"config",
"[",
"'PAGES_TEMPLATES'",
"]",
")",
":",
"raise",
"ValueError",
"(",
"'Template \"{0}\" does not exist.'",
... | Validate template name.
:param key: The template path.
:param value: The template name.
:raises ValueError: If template name is wrong. | [
"Validate",
"template",
"name",
"."
] | python | train | 36.545455 |
theonion/django-bulbs | bulbs/content/models.py | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/content/models.py#L597-L606 | def save(self, *args, **kwargs):
"""sets uuid for url
:param args: inline arguments (optional)
:param kwargs: keyword arguments (optional)
:return: `super.save()`
"""
if not self.id: # this is a totally new instance, create uuid value
self.url_uuid = str(uui... | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"id",
":",
"# this is a totally new instance, create uuid value",
"self",
".",
"url_uuid",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
... | sets uuid for url
:param args: inline arguments (optional)
:param kwargs: keyword arguments (optional)
:return: `super.save()` | [
"sets",
"uuid",
"for",
"url"
] | python | train | 39.9 |
softlayer/softlayer-python | SoftLayer/managers/storage_utils.py | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/storage_utils.py#L647-L786 | def prepare_replicant_order_object(manager, snapshot_schedule, location,
tier, volume, volume_type):
"""Prepare the order object which is submitted to the placeOrder() method
:param manager: The File or Block manager calling this function
:param snapshot_schedule: The pri... | [
"def",
"prepare_replicant_order_object",
"(",
"manager",
",",
"snapshot_schedule",
",",
"location",
",",
"tier",
",",
"volume",
",",
"volume_type",
")",
":",
"# Ensure the primary volume and snapshot space are not set for cancellation",
"if",
"'billingItem'",
"not",
"in",
"... | Prepare the order object which is submitted to the placeOrder() method
:param manager: The File or Block manager calling this function
:param snapshot_schedule: The primary volume's snapshot
schedule to use for replication
:param location: The location for the ordered replican... | [
"Prepare",
"the",
"order",
"object",
"which",
"is",
"submitted",
"to",
"the",
"placeOrder",
"()",
"method"
] | python | train | 45.242857 |
clalancette/pycdlib | pycdlib/pycdlib.py | https://github.com/clalancette/pycdlib/blob/1e7b77a809e905d67dc71e12d70e850be26b6233/pycdlib/pycdlib.py#L5593-L5650 | def full_path_from_dirrecord(self, rec, rockridge=False):
# type: (Union[dr.DirectoryRecord, udfmod.UDFFileEntry], bool) -> str
'''
A method to get the absolute path of a directory record.
Parameters:
rec - The directory record to get the full path for.
rockridge - Whe... | [
"def",
"full_path_from_dirrecord",
"(",
"self",
",",
"rec",
",",
"rockridge",
"=",
"False",
")",
":",
"# type: (Union[dr.DirectoryRecord, udfmod.UDFFileEntry], bool) -> str",
"if",
"not",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInvalidI... | A method to get the absolute path of a directory record.
Parameters:
rec - The directory record to get the full path for.
rockridge - Whether to get the rock ridge full path.
Returns:
A string representing the absolute path to the file on the ISO. | [
"A",
"method",
"to",
"get",
"the",
"absolute",
"path",
"of",
"a",
"directory",
"record",
"."
] | python | train | 40.568966 |
postmanlabs/httpbin | httpbin/core.py | https://github.com/postmanlabs/httpbin/blob/f8ec666b4d1b654e4ff6aedd356f510dcac09f83/httpbin/core.py#L1092-L1192 | def digest_auth(
qop=None, user="user", passwd="passwd", algorithm="MD5", stale_after="never"
):
"""Prompts the user for authorization using Digest Auth + Algorithm.
allow settings the stale_after argument.
---
tags:
- Auth
parameters:
- in: path
name: qop
type: strin... | [
"def",
"digest_auth",
"(",
"qop",
"=",
"None",
",",
"user",
"=",
"\"user\"",
",",
"passwd",
"=",
"\"passwd\"",
",",
"algorithm",
"=",
"\"MD5\"",
",",
"stale_after",
"=",
"\"never\"",
")",
":",
"require_cookie_handling",
"=",
"request",
".",
"args",
".",
"g... | Prompts the user for authorization using Digest Auth + Algorithm.
allow settings the stale_after argument.
---
tags:
- Auth
parameters:
- in: path
name: qop
type: string
description: auth or auth-int
- in: path
name: user
type: string
- in:... | [
"Prompts",
"the",
"user",
"for",
"authorization",
"using",
"Digest",
"Auth",
"+",
"Algorithm",
".",
"allow",
"settings",
"the",
"stale_after",
"argument",
".",
"---",
"tags",
":",
"-",
"Auth",
"parameters",
":",
"-",
"in",
":",
"path",
"name",
":",
"qop",
... | python | train | 30.514851 |
IBMStreams/pypi.streamsx | streamsx/spl/spl.py | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/spl/spl.py#L1100-L1113 | def sink(wrapped):
"""Creates an SPL operator with a single input port.
A SPL operator with a single input port and no output ports.
For each tuple on the input port the decorated function
is called passing the contents of the tuple.
.. deprecated:: 1.8
Recommended to use :py:class:`@spl.f... | [
"def",
"sink",
"(",
"wrapped",
")",
":",
"if",
"not",
"inspect",
".",
"isfunction",
"(",
"wrapped",
")",
":",
"raise",
"TypeError",
"(",
"'A function is required'",
")",
"return",
"_wrapforsplop",
"(",
"_OperatorType",
".",
"Sink",
",",
"wrapped",
",",
"'pos... | Creates an SPL operator with a single input port.
A SPL operator with a single input port and no output ports.
For each tuple on the input port the decorated function
is called passing the contents of the tuple.
.. deprecated:: 1.8
Recommended to use :py:class:`@spl.for_each <for_each>` instea... | [
"Creates",
"an",
"SPL",
"operator",
"with",
"a",
"single",
"input",
"port",
"."
] | python | train | 36.214286 |
bradmontgomery/django-blargg | blargg/models.py | https://github.com/bradmontgomery/django-blargg/blob/5d683e04723889a0d1c6d6cf1a67a3d431a2e617/blargg/models.py#L163-L181 | def save(self, *args, **kwargs):
"""Auto-generate a slug from the name."""
self._create_slug()
self._create_date_slug()
self._render_content()
# Call ``_set_published`` the *first* time this Entry is published.
# NOTE: if this is unpublished, and then republished, this m... | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_create_slug",
"(",
")",
"self",
".",
"_create_date_slug",
"(",
")",
"self",
".",
"_render_content",
"(",
")",
"# Call ``_set_published`` the *first* time this Entry... | Auto-generate a slug from the name. | [
"Auto",
"-",
"generate",
"a",
"slug",
"from",
"the",
"name",
"."
] | python | train | 41.210526 |
bspaans/python-mingus | mingus/extra/tablature.py | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/tablature.py#L142-L208 | def from_NoteContainer(notes, width=80, tuning=None):
"""Return a string made out of ASCII tablature representing a
NoteContainer object or list of note strings / Note objects.
Throw a FingerError if no playable fingering can be found.
'tuning' should be a StringTuning object or None for the default t... | [
"def",
"from_NoteContainer",
"(",
"notes",
",",
"width",
"=",
"80",
",",
"tuning",
"=",
"None",
")",
":",
"if",
"tuning",
"is",
"None",
":",
"tuning",
"=",
"default_tuning",
"result",
"=",
"begin_track",
"(",
"tuning",
")",
"l",
"=",
"len",
"(",
"resul... | Return a string made out of ASCII tablature representing a
NoteContainer object or list of note strings / Note objects.
Throw a FingerError if no playable fingering can be found.
'tuning' should be a StringTuning object or None for the default tuning.
To force a certain fingering you can use a 'strin... | [
"Return",
"a",
"string",
"made",
"out",
"of",
"ASCII",
"tablature",
"representing",
"a",
"NoteContainer",
"object",
"or",
"list",
"of",
"note",
"strings",
"/",
"Note",
"objects",
"."
] | python | train | 33.208955 |
Tinche/cattrs | src/cattr/converters.py | https://github.com/Tinche/cattrs/blob/481bc9bdb69b2190d699b54f331c8c5c075506d5/src/cattr/converters.py#L275-L284 | def structure_attrs_fromtuple(self, obj, cl):
# type: (Tuple, Type[T]) -> T
"""Load an attrs class from a sequence (tuple)."""
conv_obj = [] # A list of converter parameters.
for a, value in zip(cl.__attrs_attrs__, obj): # type: ignore
# We detect the type by the metadata.
... | [
"def",
"structure_attrs_fromtuple",
"(",
"self",
",",
"obj",
",",
"cl",
")",
":",
"# type: (Tuple, Type[T]) -> T",
"conv_obj",
"=",
"[",
"]",
"# A list of converter parameters.",
"for",
"a",
",",
"value",
"in",
"zip",
"(",
"cl",
".",
"__attrs_attrs__",
",",
"obj... | Load an attrs class from a sequence (tuple). | [
"Load",
"an",
"attrs",
"class",
"from",
"a",
"sequence",
"(",
"tuple",
")",
"."
] | python | train | 45.3 |
fvdsn/py-xml-escpos | xmlescpos/escpos.py | https://github.com/fvdsn/py-xml-escpos/blob/7f77e039c960d5773fb919aed02ba392dccbc360/xmlescpos/escpos.py#L145-L153 | def push(self, style={}):
"""push a new level on the stack with a style dictionnary containing style:value pairs"""
_style = {}
for attr in style:
if attr in self.cmds and not style[attr] in self.cmds[attr]:
print 'WARNING: ESC/POS PRINTING: ignoring invalid value: '+... | [
"def",
"push",
"(",
"self",
",",
"style",
"=",
"{",
"}",
")",
":",
"_style",
"=",
"{",
"}",
"for",
"attr",
"in",
"style",
":",
"if",
"attr",
"in",
"self",
".",
"cmds",
"and",
"not",
"style",
"[",
"attr",
"]",
"in",
"self",
".",
"cmds",
"[",
"... | push a new level on the stack with a style dictionnary containing style:value pairs | [
"push",
"a",
"new",
"level",
"on",
"the",
"stack",
"with",
"a",
"style",
"dictionnary",
"containing",
"style",
":",
"value",
"pairs"
] | python | train | 53.222222 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L160-L172 | def _signal_handler(self, signal_interupt, frame): # pylint: disable=W0613
"""Handle singal interrupt.
Args:
signal_interupt ([type]): [Description]
frame ([type]): [Description]
"""
if self.container is not None:
print('{}{}Stopping docker container... | [
"def",
"_signal_handler",
"(",
"self",
",",
"signal_interupt",
",",
"frame",
")",
":",
"# pylint: disable=W0613",
"if",
"self",
".",
"container",
"is",
"not",
"None",
":",
"print",
"(",
"'{}{}Stopping docker container.'",
".",
"format",
"(",
"c",
".",
"Style",
... | Handle singal interrupt.
Args:
signal_interupt ([type]): [Description]
frame ([type]): [Description] | [
"Handle",
"singal",
"interrupt",
"."
] | python | train | 43.538462 |
sqlboy/fileseq | src/fileseq/frameset.py | https://github.com/sqlboy/fileseq/blob/f26c3c3c383134ce27d5dfe37793e1ebe88e69ad/src/fileseq/frameset.py#L818-L833 | def issubset(self, other):
"""
Check if the contents of `self` is a subset of the contents of
`other.`
Args:
other (:class:`FrameSet`):
Returns:
bool:
:class:`NotImplemented`: if `other` fails to convert to a :class:`FrameSet`
"""
... | [
"def",
"issubset",
"(",
"self",
",",
"other",
")",
":",
"other",
"=",
"self",
".",
"_cast_to_frameset",
"(",
"other",
")",
"if",
"other",
"is",
"NotImplemented",
":",
"return",
"NotImplemented",
"return",
"self",
".",
"items",
"<=",
"other",
".",
"items"
] | Check if the contents of `self` is a subset of the contents of
`other.`
Args:
other (:class:`FrameSet`):
Returns:
bool:
:class:`NotImplemented`: if `other` fails to convert to a :class:`FrameSet` | [
"Check",
"if",
"the",
"contents",
"of",
"self",
"is",
"a",
"subset",
"of",
"the",
"contents",
"of",
"other",
"."
] | python | train | 28.625 |
log2timeline/plaso | plaso/engine/knowledge_base.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/engine/knowledge_base.py#L242-L259 | def GetValue(self, identifier, default_value=None):
"""Retrieves a value by identifier.
Args:
identifier (str): case insensitive unique identifier for the value.
default_value (object): default value.
Returns:
object: value or default value if not available.
Raises:
TypeError:... | [
"def",
"GetValue",
"(",
"self",
",",
"identifier",
",",
"default_value",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"identifier",
",",
"py2to3",
".",
"STRING_TYPES",
")",
":",
"raise",
"TypeError",
"(",
"'Identifier not a string type.'",
")",
"iden... | Retrieves a value by identifier.
Args:
identifier (str): case insensitive unique identifier for the value.
default_value (object): default value.
Returns:
object: value or default value if not available.
Raises:
TypeError: if the identifier is not a string type. | [
"Retrieves",
"a",
"value",
"by",
"identifier",
"."
] | python | train | 30.777778 |
rbuffat/pyepw | pyepw/epw.py | https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L1671-L1691 | def db004(self, value=None):
""" Corresponds to IDD Field `db004`
Dry-bulb temperature corresponding to 0.4% annual cumulative frequency of occurrence (warm conditions)
Args:
value (float): value for IDD Field `db004`
Unit: C
if `value` is None it wi... | [
"def",
"db004",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"float",
"(",
"value",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'value {} need to be of type float '"... | Corresponds to IDD Field `db004`
Dry-bulb temperature corresponding to 0.4% annual cumulative frequency of occurrence (warm conditions)
Args:
value (float): value for IDD Field `db004`
Unit: C
if `value` is None it will not be checked against the
... | [
"Corresponds",
"to",
"IDD",
"Field",
"db004",
"Dry",
"-",
"bulb",
"temperature",
"corresponding",
"to",
"0",
".",
"4%",
"annual",
"cumulative",
"frequency",
"of",
"occurrence",
"(",
"warm",
"conditions",
")"
] | python | train | 36.333333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.