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 |
|---|---|---|---|---|---|---|---|---|---|
nok/sklearn-porter | sklearn_porter/estimator/classifier/GaussianNB/__init__.py | https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/estimator/classifier/GaussianNB/__init__.py#L201-L212 | def create_class(self, method):
"""
Build the estimator class.
Returns
-------
:return : string
The built class as string.
"""
self.__dict__.update(dict(method=method))
temp_class = self.temp('separated.class')
return temp_class.format... | [
"def",
"create_class",
"(",
"self",
",",
"method",
")",
":",
"self",
".",
"__dict__",
".",
"update",
"(",
"dict",
"(",
"method",
"=",
"method",
")",
")",
"temp_class",
"=",
"self",
".",
"temp",
"(",
"'separated.class'",
")",
"return",
"temp_class",
".",
... | Build the estimator class.
Returns
-------
:return : string
The built class as string. | [
"Build",
"the",
"estimator",
"class",
"."
] | python | train | 27.166667 |
ContextLab/hypertools | hypertools/tools/align.py | https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/tools/align.py#L13-L141 | def align(data, align='hyper', normalize=None, ndims=None, method=None,
format_data=True):
"""
Aligns a list of arrays
This function takes a list of high dimensional arrays and 'hyperaligns' them
to a 'common' space, or coordinate system following the approach outlined by
Haxby et al, 201... | [
"def",
"align",
"(",
"data",
",",
"align",
"=",
"'hyper'",
",",
"normalize",
"=",
"None",
",",
"ndims",
"=",
"None",
",",
"method",
"=",
"None",
",",
"format_data",
"=",
"True",
")",
":",
"# if model is None, just return data",
"if",
"align",
"is",
"None",... | Aligns a list of arrays
This function takes a list of high dimensional arrays and 'hyperaligns' them
to a 'common' space, or coordinate system following the approach outlined by
Haxby et al, 2011. Hyperalignment uses linear transformations (rotation,
reflection, translation, scaling) to register a grou... | [
"Aligns",
"a",
"list",
"of",
"arrays"
] | python | train | 40.589147 |
apacha/OMR-Datasets | omrdatasettools/image_generators/MuscimaPlusPlusImageGenerator.py | https://github.com/apacha/OMR-Datasets/blob/d0a22a03ae35caeef211729efa340e1ec0e01ea5/omrdatasettools/image_generators/MuscimaPlusPlusImageGenerator.py#L37-L43 | def get_all_xml_file_paths(self, raw_data_directory: str) -> List[str]:
""" Loads all XML-files that are located in the folder.
:param raw_data_directory: Path to the raw directory, where the MUSCIMA++ dataset was extracted to
"""
raw_data_directory = os.path.join(raw_data_directory, "v1... | [
"def",
"get_all_xml_file_paths",
"(",
"self",
",",
"raw_data_directory",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"raw_data_directory",
"=",
"os",
".",
"path",
".",
"join",
"(",
"raw_data_directory",
",",
"\"v1.0\"",
",",
"\"data\"",
",",
"\"crop... | Loads all XML-files that are located in the folder.
:param raw_data_directory: Path to the raw directory, where the MUSCIMA++ dataset was extracted to | [
"Loads",
"all",
"XML",
"-",
"files",
"that",
"are",
"located",
"in",
"the",
"folder",
".",
":",
"param",
"raw_data_directory",
":",
"Path",
"to",
"the",
"raw",
"directory",
"where",
"the",
"MUSCIMA",
"++",
"dataset",
"was",
"extracted",
"to"
] | python | train | 68.142857 |
androguard/androguard | androguard/session.py | https://github.com/androguard/androguard/blob/984c0d981be2950cf0451e484f7b0d4d53bc4911/androguard/session.py#L413-L449 | def get_objects_apk(self, filename=None, digest=None):
"""
Returns APK, DalvikVMFormat and Analysis of a specified APK.
You must specify either `filename` or `digest`.
It is possible to use both, but in this case only `digest` is used.
example::
s = Session()
... | [
"def",
"get_objects_apk",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"digest",
"=",
"None",
")",
":",
"if",
"not",
"filename",
"and",
"not",
"digest",
":",
"raise",
"ValueError",
"(",
"\"Must give at least filename or digest!\"",
")",
"if",
"digest",
"is"... | Returns APK, DalvikVMFormat and Analysis of a specified APK.
You must specify either `filename` or `digest`.
It is possible to use both, but in this case only `digest` is used.
example::
s = Session()
digest = s.add("some.apk")
a, d, dx = s.get_objects_apk(... | [
"Returns",
"APK",
"DalvikVMFormat",
"and",
"Analysis",
"of",
"a",
"specified",
"APK",
"."
] | python | train | 33.216216 |
awkman/pywifi | pywifi/_wifiutil_linux.py | https://github.com/awkman/pywifi/blob/719baf73d8d32c623dbaf5e9de5d973face152a4/pywifi/_wifiutil_linux.py#L122-L167 | def add_network_profile(self, obj, params):
"""Add an AP profile for connecting to afterward."""
network_id = self._send_cmd_to_wpas(obj['name'], 'ADD_NETWORK', True)
network_id = network_id.strip()
params.process_akm()
self._send_cmd_to_wpas(
obj['name'],
... | [
"def",
"add_network_profile",
"(",
"self",
",",
"obj",
",",
"params",
")",
":",
"network_id",
"=",
"self",
".",
"_send_cmd_to_wpas",
"(",
"obj",
"[",
"'name'",
"]",
",",
"'ADD_NETWORK'",
",",
"True",
")",
"network_id",
"=",
"network_id",
".",
"strip",
"(",... | Add an AP profile for connecting to afterward. | [
"Add",
"an",
"AP",
"profile",
"for",
"connecting",
"to",
"afterward",
"."
] | python | train | 32.108696 |
kubernetes-client/python | kubernetes/client/apis/custom_objects_api.py | https://github.com/kubernetes-client/python/blob/5e512ff564c244c50cab780d821542ed56aa965a/kubernetes/client/apis/custom_objects_api.py#L909-L932 | def get_namespaced_custom_object(self, group, version, namespace, plural, name, **kwargs):
"""
Returns a namespace scoped custom object
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_n... | [
"def",
"get_namespaced_custom_object",
"(",
"self",
",",
"group",
",",
"version",
",",
"namespace",
",",
"plural",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",... | Returns a namespace scoped custom object
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_namespaced_custom_object(group, version, namespace, plural, name, async_req=True)
>>> result = thread.ge... | [
"Returns",
"a",
"namespace",
"scoped",
"custom",
"object",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"pass",
"async_req",
"=",
"True",
">>>",
"thread... | python | train | 55.375 |
PSPC-SPAC-buyandsell/von_anchor | von_anchor/anchor/rrbuilder.py | https://github.com/PSPC-SPAC-buyandsell/von_anchor/blob/78ac1de67be42a676274f4bf71fe12f66e72f309/von_anchor/anchor/rrbuilder.py#L304-L327 | async def stop(wallet_name: str) -> None:
"""
Gracefully stop an external revocation registry builder, waiting for its current.
The indy-sdk toolkit uses a temporary directory for tails file mustration,
and shutting down the toolkit removes the directory, crashing the external
t... | [
"async",
"def",
"stop",
"(",
"wallet_name",
":",
"str",
")",
"->",
"None",
":",
"LOGGER",
".",
"debug",
"(",
"'RevRegBuilder.stop >>>'",
")",
"dir_sentinel",
"=",
"join",
"(",
"RevRegBuilder",
".",
"dir_tails_sentinel",
"(",
"wallet_name",
")",
")",
"if",
"i... | Gracefully stop an external revocation registry builder, waiting for its current.
The indy-sdk toolkit uses a temporary directory for tails file mustration,
and shutting down the toolkit removes the directory, crashing the external
tails file write. This method allows a graceful stop to wait fo... | [
"Gracefully",
"stop",
"an",
"external",
"revocation",
"registry",
"builder",
"waiting",
"for",
"its",
"current",
"."
] | python | train | 39.916667 |
cmorisse/ikp3db | ikp3db.py | https://github.com/cmorisse/ikp3db/blob/a0f318d4e8494b2e6f2f07ec0f1202ca023c920f/ikp3db.py#L766-L842 | def extract_object_properties(self, o, limit_size=False):
"""Extracts all properties from an object (eg. f_locals, f_globals,
user dict, instance ...) and returns them as an array of variables.
"""
try:
prop_str = repr(o)[:512]
except:
prop_str = "Error w... | [
"def",
"extract_object_properties",
"(",
"self",
",",
"o",
",",
"limit_size",
"=",
"False",
")",
":",
"try",
":",
"prop_str",
"=",
"repr",
"(",
"o",
")",
"[",
":",
"512",
"]",
"except",
":",
"prop_str",
"=",
"\"Error while extracting value\"",
"_logger",
"... | Extracts all properties from an object (eg. f_locals, f_globals,
user dict, instance ...) and returns them as an array of variables. | [
"Extracts",
"all",
"properties",
"from",
"an",
"object",
"(",
"eg",
".",
"f_locals",
"f_globals",
"user",
"dict",
"instance",
"...",
")",
"and",
"returns",
"them",
"as",
"an",
"array",
"of",
"variables",
"."
] | python | train | 50.077922 |
martinkosir/neverbounce-python | neverbounce/client.py | https://github.com/martinkosir/neverbounce-python/blob/8d8b3f381dbff2a753a8770fac0d2bfab80d5bec/neverbounce/client.py#L125-L148 | def _handle_response(response):
"""
Handle the response and possible failures.
:param Response response: Response data.
:return: A dictionary or a string with response data.
:raises: NeverBounceAPIError if the API call fails.
"""
if not response.ok:
ra... | [
"def",
"_handle_response",
"(",
"response",
")",
":",
"if",
"not",
"response",
".",
"ok",
":",
"raise",
"NeverBounceAPIError",
"(",
"response",
")",
"if",
"response",
".",
"headers",
".",
"get",
"(",
"'Content-Type'",
")",
"==",
"'application/octet-stream'",
"... | Handle the response and possible failures.
:param Response response: Response data.
:return: A dictionary or a string with response data.
:raises: NeverBounceAPIError if the API call fails. | [
"Handle",
"the",
"response",
"and",
"possible",
"failures",
".",
":",
"param",
"Response",
"response",
":",
"Response",
"data",
".",
":",
"return",
":",
"A",
"dictionary",
"or",
"a",
"string",
"with",
"response",
"data",
".",
":",
"raises",
":",
"NeverBoun... | python | train | 39.625 |
rbw/pysnow | pysnow/params_builder.py | https://github.com/rbw/pysnow/blob/87c8ce0d3a089c2f59247f30efbd545fcdb8e985/pysnow/params_builder.py#L156-L164 | def exclude_reference_link(self, exclude):
"""Sets `sysparm_exclude_reference_link` to a bool value
:param exclude: bool
"""
if not isinstance(exclude, bool):
raise InvalidUsage('exclude_reference_link must be of type bool')
self._sysparms['sysparm_exclude_reference... | [
"def",
"exclude_reference_link",
"(",
"self",
",",
"exclude",
")",
":",
"if",
"not",
"isinstance",
"(",
"exclude",
",",
"bool",
")",
":",
"raise",
"InvalidUsage",
"(",
"'exclude_reference_link must be of type bool'",
")",
"self",
".",
"_sysparms",
"[",
"'sysparm_e... | Sets `sysparm_exclude_reference_link` to a bool value
:param exclude: bool | [
"Sets",
"sysparm_exclude_reference_link",
"to",
"a",
"bool",
"value"
] | python | train | 36.555556 |
wbond/certvalidator | certvalidator/registry.py | https://github.com/wbond/certvalidator/blob/c62233a713bcc36963e9d82323ec8d84f8e01485/certvalidator/registry.py#L325-L358 | def _walk_issuers(self, path, paths, failed_paths):
"""
Recursively looks through the list of known certificates for the issuer
of the certificate specified, stopping once the certificate in question
is one contained within the CA certs list
:param path:
A Validation... | [
"def",
"_walk_issuers",
"(",
"self",
",",
"path",
",",
"paths",
",",
"failed_paths",
")",
":",
"if",
"path",
".",
"first",
".",
"signature",
"in",
"self",
".",
"_ca_lookup",
":",
"paths",
".",
"append",
"(",
"path",
")",
"return",
"new_branches",
"=",
... | Recursively looks through the list of known certificates for the issuer
of the certificate specified, stopping once the certificate in question
is one contained within the CA certs list
:param path:
A ValidationPath object representing the current traversal of
possible p... | [
"Recursively",
"looks",
"through",
"the",
"list",
"of",
"known",
"certificates",
"for",
"the",
"issuer",
"of",
"the",
"certificate",
"specified",
"stopping",
"once",
"the",
"certificate",
"in",
"question",
"is",
"one",
"contained",
"within",
"the",
"CA",
"certs"... | python | train | 34.5 |
yinkaisheng/Python-UIAutomation-for-Windows | uiautomation/uiautomation.py | https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L5693-L5709 | def GetAncestorControl(self, condition: Callable) -> 'Control':
"""
Get a ancestor control that matches the condition.
condition: Callable, function (control: Control, depth: int)->bool,
depth starts with -1 and decreses when search goes up.
Return `Control` subclass o... | [
"def",
"GetAncestorControl",
"(",
"self",
",",
"condition",
":",
"Callable",
")",
"->",
"'Control'",
":",
"ancestor",
"=",
"self",
"depth",
"=",
"0",
"while",
"True",
":",
"ancestor",
"=",
"ancestor",
".",
"GetParentControl",
"(",
")",
"depth",
"-=",
"1",
... | Get a ancestor control that matches the condition.
condition: Callable, function (control: Control, depth: int)->bool,
depth starts with -1 and decreses when search goes up.
Return `Control` subclass or None. | [
"Get",
"a",
"ancestor",
"control",
"that",
"matches",
"the",
"condition",
".",
"condition",
":",
"Callable",
"function",
"(",
"control",
":",
"Control",
"depth",
":",
"int",
")",
"-",
">",
"bool",
"depth",
"starts",
"with",
"-",
"1",
"and",
"decreses",
"... | python | valid | 35.705882 |
Contraz/demosys-py | demosys/context/headless.py | https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/context/headless.py#L43-L50 | def draw(self, current_time, frame_time):
"""
Calls the superclass ``draw()`` methods and checks ``HEADLESS_FRAMES``/``HEADLESS_DURATION``
"""
super().draw(current_time, frame_time)
if self.headless_duration and current_time >= self.headless_duration:
self.close() | [
"def",
"draw",
"(",
"self",
",",
"current_time",
",",
"frame_time",
")",
":",
"super",
"(",
")",
".",
"draw",
"(",
"current_time",
",",
"frame_time",
")",
"if",
"self",
".",
"headless_duration",
"and",
"current_time",
">=",
"self",
".",
"headless_duration",
... | Calls the superclass ``draw()`` methods and checks ``HEADLESS_FRAMES``/``HEADLESS_DURATION`` | [
"Calls",
"the",
"superclass",
"draw",
"()",
"methods",
"and",
"checks",
"HEADLESS_FRAMES",
"/",
"HEADLESS_DURATION"
] | python | valid | 38.75 |
suds-community/suds | suds/sax/element.py | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/element.py#L503-L521 | def getChildren(self, name=None, ns=None):
"""
Get a list of children by (optional) name and/or (optional) namespace.
@param name: The name of a child element (may contain a prefix).
@type name: basestring
@param ns: An optional namespace used to match the child.
@type n... | [
"def",
"getChildren",
"(",
"self",
",",
"name",
"=",
"None",
",",
"ns",
"=",
"None",
")",
":",
"if",
"ns",
"is",
"None",
":",
"if",
"name",
"is",
"None",
":",
"return",
"self",
".",
"children",
"prefix",
",",
"name",
"=",
"splitPrefix",
"(",
"name"... | Get a list of children by (optional) name and/or (optional) namespace.
@param name: The name of a child element (may contain a prefix).
@type name: basestring
@param ns: An optional namespace used to match the child.
@type ns: (I{prefix}, I{name})
@return: The list of matching c... | [
"Get",
"a",
"list",
"of",
"children",
"by",
"(",
"optional",
")",
"name",
"and",
"/",
"or",
"(",
"optional",
")",
"namespace",
"."
] | python | train | 36.789474 |
zacernst/timed_dict | timed_dict/timed_dict.py | https://github.com/zacernst/timed_dict/blob/01a1d145d246832e63c2e92e11d91cac5c3f2d1e/timed_dict/timed_dict.py#L287-L316 | def sweep(self):
'''
This methods runs in a separate thread. So long as
`self.sweep_flag` is set, it expires keys according to
the process explained in the docstring for the `TimedDict`
class. The thread is halted by calling `self.stop_sweep()`,
which sets the `self.sweep... | [
"def",
"sweep",
"(",
"self",
")",
":",
"while",
"self",
".",
"sweep_flag",
":",
"current_time",
"=",
"time",
".",
"time",
"(",
")",
"expire_keys",
"=",
"set",
"(",
")",
"keys_checked",
"=",
"0.",
"items",
"=",
"list",
"(",
"self",
".",
"time_dict",
"... | This methods runs in a separate thread. So long as
`self.sweep_flag` is set, it expires keys according to
the process explained in the docstring for the `TimedDict`
class. The thread is halted by calling `self.stop_sweep()`,
which sets the `self.sweep_flag` to `False`. | [
"This",
"methods",
"runs",
"in",
"a",
"separate",
"thread",
".",
"So",
"long",
"as",
"self",
".",
"sweep_flag",
"is",
"set",
"it",
"expires",
"keys",
"according",
"to",
"the",
"process",
"explained",
"in",
"the",
"docstring",
"for",
"the",
"TimedDict",
"cl... | python | train | 40.6 |
gem/oq-engine | openquake/hazardlib/contexts.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/contexts.py#L146-L172 | def add_rup_params(self, rupture):
"""
Add .REQUIRES_RUPTURE_PARAMETERS to the rupture
"""
for param in self.REQUIRES_RUPTURE_PARAMETERS:
if param == 'mag':
value = rupture.mag
elif param == 'strike':
value = rupture.surface.get_str... | [
"def",
"add_rup_params",
"(",
"self",
",",
"rupture",
")",
":",
"for",
"param",
"in",
"self",
".",
"REQUIRES_RUPTURE_PARAMETERS",
":",
"if",
"param",
"==",
"'mag'",
":",
"value",
"=",
"rupture",
".",
"mag",
"elif",
"param",
"==",
"'strike'",
":",
"value",
... | Add .REQUIRES_RUPTURE_PARAMETERS to the rupture | [
"Add",
".",
"REQUIRES_RUPTURE_PARAMETERS",
"to",
"the",
"rupture"
] | python | train | 41 |
softlayer/softlayer-python | SoftLayer/utils.py | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/utils.py#L301-L313 | def clean_time(sltime, in_format='%Y-%m-%dT%H:%M:%S%z', out_format='%Y-%m-%d %H:%M'):
"""Easy way to format time strings
:param string sltime: A softlayer formatted time string
:param string in_format: Datetime format for strptime
:param string out_format: Datetime format for strftime
"""
try:
... | [
"def",
"clean_time",
"(",
"sltime",
",",
"in_format",
"=",
"'%Y-%m-%dT%H:%M:%S%z'",
",",
"out_format",
"=",
"'%Y-%m-%d %H:%M'",
")",
":",
"try",
":",
"clean",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"sltime",
",",
"in_format",
")",
"return",
... | Easy way to format time strings
:param string sltime: A softlayer formatted time string
:param string in_format: Datetime format for strptime
:param string out_format: Datetime format for strftime | [
"Easy",
"way",
"to",
"format",
"time",
"strings"
] | python | train | 38.461538 |
dw/mitogen | ansible_mitogen/target.py | https://github.com/dw/mitogen/blob/a7fdb55e1300a7e0a5e404b09eb730cf9a525da7/ansible_mitogen/target.py#L155-L171 | def get_small_file(context, path):
"""
Basic in-memory caching module fetcher. This generates one roundtrip for
every previously unseen file, so it is only a temporary solution.
:param context:
Context we should direct FileService requests to. For now (and probably
forever) this is just... | [
"def",
"get_small_file",
"(",
"context",
",",
"path",
")",
":",
"pool",
"=",
"mitogen",
".",
"service",
".",
"get_or_create_pool",
"(",
"router",
"=",
"context",
".",
"router",
")",
"service",
"=",
"pool",
".",
"get_service",
"(",
"u'mitogen.service.PushFileSe... | Basic in-memory caching module fetcher. This generates one roundtrip for
every previously unseen file, so it is only a temporary solution.
:param context:
Context we should direct FileService requests to. For now (and probably
forever) this is just the top-level Mitogen connection manager proce... | [
"Basic",
"in",
"-",
"memory",
"caching",
"module",
"fetcher",
".",
"This",
"generates",
"one",
"roundtrip",
"for",
"every",
"previously",
"unseen",
"file",
"so",
"it",
"is",
"only",
"a",
"temporary",
"solution",
"."
] | python | train | 42.764706 |
Yelp/detect-secrets | detect_secrets/core/audit.py | https://github.com/Yelp/detect-secrets/blob/473923ea71f1ac2b5ea1eacc49b98f97967e3d05/detect_secrets/core/audit.py#L275-L311 | def _comparison_generator(old_list, new_list, compare_fn):
"""
:type old_list: sorted list
:type new_list: sorted list
:type compare_fn: function
:param compare_fn:
takes two arguments, A and B
returns 0 if equal
returns -1 if A is less than B
else returns 1
"""
... | [
"def",
"_comparison_generator",
"(",
"old_list",
",",
"new_list",
",",
"compare_fn",
")",
":",
"old_index",
"=",
"0",
"new_index",
"=",
"0",
"while",
"old_index",
"<",
"len",
"(",
"old_list",
")",
"and",
"new_index",
"<",
"len",
"(",
"new_list",
")",
":",
... | :type old_list: sorted list
:type new_list: sorted list
:type compare_fn: function
:param compare_fn:
takes two arguments, A and B
returns 0 if equal
returns -1 if A is less than B
else returns 1 | [
":",
"type",
"old_list",
":",
"sorted",
"list",
":",
"type",
"new_list",
":",
"sorted",
"list"
] | python | train | 29.27027 |
DataONEorg/d1_python | lib_common/src/d1_common/wrap/simple_xml.py | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/wrap/simple_xml.py#L123-L131 | def get_pretty_xml(self, encoding='unicode'):
"""Returns:
str : Current state of the wrapper as a pretty printed XML string.
"""
return d1_common.xml.reformat_to_pretty_xml(
xml.etree.ElementTree.tostring(self._root_el, encoding)
) | [
"def",
"get_pretty_xml",
"(",
"self",
",",
"encoding",
"=",
"'unicode'",
")",
":",
"return",
"d1_common",
".",
"xml",
".",
"reformat_to_pretty_xml",
"(",
"xml",
".",
"etree",
".",
"ElementTree",
".",
"tostring",
"(",
"self",
".",
"_root_el",
",",
"encoding",... | Returns:
str : Current state of the wrapper as a pretty printed XML string. | [
"Returns",
":"
] | python | train | 30.777778 |
twisted/epsilon | epsilon/ampauth.py | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/ampauth.py#L123-L138 | def checkPassword(self, password):
"""
Check the given plaintext password against the response in this
credentials object.
@type password: C{str}
@param password: The known correct password associated with
C{self.username}.
@return: A C{bool}, C{True} if thi... | [
"def",
"checkPassword",
"(",
"self",
",",
"password",
")",
":",
"if",
"isinstance",
"(",
"password",
",",
"unicode",
")",
":",
"password",
"=",
"password",
".",
"encode",
"(",
"'utf-8'",
")",
"correctResponse",
"=",
"_calcResponse",
"(",
"self",
".",
"chal... | Check the given plaintext password against the response in this
credentials object.
@type password: C{str}
@param password: The known correct password associated with
C{self.username}.
@return: A C{bool}, C{True} if this credentials object agrees with the
given ... | [
"Check",
"the",
"given",
"plaintext",
"password",
"against",
"the",
"response",
"in",
"this",
"credentials",
"object",
"."
] | python | train | 38.5625 |
materialsproject/pymatgen | pymatgen/core/tensors.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/core/tensors.py#L167-L182 | def project(self, n):
"""
Convenience method for projection of a tensor into a
vector. Returns the tensor dotted into a unit vector
along the input n.
Args:
n (3x1 array-like): direction to project onto
Returns (float):
scalar value correspondin... | [
"def",
"project",
"(",
"self",
",",
"n",
")",
":",
"n",
"=",
"get_uvec",
"(",
"n",
")",
"return",
"self",
".",
"einsum_sequence",
"(",
"[",
"n",
"]",
"*",
"self",
".",
"rank",
")"
] | Convenience method for projection of a tensor into a
vector. Returns the tensor dotted into a unit vector
along the input n.
Args:
n (3x1 array-like): direction to project onto
Returns (float):
scalar value corresponding to the projection of
the ten... | [
"Convenience",
"method",
"for",
"projection",
"of",
"a",
"tensor",
"into",
"a",
"vector",
".",
"Returns",
"the",
"tensor",
"dotted",
"into",
"a",
"unit",
"vector",
"along",
"the",
"input",
"n",
"."
] | python | train | 28.5 |
persandstrom/python-verisure | verisure/session.py | https://github.com/persandstrom/python-verisure/blob/babd25e7f8fb2b24f12e4109dfa8a04041e8dcb8/verisure/session.py#L349-L365 | def get_lock_config(self, device_label):
""" Get lock configuration
Args:
device_label (str): device label of lock
"""
response = None
try:
response = requests.get(
urls.lockconfig(self._giid, device_label),
headers={
... | [
"def",
"get_lock_config",
"(",
"self",
",",
"device_label",
")",
":",
"response",
"=",
"None",
"try",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"urls",
".",
"lockconfig",
"(",
"self",
".",
"_giid",
",",
"device_label",
")",
",",
"headers",
"=",
... | Get lock configuration
Args:
device_label (str): device label of lock | [
"Get",
"lock",
"configuration"
] | python | train | 35.823529 |
NatLibFi/Skosify | skosify/skosify.py | https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/skosify.py#L288-L309 | def transform_relations(rdf, relationmap):
"""Transform YSO-style concept relations into SKOS equivalents."""
affected_types = (SKOS.Concept, SKOS.Collection,
SKOSEXT.DeprecatedConcept)
props = set()
for t in affected_types:
for conc in rdf.subjects(RDF.type, t):
... | [
"def",
"transform_relations",
"(",
"rdf",
",",
"relationmap",
")",
":",
"affected_types",
"=",
"(",
"SKOS",
".",
"Concept",
",",
"SKOS",
".",
"Collection",
",",
"SKOSEXT",
".",
"DeprecatedConcept",
")",
"props",
"=",
"set",
"(",
")",
"for",
"t",
"in",
"a... | Transform YSO-style concept relations into SKOS equivalents. | [
"Transform",
"YSO",
"-",
"style",
"concept",
"relations",
"into",
"SKOS",
"equivalents",
"."
] | python | train | 38.909091 |
jazzband/django-ddp | setup.py | https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/setup.py#L48-L57 | def initialize_options(self):
"""Set command option defaults."""
setuptools.command.build_py.build_py.initialize_options(self)
self.meteor = 'meteor'
self.meteor_debug = False
self.build_lib = None
self.package_dir = None
self.meteor_builds = []
self.no_pr... | [
"def",
"initialize_options",
"(",
"self",
")",
":",
"setuptools",
".",
"command",
".",
"build_py",
".",
"build_py",
".",
"initialize_options",
"(",
"self",
")",
"self",
".",
"meteor",
"=",
"'meteor'",
"self",
".",
"meteor_debug",
"=",
"False",
"self",
".",
... | Set command option defaults. | [
"Set",
"command",
"option",
"defaults",
"."
] | python | test | 35.3 |
soerenwolfers/swutil | swutil/plots.py | https://github.com/soerenwolfers/swutil/blob/2d598f2deac8b7e20df95dbc68017e5ab5d6180c/swutil/plots.py#L194-L250 | def ezplot(f,xlim,ylim=None,ax = None,vectorized=True,N=None,contour = False,args=None,kwargs=None,dry_run=False,show=None,include_endpoints=False):
'''
Plot polynomial approximation.
:param vectorized: `f` can handle an array of inputs
'''
kwargs = kwargs or {}
args = args or []
d = 1 ... | [
"def",
"ezplot",
"(",
"f",
",",
"xlim",
",",
"ylim",
"=",
"None",
",",
"ax",
"=",
"None",
",",
"vectorized",
"=",
"True",
",",
"N",
"=",
"None",
",",
"contour",
"=",
"False",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"dry_run",
... | Plot polynomial approximation.
:param vectorized: `f` can handle an array of inputs | [
"Plot",
"polynomial",
"approximation",
".",
":",
"param",
"vectorized",
":",
"f",
"can",
"handle",
"an",
"array",
"of",
"inputs"
] | python | valid | 37.649123 |
CitrineInformatics/python-citrination-client | citrination_client/views/client.py | https://github.com/CitrineInformatics/python-citrination-client/blob/409984fc65ce101a620f069263f155303492465c/citrination_client/views/client.py#L195-L212 | def __snake_case(self, descriptor):
"""
Utility method to convert camelcase to snake
:param descriptor: The dictionary to convert
"""
newdict = {}
for i, (k, v) in enumerate(descriptor.items()):
newkey = ""
for j, c in enumerate(k):
... | [
"def",
"__snake_case",
"(",
"self",
",",
"descriptor",
")",
":",
"newdict",
"=",
"{",
"}",
"for",
"i",
",",
"(",
"k",
",",
"v",
")",
"in",
"enumerate",
"(",
"descriptor",
".",
"items",
"(",
")",
")",
":",
"newkey",
"=",
"\"\"",
"for",
"j",
",",
... | Utility method to convert camelcase to snake
:param descriptor: The dictionary to convert | [
"Utility",
"method",
"to",
"convert",
"camelcase",
"to",
"snake",
":",
"param",
"descriptor",
":",
"The",
"dictionary",
"to",
"convert"
] | python | valid | 30.444444 |
GNS3/gns3-server | gns3server/controller/gns3vm/vmware_gns3_vm.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/vmware_gns3_vm.py#L63-L86 | def _set_vcpus_ram(self, vcpus, ram):
"""
Set the number of vCPU cores and amount of RAM for the GNS3 VM.
:param vcpus: number of vCPU cores
:param ram: amount of RAM
"""
# memory must be a multiple of 4 (VMware requirement)
if ram % 4 != 0:
raise GN... | [
"def",
"_set_vcpus_ram",
"(",
"self",
",",
"vcpus",
",",
"ram",
")",
":",
"# memory must be a multiple of 4 (VMware requirement)",
"if",
"ram",
"%",
"4",
"!=",
"0",
":",
"raise",
"GNS3VMError",
"(",
"\"Allocated memory {} for the GNS3 VM must be a multiple of 4\"",
".",
... | Set the number of vCPU cores and amount of RAM for the GNS3 VM.
:param vcpus: number of vCPU cores
:param ram: amount of RAM | [
"Set",
"the",
"number",
"of",
"vCPU",
"cores",
"and",
"amount",
"of",
"RAM",
"for",
"the",
"GNS3",
"VM",
"."
] | python | train | 44.083333 |
SHDShim/pytheos | pytheos/eqn_therm_Dorogokupets2007.py | https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_therm_Dorogokupets2007.py#L24-L43 | def altshuler_debyetemp(v, v0, gamma0, gamma_inf, beta, theta0):
"""
calculate Debye temperature for Altshuler equation
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param gamma0: Gruneisen parameter at 1 bar
:param gamma_inf: Gruneisen parameter at infinite pre... | [
"def",
"altshuler_debyetemp",
"(",
"v",
",",
"v0",
",",
"gamma0",
",",
"gamma_inf",
",",
"beta",
",",
"theta0",
")",
":",
"x",
"=",
"v",
"/",
"v0",
"if",
"isuncertainties",
"(",
"[",
"v",
",",
"v0",
",",
"gamma0",
",",
"gamma_inf",
",",
"beta",
","... | calculate Debye temperature for Altshuler equation
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param gamma0: Gruneisen parameter at 1 bar
:param gamma_inf: Gruneisen parameter at infinite pressure
:param beta: volume dependence of Gruneisen parameter
:param th... | [
"calculate",
"Debye",
"temperature",
"for",
"Altshuler",
"equation"
] | python | train | 41.6 |
contentful/contentful-management.py | contentful_management/resource.py | https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/resource.py#L130-L146 | def reload(self, result=None):
"""
Reloads the resource.
"""
if result is None:
result = self._client._get(
self.__class__.base_url(
self.sys['space'].id,
self.sys['id'],
environment_id=self._environ... | [
"def",
"reload",
"(",
"self",
",",
"result",
"=",
"None",
")",
":",
"if",
"result",
"is",
"None",
":",
"result",
"=",
"self",
".",
"_client",
".",
"_get",
"(",
"self",
".",
"__class__",
".",
"base_url",
"(",
"self",
".",
"sys",
"[",
"'space'",
"]",... | Reloads the resource. | [
"Reloads",
"the",
"resource",
"."
] | python | train | 24 |
higlass/higlass-python | higlass/client.py | https://github.com/higlass/higlass-python/blob/0a5bf2759cc0020844aefbf0df4f9e8f9137a0b7/higlass/client.py#L138-L145 | def change_options(self, **kwargs):
'''
Change one of the track's options in the viewconf
'''
new_options = json.loads(json.dumps(self.viewconf['options']))
new_options = {**new_options, **kwargs}
return self.change_attributes(options=new_options) | [
"def",
"change_options",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"new_options",
"=",
"json",
".",
"loads",
"(",
"json",
".",
"dumps",
"(",
"self",
".",
"viewconf",
"[",
"'options'",
"]",
")",
")",
"new_options",
"=",
"{",
"*",
"*",
"new_optio... | Change one of the track's options in the viewconf | [
"Change",
"one",
"of",
"the",
"track",
"s",
"options",
"in",
"the",
"viewconf"
] | python | train | 36.125 |
epfl-lts2/pygsp | pygsp/graphs/_io.py | https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/graphs/_io.py#L406-L485 | def load(cls, path, fmt=None, backend=None):
r"""Load a graph from a file.
Edge weights are retrieved as an edge attribute named "weight".
Signals are retrieved from node attributes,
and stored in the :attr:`signals` dictionary under the attribute name.
`N`-dimensional signals ... | [
"def",
"load",
"(",
"cls",
",",
"path",
",",
"fmt",
"=",
"None",
",",
"backend",
"=",
"None",
")",
":",
"if",
"fmt",
"is",
"None",
":",
"fmt",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"path",
")",
"[",
"1",
"]",
"[",
"1",
":",
"]",
"if... | r"""Load a graph from a file.
Edge weights are retrieved as an edge attribute named "weight".
Signals are retrieved from node attributes,
and stored in the :attr:`signals` dictionary under the attribute name.
`N`-dimensional signals that were broken during export are joined.
P... | [
"r",
"Load",
"a",
"graph",
"from",
"a",
"file",
"."
] | python | train | 33.95 |
poppy-project/pypot | pypot/dynamixel/io/abstract_io.py | https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/dynamixel/io/abstract_io.py#L290-L292 | def switch_led_on(self, ids):
""" Switches on the LED of the motors with the specified ids. """
self._set_LED(dict(zip(ids, itertools.repeat(True)))) | [
"def",
"switch_led_on",
"(",
"self",
",",
"ids",
")",
":",
"self",
".",
"_set_LED",
"(",
"dict",
"(",
"zip",
"(",
"ids",
",",
"itertools",
".",
"repeat",
"(",
"True",
")",
")",
")",
")"
] | Switches on the LED of the motors with the specified ids. | [
"Switches",
"on",
"the",
"LED",
"of",
"the",
"motors",
"with",
"the",
"specified",
"ids",
"."
] | python | train | 54.333333 |
fhamborg/news-please | newsplease/helper_classes/sub_classes/heuristics_manager.py | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/sub_classes/heuristics_manager.py#L36-L67 | def is_article(self, response, url):
"""
Tests if the given response is an article by calling and checking
the heuristics set in config.cfg and sitelist.json
:param obj response: The response of the site.
:param str url: The base_url (needed to get the site-specific config
... | [
"def",
"is_article",
"(",
"self",
",",
"response",
",",
"url",
")",
":",
"site",
"=",
"self",
".",
"__sites_object",
"[",
"url",
"]",
"heuristics",
"=",
"self",
".",
"__get_enabled_heuristics",
"(",
"url",
")",
"self",
".",
"log",
".",
"info",
"(",
"\"... | Tests if the given response is an article by calling and checking
the heuristics set in config.cfg and sitelist.json
:param obj response: The response of the site.
:param str url: The base_url (needed to get the site-specific config
from the JSON-file)
:return bo... | [
"Tests",
"if",
"the",
"given",
"response",
"is",
"an",
"article",
"by",
"calling",
"and",
"checking",
"the",
"heuristics",
"set",
"in",
"config",
".",
"cfg",
"and",
"sitelist",
".",
"json"
] | python | train | 42.09375 |
Accelize/pycosio | pycosio/_core/io_base_buffered.py | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_buffered.py#L439-L471 | def seek(self, offset, whence=SEEK_SET):
"""
Change the stream position to the given byte offset.
Args:
offset: Offset is interpreted relative to the position indicated by
whence.
whence: The default value for whence is SEEK_SET.
Values fo... | [
"def",
"seek",
"(",
"self",
",",
"offset",
",",
"whence",
"=",
"SEEK_SET",
")",
":",
"if",
"not",
"self",
".",
"_seekable",
":",
"raise",
"UnsupportedOperation",
"(",
"'seek'",
")",
"# Only read mode is seekable",
"with",
"self",
".",
"_seek_lock",
":",
"# S... | Change the stream position to the given byte offset.
Args:
offset: Offset is interpreted relative to the position indicated by
whence.
whence: The default value for whence is SEEK_SET.
Values for whence are:
SEEK_SET or 0 – start of the st... | [
"Change",
"the",
"stream",
"position",
"to",
"the",
"given",
"byte",
"offset",
"."
] | python | train | 33.727273 |
saltstack/salt | salt/wheel/__init__.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/wheel/__init__.py#L130-L144 | def cmd(self, fun, arg=None, pub_data=None, kwarg=None, print_event=True, full_return=False):
'''
Execute a function
.. code-block:: python
>>> wheel.cmd('key.finger', ['jerry'])
{'minions': {'jerry': '5d:f6:79:43:5e:d4:42:3f:57:b8:45:a8:7e:a4:6e:ca'}}
'''
... | [
"def",
"cmd",
"(",
"self",
",",
"fun",
",",
"arg",
"=",
"None",
",",
"pub_data",
"=",
"None",
",",
"kwarg",
"=",
"None",
",",
"print_event",
"=",
"True",
",",
"full_return",
"=",
"False",
")",
":",
"return",
"super",
"(",
"WheelClient",
",",
"self",
... | Execute a function
.. code-block:: python
>>> wheel.cmd('key.finger', ['jerry'])
{'minions': {'jerry': '5d:f6:79:43:5e:d4:42:3f:57:b8:45:a8:7e:a4:6e:ca'}} | [
"Execute",
"a",
"function"
] | python | train | 41.133333 |
rembish/cfb | cfb/directory/__init__.py | https://github.com/rembish/cfb/blob/9bcd75caad4353b186ce518d2da78aeeb52d3131/cfb/directory/__init__.py#L25-L38 | def read(self):
"""
This module is lazy-loaded by default. You can read all internal
structure by calling this method.
"""
stack = [self[0].child]
while stack:
current = stack.pop()
if current.right:
stack.append(current.right)
... | [
"def",
"read",
"(",
"self",
")",
":",
"stack",
"=",
"[",
"self",
"[",
"0",
"]",
".",
"child",
"]",
"while",
"stack",
":",
"current",
"=",
"stack",
".",
"pop",
"(",
")",
"if",
"current",
".",
"right",
":",
"stack",
".",
"append",
"(",
"current",
... | This module is lazy-loaded by default. You can read all internal
structure by calling this method. | [
"This",
"module",
"is",
"lazy",
"-",
"loaded",
"by",
"default",
".",
"You",
"can",
"read",
"all",
"internal",
"structure",
"by",
"calling",
"this",
"method",
"."
] | python | train | 28.5 |
tensorflow/probability | tensorflow_probability/python/internal/distribution_util.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/distribution_util.py#L180-L278 | def make_diag_scale(loc=None,
scale_diag=None,
scale_identity_multiplier=None,
shape_hint=None,
validate_args=False,
assert_positive=False,
name=None,
dtype=None):
"""Creates a L... | [
"def",
"make_diag_scale",
"(",
"loc",
"=",
"None",
",",
"scale_diag",
"=",
"None",
",",
"scale_identity_multiplier",
"=",
"None",
",",
"shape_hint",
"=",
"None",
",",
"validate_args",
"=",
"False",
",",
"assert_positive",
"=",
"False",
",",
"name",
"=",
"Non... | Creates a LinearOperator representing a diagonal matrix.
Args:
loc: Floating-point `Tensor`. This is used for inferring shape in the case
where only `scale_identity_multiplier` is set.
scale_diag: Floating-point `Tensor` representing the diagonal matrix.
`scale_diag` has shape [N1, N2, ... k], w... | [
"Creates",
"a",
"LinearOperator",
"representing",
"a",
"diagonal",
"matrix",
"."
] | python | test | 39.646465 |
jameslyons/pycipher | pycipher/playfair.py | https://github.com/jameslyons/pycipher/blob/8f1d7cf3cba4e12171e27d9ce723ad890194de19/pycipher/playfair.py#L64-L81 | def decipher(self, string):
"""Decipher string using Playfair cipher according to initialised key. Punctuation and whitespace
are removed from the input. The ciphertext should be an even number of characters. If the input ciphertext is not an even number of characters, an 'X' will be appended.
... | [
"def",
"decipher",
"(",
"self",
",",
"string",
")",
":",
"string",
"=",
"self",
".",
"remove_punctuation",
"(",
"string",
")",
"if",
"len",
"(",
"string",
")",
"%",
"2",
"==",
"1",
":",
"string",
"+=",
"'X'",
"ret",
"=",
"''",
"for",
"c",
"in",
"... | Decipher string using Playfair cipher according to initialised key. Punctuation and whitespace
are removed from the input. The ciphertext should be an even number of characters. If the input ciphertext is not an even number of characters, an 'X' will be appended.
Example::
plaintext = Play... | [
"Decipher",
"string",
"using",
"Playfair",
"cipher",
"according",
"to",
"initialised",
"key",
".",
"Punctuation",
"and",
"whitespace",
"are",
"removed",
"from",
"the",
"input",
".",
"The",
"ciphertext",
"should",
"be",
"an",
"even",
"number",
"of",
"characters",... | python | train | 42.388889 |
pivotal-energy-solutions/django-datatable-view | datatableview/views/xeditable.py | https://github.com/pivotal-energy-solutions/django-datatable-view/blob/00b77a9b5051c34e258c51b06c020e92edf15034/datatableview/views/xeditable.py#L91-L100 | def get_xeditable_form_kwargs(self):
""" Returns a dict of keyword arguments to be sent to the xeditable form class. """
kwargs = {
'model': self.get_queryset().model,
}
if self.request.method in ('POST', 'PUT'):
kwargs.update({
'data': self.reques... | [
"def",
"get_xeditable_form_kwargs",
"(",
"self",
")",
":",
"kwargs",
"=",
"{",
"'model'",
":",
"self",
".",
"get_queryset",
"(",
")",
".",
"model",
",",
"}",
"if",
"self",
".",
"request",
".",
"method",
"in",
"(",
"'POST'",
",",
"'PUT'",
")",
":",
"k... | Returns a dict of keyword arguments to be sent to the xeditable form class. | [
"Returns",
"a",
"dict",
"of",
"keyword",
"arguments",
"to",
"be",
"sent",
"to",
"the",
"xeditable",
"form",
"class",
"."
] | python | train | 35.5 |
pandas-dev/pandas | pandas/plotting/_style.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/plotting/_style.py#L151-L161 | def use(self, key, value):
"""
Temporarily set a parameter value using the with statement.
Aliasing allowed.
"""
old_value = self[key]
try:
self[key] = value
yield self
finally:
self[key] = old_value | [
"def",
"use",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"old_value",
"=",
"self",
"[",
"key",
"]",
"try",
":",
"self",
"[",
"key",
"]",
"=",
"value",
"yield",
"self",
"finally",
":",
"self",
"[",
"key",
"]",
"=",
"old_value"
] | Temporarily set a parameter value using the with statement.
Aliasing allowed. | [
"Temporarily",
"set",
"a",
"parameter",
"value",
"using",
"the",
"with",
"statement",
".",
"Aliasing",
"allowed",
"."
] | python | train | 25.545455 |
sdispater/orator | orator/schema/blueprint.py | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/schema/blueprint.py#L19-L30 | def build(self, connection, grammar):
"""
Execute the blueprint against the database.
:param connection: The connection to use
:type connection: orator.connections.Connection
:param grammar: The grammar to user
:type grammar: orator.query.grammars.QueryGrammar
"... | [
"def",
"build",
"(",
"self",
",",
"connection",
",",
"grammar",
")",
":",
"for",
"statement",
"in",
"self",
".",
"to_sql",
"(",
"connection",
",",
"grammar",
")",
":",
"connection",
".",
"statement",
"(",
"statement",
")"
] | Execute the blueprint against the database.
:param connection: The connection to use
:type connection: orator.connections.Connection
:param grammar: The grammar to user
:type grammar: orator.query.grammars.QueryGrammar | [
"Execute",
"the",
"blueprint",
"against",
"the",
"database",
"."
] | python | train | 34.5 |
peopledoc/django-agnocomplete | agnocomplete/decorators.py | https://github.com/peopledoc/django-agnocomplete/blob/9bf21db2f2036ba5059b843acd32902a09192053/agnocomplete/decorators.py#L8-L38 | def allow_create(function):
"""
Decorate the `form_valid` method in a Create/Update class to create new
values if necessary.
.. warning::
Make sure that this decorator **only** decorates the ``form_valid()``
method and **only** this one.
"""
@wraps(function)
def _wrapped_f... | [
"def",
"allow_create",
"(",
"function",
")",
":",
"@",
"wraps",
"(",
"function",
")",
"def",
"_wrapped_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"form",
"=",
"args",
"[",
"0",
"]",
"# If this argument is not a form, there are a lot of chances... | Decorate the `form_valid` method in a Create/Update class to create new
values if necessary.
.. warning::
Make sure that this decorator **only** decorates the ``form_valid()``
method and **only** this one. | [
"Decorate",
"the",
"form_valid",
"method",
"in",
"a",
"Create",
"/",
"Update",
"class",
"to",
"create",
"new",
"values",
"if",
"necessary",
"."
] | python | train | 36.967742 |
geronimp/graftM | graftm/sequence_searcher.py | https://github.com/geronimp/graftM/blob/c82576517290167f605fd0bc4facd009cee29f48/graftm/sequence_searcher.py#L155-L223 | def hmmsearch(self, output_path, input_path, unpack, seq_type, threads, cutoff, orfm):
'''
hmmsearch - Search raw reads for hits using search_hmm list
Parameters
----------
output_path : str
path to output domtblout table
input_path : str
path to ... | [
"def",
"hmmsearch",
"(",
"self",
",",
"output_path",
",",
"input_path",
",",
"unpack",
",",
"seq_type",
",",
"threads",
",",
"cutoff",
",",
"orfm",
")",
":",
"# Define the base hmmsearch command.",
"logging",
".",
"debug",
"(",
"\"Using %i HMMs to search\"",
"%",
... | hmmsearch - Search raw reads for hits using search_hmm list
Parameters
----------
output_path : str
path to output domtblout table
input_path : str
path to input sequences to search
unpack : UnpackRawReads
UnpackRawReads object, returns string... | [
"hmmsearch",
"-",
"Search",
"raw",
"reads",
"for",
"hits",
"using",
"search_hmm",
"list"
] | python | train | 43.478261 |
SuperCowPowers/workbench | workbench/workers/pe_features.py | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/pe_features.py#L112-L306 | def extract_features_using_pefile(self, pef):
''' Process the PE File using the Python pefile module. '''
# Store all extracted features into feature lists
extracted_dense = {}
extracted_sparse = {}
# Now slog through the info and extract the features
feature_not_found_... | [
"def",
"extract_features_using_pefile",
"(",
"self",
",",
"pef",
")",
":",
"# Store all extracted features into feature lists",
"extracted_dense",
"=",
"{",
"}",
"extracted_sparse",
"=",
"{",
"}",
"# Now slog through the info and extract the features",
"feature_not_found_flag",
... | Process the PE File using the Python pefile module. | [
"Process",
"the",
"PE",
"File",
"using",
"the",
"Python",
"pefile",
"module",
"."
] | python | train | 48.133333 |
ThreatResponse/margaritashotgun | margaritashotgun/cli.py | https://github.com/ThreatResponse/margaritashotgun/blob/6dee53ef267959b214953439968244cc46a19690/margaritashotgun/cli.py#L179-L244 | def configure_args(self, arguments):
"""
Create configuration has from command line arguments
:type arguments: :py:class:`argparse.Namespace`
:params arguments: arguments produced by :py:meth:`Cli.parse_args()`
"""
module, key, config_path = self.check_file_paths(argume... | [
"def",
"configure_args",
"(",
"self",
",",
"arguments",
")",
":",
"module",
",",
"key",
",",
"config_path",
"=",
"self",
".",
"check_file_paths",
"(",
"arguments",
".",
"module",
",",
"arguments",
".",
"key",
",",
"arguments",
".",
"config",
")",
"log_dir"... | Create configuration has from command line arguments
:type arguments: :py:class:`argparse.Namespace`
:params arguments: arguments produced by :py:meth:`Cli.parse_args()` | [
"Create",
"configuration",
"has",
"from",
"command",
"line",
"arguments"
] | python | train | 41.409091 |
bykof/billomapy | billomapy/billomapy.py | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L2451-L2460 | def get_credit_notes_per_page(self, per_page=1000, page=1, params=None):
"""
Get credit notes per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list
"""
... | [
"def",
"get_credit_notes_per_page",
"(",
"self",
",",
"per_page",
"=",
"1000",
",",
"page",
"=",
"1",
",",
"params",
"=",
"None",
")",
":",
"return",
"self",
".",
"_get_resource_per_page",
"(",
"resource",
"=",
"CREDIT_NOTES",
",",
"per_page",
"=",
"per_page... | Get credit notes per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list | [
"Get",
"credit",
"notes",
"per",
"page"
] | python | train | 41.9 |
pgxcentre/geneparse | geneparse/readers/bgen.py | https://github.com/pgxcentre/geneparse/blob/f698f9708af4c7962d384a70a5a14006b1cb7108/geneparse/readers/bgen.py#L76-L117 | def get_variant_genotypes(self, variant):
"""Get the genotypes from a well formed variant instance.
Args:
marker (Variant): A Variant instance.
Returns:
A list of Genotypes instance containing a pointer to the variant as
well as a vector of encoded genotypes... | [
"def",
"get_variant_genotypes",
"(",
"self",
",",
"variant",
")",
":",
"# The chromosome to search for (if a general one is set, that's the one",
"# we need to search for)",
"chrom",
"=",
"variant",
".",
"chrom",
".",
"name",
"if",
"self",
".",
"chrom",
"is",
"not",
"No... | Get the genotypes from a well formed variant instance.
Args:
marker (Variant): A Variant instance.
Returns:
A list of Genotypes instance containing a pointer to the variant as
well as a vector of encoded genotypes. | [
"Get",
"the",
"genotypes",
"from",
"a",
"well",
"formed",
"variant",
"instance",
"."
] | python | train | 33.690476 |
spacetelescope/stsci.tools | lib/stsci/tools/basicpar.py | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/basicpar.py#L407-L434 | def checkOneValue(self,v,strict=0):
"""Checks a single value to see if it is in range or choice list
Allows indirection strings starting with ")". Assumes
v has already been converted to right value by
_coerceOneValue. Returns value if OK, or raises
ValueError if not OK.
... | [
"def",
"checkOneValue",
"(",
"self",
",",
"v",
",",
"strict",
"=",
"0",
")",
":",
"if",
"v",
"in",
"[",
"None",
",",
"INDEF",
"]",
"or",
"(",
"isinstance",
"(",
"v",
",",
"str",
")",
"and",
"v",
"[",
":",
"1",
"]",
"==",
"\")\"",
")",
":",
... | Checks a single value to see if it is in range or choice list
Allows indirection strings starting with ")". Assumes
v has already been converted to right value by
_coerceOneValue. Returns value if OK, or raises
ValueError if not OK. | [
"Checks",
"a",
"single",
"value",
"to",
"see",
"if",
"it",
"is",
"in",
"range",
"or",
"choice",
"list"
] | python | train | 46.178571 |
BerkeleyAutomation/perception | perception/image.py | https://github.com/BerkeleyAutomation/perception/blob/03d9b37dd6b66896cdfe173905c9413c8c3c5df6/perception/image.py#L2197-L2207 | def inverse(self):
""" Inverts image (all nonzeros become zeros and vice verse)
Returns
-------
:obj:`BinaryImage`
inverse of this binary image
"""
data = np.zeros(self.shape).astype(np.uint8)
ind = np.where(self.data == 0)
data[ind[0], ind[1],... | [
"def",
"inverse",
"(",
"self",
")",
":",
"data",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"shape",
")",
".",
"astype",
"(",
"np",
".",
"uint8",
")",
"ind",
"=",
"np",
".",
"where",
"(",
"self",
".",
"data",
"==",
"0",
")",
"data",
"[",
"ind... | Inverts image (all nonzeros become zeros and vice verse)
Returns
-------
:obj:`BinaryImage`
inverse of this binary image | [
"Inverts",
"image",
"(",
"all",
"nonzeros",
"become",
"zeros",
"and",
"vice",
"verse",
")",
"Returns",
"-------",
":",
"obj",
":",
"BinaryImage",
"inverse",
"of",
"this",
"binary",
"image"
] | python | train | 34.636364 |
guaix-ucm/numina | numina/logger.py | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/logger.py#L30-L54 | def log_to_history(logger, name):
"""Decorate function, adding a logger handler stored in FITS."""
def log_to_history_decorator(method):
def l2h_method(self, ri):
history_header = fits.Header()
fh = FITSHistoryHandler(history_header)
fh.setLevel(logging.INFO)
... | [
"def",
"log_to_history",
"(",
"logger",
",",
"name",
")",
":",
"def",
"log_to_history_decorator",
"(",
"method",
")",
":",
"def",
"l2h_method",
"(",
"self",
",",
"ri",
")",
":",
"history_header",
"=",
"fits",
".",
"Header",
"(",
")",
"fh",
"=",
"FITSHist... | Decorate function, adding a logger handler stored in FITS. | [
"Decorate",
"function",
"adding",
"a",
"logger",
"handler",
"stored",
"in",
"FITS",
"."
] | python | train | 30.88 |
ejeschke/ginga | ginga/ImageView.py | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L3344-L3363 | def get_rgb_image_as_bytes(self, format='png', quality=90):
"""Get the current image shown in the viewer, with any overlaid
graphics, in the form of a buffer in the form of bytes.
Parameters
----------
format : str
See :meth:`get_rgb_image_as_buffer`.
qualit... | [
"def",
"get_rgb_image_as_bytes",
"(",
"self",
",",
"format",
"=",
"'png'",
",",
"quality",
"=",
"90",
")",
":",
"obuf",
"=",
"self",
".",
"get_rgb_image_as_buffer",
"(",
"format",
"=",
"format",
",",
"quality",
"=",
"quality",
")",
"return",
"bytes",
"(",
... | Get the current image shown in the viewer, with any overlaid
graphics, in the form of a buffer in the form of bytes.
Parameters
----------
format : str
See :meth:`get_rgb_image_as_buffer`.
quality: int
See :meth:`get_rgb_image_as_buffer`.
Return... | [
"Get",
"the",
"current",
"image",
"shown",
"in",
"the",
"viewer",
"with",
"any",
"overlaid",
"graphics",
"in",
"the",
"form",
"of",
"a",
"buffer",
"in",
"the",
"form",
"of",
"bytes",
"."
] | python | train | 30.25 |
brandon-rhodes/python-jplephem | jplephem/daf.py | https://github.com/brandon-rhodes/python-jplephem/blob/48c99ce40c627e24c95479d8845e312ea168f567/jplephem/daf.py#L92-L117 | def map_words(self, start, end):
"""Return a memory-map of the elements `start` through `end`.
The memory map will offer the 8-byte double-precision floats
("elements") in the file from index `start` through to the index
`end`, inclusive, both counting the first float as element 1.
... | [
"def",
"map_words",
"(",
"self",
",",
"start",
",",
"end",
")",
":",
"i",
",",
"j",
"=",
"8",
"*",
"start",
"-",
"8",
",",
"8",
"*",
"end",
"try",
":",
"fileno",
"=",
"self",
".",
"file",
".",
"fileno",
"(",
")",
"except",
"(",
"AttributeError"... | Return a memory-map of the elements `start` through `end`.
The memory map will offer the 8-byte double-precision floats
("elements") in the file from index `start` through to the index
`end`, inclusive, both counting the first float as element 1.
Memory maps must begin on a page boundar... | [
"Return",
"a",
"memory",
"-",
"map",
"of",
"the",
"elements",
"start",
"through",
"end",
"."
] | python | test | 39.846154 |
saltstack/salt | salt/thorium/calc.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/calc.py#L273-L293 | def mode(name, num, minimum=0, maximum=0, ref=None):
'''
Calculates the mode of the ``num`` most recent values. Requires a list.
USAGE:
.. code-block:: yaml
foo:
calc.mode:
- name: myregentry
- num: 5
'''
return calc(
name=name,
num=nu... | [
"def",
"mode",
"(",
"name",
",",
"num",
",",
"minimum",
"=",
"0",
",",
"maximum",
"=",
"0",
",",
"ref",
"=",
"None",
")",
":",
"return",
"calc",
"(",
"name",
"=",
"name",
",",
"num",
"=",
"num",
",",
"oper",
"=",
"'mode'",
",",
"minimum",
"=",
... | Calculates the mode of the ``num`` most recent values. Requires a list.
USAGE:
.. code-block:: yaml
foo:
calc.mode:
- name: myregentry
- num: 5 | [
"Calculates",
"the",
"mode",
"of",
"the",
"num",
"most",
"recent",
"values",
".",
"Requires",
"a",
"list",
"."
] | python | train | 18.809524 |
michaelpb/omnic | omnic/worker/manager.py | https://github.com/michaelpb/omnic/blob/1111cfd73c9dc1955afe42d9cf2a468c46f83cd6/omnic/worker/manager.py#L61-L66 | async def async_enqueue_download(self, resource):
'''
Enqueue the download of the given foreign resource.
'''
worker = self.pick_sticky(resource.url_string)
await worker.enqueue(enums.Task.DOWNLOAD, (resource,)) | [
"async",
"def",
"async_enqueue_download",
"(",
"self",
",",
"resource",
")",
":",
"worker",
"=",
"self",
".",
"pick_sticky",
"(",
"resource",
".",
"url_string",
")",
"await",
"worker",
".",
"enqueue",
"(",
"enums",
".",
"Task",
".",
"DOWNLOAD",
",",
"(",
... | Enqueue the download of the given foreign resource. | [
"Enqueue",
"the",
"download",
"of",
"the",
"given",
"foreign",
"resource",
"."
] | python | train | 41 |
spyder-ide/spyder | spyder/widgets/mixins.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/mixins.py#L410-L416 | def set_cursor_position(self, position):
"""Set cursor position"""
position = self.get_position(position)
cursor = self.textCursor()
cursor.setPosition(position)
self.setTextCursor(cursor)
self.ensureCursorVisible() | [
"def",
"set_cursor_position",
"(",
"self",
",",
"position",
")",
":",
"position",
"=",
"self",
".",
"get_position",
"(",
"position",
")",
"cursor",
"=",
"self",
".",
"textCursor",
"(",
")",
"cursor",
".",
"setPosition",
"(",
"position",
")",
"self",
".",
... | Set cursor position | [
"Set",
"cursor",
"position"
] | python | train | 37.571429 |
christophertbrown/bioscripts | ctbBio/strip_align_inserts.py | https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/strip_align_inserts.py#L12-L18 | def strip_inserts(fasta):
"""
remove insertion columns from aligned fasta file
"""
for seq in parse_fasta(fasta):
seq[1] = ''.join([b for b in seq[1] if b == '-' or b.isupper()])
yield seq | [
"def",
"strip_inserts",
"(",
"fasta",
")",
":",
"for",
"seq",
"in",
"parse_fasta",
"(",
"fasta",
")",
":",
"seq",
"[",
"1",
"]",
"=",
"''",
".",
"join",
"(",
"[",
"b",
"for",
"b",
"in",
"seq",
"[",
"1",
"]",
"if",
"b",
"==",
"'-'",
"or",
"b",... | remove insertion columns from aligned fasta file | [
"remove",
"insertion",
"columns",
"from",
"aligned",
"fasta",
"file"
] | python | train | 30.571429 |
d0c-s4vage/pfp | pfp/fields.py | https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/fields.py#L1743-L1749 | def _pfp__set_value(self, new_val):
"""Set the value of the String, taking into account
escaping and such as well
"""
if not isinstance(new_val, Field):
new_val = utils.binary(utils.string_escape(new_val))
super(String, self)._pfp__set_value(new_val) | [
"def",
"_pfp__set_value",
"(",
"self",
",",
"new_val",
")",
":",
"if",
"not",
"isinstance",
"(",
"new_val",
",",
"Field",
")",
":",
"new_val",
"=",
"utils",
".",
"binary",
"(",
"utils",
".",
"string_escape",
"(",
"new_val",
")",
")",
"super",
"(",
"Str... | Set the value of the String, taking into account
escaping and such as well | [
"Set",
"the",
"value",
"of",
"the",
"String",
"taking",
"into",
"account",
"escaping",
"and",
"such",
"as",
"well"
] | python | train | 42.285714 |
genialis/resolwe | resolwe/flow/signals.py | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/signals.py#L39-L42 | def delete_entity(sender, instance, **kwargs):
"""Delete Entity when last Data object is deleted."""
# 1 means that the last Data object is going to be deleted.
Entity.objects.annotate(num_data=Count('data')).filter(data=instance, num_data=1).delete() | [
"def",
"delete_entity",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"# 1 means that the last Data object is going to be deleted.",
"Entity",
".",
"objects",
".",
"annotate",
"(",
"num_data",
"=",
"Count",
"(",
"'data'",
")",
")",
".",
"fil... | Delete Entity when last Data object is deleted. | [
"Delete",
"Entity",
"when",
"last",
"Data",
"object",
"is",
"deleted",
"."
] | python | train | 65 |
quantopian/trading_calendars | trading_calendars/calendar_utils.py | https://github.com/quantopian/trading_calendars/blob/951711c82c8a2875c09e96e2979faaf8734fb4df/trading_calendars/calendar_utils.py#L287-L298 | def deregister_calendar(self, name):
"""
If a calendar is registered with the given name, it is de-registered.
Parameters
----------
cal_name : str
The name of the calendar to be deregistered.
"""
self._calendars.pop(name, None)
self._calendar... | [
"def",
"deregister_calendar",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"_calendars",
".",
"pop",
"(",
"name",
",",
"None",
")",
"self",
".",
"_calendar_factories",
".",
"pop",
"(",
"name",
",",
"None",
")",
"self",
".",
"_aliases",
".",
"pop",
... | If a calendar is registered with the given name, it is de-registered.
Parameters
----------
cal_name : str
The name of the calendar to be deregistered. | [
"If",
"a",
"calendar",
"is",
"registered",
"with",
"the",
"given",
"name",
"it",
"is",
"de",
"-",
"registered",
"."
] | python | train | 31.083333 |
ska-sa/purr | Purr/LogEntry.py | https://github.com/ska-sa/purr/blob/4c848768d0485d0f88b30850d0d5372221b21b66/Purr/LogEntry.py#L220-L262 | def load(self, pathname):
"""Loads entry from directory."""
match = self._entry_re.match(pathname)
if not match:
return None
self.ignore = (match.group(1) == "ignore")
if not os.path.isdir(pathname):
raise ValueError("%s: not a directory" % pathname)
... | [
"def",
"load",
"(",
"self",
",",
"pathname",
")",
":",
"match",
"=",
"self",
".",
"_entry_re",
".",
"match",
"(",
"pathname",
")",
"if",
"not",
"match",
":",
"return",
"None",
"self",
".",
"ignore",
"=",
"(",
"match",
".",
"group",
"(",
"1",
")",
... | Loads entry from directory. | [
"Loads",
"entry",
"from",
"directory",
"."
] | python | train | 49.162791 |
bwhite/hadoopy | hadoopy/_hdfs.py | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/_hdfs.py#L159-L169 | def stat(path, format):
"""Call stat on file
:param path: HDFS Path
:param format: Stat format
:returns: Stat output
:raises: IOError: If unsuccessful
"""
cmd = "hadoop fs -stat %s %s" % (format, path)
rcode, stdout, stderr = _checked_hadoop_fs_command(cmd)
return stdout.rstrip() | [
"def",
"stat",
"(",
"path",
",",
"format",
")",
":",
"cmd",
"=",
"\"hadoop fs -stat %s %s\"",
"%",
"(",
"format",
",",
"path",
")",
"rcode",
",",
"stdout",
",",
"stderr",
"=",
"_checked_hadoop_fs_command",
"(",
"cmd",
")",
"return",
"stdout",
".",
"rstrip"... | Call stat on file
:param path: HDFS Path
:param format: Stat format
:returns: Stat output
:raises: IOError: If unsuccessful | [
"Call",
"stat",
"on",
"file"
] | python | train | 27.909091 |
jorahn/icy | icy/ml/metrics.py | https://github.com/jorahn/icy/blob/d0bd765c933b2d9bff4d7d646c0938348b9c5c25/icy/ml/metrics.py#L181-L202 | def sle(actual, predicted):
"""
Computes the squared log error.
This function computes the squared log error between two numbers,
or for element between a pair of lists or numpy arrays.
Parameters
----------
actual : int, float, list of numbers, numpy array
The ground truth va... | [
"def",
"sle",
"(",
"actual",
",",
"predicted",
")",
":",
"return",
"(",
"np",
".",
"power",
"(",
"np",
".",
"log",
"(",
"np",
".",
"array",
"(",
"actual",
")",
"+",
"1",
")",
"-",
"np",
".",
"log",
"(",
"np",
".",
"array",
"(",
"predicted",
"... | Computes the squared log error.
This function computes the squared log error between two numbers,
or for element between a pair of lists or numpy arrays.
Parameters
----------
actual : int, float, list of numbers, numpy array
The ground truth value
predicted : same type as actual
... | [
"Computes",
"the",
"squared",
"log",
"error",
"."
] | python | train | 27.590909 |
ConsenSys/mythril-classic | mythril/mythril/mythril_config.py | https://github.com/ConsenSys/mythril-classic/blob/27af71c34b2ce94f4fae5613ec457f93df1a8f56/mythril/mythril/mythril_config.py#L215-L226 | def _set_rpc(self, rpc_type: str) -> None:
"""
Sets rpc based on the type
:param rpc_type: The type of connection: like infura, ganache, localhost
:return:
"""
if rpc_type == "infura":
self.set_api_rpc_infura()
elif rpc_type == "localhost":
... | [
"def",
"_set_rpc",
"(",
"self",
",",
"rpc_type",
":",
"str",
")",
"->",
"None",
":",
"if",
"rpc_type",
"==",
"\"infura\"",
":",
"self",
".",
"set_api_rpc_infura",
"(",
")",
"elif",
"rpc_type",
"==",
"\"localhost\"",
":",
"self",
".",
"set_api_rpc_localhost",... | Sets rpc based on the type
:param rpc_type: The type of connection: like infura, ganache, localhost
:return: | [
"Sets",
"rpc",
"based",
"on",
"the",
"type",
":",
"param",
"rpc_type",
":",
"The",
"type",
"of",
"connection",
":",
"like",
"infura",
"ganache",
"localhost",
":",
"return",
":"
] | python | train | 32.583333 |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L261-L284 | def str2chars(strings) -> numpy.ndarray:
"""Return |numpy.ndarray| containing the byte characters (second axis)
of all given strings (first axis).
>>> from hydpy.core.netcdftools import str2chars
>>> str2chars(['zeros', 'ones'])
array([[b'z', b'e', b'r', b'o', b's'],
[b'o', b'n', b'e', b... | [
"def",
"str2chars",
"(",
"strings",
")",
"->",
"numpy",
".",
"ndarray",
":",
"maxlen",
"=",
"0",
"for",
"name",
"in",
"strings",
":",
"maxlen",
"=",
"max",
"(",
"maxlen",
",",
"len",
"(",
"name",
")",
")",
"# noinspection PyTypeChecker",
"chars",
"=",
... | Return |numpy.ndarray| containing the byte characters (second axis)
of all given strings (first axis).
>>> from hydpy.core.netcdftools import str2chars
>>> str2chars(['zeros', 'ones'])
array([[b'z', b'e', b'r', b'o', b's'],
[b'o', b'n', b'e', b's', b'']],
dtype='|S1')
>>> str2... | [
"Return",
"|numpy",
".",
"ndarray|",
"containing",
"the",
"byte",
"characters",
"(",
"second",
"axis",
")",
"of",
"all",
"given",
"strings",
"(",
"first",
"axis",
")",
"."
] | python | train | 31.291667 |
sailthru/sailthru-python-client | sailthru/sailthru_client.py | https://github.com/sailthru/sailthru-python-client/blob/22aa39ba0c5bddd7b8743e24ada331128c0f4f54/sailthru/sailthru_client.py#L648-L689 | def receive_hardbounce_post(self, post_params):
"""
Hard bounce postbacks
"""
if isinstance(post_params, dict):
required_params = ['action', 'email', 'sig']
if not self.check_for_valid_postback_actions(required_params, post_params):
return False
... | [
"def",
"receive_hardbounce_post",
"(",
"self",
",",
"post_params",
")",
":",
"if",
"isinstance",
"(",
"post_params",
",",
"dict",
")",
":",
"required_params",
"=",
"[",
"'action'",
",",
"'email'",
",",
"'sig'",
"]",
"if",
"not",
"self",
".",
"check_for_valid... | Hard bounce postbacks | [
"Hard",
"bounce",
"postbacks"
] | python | train | 31.428571 |
xray7224/PyPump | pypump/store.py | https://github.com/xray7224/PyPump/blob/f921f691c39fe021f4fd124b6bc91718c9e49b4a/pypump/store.py#L191-L203 | def load(cls, webfinger, pypump):
""" Load JSON from disk into store object """
filename = cls.get_filename()
if os.path.isfile(filename):
data = open(filename).read()
data = json.loads(data)
store = cls(data, filename=filename)
else:
stor... | [
"def",
"load",
"(",
"cls",
",",
"webfinger",
",",
"pypump",
")",
":",
"filename",
"=",
"cls",
".",
"get_filename",
"(",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"data",
"=",
"open",
"(",
"filename",
")",
".",
"read",
... | Load JSON from disk into store object | [
"Load",
"JSON",
"from",
"disk",
"into",
"store",
"object"
] | python | train | 29.923077 |
deepmipt/DeepPavlov | deeppavlov/metrics/log_loss.py | https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/metrics/log_loss.py#L25-L37 | def sk_log_loss(y_true: Union[List[List[float]], List[List[int]], np.ndarray],
y_predicted: Union[List[List[float]], List[List[int]], np.ndarray]) -> float:
"""
Calculates log loss.
Args:
y_true: list or array of true values
y_predicted: list or array of predicted values
... | [
"def",
"sk_log_loss",
"(",
"y_true",
":",
"Union",
"[",
"List",
"[",
"List",
"[",
"float",
"]",
"]",
",",
"List",
"[",
"List",
"[",
"int",
"]",
"]",
",",
"np",
".",
"ndarray",
"]",
",",
"y_predicted",
":",
"Union",
"[",
"List",
"[",
"List",
"[",
... | Calculates log loss.
Args:
y_true: list or array of true values
y_predicted: list or array of predicted values
Returns:
Log loss | [
"Calculates",
"log",
"loss",
"."
] | python | test | 29.538462 |
CZ-NIC/yangson | yangson/datatype.py | https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/datatype.py#L317-L320 | def from_raw(self, raw: RawScalar) -> Optional[bool]:
"""Override superclass method."""
if isinstance(raw, bool):
return raw | [
"def",
"from_raw",
"(",
"self",
",",
"raw",
":",
"RawScalar",
")",
"->",
"Optional",
"[",
"bool",
"]",
":",
"if",
"isinstance",
"(",
"raw",
",",
"bool",
")",
":",
"return",
"raw"
] | Override superclass method. | [
"Override",
"superclass",
"method",
"."
] | python | train | 37.25 |
fastai/fastai | fastai/layers.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L293-L302 | def simple_cnn(actns:Collection[int], kernel_szs:Collection[int]=None,
strides:Collection[int]=None, bn=False) -> nn.Sequential:
"CNN with `conv_layer` defined by `actns`, `kernel_szs` and `strides`, plus batchnorm if `bn`."
nl = len(actns)-1
kernel_szs = ifnone(kernel_szs, [3]*nl)
stride... | [
"def",
"simple_cnn",
"(",
"actns",
":",
"Collection",
"[",
"int",
"]",
",",
"kernel_szs",
":",
"Collection",
"[",
"int",
"]",
"=",
"None",
",",
"strides",
":",
"Collection",
"[",
"int",
"]",
"=",
"None",
",",
"bn",
"=",
"False",
")",
"->",
"nn",
".... | CNN with `conv_layer` defined by `actns`, `kernel_szs` and `strides`, plus batchnorm if `bn`. | [
"CNN",
"with",
"conv_layer",
"defined",
"by",
"actns",
"kernel_szs",
"and",
"strides",
"plus",
"batchnorm",
"if",
"bn",
"."
] | python | train | 60.1 |
google/grumpy | third_party/pythonparser/parser.py | https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pythonparser/parser.py#L547-L549 | def eval_input(self, expr):
"""eval_input: testlist NEWLINE* ENDMARKER"""
return ast.Expression(body=[expr], loc=expr.loc) | [
"def",
"eval_input",
"(",
"self",
",",
"expr",
")",
":",
"return",
"ast",
".",
"Expression",
"(",
"body",
"=",
"[",
"expr",
"]",
",",
"loc",
"=",
"expr",
".",
"loc",
")"
] | eval_input: testlist NEWLINE* ENDMARKER | [
"eval_input",
":",
"testlist",
"NEWLINE",
"*",
"ENDMARKER"
] | python | valid | 45.333333 |
ajyoon/blur | blur/markov/graph.py | https://github.com/ajyoon/blur/blob/25fcf083af112bb003956a7a7e1c6ff7d8fef279/blur/markov/graph.py#L524-L559 | def from_file(cls,
source,
distance_weights=None,
merge_same_words=False,
group_marker_opening='<<',
group_marker_closing='>>'):
"""
Read a string from a file and derive a ``Graph`` from it.
This is a conv... | [
"def",
"from_file",
"(",
"cls",
",",
"source",
",",
"distance_weights",
"=",
"None",
",",
"merge_same_words",
"=",
"False",
",",
"group_marker_opening",
"=",
"'<<'",
",",
"group_marker_closing",
"=",
"'>>'",
")",
":",
"source_string",
"=",
"open",
"(",
"source... | Read a string from a file and derive a ``Graph`` from it.
This is a convenience function for opening a file and passing its
contents to ``Graph.from_string()`` (see that for more detail)
Args:
source (str): the file to read and derive the graph from
distance_weights (di... | [
"Read",
"a",
"string",
"from",
"a",
"file",
"and",
"derive",
"a",
"Graph",
"from",
"it",
"."
] | python | train | 43.916667 |
revelc/pyaccumulo | pyaccumulo/proxy/AccumuloProxy.py | https://github.com/revelc/pyaccumulo/blob/8adcf535bb82ba69c749efce785c9efc487e85de/pyaccumulo/proxy/AccumuloProxy.py#L2091-L2098 | def getActiveCompactions(self, login, tserver):
"""
Parameters:
- login
- tserver
"""
self.send_getActiveCompactions(login, tserver)
return self.recv_getActiveCompactions() | [
"def",
"getActiveCompactions",
"(",
"self",
",",
"login",
",",
"tserver",
")",
":",
"self",
".",
"send_getActiveCompactions",
"(",
"login",
",",
"tserver",
")",
"return",
"self",
".",
"recv_getActiveCompactions",
"(",
")"
] | Parameters:
- login
- tserver | [
"Parameters",
":",
"-",
"login",
"-",
"tserver"
] | python | train | 24.375 |
arkottke/pysra | pysra/site.py | https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/site.py#L129-L149 | def _update(self):
"""Initialize the 1D interpolation."""
if self.strains.size and self.strains.size == self.values.size:
x = np.log(self.strains)
y = self.values
if x.size < 4:
self._interpolater = interp1d(
x,
... | [
"def",
"_update",
"(",
"self",
")",
":",
"if",
"self",
".",
"strains",
".",
"size",
"and",
"self",
".",
"strains",
".",
"size",
"==",
"self",
".",
"values",
".",
"size",
":",
"x",
"=",
"np",
".",
"log",
"(",
"self",
".",
"strains",
")",
"y",
"=... | Initialize the 1D interpolation. | [
"Initialize",
"the",
"1D",
"interpolation",
"."
] | python | train | 30.761905 |
tropo/tropo-webapi-python | build/lib/tropo.py | https://github.com/tropo/tropo-webapi-python/blob/f87772644a6b45066a4c5218f0c1f6467b64ab3c/build/lib/tropo.py#L864-L878 | def RenderJson(self, pretty=False):
"""
Render a Tropo object into a Json string.
"""
steps = self._steps
topdict = {}
topdict['tropo'] = steps
if pretty:
try:
json = jsonlib.dumps(topdict, indent=4, sort_keys=False)
except ... | [
"def",
"RenderJson",
"(",
"self",
",",
"pretty",
"=",
"False",
")",
":",
"steps",
"=",
"self",
".",
"_steps",
"topdict",
"=",
"{",
"}",
"topdict",
"[",
"'tropo'",
"]",
"=",
"steps",
"if",
"pretty",
":",
"try",
":",
"json",
"=",
"jsonlib",
".",
"dum... | Render a Tropo object into a Json string. | [
"Render",
"a",
"Tropo",
"object",
"into",
"a",
"Json",
"string",
"."
] | python | train | 29.2 |
inveniosoftware-contrib/invenio-workflows | invenio_workflows/api.py | https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/api.py#L149-L159 | def get(cls, id_):
"""Return a workflow object from id."""
with db.session.no_autoflush:
query = cls.dbmodel.query.filter_by(id=id_)
try:
model = query.one()
except NoResultFound:
raise WorkflowsMissingObject("No object for for id {0}".... | [
"def",
"get",
"(",
"cls",
",",
"id_",
")",
":",
"with",
"db",
".",
"session",
".",
"no_autoflush",
":",
"query",
"=",
"cls",
".",
"dbmodel",
".",
"query",
".",
"filter_by",
"(",
"id",
"=",
"id_",
")",
"try",
":",
"model",
"=",
"query",
".",
"one"... | Return a workflow object from id. | [
"Return",
"a",
"workflow",
"object",
"from",
"id",
"."
] | python | train | 35.454545 |
redhat-openstack/python-tripleo-helper | tripleohelper/host0.py | https://github.com/redhat-openstack/python-tripleo-helper/blob/bfa165538335edb1088170c7a92f097167225c81/tripleohelper/host0.py#L35-L42 | def configure(self, rhsm=None, repositories=None):
"""This method will configure the host0 and run the hypervisor."""
if rhsm is not None:
self.rhsm_register(rhsm)
if repositories is not None:
self.enable_repositories(repositories)
self.create_stack_user()
... | [
"def",
"configure",
"(",
"self",
",",
"rhsm",
"=",
"None",
",",
"repositories",
"=",
"None",
")",
":",
"if",
"rhsm",
"is",
"not",
"None",
":",
"self",
".",
"rhsm_register",
"(",
"rhsm",
")",
"if",
"repositories",
"is",
"not",
"None",
":",
"self",
"."... | This method will configure the host0 and run the hypervisor. | [
"This",
"method",
"will",
"configure",
"the",
"host0",
"and",
"run",
"the",
"hypervisor",
"."
] | python | train | 42.25 |
JasonKessler/scattertext | scattertext/__init__.py | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/__init__.py#L608-L678 | def word_similarity_explorer_gensim(corpus,
category,
target_term,
category_name=None,
not_category_name=None,
word2vec=None,
... | [
"def",
"word_similarity_explorer_gensim",
"(",
"corpus",
",",
"category",
",",
"target_term",
",",
"category_name",
"=",
"None",
",",
"not_category_name",
"=",
"None",
",",
"word2vec",
"=",
"None",
",",
"alpha",
"=",
"0.01",
",",
"max_p_val",
"=",
"0.1",
",",
... | Parameters
----------
corpus : Corpus
Corpus to use.
category : str
Name of category column as it appears in original data frame.
category_name : str
Name of category to use. E.g., "5-star reviews."
not_category_name : str
Name of ... | [
"Parameters",
"----------",
"corpus",
":",
"Corpus",
"Corpus",
"to",
"use",
".",
"category",
":",
"str",
"Name",
"of",
"category",
"column",
"as",
"it",
"appears",
"in",
"original",
"data",
"frame",
".",
"category_name",
":",
"str",
"Name",
"of",
"category",... | python | train | 41.971831 |
mongodb/mongo-python-driver | pymongo/mongo_client.py | https://github.com/mongodb/mongo-python-driver/blob/c29c21449e3aae74154207058cf85fd94018d4cd/pymongo/mongo_client.py#L1085-L1104 | def _end_sessions(self, session_ids):
"""Send endSessions command(s) with the given session ids."""
try:
# Use SocketInfo.command directly to avoid implicitly creating
# another session.
with self._socket_for_reads(
ReadPreference.PRIMARY_PREFERRED... | [
"def",
"_end_sessions",
"(",
"self",
",",
"session_ids",
")",
":",
"try",
":",
"# Use SocketInfo.command directly to avoid implicitly creating",
"# another session.",
"with",
"self",
".",
"_socket_for_reads",
"(",
"ReadPreference",
".",
"PRIMARY_PREFERRED",
",",
"None",
"... | Send endSessions command(s) with the given session ids. | [
"Send",
"endSessions",
"command",
"(",
"s",
")",
"with",
"the",
"given",
"session",
"ids",
"."
] | python | train | 44.65 |
singularityhub/sregistry-cli | sregistry/main/s3/__init__.py | https://github.com/singularityhub/sregistry-cli/blob/abc96140a1d15b5e96d83432e1e0e1f4f8f36331/sregistry/main/s3/__init__.py#L92-L114 | def get_resource(self):
'''use the user provided endpoint and keys (from environment) to
connect to the resource. We can share the aws environment
variables:
AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY
https://docs.aws.amazon.com/cli/latest/userguide/cli-conf... | [
"def",
"get_resource",
"(",
"self",
")",
":",
"# If base is not defined, assume using aws client",
"if",
"self",
".",
"base",
"!=",
"None",
":",
"# s3.ServiceResource()",
"self",
".",
"s3",
"=",
"boto3",
".",
"resource",
"(",
"'s3'",
",",
"endpoint_url",
"=",
"s... | use the user provided endpoint and keys (from environment) to
connect to the resource. We can share the aws environment
variables:
AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY
https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-envvars.html | [
"use",
"the",
"user",
"provided",
"endpoint",
"and",
"keys",
"(",
"from",
"environment",
")",
"to",
"connect",
"to",
"the",
"resource",
".",
"We",
"can",
"share",
"the",
"aws",
"environment",
"variables",
":"
] | python | test | 39.913043 |
onecodex/onecodex | onecodex/lib/upload.py | https://github.com/onecodex/onecodex/blob/326a0a1af140e3a57ccf31c3c9c5e17a5775c13d/onecodex/lib/upload.py#L334-L384 | def _call_init_upload(file_name, file_size, metadata, tags, project, samples_resource):
"""Call init_upload at the One Codex API and return data used to upload the file.
Parameters
----------
file_name : `string`
The file_name you wish to associate this fastx file with at One Codex.
file_si... | [
"def",
"_call_init_upload",
"(",
"file_name",
",",
"file_size",
",",
"metadata",
",",
"tags",
",",
"project",
",",
"samples_resource",
")",
":",
"upload_args",
"=",
"{",
"\"filename\"",
":",
"file_name",
",",
"\"size\"",
":",
"file_size",
",",
"\"upload_type\"",... | Call init_upload at the One Codex API and return data used to upload the file.
Parameters
----------
file_name : `string`
The file_name you wish to associate this fastx file with at One Codex.
file_size : `integer`
Accurate size of file to be uploaded, in bytes.
metadata : `dict`, o... | [
"Call",
"init_upload",
"at",
"the",
"One",
"Codex",
"API",
"and",
"return",
"data",
"used",
"to",
"upload",
"the",
"file",
"."
] | python | train | 33.156863 |
Crypto-toolbox/bitex | bitex/api/WSS/bitstamp.py | https://github.com/Crypto-toolbox/bitex/blob/56d46ea3db6de5219a72dad9b052fbabc921232f/bitex/api/WSS/bitstamp.py#L67-L78 | def start(self):
"""
Extension of Pusher.connect() method, which registers all callbacks with
the relevant channels, before initializing a connection.
:return:
"""
super(BitstampWSS, self).start()
self.pusher = pusherclient.Pusher(self.addr, **self.__pusher_optio... | [
"def",
"start",
"(",
"self",
")",
":",
"super",
"(",
"BitstampWSS",
",",
"self",
")",
".",
"start",
"(",
")",
"self",
".",
"pusher",
"=",
"pusherclient",
".",
"Pusher",
"(",
"self",
".",
"addr",
",",
"*",
"*",
"self",
".",
"__pusher_options",
")",
... | Extension of Pusher.connect() method, which registers all callbacks with
the relevant channels, before initializing a connection.
:return: | [
"Extension",
"of",
"Pusher",
".",
"connect",
"()",
"method",
"which",
"registers",
"all",
"callbacks",
"with",
"the",
"relevant",
"channels",
"before",
"initializing",
"a",
"connection",
".",
":",
"return",
":"
] | python | train | 39.333333 |
tensorflow/cleverhans | cleverhans/evaluation.py | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/evaluation.py#L191-L228 | def run_attack(sess, model, x, y, attack, attack_params, batch_size=None,
devices=None, feed=None, pass_y=False):
"""
Run attack on every example in a dataset.
:param sess: tf.Session
:param model: cleverhans.model.Model
:param x: numpy array containing input examples (e.g. MNIST().x_test )
:... | [
"def",
"run_attack",
"(",
"sess",
",",
"model",
",",
"x",
",",
"y",
",",
"attack",
",",
"attack_params",
",",
"batch_size",
"=",
"None",
",",
"devices",
"=",
"None",
",",
"feed",
"=",
"None",
",",
"pass_y",
"=",
"False",
")",
":",
"_check_x",
"(",
... | Run attack on every example in a dataset.
:param sess: tf.Session
:param model: cleverhans.model.Model
:param x: numpy array containing input examples (e.g. MNIST().x_test )
:param y: numpy array containing example labels (e.g. MNIST().y_test )
:param attack: cleverhans.attack.Attack
:param attack_params: d... | [
"Run",
"attack",
"on",
"every",
"example",
"in",
"a",
"dataset",
".",
":",
"param",
"sess",
":",
"tf",
".",
"Session",
":",
"param",
"model",
":",
"cleverhans",
".",
"model",
".",
"Model",
":",
"param",
"x",
":",
"numpy",
"array",
"containing",
"input"... | python | train | 47 |
bcbio/bcbio-nextgen | bcbio/provenance/diagnostics.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/provenance/diagnostics.py#L71-L77 | def _get_provitem_from_args(xs):
"""Retrieve processed item from list of input arguments.
"""
for i, x in enumerate(xs):
if _has_provenance(x):
return i, x
return -1, None | [
"def",
"_get_provitem_from_args",
"(",
"xs",
")",
":",
"for",
"i",
",",
"x",
"in",
"enumerate",
"(",
"xs",
")",
":",
"if",
"_has_provenance",
"(",
"x",
")",
":",
"return",
"i",
",",
"x",
"return",
"-",
"1",
",",
"None"
] | Retrieve processed item from list of input arguments. | [
"Retrieve",
"processed",
"item",
"from",
"list",
"of",
"input",
"arguments",
"."
] | python | train | 28.714286 |
brap/brap | brap/graph.py | https://github.com/brap/brap/blob/227d1b6ce2799b7caf1d98d8805e821d19d0969b/brap/graph.py#L57-L84 | def merge(self, subordinate_graph):
"""
merge rules:
00 + 00 == 00 00 + 0B == 0B
0A + 00 == 0A 0A + 0B == 0A
A0 + 00 == A0 A0 + 0B == AB
AA + 00 == AA AA + 0B == AB
00 + B0 == B0 00 + BB == BB
0A + B0 == BA 0A + BB == BA
A0 + B0 ... | [
"def",
"merge",
"(",
"self",
",",
"subordinate_graph",
")",
":",
"if",
"not",
"isinstance",
"(",
"subordinate_graph",
",",
"Graph",
")",
":",
"raise",
"Exception",
"(",
"\"Graph is expected to only merge with a Graph.\"",
")",
"subordinate_nodes",
"=",
"subordinate_gr... | merge rules:
00 + 00 == 00 00 + 0B == 0B
0A + 00 == 0A 0A + 0B == 0A
A0 + 00 == A0 A0 + 0B == AB
AA + 00 == AA AA + 0B == AB
00 + B0 == B0 00 + BB == BB
0A + B0 == BA 0A + BB == BA
A0 + B0 == A0 A0 + BB == AB
AA + B0 == AA AA + BB ... | [
"merge",
"rules",
":",
"00",
"+",
"00",
"==",
"00",
"00",
"+",
"0B",
"==",
"0B",
"0A",
"+",
"00",
"==",
"0A",
"0A",
"+",
"0B",
"==",
"0A",
"A0",
"+",
"00",
"==",
"A0",
"A0",
"+",
"0B",
"==",
"AB",
"AA",
"+",
"00",
"==",
"AA",
"AA",
"+",
... | python | train | 31.642857 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_link.py | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_link.py#L310-L334 | def handle_msec_timestamp(self, m, master):
'''special handling for MAVLink packets with a time_boot_ms field'''
if m.get_type() == 'GLOBAL_POSITION_INT':
# this is fix time, not boot time
return
msec = m.time_boot_ms
if msec + 30000 < master.highest_msec:
... | [
"def",
"handle_msec_timestamp",
"(",
"self",
",",
"m",
",",
"master",
")",
":",
"if",
"m",
".",
"get_type",
"(",
")",
"==",
"'GLOBAL_POSITION_INT'",
":",
"# this is fix time, not boot time",
"return",
"msec",
"=",
"m",
".",
"time_boot_ms",
"if",
"msec",
"+",
... | special handling for MAVLink packets with a time_boot_ms field | [
"special",
"handling",
"for",
"MAVLink",
"packets",
"with",
"a",
"time_boot_ms",
"field"
] | python | train | 38.84 |
libtcod/python-tcod | examples/termbox/termbox.py | https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/examples/termbox/termbox.py#L202-L205 | def change_cell(self, x, y, ch, fg, bg):
"""Change cell in position (x;y).
"""
self.console.draw_char(x, y, ch, fg, bg) | [
"def",
"change_cell",
"(",
"self",
",",
"x",
",",
"y",
",",
"ch",
",",
"fg",
",",
"bg",
")",
":",
"self",
".",
"console",
".",
"draw_char",
"(",
"x",
",",
"y",
",",
"ch",
",",
"fg",
",",
"bg",
")"
] | Change cell in position (x;y). | [
"Change",
"cell",
"in",
"position",
"(",
"x",
";",
"y",
")",
"."
] | python | train | 35 |
ambitioninc/django-query-builder | querybuilder/query.py | https://github.com/ambitioninc/django-query-builder/blob/113a7d845d3ddc6a45621b9880308e756f87c5bf/querybuilder/query.py#L310-L326 | def get_condition_value(self, operator, value):
"""
Gets the condition value based on the operator and value
:param operator: the condition operator name
:type operator: str
:param value: the value to be formatted based on the condition operator
:type value: object
... | [
"def",
"get_condition_value",
"(",
"self",
",",
"operator",
",",
"value",
")",
":",
"if",
"operator",
"in",
"(",
"'contains'",
",",
"'icontains'",
")",
":",
"value",
"=",
"'%{0}%'",
".",
"format",
"(",
"value",
")",
"elif",
"operator",
"==",
"'startswith'"... | Gets the condition value based on the operator and value
:param operator: the condition operator name
:type operator: str
:param value: the value to be formatted based on the condition operator
:type value: object
:return: the comparison operator from the Where class's comparis... | [
"Gets",
"the",
"condition",
"value",
"based",
"on",
"the",
"operator",
"and",
"value"
] | python | train | 35.470588 |
ArchiveTeam/wpull | wpull/application/tasks/stats.py | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/application/tasks/stats.py#L45-L82 | def _print_stats(cls, stats: Statistics, human_format_speed: bool=True):
'''Log the final statistics to the user.'''
time_length = datetime.timedelta(
seconds=int(stats.stop_time - stats.start_time)
)
file_size = wpull.string.format_size(stats.size)
if stats.bandwidt... | [
"def",
"_print_stats",
"(",
"cls",
",",
"stats",
":",
"Statistics",
",",
"human_format_speed",
":",
"bool",
"=",
"True",
")",
":",
"time_length",
"=",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"int",
"(",
"stats",
".",
"stop_time",
"-",
"stats",
... | Log the final statistics to the user. | [
"Log",
"the",
"final",
"statistics",
"to",
"the",
"user",
"."
] | python | train | 35.078947 |
hotdoc/hotdoc | hotdoc/core/tree.py | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/tree.py#L269-L303 | def format(self, formatter, link_resolver, output):
"""
Banana banana
"""
if not self.title and self.name:
title = os.path.splitext(self.name)[0]
self.title = os.path.basename(title).replace('-', ' ')
self.formatted_contents = u''
self.build_pat... | [
"def",
"format",
"(",
"self",
",",
"formatter",
",",
"link_resolver",
",",
"output",
")",
":",
"if",
"not",
"self",
".",
"title",
"and",
"self",
".",
"name",
":",
"title",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"self",
".",
"name",
")",
"[",... | Banana banana | [
"Banana",
"banana"
] | python | train | 32.228571 |
kowalpy/Robot-Framework-FTP-Library | FtpLibrary.py | https://github.com/kowalpy/Robot-Framework-FTP-Library/blob/90794be0a12af489ac98e8ae3b4ff450c83e2f3d/FtpLibrary.py#L419-L436 | def send_cmd(self, command, connId='default'):
"""
Sends any command to FTP server. Returns server output.
Parameters:
- command - any valid command to be sent (invalid will result in exception).
- connId(optional) - connection identifier. By default equals 'default'
Exam... | [
"def",
"send_cmd",
"(",
"self",
",",
"command",
",",
"connId",
"=",
"'default'",
")",
":",
"thisConn",
"=",
"self",
".",
"__getConnection",
"(",
"connId",
")",
"outputMsg",
"=",
"\"\"",
"try",
":",
"outputMsg",
"+=",
"str",
"(",
"thisConn",
".",
"sendcmd... | Sends any command to FTP server. Returns server output.
Parameters:
- command - any valid command to be sent (invalid will result in exception).
- connId(optional) - connection identifier. By default equals 'default'
Example:
| send cmd | HELP | | [
"Sends",
"any",
"command",
"to",
"FTP",
"server",
".",
"Returns",
"server",
"output",
".",
"Parameters",
":",
"-",
"command",
"-",
"any",
"valid",
"command",
"to",
"be",
"sent",
"(",
"invalid",
"will",
"result",
"in",
"exception",
")",
".",
"-",
"connId"... | python | train | 36.5 |
Qiskit/qiskit-terra | qiskit/quantum_info/operators/pauli.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/pauli.py#L82-L110 | def from_label(cls, label):
r"""Take pauli string to construct pauli.
The qubit index of pauli label is q_{n-1} ... q_0.
E.g., a pauli is $P_{n-1} \otimes ... \otimes P_0$
Args:
label (str): pauli label
Returns:
Pauli: the constructed pauli
Rai... | [
"def",
"from_label",
"(",
"cls",
",",
"label",
")",
":",
"z",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"label",
")",
",",
"dtype",
"=",
"np",
".",
"bool",
")",
"x",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"label",
")",
",",
"dtype",
"=",
... | r"""Take pauli string to construct pauli.
The qubit index of pauli label is q_{n-1} ... q_0.
E.g., a pauli is $P_{n-1} \otimes ... \otimes P_0$
Args:
label (str): pauli label
Returns:
Pauli: the constructed pauli
Raises:
QiskitError: invali... | [
"r",
"Take",
"pauli",
"string",
"to",
"construct",
"pauli",
"."
] | python | test | 32.551724 |
dacker-team/pyzure | pyzure/send/common.py | https://github.com/dacker-team/pyzure/blob/1e6d202f91ca0f080635adc470d9d18585056d53/pyzure/send/common.py#L77-L96 | def print_progress_bar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█'):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
prefix - Optional : p... | [
"def",
"print_progress_bar",
"(",
"iteration",
",",
"total",
",",
"prefix",
"=",
"''",
",",
"suffix",
"=",
"''",
",",
"decimals",
"=",
"1",
",",
"length",
"=",
"100",
",",
"fill",
"=",
"'█'):",
"",
"",
"percent",
"=",
"(",
"\"{0:.\"",
"+",
"str",
"... | Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
prefix - Optional : prefix string (Str)
suffix - Optional : suffix string (Str)
decimals - Optional : pos... | [
"Call",
"in",
"a",
"loop",
"to",
"create",
"terminal",
"progress",
"bar"
] | python | train | 48.5 |
google/mobly | mobly/controllers/attenuator_lib/minicircuits.py | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/attenuator_lib/minicircuits.py#L76-L104 | def set_atten(self, idx, value):
"""Sets the attenuation value for a particular signal path.
Args:
idx: Zero-based index int which is the identifier for a particular
signal path in an instrument. For instruments that only has one
channel, this is ignored by t... | [
"def",
"set_atten",
"(",
"self",
",",
"idx",
",",
"value",
")",
":",
"if",
"not",
"self",
".",
"is_open",
":",
"raise",
"attenuator",
".",
"Error",
"(",
"\"Connection to attenuator at %s is not open!\"",
"%",
"self",
".",
"_telnet_client",
".",
"host",
")",
... | Sets the attenuation value for a particular signal path.
Args:
idx: Zero-based index int which is the identifier for a particular
signal path in an instrument. For instruments that only has one
channel, this is ignored by the device.
value: A float that i... | [
"Sets",
"the",
"attenuation",
"value",
"for",
"a",
"particular",
"signal",
"path",
"."
] | python | train | 46.655172 |
MisterY/asset-allocation | asset_allocation/model.py | https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/model.py#L248-L264 | def __calculate_current_value(self, asset_class: AssetClass):
""" Calculate totals for asset class by adding all the children values """
# Is this the final asset class, the one with stocks?
if asset_class.stocks:
# add all the stocks
stocks_sum = Decimal(0)
f... | [
"def",
"__calculate_current_value",
"(",
"self",
",",
"asset_class",
":",
"AssetClass",
")",
":",
"# Is this the final asset class, the one with stocks?",
"if",
"asset_class",
".",
"stocks",
":",
"# add all the stocks",
"stocks_sum",
"=",
"Decimal",
"(",
"0",
")",
"for"... | Calculate totals for asset class by adding all the children values | [
"Calculate",
"totals",
"for",
"asset",
"class",
"by",
"adding",
"all",
"the",
"children",
"values"
] | python | train | 42.882353 |
projectatomic/atomic-reactor | atomic_reactor/util.py | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/util.py#L1566-L1582 | def get_image_platform_digest(self, image, platform):
"""Get digest of specified image and platform
:param ImageName image: image
:param str platform: name of the platform/arch (x86_64, ppc64le, ...)
:raises KeyError: when digest is not found
:rtype: str
:return: digest ... | [
"def",
"get_image_platform_digest",
"(",
"self",
",",
"image",
",",
"platform",
")",
":",
"image_digests",
"=",
"self",
".",
"get_image_digests",
"(",
"image",
")",
"digest",
"=",
"image_digests",
".",
"get",
"(",
"platform",
")",
"if",
"digest",
"is",
"None... | Get digest of specified image and platform
:param ImageName image: image
:param str platform: name of the platform/arch (x86_64, ppc64le, ...)
:raises KeyError: when digest is not found
:rtype: str
:return: digest of the specified image (fedora@sha256:...) | [
"Get",
"digest",
"of",
"specified",
"image",
"and",
"platform"
] | python | train | 37.470588 |
wangsix/vmo | vmo/analysis/analysis.py | https://github.com/wangsix/vmo/blob/bb1cc4cf1f33f0bb49e38c91126c1be1a0cdd09d/vmo/analysis/analysis.py#L469-L503 | def _query_k(k, i, P, oracle, query, trn, state_cache, dist_cache, smooth=False, D=None, weight=0.5):
"""A helper function for query-matching function`s iteration over observations.
Args:
k - index of the candidate path
i - index of the frames of the observations
P - the path matrix... | [
"def",
"_query_k",
"(",
"k",
",",
"i",
",",
"P",
",",
"oracle",
",",
"query",
",",
"trn",
",",
"state_cache",
",",
"dist_cache",
",",
"smooth",
"=",
"False",
",",
"D",
"=",
"None",
",",
"weight",
"=",
"0.5",
")",
":",
"_trn",
"=",
"trn",
"(",
"... | A helper function for query-matching function`s iteration over observations.
Args:
k - index of the candidate path
i - index of the frames of the observations
P - the path matrix of size K x N, K the number for paths initiated,
N the frame number of observations
ora... | [
"A",
"helper",
"function",
"for",
"query",
"-",
"matching",
"function",
"s",
"iteration",
"over",
"observations",
".",
"Args",
":",
"k",
"-",
"index",
"of",
"the",
"candidate",
"path",
"i",
"-",
"index",
"of",
"the",
"frames",
"of",
"the",
"observations",
... | python | train | 50.742857 |
skioo/django-datatrans-gateway | datatrans/gateway/notification.py | https://github.com/skioo/django-datatrans-gateway/blob/1c4de5b589403e4ec3aadc4ff2fc1eb17b34bcc7/datatrans/gateway/notification.py#L19-L134 | def parse_notification_xml(xml: str) -> Union[AliasRegistration, Payment]:
""""
Both alias registration and payments are received here.
We can differentiate them by looking at the use-alias user-parameter (and verifying the amount is o).
"""
body = fromstring(xml).find('body')
transaction = bod... | [
"def",
"parse_notification_xml",
"(",
"xml",
":",
"str",
")",
"->",
"Union",
"[",
"AliasRegistration",
",",
"Payment",
"]",
":",
"body",
"=",
"fromstring",
"(",
"xml",
")",
".",
"find",
"(",
"'body'",
")",
"transaction",
"=",
"body",
".",
"find",
"(",
... | Both alias registration and payments are received here.
We can differentiate them by looking at the use-alias user-parameter (and verifying the amount is o). | [
"Both",
"alias",
"registration",
"and",
"payments",
"are",
"received",
"here",
".",
"We",
"can",
"differentiate",
"them",
"by",
"looking",
"at",
"the",
"use",
"-",
"alias",
"user",
"-",
"parameter",
"(",
"and",
"verifying",
"the",
"amount",
"is",
"o",
")",... | python | test | 36.724138 |
saltstack/salt | salt/modules/junos.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/junos.py#L534-L562 | def diff(**kwargs):
'''
Returns the difference between the candidate and the current configuration
id : 0
The rollback ID value (0-49)
CLI Example:
.. code-block:: bash
salt 'device_name' junos.diff 3
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
id_ = kwargs.po... | [
"def",
"diff",
"(",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"salt",
".",
"utils",
".",
"args",
".",
"clean_kwargs",
"(",
"*",
"*",
"kwargs",
")",
"id_",
"=",
"kwargs",
".",
"pop",
"(",
"'id'",
",",
"0",
")",
"if",
"kwargs",
":",
"salt",
".... | Returns the difference between the candidate and the current configuration
id : 0
The rollback ID value (0-49)
CLI Example:
.. code-block:: bash
salt 'device_name' junos.diff 3 | [
"Returns",
"the",
"difference",
"between",
"the",
"candidate",
"and",
"the",
"current",
"configuration"
] | python | train | 23 |
Erotemic/timerit | timerit/core.py | https://github.com/Erotemic/timerit/blob/625449f5359f757fb0ab8093b228dc8f37b8ffaf/timerit/core.py#L81-L87 | def toc(self):
""" stops the timer """
elapsed = self._time() - self.tstart
if self.verbose:
self.write('...toc(%r)=%.4fs\n' % (self.label, elapsed))
self.flush()
return elapsed | [
"def",
"toc",
"(",
"self",
")",
":",
"elapsed",
"=",
"self",
".",
"_time",
"(",
")",
"-",
"self",
".",
"tstart",
"if",
"self",
".",
"verbose",
":",
"self",
".",
"write",
"(",
"'...toc(%r)=%.4fs\\n'",
"%",
"(",
"self",
".",
"label",
",",
"elapsed",
... | stops the timer | [
"stops",
"the",
"timer"
] | python | train | 32.428571 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.