text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def find(s):
"""
Find an amino acid whose name or abbreviation is s.
@param s: A C{str} amino acid specifier. This may be a full name,
a 3-letter abbreviation or a 1-letter abbreviation. Case is ignored.
return: An L{AminoAcid} instance or C{None} if no matching amino acid can
be locate... | [
"def",
"find",
"(",
"s",
")",
":",
"abbrev1",
"=",
"None",
"origS",
"=",
"s",
"if",
"' '",
"in",
"s",
":",
"# Convert first word to title case, others to lower.",
"first",
",",
"rest",
"=",
"s",
".",
"split",
"(",
"' '",
",",
"1",
")",
"s",
"=",
"first... | 29.463415 | 18.926829 |
def get_dependent_items(self, item) -> typing.List:
"""Return the list of data items containing data that directly depends on data in this item."""
with self.__dependency_tree_lock:
return copy.copy(self.__dependency_tree_source_to_target_map.get(weakref.ref(item), list())) | [
"def",
"get_dependent_items",
"(",
"self",
",",
"item",
")",
"->",
"typing",
".",
"List",
":",
"with",
"self",
".",
"__dependency_tree_lock",
":",
"return",
"copy",
".",
"copy",
"(",
"self",
".",
"__dependency_tree_source_to_target_map",
".",
"get",
"(",
"weak... | 74.75 | 19 |
def detailxy(self, canvas, button, data_x, data_y):
"""Motion event in the pick fits window. Show the pointing
information under the cursor.
"""
if button == 0:
# TODO: we could track the focus changes to make this check
# more efficient
chviewer = se... | [
"def",
"detailxy",
"(",
"self",
",",
"canvas",
",",
"button",
",",
"data_x",
",",
"data_y",
")",
":",
"if",
"button",
"==",
"0",
":",
"# TODO: we could track the focus changes to make this check",
"# more efficient",
"chviewer",
"=",
"self",
".",
"fv",
".",
"get... | 38.823529 | 14 |
def print_code_table(self, out=sys.stdout):
"""
Print code table overview
"""
out.write(u'bits code (value) symbol\n')
for symbol, (bitsize, value) in sorted(self._table.items()):
out.write(u'{b:4d} {c:10} ({v:5d}) {s!r}\n'.format(
b=bitsize,... | [
"def",
"print_code_table",
"(",
"self",
",",
"out",
"=",
"sys",
".",
"stdout",
")",
":",
"out",
".",
"write",
"(",
"u'bits code (value) symbol\\n'",
")",
"for",
"symbol",
",",
"(",
"bitsize",
",",
"value",
")",
"in",
"sorted",
"(",
"self",
".",
"... | 42.555556 | 16.333333 |
def is_locked(self):
"""Return True, if URI is locked."""
if self.provider.lock_manager is None:
return False
return self.provider.lock_manager.is_url_locked(self.get_ref_url()) | [
"def",
"is_locked",
"(",
"self",
")",
":",
"if",
"self",
".",
"provider",
".",
"lock_manager",
"is",
"None",
":",
"return",
"False",
"return",
"self",
".",
"provider",
".",
"lock_manager",
".",
"is_url_locked",
"(",
"self",
".",
"get_ref_url",
"(",
")",
... | 41.8 | 15.4 |
def get_temperature(self, channel, sensor='VNTC'):
'''Reading temperature
'''
# NTC type SEMITEC 103KT1608 http://www.semitec.co.jp/english/products/pdf/KT_Thermistor.pdf
#
# R_NTC = R_25 * exp(B_NTC * (1/T - 1/T_25))
#
# R_NTC measured NTC resistance
# R_NTC_25 ... | [
"def",
"get_temperature",
"(",
"self",
",",
"channel",
",",
"sensor",
"=",
"'VNTC'",
")",
":",
"# NTC type SEMITEC 103KT1608 http://www.semitec.co.jp/english/products/pdf/KT_Thermistor.pdf",
"#",
"# R_NTC = R_25 * exp(B_NTC * (1/T - 1/T_25))",
"#",
"# R_NTC ... | 55.482759 | 37.62069 |
def replace_tab_indent(s, replace=" "):
"""
:param str s: string with tabs
:param str replace: e.g. 4 spaces
:rtype: str
"""
prefix = get_indent_prefix(s)
return prefix.replace("\t", replace) + s[len(prefix):] | [
"def",
"replace_tab_indent",
"(",
"s",
",",
"replace",
"=",
"\" \"",
")",
":",
"prefix",
"=",
"get_indent_prefix",
"(",
"s",
")",
"return",
"prefix",
".",
"replace",
"(",
"\"\\t\"",
",",
"replace",
")",
"+",
"s",
"[",
"len",
"(",
"prefix",
")",
":",... | 29.125 | 7.625 |
def auto_up(self, count=1, go_to_start_of_line_if_history_changes=False):
"""
If we're not on the first line (of a multiline input) go a line up,
otherwise go back in history. (If nothing is selected.)
"""
if self.complete_state:
self.complete_previous(count=count)
... | [
"def",
"auto_up",
"(",
"self",
",",
"count",
"=",
"1",
",",
"go_to_start_of_line_if_history_changes",
"=",
"False",
")",
":",
"if",
"self",
".",
"complete_state",
":",
"self",
".",
"complete_previous",
"(",
"count",
"=",
"count",
")",
"elif",
"self",
".",
... | 44.2 | 15 |
def update_thumbnail_via_upload(api_key, api_secret, video_key, local_video_image_path='', api_format='json',
**kwargs):
"""
Function which updates the thumbnail for a particular video object with a locally saved image.
:param api_key: <string> JWPlatform api-key
:param ... | [
"def",
"update_thumbnail_via_upload",
"(",
"api_key",
",",
"api_secret",
",",
"video_key",
",",
"local_video_image_path",
"=",
"''",
",",
"api_format",
"=",
"'json'",
",",
"*",
"*",
"kwargs",
")",
":",
"jwplatform_client",
"=",
"jwplatform",
".",
"Client",
"(",
... | 46.5 | 24.2 |
def serialize(self, cls, record):
"""
Serialize the record to JSON. cls unused in this implementation.
>>> s = teststore()
>>> s.serialize('tstoretest', {'id': '1', 'name': 'Toto'})
'{"id": "1", "name": "Toto"}'
"""
return json.dumps(record, cls=self.encoder) | [
"def",
"serialize",
"(",
"self",
",",
"cls",
",",
"record",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"record",
",",
"cls",
"=",
"self",
".",
"encoder",
")"
] | 34.222222 | 14.666667 |
def typelogged(memb):
"""Decorator applicable to functions, methods, properties,
classes or modules (by explicit call).
If applied on a module, memb must be a module or a module name contained in sys.modules.
See pytypes.set_global_typelogged_decorator to apply this on all modules.
Observes function... | [
"def",
"typelogged",
"(",
"memb",
")",
":",
"if",
"not",
"pytypes",
".",
"typelogging_enabled",
":",
"return",
"memb",
"if",
"_check_as_func",
"(",
"memb",
")",
":",
"return",
"typelogged_func",
"(",
"memb",
")",
"if",
"isclass",
"(",
"memb",
")",
":",
"... | 42.6 | 15.85 |
def active(self) -> bool:
"""Indicate if this RunState is currently active."""
states = self._client.get_state(self._state_url)['states']
for state in states:
state = state['State']
if int(state['Id']) == self._state_id:
# yes, the ZM API uses the *string*... | [
"def",
"active",
"(",
"self",
")",
"->",
"bool",
":",
"states",
"=",
"self",
".",
"_client",
".",
"get_state",
"(",
"self",
".",
"_state_url",
")",
"[",
"'states'",
"]",
"for",
"state",
"in",
"states",
":",
"state",
"=",
"state",
"[",
"'State'",
"]",... | 44.111111 | 13.666667 |
def set_flushing_policy(flushing_policy):
"""Serialize this policy for Monitor to pick up."""
if "RAY_USE_NEW_GCS" not in os.environ:
raise Exception(
"set_flushing_policy() is only available when environment "
"variable RAY_USE_NEW_GCS is present at both compile and run time."
... | [
"def",
"set_flushing_policy",
"(",
"flushing_policy",
")",
":",
"if",
"\"RAY_USE_NEW_GCS\"",
"not",
"in",
"os",
".",
"environ",
":",
"raise",
"Exception",
"(",
"\"set_flushing_policy() is only available when environment \"",
"\"variable RAY_USE_NEW_GCS is present at both compile ... | 43.75 | 17 |
def reload(request):
"""Reload local requirements file."""
refresh_packages.clean()
refresh_packages.local()
refresh_packages.remote()
url = request.META.get('HTTP_REFERER')
if url:
return HttpResponseRedirect(url)
else:
return HttpResponse('Local requirements list has been r... | [
"def",
"reload",
"(",
"request",
")",
":",
"refresh_packages",
".",
"clean",
"(",
")",
"refresh_packages",
".",
"local",
"(",
")",
"refresh_packages",
".",
"remote",
"(",
")",
"url",
"=",
"request",
".",
"META",
".",
"get",
"(",
"'HTTP_REFERER'",
")",
"i... | 32.1 | 15 |
def baldwinsoc_winners(self, profile):
"""
Returns an integer list that represents all possible winners of a profile under baldwin rule.
:ivar Profile profile: A Profile object that represents an election profile.
"""
ordering = profile.getOrderVectors()
m = profile.numC... | [
"def",
"baldwinsoc_winners",
"(",
"self",
",",
"profile",
")",
":",
"ordering",
"=",
"profile",
".",
"getOrderVectors",
"(",
")",
"m",
"=",
"profile",
".",
"numCands",
"prefcounts",
"=",
"profile",
".",
"getPreferenceCounts",
"(",
")",
"if",
"min",
"(",
"o... | 43.180328 | 20.262295 |
def create_rich_menu(self, rich_menu, timeout=None):
"""Call create rich menu API.
https://developers.line.me/en/docs/messaging-api/reference/#create-rich-menu
:param rich_menu: Inquired to create a rich menu object.
:type rich_menu: T <= :py:class:`linebot.models.rich_menu.RichMenu`
... | [
"def",
"create_rich_menu",
"(",
"self",
",",
"rich_menu",
",",
"timeout",
"=",
"None",
")",
":",
"response",
"=",
"self",
".",
"_post",
"(",
"'/v2/bot/richmenu'",
",",
"data",
"=",
"rich_menu",
".",
"as_json_string",
"(",
")",
",",
"timeout",
"=",
"timeout... | 40.7 | 21.6 |
def count_node_match(self, pattern, adict=None):
"""
Return the number of nodes that match the pattern.
:param pattern:
:param adict:
:return: int
"""
mydict = self._filetree if adict is None else adict
k = 0
if isinstance(mydict, dict):
... | [
"def",
"count_node_match",
"(",
"self",
",",
"pattern",
",",
"adict",
"=",
"None",
")",
":",
"mydict",
"=",
"self",
".",
"_filetree",
"if",
"adict",
"is",
"None",
"else",
"adict",
"k",
"=",
"0",
"if",
"isinstance",
"(",
"mydict",
",",
"dict",
")",
":... | 26.333333 | 19.190476 |
def _GetDataStreams(self):
"""Retrieves the data streams.
Returns:
list[TSKDataStream]: data streams.
"""
if self._data_streams is None:
if self._file_system.IsHFS():
known_data_attribute_types = [
pytsk3.TSK_FS_ATTR_TYPE_HFS_DEFAULT,
pytsk3.TSK_FS_ATTR_TYPE_... | [
"def",
"_GetDataStreams",
"(",
"self",
")",
":",
"if",
"self",
".",
"_data_streams",
"is",
"None",
":",
"if",
"self",
".",
"_file_system",
".",
"IsHFS",
"(",
")",
":",
"known_data_attribute_types",
"=",
"[",
"pytsk3",
".",
"TSK_FS_ATTR_TYPE_HFS_DEFAULT",
",",
... | 32.386364 | 19.818182 |
def illumination(x, gamma=1., contrast=1., saturation=1., is_random=False):
"""Perform illumination augmentation for a single image, randomly or non-randomly.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
gamma : float
Change bright... | [
"def",
"illumination",
"(",
"x",
",",
"gamma",
"=",
"1.",
",",
"contrast",
"=",
"1.",
",",
"saturation",
"=",
"1.",
",",
"is_random",
"=",
"False",
")",
":",
"if",
"is_random",
":",
"if",
"not",
"(",
"len",
"(",
"gamma",
")",
"==",
"len",
"(",
"c... | 40.211268 | 27.690141 |
def setUserPasswdCredentials(self, username, password):
"""Set username and password in ``disk.0.os.credentials``."""
self.setCredentialValues(username=username, password=password) | [
"def",
"setUserPasswdCredentials",
"(",
"self",
",",
"username",
",",
"password",
")",
":",
"self",
".",
"setCredentialValues",
"(",
"username",
"=",
"username",
",",
"password",
"=",
"password",
")"
] | 48.5 | 21.25 |
def glance(msg, flavor='chat', long=False):
"""
Extract "headline" info about a message.
Use parameter ``long`` to control whether a short or long tuple is returned.
When ``flavor`` is ``chat``
(``msg`` being a `Message <https://core.telegram.org/bots/api#message>`_ object):
- short: (content_... | [
"def",
"glance",
"(",
"msg",
",",
"flavor",
"=",
"'chat'",
",",
"long",
"=",
"False",
")",
":",
"def",
"gl_chat",
"(",
")",
":",
"content_type",
"=",
"_find_first_key",
"(",
"msg",
",",
"all_content_types",
")",
"if",
"long",
":",
"return",
"content_type... | 43.702381 | 32.202381 |
def diff(self, dim, n=1, label='upper'):
"""Calculate the n-th order discrete difference along given axis.
Parameters
----------
dim : str, optional
Dimension over which to calculate the finite difference.
n : int, optional
The number of times values are ... | [
"def",
"diff",
"(",
"self",
",",
"dim",
",",
"n",
"=",
"1",
",",
"label",
"=",
"'upper'",
")",
":",
"ds",
"=",
"self",
".",
"_to_temp_dataset",
"(",
")",
".",
"diff",
"(",
"n",
"=",
"n",
",",
"dim",
"=",
"dim",
",",
"label",
"=",
"label",
")"... | 31.825 | 18.175 |
def POST(self, **kwargs):
r'''
.. http:post:: /token
Generate a Salt eauth token
:status 200: |200|
:status 400: |400|
:status 401: |401|
**Example request:**
.. code-block:: bash
curl -sSk https://localhost:8000/token \
... | [
"def",
"POST",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"creds",
"in",
"cherrypy",
".",
"request",
".",
"lowstate",
":",
"try",
":",
"creds",
".",
"update",
"(",
"{",
"'client'",
":",
"'runner'",
",",
"'fun'",
":",
"'auth.mk_token'",
",... | 27.584906 | 17.169811 |
def decompile(
bytecode_version, co, out=None, showasm=None, showast=False,
timestamp=None, showgrammar=False, code_objects={},
source_size=None, is_pypy=None, magic_int=None,
mapstream=None, do_fragments=False):
"""
ingests and deparses a given code block 'co'
if `bytecode_... | [
"def",
"decompile",
"(",
"bytecode_version",
",",
"co",
",",
"out",
"=",
"None",
",",
"showasm",
"=",
"None",
",",
"showast",
"=",
"False",
",",
"timestamp",
"=",
"None",
",",
"showgrammar",
"=",
"False",
",",
"code_objects",
"=",
"{",
"}",
",",
"sourc... | 35.891892 | 19.648649 |
def make_hasher(algorithm_id):
"""Create a hashing object for the given signing algorithm."""
if algorithm_id == 1:
return hashes.Hash(hashes.SHA1(), default_backend())
elif algorithm_id == 2:
return hashes.Hash(hashes.SHA384(), default_backend())
else:
raise ValueError("Unsuppor... | [
"def",
"make_hasher",
"(",
"algorithm_id",
")",
":",
"if",
"algorithm_id",
"==",
"1",
":",
"return",
"hashes",
".",
"Hash",
"(",
"hashes",
".",
"SHA1",
"(",
")",
",",
"default_backend",
"(",
")",
")",
"elif",
"algorithm_id",
"==",
"2",
":",
"return",
"... | 44.375 | 18.375 |
def parse_datetime(time_str):
"""
Wraps dateutil's parser function to set an explicit UTC timezone, and
to make sure microseconds are 0. Unified Uploader format and EMK format
bother don't use microseconds at all.
:param str time_str: The date/time str to parse.
:rtype: datetime.datetime
:r... | [
"def",
"parse_datetime",
"(",
"time_str",
")",
":",
"try",
":",
"return",
"dateutil",
".",
"parser",
".",
"parse",
"(",
"time_str",
")",
".",
"replace",
"(",
"microsecond",
"=",
"0",
")",
".",
"astimezone",
"(",
"UTC_TZINFO",
")",
"except",
"ValueError",
... | 36.058824 | 16.176471 |
def dump_json_data(page):
"""
Return a python dict representation of this page for use as part of
a JSON export.
"""
def content_langs_ordered():
"""
Return a list of languages ordered by the page content
with the latest creation date in each. This will be used
to ma... | [
"def",
"dump_json_data",
"(",
"page",
")",
":",
"def",
"content_langs_ordered",
"(",
")",
":",
"\"\"\"\n Return a list of languages ordered by the page content\n with the latest creation date in each. This will be used\n to maintain the state of the language_up_to_date te... | 37.986301 | 16.356164 |
def set_printoptions(**kwargs):
"""Set printing options.
These options determine the way JPEG 2000 boxes are displayed.
Parameters
----------
short : bool, optional
When True, only the box ID, offset, and length are displayed. Useful
for displaying only the basic structure or skel... | [
"def",
"set_printoptions",
"(",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"'Use set_option instead of set_printoptions.'",
",",
"DeprecationWarning",
")",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"key",
... | 33.742857 | 23.371429 |
def close_socket(sock):
'''Shutdown and close the socket.'''
if sock:
try:
sock.shutdown(socket.SHUT_RDWR)
except Exception:
pass
try:
sock.close()
except Exception:
pass | [
"def",
"close_socket",
"(",
"sock",
")",
":",
"if",
"sock",
":",
"try",
":",
"sock",
".",
"shutdown",
"(",
"socket",
".",
"SHUT_RDWR",
")",
"except",
"Exception",
":",
"pass",
"try",
":",
"sock",
".",
"close",
"(",
")",
"except",
"Exception",
":",
"p... | 22.545455 | 18 |
def prettyXml(elem):
""" Return a pretty-printed XML string for the ElementTree Element.
"""
roughString = ET.tostring(elem, "utf-8")
reparsed = minidom.parseString(roughString)
return reparsed.toprettyxml(indent=" ") | [
"def",
"prettyXml",
"(",
"elem",
")",
":",
"roughString",
"=",
"ET",
".",
"tostring",
"(",
"elem",
",",
"\"utf-8\"",
")",
"reparsed",
"=",
"minidom",
".",
"parseString",
"(",
"roughString",
")",
"return",
"reparsed",
".",
"toprettyxml",
"(",
"indent",
"=",... | 38.833333 | 5.833333 |
def account(self):
"""
:returns: Account provided as the authenticating account
:rtype: AccountContext
"""
if self._account is None:
self._account = AccountContext(self, self.domain.twilio.account_sid)
return self._account | [
"def",
"account",
"(",
"self",
")",
":",
"if",
"self",
".",
"_account",
"is",
"None",
":",
"self",
".",
"_account",
"=",
"AccountContext",
"(",
"self",
",",
"self",
".",
"domain",
".",
"twilio",
".",
"account_sid",
")",
"return",
"self",
".",
"_account... | 34.375 | 14.375 |
def scale(self, replicas):
"""
Scale service container.
Args:
replicas (int): The number of containers that should be running.
Returns:
bool: ``True`` if successful.
"""
if 'Global' in self.attrs['Spec']['Mode'].keys():
raise Invalid... | [
"def",
"scale",
"(",
"self",
",",
"replicas",
")",
":",
"if",
"'Global'",
"in",
"self",
".",
"attrs",
"[",
"'Spec'",
"]",
"[",
"'Mode'",
"]",
".",
"keys",
"(",
")",
":",
"raise",
"InvalidArgument",
"(",
"'Cannot scale a global container'",
")",
"service_mo... | 33.944444 | 23.055556 |
def bedrooms(self):
"""
This method gets the number of bedrooms.
:return:
"""
try:
if self._data_from_search:
info = self._data_from_search.find(
'ul', {"class": "info"}).text
s = info.split('|')
nb =... | [
"def",
"bedrooms",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"_data_from_search",
":",
"info",
"=",
"self",
".",
"_data_from_search",
".",
"find",
"(",
"'ul'",
",",
"{",
"\"class\"",
":",
"\"info\"",
"}",
")",
".",
"text",
"s",
"=",
"info... | 37.153846 | 13.615385 |
def staticbundle(bundle, mimetype=None, **attrs):
"""
>>> {% staticbundle 'bundlename.css' %}
>>> {% staticbundle 'bundlename.css' media='screen' %}
>>> {% staticbundle 'bundlename' mimetype='text/css' %}
"""
config = getattr(settings, 'STATIC_BUNDLES', {})
if settings.DEBUG and 'packages' ... | [
"def",
"staticbundle",
"(",
"bundle",
",",
"mimetype",
"=",
"None",
",",
"*",
"*",
"attrs",
")",
":",
"config",
"=",
"getattr",
"(",
"settings",
",",
"'STATIC_BUNDLES'",
",",
"{",
"}",
")",
"if",
"settings",
".",
"DEBUG",
"and",
"'packages'",
"in",
"co... | 35.291667 | 20.847222 |
def clip(self):
""" Clip images based on bounds provided
Implementation is borrowed from
https://github.com/brendan-ward/rasterio/blob/e3687ce0ccf8ad92844c16d913a6482d5142cf48/rasterio/rio/convert.py
"""
self.output("Clipping", normal=True)
# create new folder for clipp... | [
"def",
"clip",
"(",
"self",
")",
":",
"self",
".",
"output",
"(",
"\"Clipping\"",
",",
"normal",
"=",
"True",
")",
"# create new folder for clipped images",
"path",
"=",
"check_create_folder",
"(",
"join",
"(",
"self",
".",
"scene_path",
",",
"'clipped'",
")",... | 37.740741 | 20.981481 |
def export_ovf(self):
"""
Exports OVf of currently iterated VM (dictated by api.env.hosts)
:return: ovf location
"""
# Breaking down SOAP Cookie &
# creating Header
soap_cookie = self.vcenter_conn._stub.cookie
cookies = break_down_cookie(soap_cookie)
... | [
"def",
"export_ovf",
"(",
"self",
")",
":",
"# Breaking down SOAP Cookie &",
"# creating Header",
"soap_cookie",
"=",
"self",
".",
"vcenter_conn",
".",
"_stub",
".",
"cookie",
"cookies",
"=",
"break_down_cookie",
"(",
"soap_cookie",
")",
"headers",
"=",
"{",
"'Acc... | 45.542857 | 18.514286 |
def unpackNodeMsg(self, msg, frm) -> None:
"""
If the message is a batch message validate each message in the batch,
otherwise add the message to the node's inbox.
:param msg: a node message
:param frm: the name of the node that sent this `msg`
"""
# TODO: why do... | [
"def",
"unpackNodeMsg",
"(",
"self",
",",
"msg",
",",
"frm",
")",
"->",
"None",
":",
"# TODO: why do we unpack batches here? Batching is a feature of",
"# a transport, it should be encapsulated.",
"if",
"isinstance",
"(",
"msg",
",",
"Batch",
")",
":",
"logger",
".",
... | 42.913043 | 18.043478 |
def create_db(self, models):
"""Creates the in-memory SQLite database from the model
configuration."""
# first create the table definitions
self.tables = dict(
[
(model_name, self.create_model_table(model))
for model_name, model in iteritems(mo... | [
"def",
"create_db",
"(",
"self",
",",
"models",
")",
":",
"# first create the table definitions",
"self",
".",
"tables",
"=",
"dict",
"(",
"[",
"(",
"model_name",
",",
"self",
".",
"create_model_table",
"(",
"model",
")",
")",
"for",
"model_name",
",",
"mode... | 36.45 | 15.55 |
def get_smart_task(self, task_id):
"""
Return specified transition.
Returns a Command.
"""
def process_result(result):
return SmartTask(self, result)
return Command('get', [ROOT_SMART_TASKS, task_id],
process_result=process_result) | [
"def",
"get_smart_task",
"(",
"self",
",",
"task_id",
")",
":",
"def",
"process_result",
"(",
"result",
")",
":",
"return",
"SmartTask",
"(",
"self",
",",
"result",
")",
"return",
"Command",
"(",
"'get'",
",",
"[",
"ROOT_SMART_TASKS",
",",
"task_id",
"]",
... | 27.818182 | 12.909091 |
def ae_partial_waves(self):
"""Dictionary with the AE partial waves indexed by state."""
ae_partial_waves = OrderedDict()
for mesh, values, attrib in self._parse_all_radfuncs("ae_partial_wave"):
state = attrib["state"]
#val_state = self.valence_states[state]
a... | [
"def",
"ae_partial_waves",
"(",
"self",
")",
":",
"ae_partial_waves",
"=",
"OrderedDict",
"(",
")",
"for",
"mesh",
",",
"values",
",",
"attrib",
"in",
"self",
".",
"_parse_all_radfuncs",
"(",
"\"ae_partial_wave\"",
")",
":",
"state",
"=",
"attrib",
"[",
"\"s... | 44.222222 | 16 |
def values(self, name):
"""
RETURN VALUES FOR THE GIVEN PATH NAME
:param name:
:return:
"""
return list(self.lookup_variables.get(unnest_path(name), Null)) | [
"def",
"values",
"(",
"self",
",",
"name",
")",
":",
"return",
"list",
"(",
"self",
".",
"lookup_variables",
".",
"get",
"(",
"unnest_path",
"(",
"name",
")",
",",
"Null",
")",
")"
] | 28.142857 | 13.857143 |
def column_type(self, column_name):
"""
Report column type as one of 'local', 'series', or 'function'.
Parameters
----------
column_name : str
Returns
-------
col_type : {'local', 'series', 'function'}
'local' means that the column is part of... | [
"def",
"column_type",
"(",
"self",
",",
"column_name",
")",
":",
"extra_cols",
"=",
"list_columns_for_table",
"(",
"self",
".",
"name",
")",
"if",
"column_name",
"in",
"extra_cols",
":",
"col",
"=",
"_COLUMNS",
"[",
"(",
"self",
".",
"name",
",",
"column_n... | 31.064516 | 21.258065 |
def _unstructure_seq(self, seq):
"""Convert a sequence to primitive equivalents."""
# We can reuse the sequence class, so tuples stay tuples.
dispatch = self._unstructure_func.dispatch
return seq.__class__(dispatch(e.__class__)(e) for e in seq) | [
"def",
"_unstructure_seq",
"(",
"self",
",",
"seq",
")",
":",
"# We can reuse the sequence class, so tuples stay tuples.",
"dispatch",
"=",
"self",
".",
"_unstructure_func",
".",
"dispatch",
"return",
"seq",
".",
"__class__",
"(",
"dispatch",
"(",
"e",
".",
"__class... | 54.4 | 14 |
def set_request(self, method=None, sub_url="", data=None, params=None,
proxies=None):
"""
:param method: str of the method of the api_call
:param sub_url: str of the url after the uri
:param data: dict of form data to be sent with the request
:param params: di... | [
"def",
"set_request",
"(",
"self",
",",
"method",
"=",
"None",
",",
"sub_url",
"=",
"\"\"",
",",
"data",
"=",
"None",
",",
"params",
"=",
"None",
",",
"proxies",
"=",
"None",
")",
":",
"self",
".",
"method",
"=",
"method",
"or",
"self",
".",
"metho... | 42.580645 | 15.612903 |
def for_request(request, body=None):
"""Creates the context for a specific request."""
tenant, jwt_data = Tenant.objects.for_request(request, body)
webhook_sender_id = jwt_data.get('sub')
sender_data = None
if body and 'item' in body:
if 'sender' in body['item']:
... | [
"def",
"for_request",
"(",
"request",
",",
"body",
"=",
"None",
")",
":",
"tenant",
",",
"jwt_data",
"=",
"Tenant",
".",
"objects",
".",
"for_request",
"(",
"request",
",",
"body",
")",
"webhook_sender_id",
"=",
"jwt_data",
".",
"get",
"(",
"'sub'",
")",... | 39.222222 | 17.037037 |
def gradient_line(xs, ys, colormap_name='jet', ax=None):
'''Plot a 2-d line with a gradient representing ordering.
See http://stackoverflow.com/q/8500700/10601 for details.'''
if ax is None:
ax = plt.gca()
cm = plt.get_cmap(colormap_name)
npts = len(xs)-1
colors = cm(np.linspace(0, 1, num=npts))
if ha... | [
"def",
"gradient_line",
"(",
"xs",
",",
"ys",
",",
"colormap_name",
"=",
"'jet'",
",",
"ax",
"=",
"None",
")",
":",
"if",
"ax",
"is",
"None",
":",
"ax",
"=",
"plt",
".",
"gca",
"(",
")",
"cm",
"=",
"plt",
".",
"get_cmap",
"(",
"colormap_name",
")... | 32.266667 | 15.6 |
def compile(pattern, flags, code, groups=0, groupindex={}, indexgroup=[None]):
"""Compiles (or rather just converts) a pattern descriptor to a SRE_Pattern
object. Actual compilation to opcodes happens in sre_compile."""
return SRE_Pattern(pattern, flags, code, groups, groupindex, indexgroup) | [
"def",
"compile",
"(",
"pattern",
",",
"flags",
",",
"code",
",",
"groups",
"=",
"0",
",",
"groupindex",
"=",
"{",
"}",
",",
"indexgroup",
"=",
"[",
"None",
"]",
")",
":",
"return",
"SRE_Pattern",
"(",
"pattern",
",",
"flags",
",",
"code",
",",
"gr... | 75.25 | 18.5 |
def QA_fetch_stock_financial_calendar_adv(code, start="all", end=None, format='pd', collections=DATABASE.report_calendar):
'获取股票日线'
#code= [code] if isinstance(code,str) else code
end = start if end is None else end
start = str(start)[0:10]
end = str(end)[0:10]
# code checking
if start == '... | [
"def",
"QA_fetch_stock_financial_calendar_adv",
"(",
"code",
",",
"start",
"=",
"\"all\"",
",",
"end",
"=",
"None",
",",
"format",
"=",
"'pd'",
",",
"collections",
"=",
"DATABASE",
".",
"report_calendar",
")",
":",
"#code= [code] if isinstance(code,str) else code",
... | 38.5 | 27.8 |
def unauthorized_view(self):
""" Prepare a Flash message and redirect to USER_UNAUTHORIZED_ENDPOINT"""
# Prepare Flash message
url = request.script_root + request.path
flash(_("You do not have permission to access '%(url)s'.", url=url), 'error')
# Redirect to USER_UNAUTHORIZED_E... | [
"def",
"unauthorized_view",
"(",
"self",
")",
":",
"# Prepare Flash message",
"url",
"=",
"request",
".",
"script_root",
"+",
"request",
".",
"path",
"flash",
"(",
"_",
"(",
"\"You do not have permission to access '%(url)s'.\"",
",",
"url",
"=",
"url",
")",
",",
... | 49.625 | 19.75 |
def _needs_evaluation(self) -> bool:
"""
Returns True when:
1. Where clause is not specified
2. Where WHERE clause is specified and it evaluates to True
Returns false if a where clause is specified and it evaluates to False
"""
return self._schema.when is ... | [
"def",
"_needs_evaluation",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"self",
".",
"_schema",
".",
"when",
"is",
"None",
"or",
"self",
".",
"_schema",
".",
"when",
".",
"evaluate",
"(",
"self",
".",
"_evaluation_context",
")"
] | 46.625 | 18.375 |
def get(self, name):
'''get a setting'''
if not name in self._vars:
raise AttributeError
setting = self._vars[name]
return setting.value | [
"def",
"get",
"(",
"self",
",",
"name",
")",
":",
"if",
"not",
"name",
"in",
"self",
".",
"_vars",
":",
"raise",
"AttributeError",
"setting",
"=",
"self",
".",
"_vars",
"[",
"name",
"]",
"return",
"setting",
".",
"value"
] | 29.166667 | 10.833333 |
def remove_unique_identity(cls, sh_db, uuid):
"""Delete a unique identity from SortingHat.
:param sh_db: SortingHat database
:param uuid: Unique identity identifier
"""
success = False
try:
api.delete_unique_identity(sh_db, uuid)
logger.debug("Uni... | [
"def",
"remove_unique_identity",
"(",
"cls",
",",
"sh_db",
",",
"uuid",
")",
":",
"success",
"=",
"False",
"try",
":",
"api",
".",
"delete_unique_identity",
"(",
"sh_db",
",",
"uuid",
")",
"logger",
".",
"debug",
"(",
"\"Unique identity %s deleted\"",
",",
"... | 32.866667 | 16.266667 |
def transform(self, X, y=None):
"""Dummy encode the categorical columns in X
Parameters
----------
X : pd.DataFrame or dd.DataFrame
y : ignored
Returns
-------
transformed : pd.DataFrame or dd.DataFrame
Same type as the input
"""
... | [
"def",
"transform",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"if",
"not",
"X",
".",
"columns",
".",
"equals",
"(",
"self",
".",
"columns_",
")",
":",
"raise",
"ValueError",
"(",
"\"Columns of 'X' do not match the training \"",
"\"columns. Got ... | 35.958333 | 19.666667 |
def correct_absolute_refs(self, construction_table):
"""Reindexe construction_table if linear reference in first three rows
present.
Uses :meth:`~Cartesian.check_absolute_refs` to obtain the problematic
indices.
Args:
construction_table (pd.DataFrame):
Retu... | [
"def",
"correct_absolute_refs",
"(",
"self",
",",
"construction_table",
")",
":",
"c_table",
"=",
"construction_table",
".",
"copy",
"(",
")",
"abs_refs",
"=",
"constants",
".",
"absolute_refs",
"problem_index",
"=",
"self",
".",
"check_absolute_refs",
"(",
"c_tab... | 36.192308 | 18.230769 |
def red_dim(self, array):
"""
This function reduces the dimensions of an array until it is
no longer of length 1.
"""
while isinstance(array, list) == True or \
isinstance(array, np.ndarray) == True:
try:
if len(array) == 1:
... | [
"def",
"red_dim",
"(",
"self",
",",
"array",
")",
":",
"while",
"isinstance",
"(",
"array",
",",
"list",
")",
"==",
"True",
"or",
"isinstance",
"(",
"array",
",",
"np",
".",
"ndarray",
")",
"==",
"True",
":",
"try",
":",
"if",
"len",
"(",
"array",
... | 25.529412 | 16.235294 |
def _peek(self, chars=1):
"""
Peek at the data in the server response.
Peeking should only be done when the response can be predicted.
Make sure that the socket will not block by requesting too
much data from it while peeking.
Args:
chars -- the number of charac... | [
"def",
"_peek",
"(",
"self",
",",
"chars",
"=",
"1",
")",
":",
"line",
"=",
"self",
".",
"_socket",
".",
"recv",
"(",
"chars",
",",
"socket",
".",
"MSG_PEEK",
")",
"logger",
".",
"debug",
"(",
"'Server sent (peek): '",
"+",
"line",
".",
"rstrip",
"("... | 31.333333 | 19.6 |
def verbosity(verbosity):
"""
Convert the number of times the user specified '-v' on the command-line
into a log level.
"""
verbosity = int(verbosity)
if verbosity == 0:
return logging.WARNING
if verbosity == 1:
return logging.INFO
if verbosity == 2:
return logg... | [
"def",
"verbosity",
"(",
"verbosity",
")",
":",
"verbosity",
"=",
"int",
"(",
"verbosity",
")",
"if",
"verbosity",
"==",
"0",
":",
"return",
"logging",
".",
"WARNING",
"if",
"verbosity",
"==",
"1",
":",
"return",
"logging",
".",
"INFO",
"if",
"verbosity"... | 22.823529 | 17.529412 |
def cache(self, running):
"""
save / update this gear into Ariane server cache
:param running: the new running value (True or False)
:return:
"""
LOGGER.debug("InjectorGearSkeleton.cache")
self.running = running if running is not None else False
return sel... | [
"def",
"cache",
"(",
"self",
",",
"running",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"InjectorGearSkeleton.cache\"",
")",
"self",
".",
"running",
"=",
"running",
"if",
"running",
"is",
"not",
"None",
"else",
"False",
"return",
"self",
".",
"cached_gear_acto... | 39 | 14.111111 |
def ubridge(self):
"""
Returns the uBridge hypervisor.
:returns: instance of uBridge
"""
if self._ubridge_hypervisor and not self._ubridge_hypervisor.is_running():
self._ubridge_hypervisor = None
return self._ubridge_hypervisor | [
"def",
"ubridge",
"(",
"self",
")",
":",
"if",
"self",
".",
"_ubridge_hypervisor",
"and",
"not",
"self",
".",
"_ubridge_hypervisor",
".",
"is_running",
"(",
")",
":",
"self",
".",
"_ubridge_hypervisor",
"=",
"None",
"return",
"self",
".",
"_ubridge_hypervisor"... | 28 | 15.2 |
def length_plots(array, name, path, title=None, n50=None, color="#4CB391", figformat="png"):
"""Create histogram of normal and log transformed read lengths."""
logging.info("Nanoplotter: Creating length plots for {}.".format(name))
maxvalx = np.amax(array)
if n50:
logging.info("Nanoplotter: Usin... | [
"def",
"length_plots",
"(",
"array",
",",
"name",
",",
"path",
",",
"title",
"=",
"None",
",",
"n50",
"=",
"None",
",",
"color",
"=",
"\"#4CB391\"",
",",
"figformat",
"=",
"\"png\"",
")",
":",
"logging",
".",
"info",
"(",
"\"Nanoplotter: Creating length pl... | 42.789474 | 17.815789 |
def cache_model(key_params, timeout='default'):
"""
Caching decorator for app models in task.perform
"""
def decorator_fn(fn):
return CacheModelDecorator().decorate(key_params, timeout, fn)
return decorator_fn | [
"def",
"cache_model",
"(",
"key_params",
",",
"timeout",
"=",
"'default'",
")",
":",
"def",
"decorator_fn",
"(",
"fn",
")",
":",
"return",
"CacheModelDecorator",
"(",
")",
".",
"decorate",
"(",
"key_params",
",",
"timeout",
",",
"fn",
")",
"return",
"decor... | 28.875 | 15.125 |
def print_location(**kwargs):
"""
:param kwargs: Pass in the arguments to the function and they will be printed too!
"""
stack = inspect.stack()[1]
debug_print('{}:{} {}()'.format(stack[1], stack[2], stack[3]))
for k, v in kwargs.items():
lesser_debug_print('{} = {}'.format(k, v)) | [
"def",
"print_location",
"(",
"*",
"*",
"kwargs",
")",
":",
"stack",
"=",
"inspect",
".",
"stack",
"(",
")",
"[",
"1",
"]",
"debug_print",
"(",
"'{}:{} {}()'",
".",
"format",
"(",
"stack",
"[",
"1",
"]",
",",
"stack",
"[",
"2",
"]",
",",
"stack",
... | 34 | 16.888889 |
def _past_datetime_from(self):
"""
The datetime this event previously started in the local time zone, or
None if it never did.
"""
prevDt = self.__localBefore(timezone.localtime(), dt.time.max,
excludeCancellations=True,
... | [
"def",
"_past_datetime_from",
"(",
"self",
")",
":",
"prevDt",
"=",
"self",
".",
"__localBefore",
"(",
"timezone",
".",
"localtime",
"(",
")",
",",
"dt",
".",
"time",
".",
"max",
",",
"excludeCancellations",
"=",
"True",
",",
"excludeExtraInfo",
"=",
"True... | 41 | 16.333333 |
def get_related_entry_admin_url(entry):
"""
Returns admin URL for specified entry instance.
:param entry: the entry instance.
:return: str.
"""
namespaces = {
Document: 'wagtaildocs:edit',
Link: 'wagtaillinks:edit',
Page: 'wagtailadmin_pages:edit',
}
... | [
"def",
"get_related_entry_admin_url",
"(",
"entry",
")",
":",
"namespaces",
"=",
"{",
"Document",
":",
"'wagtaildocs:edit'",
",",
"Link",
":",
"'wagtaillinks:edit'",
",",
"Page",
":",
"'wagtailadmin_pages:edit'",
",",
"}",
"for",
"cls",
",",
"url",
"in",
"namesp... | 27.333333 | 16.777778 |
def file_hash(load, fnd):
'''
Return a file hash, the hash type is set in the master config file
'''
if 'env' in load:
# "env" is not supported; Use "saltenv".
load.pop('env')
if not all(x in load for x in ('path', 'saltenv')):
return ''
saltenv = load['saltenv']
if ... | [
"def",
"file_hash",
"(",
"load",
",",
"fnd",
")",
":",
"if",
"'env'",
"in",
"load",
":",
"# \"env\" is not supported; Use \"saltenv\".",
"load",
".",
"pop",
"(",
"'env'",
")",
"if",
"not",
"all",
"(",
"x",
"in",
"load",
"for",
"x",
"in",
"(",
"'path'",
... | 35.038462 | 17.5 |
def tcc(text: str) -> str:
"""
TCC generator, generates Thai Character Clusters
:param str text: text to be tokenized to character clusters
:return: subword (character cluster)
"""
if not text or not isinstance(text, str):
return ""
p = 0
while p < len(text):
m = PAT_TCC... | [
"def",
"tcc",
"(",
"text",
":",
"str",
")",
"->",
"str",
":",
"if",
"not",
"text",
"or",
"not",
"isinstance",
"(",
"text",
",",
"str",
")",
":",
"return",
"\"\"",
"p",
"=",
"0",
"while",
"p",
"<",
"len",
"(",
"text",
")",
":",
"m",
"=",
"PAT_... | 24.333333 | 16.444444 |
def _format_name(self, name, surname, snake_case=False):
"""Format a first name and a surname into a cohesive string.
Note that either name or surname can be empty strings, and
formatting will still succeed.
:param str name: A first name.
:param str surname: A surname.
... | [
"def",
"_format_name",
"(",
"self",
",",
"name",
",",
"surname",
",",
"snake_case",
"=",
"False",
")",
":",
"if",
"not",
"name",
"or",
"not",
"surname",
":",
"sep",
"=",
"''",
"elif",
"snake_case",
":",
"sep",
"=",
"'_'",
"else",
":",
"sep",
"=",
"... | 30.666667 | 17.962963 |
def get(self):
""" Returns state if defined else it raises a ValueError. See also
Publisher.get().
:raises ValueError: if this publisher is not initialized and has not
received any emits.
"""
if self._state is not NONE:
return self._state
return P... | [
"def",
"get",
"(",
"self",
")",
":",
"if",
"self",
".",
"_state",
"is",
"not",
"NONE",
":",
"return",
"self",
".",
"_state",
"return",
"Publisher",
".",
"get",
"(",
"self",
")"
] | 32.9 | 14.8 |
def verify_keys(self):
"""Verify that the public and private key combination is valid; raises MollomAuthenticationError otherwise"""
verify_keys_endpoint = Template("${rest_root}/site/${public_key}")
url = verify_keys_endpoint.substitute(rest_root=self._rest_root, public_key=self._public_key)
... | [
"def",
"verify_keys",
"(",
"self",
")",
":",
"verify_keys_endpoint",
"=",
"Template",
"(",
"\"${rest_root}/site/${public_key}\"",
")",
"url",
"=",
"verify_keys_endpoint",
".",
"substitute",
"(",
"rest_root",
"=",
"self",
".",
"_rest_root",
",",
"public_key",
"=",
... | 46.214286 | 28.142857 |
def _repeat_bytes(byt, rep):
"""
Get a long number for a byte being repeated for many times. This is part of the effort of optimizing
performance of angr's memory operations.
:param int byt: the byte to repeat
:param int rep: times to repeat the byte
:return: a long inte... | [
"def",
"_repeat_bytes",
"(",
"byt",
",",
"rep",
")",
":",
"if",
"rep",
"==",
"1",
":",
"return",
"byt",
"remainder",
"=",
"rep",
"%",
"2",
"quotient",
"=",
"rep",
"//",
"2",
"r_",
"=",
"memset",
".",
"_repeat_bytes",
"(",
"byt",
",",
"quotient",
")... | 28.28 | 19 |
def get_file_path(dotted_path, extension='json'):
"""
Reads a dotted file path and returns the file path.
"""
# If the operating system's file path seperator character is in the string
if os.sep in dotted_path or '/' in dotted_path:
# Assume the path is a valid file path
return dotte... | [
"def",
"get_file_path",
"(",
"dotted_path",
",",
"extension",
"=",
"'json'",
")",
":",
"# If the operating system's file path seperator character is in the string",
"if",
"os",
".",
"sep",
"in",
"dotted_path",
"or",
"'/'",
"in",
"dotted_path",
":",
"# Assume the path is a... | 30.25 | 17.05 |
def delete(method, hmc, uri, uri_parms, logon_required):
"""Operation: Delete <resource>."""
try:
resource = hmc.lookup_by_uri(uri)
except KeyError:
raise InvalidResourceError(method, uri)
resource.manager.remove(resource.oid) | [
"def",
"delete",
"(",
"method",
",",
"hmc",
",",
"uri",
",",
"uri_parms",
",",
"logon_required",
")",
":",
"try",
":",
"resource",
"=",
"hmc",
".",
"lookup_by_uri",
"(",
"uri",
")",
"except",
"KeyError",
":",
"raise",
"InvalidResourceError",
"(",
"method",... | 39.428571 | 11.571429 |
def get_frame():
"""Returns a QFrame formatted in a particular way"""
ret = QFrame()
ret.setLineWidth(1)
ret.setMidLineWidth(0)
ret.setFrameShadow(QFrame.Sunken)
ret.setFrameShape(QFrame.Box)
return ret | [
"def",
"get_frame",
"(",
")",
":",
"ret",
"=",
"QFrame",
"(",
")",
"ret",
".",
"setLineWidth",
"(",
"1",
")",
"ret",
".",
"setMidLineWidth",
"(",
"0",
")",
"ret",
".",
"setFrameShadow",
"(",
"QFrame",
".",
"Sunken",
")",
"ret",
".",
"setFrameShape",
... | 28.75 | 13.375 |
def __retrieve_internal_blob(self, key):
''' Retrieve file location from cache DB
'''
logger = getLogger()
with self.get_conn() as conn:
try:
c = conn.cursor()
if key is None:
c.execute("SELECT compressed, blob_data FROM blo... | [
"def",
"__retrieve_internal_blob",
"(",
"self",
",",
"key",
")",
":",
"logger",
"=",
"getLogger",
"(",
")",
"with",
"self",
".",
"get_conn",
"(",
")",
"as",
"conn",
":",
"try",
":",
"c",
"=",
"conn",
".",
"cursor",
"(",
")",
"if",
"key",
"is",
"Non... | 49.333333 | 25.583333 |
def TaubinSVD(XY):
"""
algebraic circle fit
input: list [[x_1, y_1], [x_2, y_2], ....]
output: a, b, r. a and b are the center of the fitting circle, and r is the radius
Algebraic circle fit by Taubin
G. Taubin, "Estimation Of Planar Curves, Surfaces And Nonplanar
Space Cu... | [
"def",
"TaubinSVD",
"(",
"XY",
")",
":",
"XY",
"=",
"numpy",
".",
"array",
"(",
"XY",
")",
"X",
"=",
"XY",
"[",
":",
",",
"0",
"]",
"-",
"numpy",
".",
"mean",
"(",
"XY",
"[",
":",
",",
"0",
"]",
")",
"# norming points by x avg",
"Y",
"=",
"XY... | 41.5 | 18.5 |
def calc_pan_pct(self, viewer, pad=0):
"""Calculate values for vertical/horizontal panning by percentages
from the current pan position.
"""
limits = viewer.get_limits()
tr = viewer.tform['data_to_scrollbar']
# calculate the corners of the entire image in unscaled carte... | [
"def",
"calc_pan_pct",
"(",
"self",
",",
"viewer",
",",
"pad",
"=",
"0",
")",
":",
"limits",
"=",
"viewer",
".",
"get_limits",
"(",
")",
"tr",
"=",
"viewer",
".",
"tform",
"[",
"'data_to_scrollbar'",
"]",
"# calculate the corners of the entire image in unscaled ... | 37.38 | 18.12 |
def __get_match_result(self, ret, ret2):
"""
Getting match result
"""
if self.another_compare == "__MATCH_AND__":
return ret and ret2
elif self.another_compare == "__MATCH_OR__":
return ret or ret2
return ret | [
"def",
"__get_match_result",
"(",
"self",
",",
"ret",
",",
"ret2",
")",
":",
"if",
"self",
".",
"another_compare",
"==",
"\"__MATCH_AND__\"",
":",
"return",
"ret",
"and",
"ret2",
"elif",
"self",
".",
"another_compare",
"==",
"\"__MATCH_OR__\"",
":",
"return",
... | 30.222222 | 8.444444 |
def dump_stats(self):
"""Logs statistics of our operation."""
log.info('Dumping statistics:')
stats = []
stats.append(
'client-request-errors {}'.format(self._client_request_errors))
stats.append('denied-allocations {}'.format(self._denied_allocations))
stats.... | [
"def",
"dump_stats",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"'Dumping statistics:'",
")",
"stats",
"=",
"[",
"]",
"stats",
".",
"append",
"(",
"'client-request-errors {}'",
".",
"format",
"(",
"self",
".",
"_client_request_errors",
")",
")",
"stats"... | 48.846154 | 22 |
def remove_platform(name, server_url):
'''
To remove specified ASAM platform from the Novell Fan-Out Driver
CLI Example:
.. code-block:: bash
salt-run asam.remove_platform my-test-vm prov1.domain.com
'''
config = _get_asam_configuration(server_url)
if not config:
return Fa... | [
"def",
"remove_platform",
"(",
"name",
",",
"server_url",
")",
":",
"config",
"=",
"_get_asam_configuration",
"(",
"server_url",
")",
"if",
"not",
"config",
":",
"return",
"False",
"url",
"=",
"config",
"[",
"'platform_config_url'",
"]",
"data",
"=",
"{",
"'... | 31.553571 | 24.410714 |
def isMasterDegraded(self):
"""
Return whether the master instance is slow.
"""
if self.acc_monitor:
self.acc_monitor.update_time(time.perf_counter())
return self.acc_monitor.is_master_degraded()
else:
return (self.instances.masterId is not Non... | [
"def",
"isMasterDegraded",
"(",
"self",
")",
":",
"if",
"self",
".",
"acc_monitor",
":",
"self",
".",
"acc_monitor",
".",
"update_time",
"(",
"time",
".",
"perf_counter",
"(",
")",
")",
"return",
"self",
".",
"acc_monitor",
".",
"is_master_degraded",
"(",
... | 50.2 | 21 |
def find_alliteration(self):
"""
Find alliterations in the complete verse.
:return:
"""
if len(self.phonological_features_text) == 0:
logger.error("No phonological transcription found")
raise ValueError
else:
first_sounds = []
... | [
"def",
"find_alliteration",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"phonological_features_text",
")",
"==",
"0",
":",
"logger",
".",
"error",
"(",
"\"No phonological transcription found\"",
")",
"raise",
"ValueError",
"else",
":",
"first_sounds",
... | 49.03125 | 19.15625 |
def parse_changelog(args: Any) -> Tuple[str, str]:
"""Return an updated changelog and and the list of changes."""
with open("CHANGELOG.rst", "r") as file:
match = re.match(
pattern=r"(.*?Unreleased\n---+\n)(.+?)(\n*[^\n]+\n---+\n.*)",
string=file.read(),
flags=re.DOTA... | [
"def",
"parse_changelog",
"(",
"args",
":",
"Any",
")",
"->",
"Tuple",
"[",
"str",
",",
"str",
"]",
":",
"with",
"open",
"(",
"\"CHANGELOG.rst\"",
",",
"\"r\"",
")",
"as",
"file",
":",
"match",
"=",
"re",
".",
"match",
"(",
"pattern",
"=",
"r\"(.*?Un... | 35.470588 | 18.647059 |
def is_ordered(self):
"""
True if site is an ordered site, i.e., with a single species with
occupancy 1.
"""
totaloccu = self.species.num_atoms
return totaloccu == 1 and len(self.species) == 1 | [
"def",
"is_ordered",
"(",
"self",
")",
":",
"totaloccu",
"=",
"self",
".",
"species",
".",
"num_atoms",
"return",
"totaloccu",
"==",
"1",
"and",
"len",
"(",
"self",
".",
"species",
")",
"==",
"1"
] | 33.428571 | 12.857143 |
def decorate_function(self, name, decorator):
"""
Decorate function with given name with given decorator.
:param str name: Name of the function.
:param callable decorator: Decorator callback.
"""
self.functions[name] = decorator(self.functions[name]) | [
"def",
"decorate_function",
"(",
"self",
",",
"name",
",",
"decorator",
")",
":",
"self",
".",
"functions",
"[",
"name",
"]",
"=",
"decorator",
"(",
"self",
".",
"functions",
"[",
"name",
"]",
")"
] | 36.5 | 13.75 |
def padDigitalData(self, dig_data, n):
"""Pad dig_data with its last element so that the new array is a
multiple of n.
"""
n = int(n)
l0 = len(dig_data)
if l0 % n == 0:
return dig_data # no need of padding
else:
ladd = n - (l0 % n)
... | [
"def",
"padDigitalData",
"(",
"self",
",",
"dig_data",
",",
"n",
")",
":",
"n",
"=",
"int",
"(",
"n",
")",
"l0",
"=",
"len",
"(",
"dig_data",
")",
"if",
"l0",
"%",
"n",
"==",
"0",
":",
"return",
"dig_data",
"# no need of padding",
"else",
":",
"lad... | 35.538462 | 12.076923 |
def list_menu(self, options, title="Choose a value", message="Choose a value", default=None, **kwargs):
"""
Show a single-selection list menu
Usage: C{dialog.list_menu(options, title="Choose a value", message="Choose a value", default=None, **kwargs)}
@param options: li... | [
"def",
"list_menu",
"(",
"self",
",",
"options",
",",
"title",
"=",
"\"Choose a value\"",
",",
"message",
"=",
"\"Choose a value\"",
",",
"default",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"choices",
"=",
"[",
"]",
"for",
"option",
"in",
"options... | 38.333333 | 21.296296 |
def solve_filter(expr, vars):
"""Filter values on the LHS by evaluating RHS with each value.
Returns any LHS values for which RHS evaluates to a true value.
"""
lhs_values, _ = __solve_for_repeated(expr.lhs, vars)
def lazy_filter():
for lhs_value in repeated.getvalues(lhs_values):
... | [
"def",
"solve_filter",
"(",
"expr",
",",
"vars",
")",
":",
"lhs_values",
",",
"_",
"=",
"__solve_for_repeated",
"(",
"expr",
".",
"lhs",
",",
"vars",
")",
"def",
"lazy_filter",
"(",
")",
":",
"for",
"lhs_value",
"in",
"repeated",
".",
"getvalues",
"(",
... | 35.461538 | 20.307692 |
def _get_dense_tensor(self, inputs, weight_collections=None, trainable=None):
"""Returns a `Tensor` to represent this feature in the input_layer()."""
del weight_collections, trainable # Unused.
m = module.Module(self.module_spec, trainable=False)
images = inputs.get(self)
return m({"images": image... | [
"def",
"_get_dense_tensor",
"(",
"self",
",",
"inputs",
",",
"weight_collections",
"=",
"None",
",",
"trainable",
"=",
"None",
")",
":",
"del",
"weight_collections",
",",
"trainable",
"# Unused.",
"m",
"=",
"module",
".",
"Module",
"(",
"self",
".",
"module_... | 53 | 13.333333 |
def prob(self, word: str) -> float:
"""
Return probability of an input word, according to the spelling dictionary
:param str word: A word to check its probability of occurrence
"""
return self.__WORDS[word] / self.__WORDS_TOTAL | [
"def",
"prob",
"(",
"self",
",",
"word",
":",
"str",
")",
"->",
"float",
":",
"return",
"self",
".",
"__WORDS",
"[",
"word",
"]",
"/",
"self",
".",
"__WORDS_TOTAL"
] | 37.428571 | 18.571429 |
def with_aad_device_authentication(cls, connection_string, authority_id="common"):
"""Creates a KustoConnection string builder that will authenticate with AAD application and
password.
:param str connection_string: Kusto connection string should by of the format: https://<clusterName>.kusto.w... | [
"def",
"with_aad_device_authentication",
"(",
"cls",
",",
"connection_string",
",",
"authority_id",
"=",
"\"common\"",
")",
":",
"kcsb",
"=",
"cls",
"(",
"connection_string",
")",
"kcsb",
"[",
"kcsb",
".",
"ValidKeywords",
".",
"aad_federated_security",
"]",
"=",
... | 53.818182 | 26.181818 |
def fetch(self):
"""
Fetch a AssetVersionInstance
:returns: Fetched AssetVersionInstance
:rtype: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionInstance
"""
params = values.of({})
payload = self._version.fetch(
'GET',
s... | [
"def",
"fetch",
"(",
"self",
")",
":",
"params",
"=",
"values",
".",
"of",
"(",
"{",
"}",
")",
"payload",
"=",
"self",
".",
"_version",
".",
"fetch",
"(",
"'GET'",
",",
"self",
".",
"_uri",
",",
"params",
"=",
"params",
",",
")",
"return",
"Asset... | 26.636364 | 18 |
def set_grads(params, params_with_grad):
"""
Copies gradients from param_with_grad to params
:param params: dst parameters
:param params_with_grad: src parameters
"""
for param, param_w_grad in zip(params, params_with_grad):
if param.grad is None:
... | [
"def",
"set_grads",
"(",
"params",
",",
"params_with_grad",
")",
":",
"for",
"param",
",",
"param_w_grad",
"in",
"zip",
"(",
"params",
",",
"params_with_grad",
")",
":",
"if",
"param",
".",
"grad",
"is",
"None",
":",
"param",
".",
"grad",
"=",
"torch",
... | 39 | 13.181818 |
def sumcols(msname, col1=None, col2=None, outcol=None, cols=None, suntract=False):
""" add col1 to col2, or sum columns in 'cols' list.
If subtract, subtract col2 from col1
"""
from pyrap.tables import table
tab = table(msname, readonly=False)
if cols:
data = 0
for col in co... | [
"def",
"sumcols",
"(",
"msname",
",",
"col1",
"=",
"None",
",",
"col2",
"=",
"None",
",",
"outcol",
"=",
"None",
",",
"cols",
"=",
"None",
",",
"suntract",
"=",
"False",
")",
":",
"from",
"pyrap",
".",
"tables",
"import",
"table",
"tab",
"=",
"tabl... | 29.208333 | 18.666667 |
def doi(self):
"""
https://es.wikipedia.org/wiki/Identificador_de_objeto_digital
:return: a random Spanish CIF or NIE or NIF
"""
return random.choice([self.cif, self.nie, self.nif])() | [
"def",
"doi",
"(",
"self",
")",
":",
"return",
"random",
".",
"choice",
"(",
"[",
"self",
".",
"cif",
",",
"self",
".",
"nie",
",",
"self",
".",
"nif",
"]",
")",
"(",
")"
] | 31.142857 | 18.285714 |
def encode(self, o):
"""
Return a JSON string representation of a Python data structure.
>>> JSONEncoder().encode({"foo": ["bar", "baz"]})
'{"foo": ["bar", "baz"]}'
"""
# This is for extremely simple cases and benchmarks.
if isinstance(o, basestring):
... | [
"def",
"encode",
"(",
"self",
",",
"o",
")",
":",
"# This is for extremely simple cases and benchmarks.",
"if",
"isinstance",
"(",
"o",
",",
"basestring",
")",
":",
"if",
"isinstance",
"(",
"o",
",",
"str",
")",
":",
"_encoding",
"=",
"self",
".",
"encoding"... | 41.043478 | 13.652174 |
def searchType(libtype):
""" Returns the integer value of the library string type.
Parameters:
libtype (str): LibType to lookup (movie, show, season, episode, artist, album, track,
collection)
Raises:
:class:`plexapi.exceptions.N... | [
"def",
"searchType",
"(",
"libtype",
")",
":",
"libtype",
"=",
"compat",
".",
"ustr",
"(",
"libtype",
")",
"if",
"libtype",
"in",
"[",
"compat",
".",
"ustr",
"(",
"v",
")",
"for",
"v",
"in",
"SEARCHTYPES",
".",
"values",
"(",
")",
"]",
":",
"return... | 39.733333 | 18 |
def _get_new_batch(self, ds_type:DatasetType)->Collection[Tensor]:
"Retrieves new batch of DatasetType, and detaches it."
return self.learn.data.one_batch(ds_type=ds_type, detach=True, denorm=False, cpu=False) | [
"def",
"_get_new_batch",
"(",
"self",
",",
"ds_type",
":",
"DatasetType",
")",
"->",
"Collection",
"[",
"Tensor",
"]",
":",
"return",
"self",
".",
"learn",
".",
"data",
".",
"one_batch",
"(",
"ds_type",
"=",
"ds_type",
",",
"detach",
"=",
"True",
",",
... | 74.333333 | 34.333333 |
def correct_means(means, opt_t0s, combs):
"""Applies optimal t0s to gaussians means.
Should be around zero afterwards.
Parameters
----------
means: numpy array of means of gaussians of all PMT combinations
opt_t0s: numpy array of optimal t0 values for all PMTs
combs: pmt combinations used ... | [
"def",
"correct_means",
"(",
"means",
",",
"opt_t0s",
",",
"combs",
")",
":",
"corrected_means",
"=",
"np",
".",
"array",
"(",
"[",
"(",
"opt_t0s",
"[",
"comb",
"[",
"1",
"]",
"]",
"-",
"opt_t0s",
"[",
"comb",
"[",
"0",
"]",
"]",
")",
"-",
"mean"... | 31.526316 | 23.157895 |
def compile_authors(cell):
"""
Split the string of author names into the BibJSON format.
:param str cell: Data from author cell
:return: (list of dicts) Author names
"""
logger_excel.info("enter compile_authors")
author_lst = []
s = cell.split(';')
for w in s:
author_lst.appe... | [
"def",
"compile_authors",
"(",
"cell",
")",
":",
"logger_excel",
".",
"info",
"(",
"\"enter compile_authors\"",
")",
"author_lst",
"=",
"[",
"]",
"s",
"=",
"cell",
".",
"split",
"(",
"';'",
")",
"for",
"w",
"in",
"s",
":",
"author_lst",
".",
"append",
... | 30 | 10.307692 |
def expected_number_of_purchases_up_to_time(self, t):
"""
Return expected number of repeat purchases up to time t.
Calculate the expected number of repeat purchases up to time t for a
randomly choose individual from the population.
Parameters
----------
t: array... | [
"def",
"expected_number_of_purchases_up_to_time",
"(",
"self",
",",
"t",
")",
":",
"r",
",",
"alpha",
",",
"a",
",",
"b",
"=",
"self",
".",
"_unload_params",
"(",
"\"r\"",
",",
"\"alpha\"",
",",
"\"a\"",
",",
"\"b\"",
")",
"hyp",
"=",
"hyp2f1",
"(",
"r... | 30.7 | 23.1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.