text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def bucket_type(self, name):
"""
Gets the bucket-type by the specified name. Bucket-types do
not always exist (unlike buckets), but this will always return
a :class:`BucketType <riak.bucket.BucketType>` object.
:param name: the bucket-type name
:type name: str
:r... | [
"def",
"bucket_type",
"(",
"self",
",",
"name",
")",
":",
"if",
"not",
"isinstance",
"(",
"name",
",",
"string_types",
")",
":",
"raise",
"TypeError",
"(",
"'BucketType name must be a string'",
")",
"btype",
"=",
"BucketType",
"(",
"self",
",",
"name",
")",
... | 38.25 | 15.75 |
def add(connect_spec, dn, attributes):
'''Add an entry to an LDAP database.
:param connect_spec:
See the documentation for the ``connect_spec`` parameter for
:py:func:`connect`.
:param dn:
Distinguished name of the entry.
:param attributes:
Non-empty dict mapping each ... | [
"def",
"add",
"(",
"connect_spec",
",",
"dn",
",",
"attributes",
")",
":",
"l",
"=",
"connect",
"(",
"connect_spec",
")",
"# convert the \"iterable of values\" to lists in case that's what",
"# addModlist() expects (also to ensure that the caller's objects",
"# are not modified)"... | 31.5 | 22.934783 |
def normal_curve_single(obj, u, normalize):
""" Evaluates the curve normal vector at the input parameter, u.
Curve normal is calculated from the 2nd derivative of the curve at the input parameter, u.
The output returns a list containing the starting point (i.e. origin) of the vector and the vector itself.
... | [
"def",
"normal_curve_single",
"(",
"obj",
",",
"u",
",",
"normalize",
")",
":",
"# 2nd derivative of the curve gives the normal",
"ders",
"=",
"obj",
".",
"derivatives",
"(",
"u",
",",
"2",
")",
"point",
"=",
"ders",
"[",
"0",
"]",
"vector",
"=",
"linalg",
... | 36.727273 | 23.5 |
def _get_subject_alternative_names(self, ext):
"""
Return a list of Subject Alternative Name values for the given x509
extension object.
"""
values = []
for san in ext.value:
if isinstance(san.value, string):
# Pass on simple string SAN values
... | [
"def",
"_get_subject_alternative_names",
"(",
"self",
",",
"ext",
")",
":",
"values",
"=",
"[",
"]",
"for",
"san",
"in",
"ext",
".",
"value",
":",
"if",
"isinstance",
"(",
"san",
".",
"value",
",",
"string",
")",
":",
"# Pass on simple string SAN values",
... | 38.3125 | 14.3125 |
def throttle_check(self):
""" Check for throttling. """
throttle = self._meta.throttle()
wait = throttle.should_be_throttled(self)
if wait:
raise HttpError(
"Throttled, wait {0} seconds.".format(wait),
status=status.HTTP_503_SERVICE_UNAVAILABLE... | [
"def",
"throttle_check",
"(",
"self",
")",
":",
"throttle",
"=",
"self",
".",
"_meta",
".",
"throttle",
"(",
")",
"wait",
"=",
"throttle",
".",
"should_be_throttled",
"(",
"self",
")",
"if",
"wait",
":",
"raise",
"HttpError",
"(",
"\"Throttled, wait {0} seco... | 39.25 | 12.375 |
def delete(self, prevent_nondicotomic=True, preserve_branch_length=False):
"""
Deletes node from the tree structure. Notice that this method
makes 'disappear' the node from the tree structure. This means
that children from the deleted node are transferred to the
next available pa... | [
"def",
"delete",
"(",
"self",
",",
"prevent_nondicotomic",
"=",
"True",
",",
"preserve_branch_length",
"=",
"False",
")",
":",
"parent",
"=",
"self",
".",
"up",
"if",
"parent",
":",
"if",
"preserve_branch_length",
":",
"if",
"len",
"(",
"self",
".",
"child... | 30.924528 | 19.528302 |
def get_tags():
"""get tags."""
tags = getattr(flask.g, 'bukudb', get_bukudb()).get_tag_all()
result = {
'tags': tags[0]
}
if request.path.startswith('/api/'):
res = jsonify(result)
else:
res = render_template('bukuserver/tags.html', result=result)
return res | [
"def",
"get_tags",
"(",
")",
":",
"tags",
"=",
"getattr",
"(",
"flask",
".",
"g",
",",
"'bukudb'",
",",
"get_bukudb",
"(",
")",
")",
".",
"get_tag_all",
"(",
")",
"result",
"=",
"{",
"'tags'",
":",
"tags",
"[",
"0",
"]",
"}",
"if",
"request",
"."... | 27.363636 | 20.363636 |
def get_token_func():
"""
This function makes a call to AAD to fetch an OAuth token
:return: the OAuth token and the interval to wait before refreshing it
"""
print("{}: token updater was triggered".format(datetime.datetime.now()))
# in this example, the OAuth token is o... | [
"def",
"get_token_func",
"(",
")",
":",
"print",
"(",
"\"{}: token updater was triggered\"",
".",
"format",
"(",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
")",
")",
"# in this example, the OAuth token is obtained using the ADAL library",
"# however, the user can us... | 56.565217 | 31.173913 |
def getContextsForExpression(self, body, getFingerprint=None, startIndex=0, maxResults=5, sparsity=1.0):
"""Get semantic contexts for the input expression
Args:
body, ExpressionOperation: The JSON encoded expression to be evaluated (required)
getFingerprint, bool: Configure if th... | [
"def",
"getContextsForExpression",
"(",
"self",
",",
"body",
",",
"getFingerprint",
"=",
"None",
",",
"startIndex",
"=",
"0",
",",
"maxResults",
"=",
"5",
",",
"sparsity",
"=",
"1.0",
")",
":",
"return",
"self",
".",
"_expressions",
".",
"getContextsForExpre... | 61.857143 | 35.428571 |
def set_maintenance_mode(value):
"""
Set maintenance_mode state to state file.
"""
# If maintenance mode is defined in settings, it can't be changed.
if settings.MAINTENANCE_MODE is not None:
raise ImproperlyConfigured(
'Maintenance mode cannot be set dynamically '
'... | [
"def",
"set_maintenance_mode",
"(",
"value",
")",
":",
"# If maintenance mode is defined in settings, it can't be changed.",
"if",
"settings",
".",
"MAINTENANCE_MODE",
"is",
"not",
"None",
":",
"raise",
"ImproperlyConfigured",
"(",
"'Maintenance mode cannot be set dynamically '",... | 31.5 | 14.625 |
def isatty(self): # nocover
"""
Returns true of the redirect is a terminal.
Notes:
Needed for IPython.embed to work properly when this class is used
to override stdout / stderr.
"""
return (self.redirect is not None and
hasattr(self.redir... | [
"def",
"isatty",
"(",
"self",
")",
":",
"# nocover",
"return",
"(",
"self",
".",
"redirect",
"is",
"not",
"None",
"and",
"hasattr",
"(",
"self",
".",
"redirect",
",",
"'isatty'",
")",
"and",
"self",
".",
"redirect",
".",
"isatty",
"(",
")",
")"
] | 35.3 | 16.7 |
def _studentized_residuals_fast(self, p=None):
"""
Returns a list of studentized residuals, (ydata - model)/error
This function relies on a previous call to set_data(), and assumes
self._massage_data() has been called (to increase speed).
Parameters
----------
... | [
"def",
"_studentized_residuals_fast",
"(",
"self",
",",
"p",
"=",
"None",
")",
":",
"if",
"len",
"(",
"self",
".",
"_set_xdata",
")",
"==",
"0",
"or",
"len",
"(",
"self",
".",
"_set_ydata",
")",
"==",
"0",
":",
"return",
"if",
"p",
"is",
"None",
":... | 37.642857 | 22.428571 |
def writeGlobalFile(self, localFileName, cleanup=False):
"""
Takes a file (as a path) and uploads it to the job store. Depending on the jobstore
used, carry out the appropriate cache functions.
"""
absLocalFileName = self._resolveAbsoluteLocalPath(localFileName)
# What d... | [
"def",
"writeGlobalFile",
"(",
"self",
",",
"localFileName",
",",
"cleanup",
"=",
"False",
")",
":",
"absLocalFileName",
"=",
"self",
".",
"_resolveAbsoluteLocalPath",
"(",
"localFileName",
")",
"# What does this do?",
"cleanupID",
"=",
"None",
"if",
"not",
"clean... | 67.90625 | 32.1875 |
def validate_value_range(self, value):
"""
Args:
value: Throws DsdlException if this value cannot be represented by this type.
"""
low, high = self.value_range
if not low <= value <= high:
error('Value [%s] is out of range %s', value, self.value_range) | [
"def",
"validate_value_range",
"(",
"self",
",",
"value",
")",
":",
"low",
",",
"high",
"=",
"self",
".",
"value_range",
"if",
"not",
"low",
"<=",
"value",
"<=",
"high",
":",
"error",
"(",
"'Value [%s] is out of range %s'",
",",
"value",
",",
"self",
".",
... | 38.625 | 15.125 |
def _format_output(selected_number, raw_data):
"""Format data to get a readable output"""
tmp_data = {}
data = collections.defaultdict(lambda: 0)
balance = raw_data.pop('balance')
for number in raw_data.keys():
tmp_data = dict([(k, int(v) if v is not None else "No limit")
... | [
"def",
"_format_output",
"(",
"selected_number",
",",
"raw_data",
")",
":",
"tmp_data",
"=",
"{",
"}",
"data",
"=",
"collections",
".",
"defaultdict",
"(",
"lambda",
":",
"0",
")",
"balance",
"=",
"raw_data",
".",
"pop",
"(",
"'balance'",
")",
"for",
"nu... | 33 | 13.8 |
def _partition(hours, partition = 3600.0):
"""
Partition a sorted list of numbers (or in this case hours).
Arguments:
hours -- sorted ndarray of hours.
partition -- maximum partition length (default: 3600.0)
"""
partition = float(partition)
relative = hours - hours[0]
total_partitions = np.ceil(relati... | [
"def",
"_partition",
"(",
"hours",
",",
"partition",
"=",
"3600.0",
")",
":",
"partition",
"=",
"float",
"(",
"partition",
")",
"relative",
"=",
"hours",
"-",
"hours",
"[",
"0",
"]",
"total_partitions",
"=",
"np",
".",
"ceil",
"(",
"relative",
"[",
"-"... | 42.545455 | 18.727273 |
def _move_template_to_destination(
self,
ignoreExisting=False):
"""
*move template to destination*
**Key Arguments:**
# -
**Return:**
- None
.. todo::
- @review: when complete, clean _move_template_to_destination met... | [
"def",
"_move_template_to_destination",
"(",
"self",
",",
"ignoreExisting",
"=",
"False",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``_move_template_to_destination`` method'",
")",
"# CREATE DIRECTORY STRUCTURE",
"sourceDirectories",
"=",
"recursive_dir... | 33.201923 | 19.288462 |
def second_order_score(y, mean, scale, shape, skewness):
""" GAS Poisson Update term potentially using second-order information - native Python function
Parameters
----------
y : float
datapoint for the time series
mean : float
location parameter for the... | [
"def",
"second_order_score",
"(",
"y",
",",
"mean",
",",
"scale",
",",
"shape",
",",
"skewness",
")",
":",
"return",
"(",
"y",
"-",
"mean",
")",
"/",
"float",
"(",
"mean",
")"
] | 28.12 | 21.4 |
def generate_dh_parameters(bit_size):
"""
Generates DH parameters for use with Diffie-Hellman key exchange. Returns
a structure in the format of DHParameter defined in PKCS#3, which is also
used by the OpenSSL dhparam tool.
THIS CAN BE VERY TIME CONSUMING!
:param bit_size:
The integer ... | [
"def",
"generate_dh_parameters",
"(",
"bit_size",
")",
":",
"if",
"not",
"isinstance",
"(",
"bit_size",
",",
"int_types",
")",
":",
"raise",
"TypeError",
"(",
"pretty_message",
"(",
"'''\n bit_size must be an integer, not %s\n '''",
",",
"type_name",... | 35.086538 | 23.721154 |
def p_global_stmt(p):
"""
global_stmt : GLOBAL global_list SEMI
| GLOBAL ident EQ expr SEMI
"""
p[0] = node.global_stmt(p[2])
for ident in p[0]:
ident.props = "G" | [
"def",
"p_global_stmt",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"node",
".",
"global_stmt",
"(",
"p",
"[",
"2",
"]",
")",
"for",
"ident",
"in",
"p",
"[",
"0",
"]",
":",
"ident",
".",
"props",
"=",
"\"G\""
] | 24.875 | 7.875 |
def save_config(self, cmd="save", confirm=False, confirm_response=""):
""" Save Config for HuaweiSSH"""
return super(HuaweiBase, self).save_config(
cmd=cmd, confirm=confirm, confirm_response=confirm_response
) | [
"def",
"save_config",
"(",
"self",
",",
"cmd",
"=",
"\"save\"",
",",
"confirm",
"=",
"False",
",",
"confirm_response",
"=",
"\"\"",
")",
":",
"return",
"super",
"(",
"HuaweiBase",
",",
"self",
")",
".",
"save_config",
"(",
"cmd",
"=",
"cmd",
",",
"conf... | 48.2 | 20.6 |
def run(self, **export_params):
"""
Make the actual request to the Import API (exporting is part of the
Import API).
:param export_params: Any additional parameters to be sent to the
Import API
:type export_params: kwargs
:return:
... | [
"def",
"run",
"(",
"self",
",",
"*",
"*",
"export_params",
")",
":",
"export_params",
"[",
"\"visualization_id\"",
"]",
"=",
"self",
".",
"visualization_id",
"return",
"super",
"(",
"ExportJob",
",",
"self",
")",
".",
"run",
"(",
"params",
"=",
"export_par... | 46.625 | 37.5 |
def addAction( self, action ):
"""
Adds the inputed action to this widget's action group. This will auto-\
create a new group if no group is already defined.
:param action | <QAction> || <str>
:return <QAction>
"""
if not isinstance(act... | [
"def",
"addAction",
"(",
"self",
",",
"action",
")",
":",
"if",
"not",
"isinstance",
"(",
"action",
",",
"QAction",
")",
":",
"action_name",
"=",
"nativestring",
"(",
"action",
")",
"action",
"=",
"QAction",
"(",
"action_name",
",",
"self",
")",
"action"... | 31.73913 | 14.347826 |
def _check_type(self, value):
"""Checks that *value* matches the type of this *Searcher*.
Checks that *value* matches the type of this *Searcher*, returning the
value if it does and raising a `TypeError` if it does not.
:return: *value* if type of *value* matches type of this *Searcher... | [
"def",
"_check_type",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"self",
".",
"match_type",
")",
":",
"raise",
"TypeError",
"(",
"'Type '",
"+",
"str",
"(",
"type",
"(",
"value",
")",
")",
"+",
"' does not match ... | 43.733333 | 24.133333 |
def decode(packet):
"""Decode a navdata packet."""
offset = 0
_ = struct.unpack_from('IIII', packet, offset)
s = _[1]
state = dict()
state['fly'] = s & 1 # FLY MASK : (0) ardrone is landed, (1) ardrone is flying
state['video'] = s >> 1 & 1 # VIDEO MASK :... | [
"def",
"decode",
"(",
"packet",
")",
":",
"offset",
"=",
"0",
"_",
"=",
"struct",
".",
"unpack_from",
"(",
"'IIII'",
",",
"packet",
",",
"offset",
")",
"s",
"=",
"_",
"[",
"1",
"]",
"state",
"=",
"dict",
"(",
")",
"state",
"[",
"'fly'",
"]",
"=... | 51.240506 | 35.949367 |
def from_file(cls, f):
"""Load vocab from a file.
:param (file) f: a file object, e.g. as returned by calling `open`
:return: a vocab object. The 0th line of the file is assigned to index 0, and so on...
"""
word2index = {}
counts = Counter()
for i, line in enume... | [
"def",
"from_file",
"(",
"cls",
",",
"f",
")",
":",
"word2index",
"=",
"{",
"}",
"counts",
"=",
"Counter",
"(",
")",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"f",
")",
":",
"word",
",",
"count_str",
"=",
"line",
".",
"split",
"(",
"'\\t'"... | 36.3125 | 15.25 |
def to_html(data):
"""
Serializes a python object as HTML
This method uses the to_json method to turn the given data object into
formatted JSON that is displayed in an HTML page. If pygments in installed,
syntax highlighting will also be applied to the JSON.
"""
base_html_template = Templat... | [
"def",
"to_html",
"(",
"data",
")",
":",
"base_html_template",
"=",
"Template",
"(",
"'''\n <html>\n <head>\n {% if style %}\n <style type=\"text/css\">\n {{ style }}\n </style>\n {% endif %}\n ... | 29.552632 | 17.236842 |
def process_data(data, models):
""" Convert ``data`` to processed data using ``models``.
Data from dictionary ``data`` is processed by each model
in list ``models``, and the results collected into a new
dictionary ``pdata`` for use in :meth:`MultiFitter.lsqfit`
and :meth:`MultiF... | [
"def",
"process_data",
"(",
"data",
",",
"models",
")",
":",
"pdata",
"=",
"gvar",
".",
"BufferDict",
"(",
")",
"for",
"m",
"in",
"MultiFitter",
".",
"flatten_models",
"(",
"models",
")",
":",
"pdata",
"[",
"m",
".",
"datatag",
"]",
"=",
"(",
"m",
... | 41.466667 | 16.066667 |
def progressed_bar(count, total=100, status=None, suffix=None, bar_len=10):
"""render a progressed.io like progress bar"""
status = status or ''
suffix = suffix or '%'
assert isinstance(count, int)
count_normalized = count if count <= total else total
filled_len = int(round(bar_len * count_norma... | [
"def",
"progressed_bar",
"(",
"count",
",",
"total",
"=",
"100",
",",
"status",
"=",
"None",
",",
"suffix",
"=",
"None",
",",
"bar_len",
"=",
"10",
")",
":",
"status",
"=",
"status",
"or",
"''",
"suffix",
"=",
"suffix",
"or",
"'%'",
"assert",
"isinst... | 41.047619 | 15.142857 |
def idfreader(fname, iddfile, conv=True):
"""read idf file and return bunches"""
data, commdct, idd_index = readidf.readdatacommdct(fname, iddfile=iddfile)
if conv:
convertallfields(data, commdct)
# fill gaps in idd
ddtt, dtls = data.dt, data.dtls
# skiplist = ["TABLE:MULTIVARIABLELOOKUP... | [
"def",
"idfreader",
"(",
"fname",
",",
"iddfile",
",",
"conv",
"=",
"True",
")",
":",
"data",
",",
"commdct",
",",
"idd_index",
"=",
"readidf",
".",
"readdatacommdct",
"(",
"fname",
",",
"iddfile",
"=",
"iddfile",
")",
"if",
"conv",
":",
"convertallfield... | 42 | 11.857143 |
def camelcase_to_underline(param_dict):
"""
将驼峰命名的参数字典键转换为下划线参数
:param:
* param_dict: (dict) 请求参数字典
:return:
* temp_dict: (dict) 转换后的参数字典
举例如下::
print('--- transform_hump_to_underline demo---')
hump_param_dict = {'firstName': 'Python', 'Second_Name': 'san', 'right... | [
"def",
"camelcase_to_underline",
"(",
"param_dict",
")",
":",
"temp_dict",
"=",
"copy",
".",
"deepcopy",
"(",
"param_dict",
")",
"# 正则",
"hump_to_underline",
"=",
"re",
".",
"compile",
"(",
"r'([a-z]|\\d)([A-Z])'",
")",
"for",
"key",
"in",
"list",
"(",
"param_... | 27 | 23.411765 |
def nl_complete_msg(sk, msg):
"""Finalize Netlink message.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L450
This function finalizes a Netlink message by completing the message with desirable flags and values depending on the
socket configuration.
- If not yet filled out, the source... | [
"def",
"nl_complete_msg",
"(",
"sk",
",",
"msg",
")",
":",
"nlh",
"=",
"msg",
".",
"nm_nlh",
"if",
"nlh",
".",
"nlmsg_pid",
"==",
"NL_AUTO_PORT",
":",
"nlh",
".",
"nlmsg_pid",
"=",
"nl_socket_get_local_port",
"(",
"sk",
")",
"if",
"nlh",
".",
"nlmsg_seq"... | 42.566667 | 23.666667 |
def _merge_mappings(*args):
"""Merges a sequence of dictionaries and/or tuples into a single dictionary.
If a given argument is a tuple, it must have two elements, the first of which is a sequence of keys and the second
of which is a single value, which will be mapped to from each of the keys in the sequen... | [
"def",
"_merge_mappings",
"(",
"*",
"args",
")",
":",
"dct",
"=",
"{",
"}",
"for",
"arg",
"in",
"args",
":",
"if",
"isinstance",
"(",
"arg",
",",
"dict",
")",
":",
"merge",
"=",
"arg",
"else",
":",
"assert",
"isinstance",
"(",
"arg",
",",
"tuple",
... | 36.875 | 21.9375 |
def validate_string_list(value):
"""Validator for string lists to be used with `add_setting`."""
try:
if sys.version_info.major < 3:
# pylint: disable-msg=W0404
from locale import getpreferredencoding
encoding = getpreferredencoding()
... | [
"def",
"validate_string_list",
"(",
"value",
")",
":",
"try",
":",
"if",
"sys",
".",
"version_info",
".",
"major",
"<",
"3",
":",
"# pylint: disable-msg=W0404",
"from",
"locale",
"import",
"getpreferredencoding",
"encoding",
"=",
"getpreferredencoding",
"(",
")",
... | 46.454545 | 10.181818 |
def prepare(base_path='data',
serialize=json.dumps,
deserialize=json.loads,
file_ext='json'):
"""After you have added your collections, prepare the database
for use."""
global _basepath, _deserialize, _serialize, _ext
_basepath = base_path
assert callable(serializ... | [
"def",
"prepare",
"(",
"base_path",
"=",
"'data'",
",",
"serialize",
"=",
"json",
".",
"dumps",
",",
"deserialize",
"=",
"json",
".",
"loads",
",",
"file_ext",
"=",
"'json'",
")",
":",
"global",
"_basepath",
",",
"_deserialize",
",",
"_serialize",
",",
"... | 35.571429 | 10.380952 |
def validate_day_start_ut(conn):
"""This validates the day_start_ut of the days table."""
G = GTFS(conn)
cur = conn.execute('SELECT date, day_start_ut FROM days')
for date, day_start_ut in cur:
#print date, day_start_ut
assert day_start_ut == G.get_day_start_ut(date) | [
"def",
"validate_day_start_ut",
"(",
"conn",
")",
":",
"G",
"=",
"GTFS",
"(",
"conn",
")",
"cur",
"=",
"conn",
".",
"execute",
"(",
"'SELECT date, day_start_ut FROM days'",
")",
"for",
"date",
",",
"day_start_ut",
"in",
"cur",
":",
"#print date, day_start_ut",
... | 41.857143 | 11.285714 |
def draw3dCoordAxis(self, img=None, thickness=8):
'''
draw the 3d coordinate axes into given image
if image == False:
create an empty image
'''
if img is None:
img = self.img
elif img is False:
img = np.zeros(shape=self.img.sha... | [
"def",
"draw3dCoordAxis",
"(",
"self",
",",
"img",
"=",
"None",
",",
"thickness",
"=",
"8",
")",
":",
"if",
"img",
"is",
"None",
":",
"img",
"=",
"self",
".",
"img",
"elif",
"img",
"is",
"False",
":",
"img",
"=",
"np",
".",
"zeros",
"(",
"shape",... | 40.774194 | 17.806452 |
def add_to(self, other):
"""
Add another chem material package to this material package.
:param other: The other material package.
"""
# Add another package.
if type(other) is MaterialPackage:
# Packages of the same material.
if self.material ==... | [
"def",
"add_to",
"(",
"self",
",",
"other",
")",
":",
"# Add another package.",
"if",
"type",
"(",
"other",
")",
"is",
"MaterialPackage",
":",
"# Packages of the same material.",
"if",
"self",
".",
"material",
"==",
"other",
".",
"material",
":",
"self",
".",
... | 40.358974 | 21.282051 |
def mass_enclosed_2d(self, r, kwargs_profile):
"""
computes the mass enclosed the projected line-of-sight
:param r: radius (arcsec)
:param kwargs_profile: keyword argument list with lens model parameters
:return: projected mass enclosed radius r
"""
kwargs = copy.... | [
"def",
"mass_enclosed_2d",
"(",
"self",
",",
"r",
",",
"kwargs_profile",
")",
":",
"kwargs",
"=",
"copy",
".",
"deepcopy",
"(",
"kwargs_profile",
")",
"try",
":",
"del",
"kwargs",
"[",
"'center_x'",
"]",
"del",
"kwargs",
"[",
"'center_y'",
"]",
"except",
... | 38.375 | 16.375 |
def walk(self,
top=None,
path=None,
depth=0,
maxdepth=-1,
class_ref=None,
class_pattern=None,
return_classname=False,
treat_dirs_as_objs=False):
"""
Walk the directory structure and content in and bel... | [
"def",
"walk",
"(",
"self",
",",
"top",
"=",
"None",
",",
"path",
"=",
"None",
",",
"depth",
"=",
"0",
",",
"maxdepth",
"=",
"-",
"1",
",",
"class_ref",
"=",
"None",
",",
"class_pattern",
"=",
"None",
",",
"return_classname",
"=",
"False",
",",
"tr... | 39.64486 | 19.775701 |
def split (properties):
""" Given a property-set of the form
v1/v2/...vN-1/<fN>vN/<fN+1>vN+1/...<fM>vM
Returns
v1 v2 ... vN-1 <fN>vN <fN+1>vN+1 ... <fM>vM
Note that vN...vM may contain slashes. This is resilient to the
substitution of backslashes for slashes, since Jam, unbidden,
s... | [
"def",
"split",
"(",
"properties",
")",
":",
"assert",
"isinstance",
"(",
"properties",
",",
"basestring",
")",
"def",
"split_one",
"(",
"properties",
")",
":",
"pieces",
"=",
"re",
".",
"split",
"(",
"__re_slash_or_backslash",
",",
"properties",
")",
"resul... | 29.548387 | 20.354839 |
def balance_of(self, address, block_identifier='latest'):
""" Return the balance of `address`. """
return self.proxy.contract.functions.balanceOf(
to_checksum_address(address),
).call(block_identifier=block_identifier) | [
"def",
"balance_of",
"(",
"self",
",",
"address",
",",
"block_identifier",
"=",
"'latest'",
")",
":",
"return",
"self",
".",
"proxy",
".",
"contract",
".",
"functions",
".",
"balanceOf",
"(",
"to_checksum_address",
"(",
"address",
")",
",",
")",
".",
"call... | 50 | 8.4 |
def participate(self):
"""Finish reading and send text"""
try:
logger.info("Entering participate method")
ready = WebDriverWait(self.driver, 10).until(
EC.element_to_be_clickable((By.ID, "finish-reading"))
)
stimulus = self.driver.find_elem... | [
"def",
"participate",
"(",
"self",
")",
":",
"try",
":",
"logger",
".",
"info",
"(",
"\"Entering participate method\"",
")",
"ready",
"=",
"WebDriverWait",
"(",
"self",
".",
"driver",
",",
"10",
")",
".",
"until",
"(",
"EC",
".",
"element_to_be_clickable",
... | 39.25 | 15.892857 |
def get_contact_by_email(self, email):
""" Returns a Contact by it's email
:param email: email to get contact for
:return: Contact for specified email
:rtype: Contact
"""
if not email:
return None
email = email.strip()
url = self.build_url('... | [
"def",
"get_contact_by_email",
"(",
"self",
",",
"email",
")",
":",
"if",
"not",
"email",
":",
"return",
"None",
"email",
"=",
"email",
".",
"strip",
"(",
")",
"url",
"=",
"self",
".",
"build_url",
"(",
"'{}/{}'",
".",
"format",
"(",
"self",
".",
"_e... | 29.130435 | 21.130435 |
def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]:
"""Rate limit a function."""
return util.rate_limited(max_per_hour, *args) | [
"def",
"rate_limited",
"(",
"max_per_hour",
":",
"int",
",",
"*",
"args",
":",
"Any",
")",
"->",
"Callable",
"[",
"...",
",",
"Any",
"]",
":",
"return",
"util",
".",
"rate_limited",
"(",
"max_per_hour",
",",
"*",
"args",
")"
] | 50.333333 | 13 |
def get_place(self, place_id, sensor=False, language=lang.ENGLISH):
"""Gets a detailed place object.
keyword arguments:
place_id -- The unique Google identifier for the required place.
sensor -- Boolean flag denoting if the location came from a
device using its' ... | [
"def",
"get_place",
"(",
"self",
",",
"place_id",
",",
"sensor",
"=",
"False",
",",
"language",
"=",
"lang",
".",
"ENGLISH",
")",
":",
"place_details",
"=",
"_get_place_details",
"(",
"place_id",
",",
"self",
".",
"api_key",
",",
"sensor",
",",
"language",... | 50.769231 | 21.307692 |
def add_segments(self, segments):
"""Add a list of segments to the composition
:param segments: Segments to add to composition
:type segments: list of :py:class:`radiotool.composer.Segment`
"""
self.tracks.update([seg.track for seg in segments])
self.segments.extend(segm... | [
"def",
"add_segments",
"(",
"self",
",",
"segments",
")",
":",
"self",
".",
"tracks",
".",
"update",
"(",
"[",
"seg",
".",
"track",
"for",
"seg",
"in",
"segments",
"]",
")",
"self",
".",
"segments",
".",
"extend",
"(",
"segments",
")"
] | 39.75 | 14.125 |
def convert_to_broker_id(string):
"""Convert string to kafka broker_id."""
error_msg = 'Positive integer or -1 required, {string} given.'.format(string=string)
try:
value = int(string)
except ValueError:
raise argparse.ArgumentTypeError(error_msg)
if value <= 0 and value != -1:
... | [
"def",
"convert_to_broker_id",
"(",
"string",
")",
":",
"error_msg",
"=",
"'Positive integer or -1 required, {string} given.'",
".",
"format",
"(",
"string",
"=",
"string",
")",
"try",
":",
"value",
"=",
"int",
"(",
"string",
")",
"except",
"ValueError",
":",
"r... | 37.4 | 17 |
def _fullsize_link_tag(self, kwargs, title):
""" Render a <a href> that points to the fullsize rendition specified """
return utils.make_tag('a', {
'href': self.get_fullsize(kwargs),
'data-lightbox': kwargs['gallery_id'],
'title': title
}) | [
"def",
"_fullsize_link_tag",
"(",
"self",
",",
"kwargs",
",",
"title",
")",
":",
"return",
"utils",
".",
"make_tag",
"(",
"'a'",
",",
"{",
"'href'",
":",
"self",
".",
"get_fullsize",
"(",
"kwargs",
")",
",",
"'data-lightbox'",
":",
"kwargs",
"[",
"'galle... | 36.625 | 13.5 |
def _set_login(self, v, load=False):
"""
Setter method for login, mapped from YANG variable /aaa_config/aaa/authentication/login (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_login is considered as a private
method. Backends looking to populate this var... | [
"def",
"_set_login",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",
... | 79.681818 | 37.545455 |
def get_asset_lookup_session(self, proxy, *args, **kwargs):
"""Gets the OsidSession associated with the asset lookup service.
arg proxy (osid.proxy.Proxy): a proxy
return: (osid.repository.AssetLookupSession) - the new
AssetLookupSession
raise: OperationFailed - una... | [
"def",
"get_asset_lookup_session",
"(",
"self",
",",
"proxy",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"supports_asset_lookup",
"(",
")",
":",
"raise",
"Unimplemented",
"(",
")",
"try",
":",
"from",
".",
"import",
... | 39.833333 | 16.333333 |
def get_hardware_source_by_id(self, hardware_source_id: str, version: str):
"""Return the hardware source API matching the hardware_source_id and version.
.. versionadded:: 1.0
Scriptable: Yes
"""
actual_version = "1.0.0"
if Utility.compare_versions(version, actual_vers... | [
"def",
"get_hardware_source_by_id",
"(",
"self",
",",
"hardware_source_id",
":",
"str",
",",
"version",
":",
"str",
")",
":",
"actual_version",
"=",
"\"1.0.0\"",
"if",
"Utility",
".",
"compare_versions",
"(",
"version",
",",
"actual_version",
")",
">",
"0",
":... | 54.25 | 32.166667 |
def handle_wiki(msg):
""" Given a wiki message, return the FAS username. """
if 'wiki.article.edit' in msg.topic:
username = msg.msg['user']
elif 'wiki.upload.complete' in msg.topic:
username = msg.msg['user_text']
else:
raise ValueError("Unhandled topic.")
return username | [
"def",
"handle_wiki",
"(",
"msg",
")",
":",
"if",
"'wiki.article.edit'",
"in",
"msg",
".",
"topic",
":",
"username",
"=",
"msg",
".",
"msg",
"[",
"'user'",
"]",
"elif",
"'wiki.upload.complete'",
"in",
"msg",
".",
"topic",
":",
"username",
"=",
"msg",
"."... | 28.090909 | 15.181818 |
def generate_simple_vcf(filename, variant_collection):
"""
Output a very simple metadata-free VCF for each variant in a variant_collection.
"""
contigs = []
positions = []
refs = []
alts = []
for variant in variant_collection:
contigs.append("chr" + variant.contig)
positi... | [
"def",
"generate_simple_vcf",
"(",
"filename",
",",
"variant_collection",
")",
":",
"contigs",
"=",
"[",
"]",
"positions",
"=",
"[",
"]",
"refs",
"=",
"[",
"]",
"alts",
"=",
"[",
"]",
"for",
"variant",
"in",
"variant_collection",
":",
"contigs",
".",
"ap... | 42.820513 | 19.487179 |
def _serve_forever_wrapper(self, _srv, poll_interval=0.1):
"""
Wrapper for the server created for a SSH forward
"""
self.logger.info('Opening tunnel: {0} <> {1}'.format(
address_to_str(_srv.local_address),
address_to_str(_srv.remote_address))
)
_sr... | [
"def",
"_serve_forever_wrapper",
"(",
"self",
",",
"_srv",
",",
"poll_interval",
"=",
"0.1",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Opening tunnel: {0} <> {1}'",
".",
"format",
"(",
"address_to_str",
"(",
"_srv",
".",
"local_address",
")",
",",
... | 38.071429 | 16.785714 |
def __set_window_title(self):
"""
Sets the Component window title.
"""
if self.has_editor_tab():
windowTitle = "{0} - {1}".format(self.__default_window_title, self.get_current_editor().file)
else:
windowTitle = "{0}".format(self.__default_window_title)
... | [
"def",
"__set_window_title",
"(",
"self",
")",
":",
"if",
"self",
".",
"has_editor_tab",
"(",
")",
":",
"windowTitle",
"=",
"\"{0} - {1}\"",
".",
"format",
"(",
"self",
".",
"__default_window_title",
",",
"self",
".",
"get_current_editor",
"(",
")",
".",
"fi... | 36.75 | 22.416667 |
def upload_release(self):
"""Upload an application bundle to the server for a given context"""
self.before_upload_release()
with settings(user=self.user):
with app_bundle():
local_bundle = env.local_bundle
env.bundle = '/tmp/' + os.path.basename(local... | [
"def",
"upload_release",
"(",
"self",
")",
":",
"self",
".",
"before_upload_release",
"(",
")",
"with",
"settings",
"(",
"user",
"=",
"self",
".",
"user",
")",
":",
"with",
"app_bundle",
"(",
")",
":",
"local_bundle",
"=",
"env",
".",
"local_bundle",
"en... | 37.051282 | 17.717949 |
def try_set_count(self, count):
"""
Sets the count to the given value if the current count is zero. If count is not zero, this method does nothing
and returns ``false``.
:param count: (int), the number of times count_down() must be invoked before threads can pass through await().
... | [
"def",
"try_set_count",
"(",
"self",
",",
"count",
")",
":",
"check_not_negative",
"(",
"count",
",",
"\"count can't be negative\"",
")",
"return",
"self",
".",
"_encode_invoke",
"(",
"count_down_latch_try_set_count_codec",
",",
"count",
"=",
"count",
")"
] | 56.7 | 34.3 |
def help_center_article_translation_update(self, article_id, locale, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/translations#update-translation"
api_path = "/api/v2/help_center/articles/{article_id}/translations/{locale}.json"
api_path = api_path.format(article_id=... | [
"def",
"help_center_article_translation_update",
"(",
"self",
",",
"article_id",
",",
"locale",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/help_center/articles/{article_id}/translations/{locale}.json\"",
"api_path",
"=",
"api_path",
".",
... | 82.4 | 42.4 |
def _setup_stats_plugins(self):
'''
Sets up the plugin stats collectors
'''
self.stats_dict['plugins'] = {}
for key in self.plugins_dict:
plugin_name = self.plugins_dict[key]['instance'].__class__.__name__
temp_key = 'stats:redis-monitor:{p}'.format(p=plug... | [
"def",
"_setup_stats_plugins",
"(",
"self",
")",
":",
"self",
".",
"stats_dict",
"[",
"'plugins'",
"]",
"=",
"{",
"}",
"for",
"key",
"in",
"self",
".",
"plugins_dict",
":",
"plugin_name",
"=",
"self",
".",
"plugins_dict",
"[",
"key",
"]",
"[",
"'instance... | 53.451613 | 21.967742 |
def onehot_features(train, test, features, full=False, sparse=False, dummy_na=True):
"""Encode categorical features using a one-hot scheme.
Parameters
----------
train : pd.DataFrame
test : pd.DataFrame
features : list
Column names in the DataFrame to be encoded.
full : bool, defaul... | [
"def",
"onehot_features",
"(",
"train",
",",
"test",
",",
"features",
",",
"full",
"=",
"False",
",",
"sparse",
"=",
"False",
",",
"dummy_na",
"=",
"True",
")",
":",
"features",
"=",
"[",
"f",
"for",
"f",
"in",
"features",
"if",
"f",
"in",
"train",
... | 34.425 | 24 |
def get_config_path(filename, *search_dirs):
"""Get the appropriate path for a filename, in that order: filename, ., PPP_CONFIG_DIR, package's etc dir."""
paths = config_search_paths(filename, *search_dirs)
for path in paths[::-1]:
if os.path.exists(path):
return path | [
"def",
"get_config_path",
"(",
"filename",
",",
"*",
"search_dirs",
")",
":",
"paths",
"=",
"config_search_paths",
"(",
"filename",
",",
"*",
"search_dirs",
")",
"for",
"path",
"in",
"paths",
"[",
":",
":",
"-",
"1",
"]",
":",
"if",
"os",
".",
"path",
... | 42.142857 | 13.714286 |
def _get_value_error_message_for_invalid_prarameter(self, parameter, value):
"""Returns the ValueError message for the given parameter.
:param string parameter: Name of the parameter the message has to be created for.
:param numeric value: Value outside the parameters interval.
:... | [
"def",
"_get_value_error_message_for_invalid_prarameter",
"(",
"self",
",",
"parameter",
",",
"value",
")",
":",
"# return if not interval is defined for the parameter",
"if",
"parameter",
"not",
"in",
"self",
".",
"_parameterIntervals",
":",
"return",
"interval",
"=",
"s... | 40.952381 | 23.47619 |
def command_show(self):
""" Show metadata """
self.parser = argparse.ArgumentParser(
description="Show metadata of available objects")
self.options_select()
self.options_formatting()
self.options_utils()
self.options = self.parser.parse_args(self.arguments[2:]... | [
"def",
"command_show",
"(",
"self",
")",
":",
"self",
".",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Show metadata of available objects\"",
")",
"self",
".",
"options_select",
"(",
")",
"self",
".",
"options_formatting",
"(",
... | 38.222222 | 12.111111 |
def dequeue(self, queue_type='default'):
"""Dequeues a job from any of the ready queues
based on the queue_type. If no job is ready,
returns a failure status.
"""
if not is_valid_identifier(queue_type):
raise BadArgumentException('`queue_type` has an invalid value.')
... | [
"def",
"dequeue",
"(",
"self",
",",
"queue_type",
"=",
"'default'",
")",
":",
"if",
"not",
"is_valid_identifier",
"(",
"queue_type",
")",
":",
"raise",
"BadArgumentException",
"(",
"'`queue_type` has an invalid value.'",
")",
"timestamp",
"=",
"str",
"(",
"generat... | 27.538462 | 19.410256 |
def json_get(parsed_json, key):
"""
Retrieves the key from a parsed_json dictionary, or raises an exception if the
key is not present
"""
if key not in parsed_json:
raise ValueError("JSON does not contain a {} field".format(key))
return parsed_json[key] | [
"def",
"json_get",
"(",
"parsed_json",
",",
"key",
")",
":",
"if",
"key",
"not",
"in",
"parsed_json",
":",
"raise",
"ValueError",
"(",
"\"JSON does not contain a {} field\"",
".",
"format",
"(",
"key",
")",
")",
"return",
"parsed_json",
"[",
"key",
"]"
] | 34.75 | 15.5 |
def symmetrize(self, method=None, copy=False):
'''Symmetrizes (ignores method). Returns a copy if copy=True.'''
if copy:
return SymmEdgePairGraph(self._pairs.copy(),
num_vertices=self._num_vertices)
shape = (self._num_vertices, self._num_vertices)
flat_inds = np.unio... | [
"def",
"symmetrize",
"(",
"self",
",",
"method",
"=",
"None",
",",
"copy",
"=",
"False",
")",
":",
"if",
"copy",
":",
"return",
"SymmEdgePairGraph",
"(",
"self",
".",
"_pairs",
".",
"copy",
"(",
")",
",",
"num_vertices",
"=",
"self",
".",
"_num_vertice... | 51.8 | 22.4 |
def palindrome(seq):
'''Test whether a sequence is palindrome.
:param seq: Sequence to analyze (DNA or RNA).
:type seq: coral.DNA or coral.RNA
:returns: Whether a sequence is a palindrome.
:rtype: bool
'''
seq_len = len(seq)
if seq_len % 2 == 0:
# Sequence has even number of ba... | [
"def",
"palindrome",
"(",
"seq",
")",
":",
"seq_len",
"=",
"len",
"(",
"seq",
")",
"if",
"seq_len",
"%",
"2",
"==",
"0",
":",
"# Sequence has even number of bases, can test non-overlapping seqs",
"wing",
"=",
"seq_len",
"/",
"2",
"l_wing",
"=",
"seq",
"[",
"... | 28.727273 | 19.909091 |
def update_when_older(self, days):
"""
Update TLD list cache file if the list is older than
number of days given in parameter `days` or if does not exist.
:param int days: number of days from last change
:return: True if update was successful, False otherwise
:rtype: boo... | [
"def",
"update_when_older",
"(",
"self",
",",
"days",
")",
":",
"last_cache",
"=",
"self",
".",
"_get_last_cachefile_modification",
"(",
")",
"if",
"last_cache",
"is",
"None",
":",
"return",
"self",
".",
"update",
"(",
")",
"time_to_update",
"=",
"last_cache",... | 30 | 20.2 |
def load(self, addr, ty):
"""
Load a value from memory into a VEX temporary register.
:param addr: The VexValue containing the addr to load from.
:param ty: The Type of the resulting data
:return: a VexValue
"""
rdt = self.irsb_c.load(addr.rdt, ty)
return... | [
"def",
"load",
"(",
"self",
",",
"addr",
",",
"ty",
")",
":",
"rdt",
"=",
"self",
".",
"irsb_c",
".",
"load",
"(",
"addr",
".",
"rdt",
",",
"ty",
")",
"return",
"VexValue",
"(",
"self",
".",
"irsb_c",
",",
"rdt",
")"
] | 33.8 | 13.2 |
def _get_marker_output(self, asset_quantities, metadata):
"""
Creates a marker output.
:param list[int] asset_quantities: The asset quantity list.
:param bytes metadata: The metadata contained in the output.
:return: An object representing the marker output.
:rtype: Tran... | [
"def",
"_get_marker_output",
"(",
"self",
",",
"asset_quantities",
",",
"metadata",
")",
":",
"payload",
"=",
"openassets",
".",
"protocol",
".",
"MarkerOutput",
"(",
"asset_quantities",
",",
"metadata",
")",
".",
"serialize_payload",
"(",
")",
"script",
"=",
... | 45.916667 | 19.916667 |
def ilsr_top1(
n_items, data, alpha=0.0, initial_params=None, max_iter=100, tol=1e-8):
"""Compute the ML estimate of model parameters using I-LSR.
This function computes the maximum-likelihood (ML) estimate of model
parameters given top-1 data (see :ref:`data-top1`), using the
iterative Luce Sp... | [
"def",
"ilsr_top1",
"(",
"n_items",
",",
"data",
",",
"alpha",
"=",
"0.0",
",",
"initial_params",
"=",
"None",
",",
"max_iter",
"=",
"100",
",",
"tol",
"=",
"1e-8",
")",
":",
"fun",
"=",
"functools",
".",
"partial",
"(",
"lsr_top1",
",",
"n_items",
"... | 35.714286 | 20.914286 |
def start(self, *args, **kwargs):
"""
Start the server thread if it wasn't created with autostart = True.
"""
if args:
LOG.debug("args: %s" % str(args))
if kwargs:
LOG.debug("kwargs: %s" % str(kwargs))
try:
self._server.start()
... | [
"def",
"start",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"args",
":",
"LOG",
".",
"debug",
"(",
"\"args: %s\"",
"%",
"str",
"(",
"args",
")",
")",
"if",
"kwargs",
":",
"LOG",
".",
"debug",
"(",
"\"kwargs: %s\"",
"%"... | 31.117647 | 12.411765 |
async def _connect(self):
"""
Connect to the 'TempDeck' port
Planned change- will connect to the correct port in case of multiple
TempDecks
"""
if self._poller:
self._poller.join()
self._driver.connect(self._port)
self._device_info = self._driv... | [
"async",
"def",
"_connect",
"(",
"self",
")",
":",
"if",
"self",
".",
"_poller",
":",
"self",
".",
"_poller",
".",
"join",
"(",
")",
"self",
".",
"_driver",
".",
"connect",
"(",
"self",
".",
"_port",
")",
"self",
".",
"_device_info",
"=",
"self",
"... | 33.5 | 11.166667 |
def read(self, device=None, offset=0, bs=None, count=1):
"""
Using DIRECT_O read from the block device specified to stdout
(Without any optional arguments will read the first 4k from the device)
"""
volume = self.get_volume(device)
block_size = bs or BLOCK_SIZE
o... | [
"def",
"read",
"(",
"self",
",",
"device",
"=",
"None",
",",
"offset",
"=",
"0",
",",
"bs",
"=",
"None",
",",
"count",
"=",
"1",
")",
":",
"volume",
"=",
"self",
".",
"get_volume",
"(",
"device",
")",
"block_size",
"=",
"bs",
"or",
"BLOCK_SIZE",
... | 39 | 17.888889 |
def defaults_section(self, value):
"""
Setter for **self.__defaults_section** attribute.
:param value: Attribute value.
:type value: unicode
"""
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
... | [
"def",
"defaults_section",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"assert",
"type",
"(",
"value",
")",
"is",
"unicode",
",",
"\"'{0}' attribute: '{1}' type is not 'unicode'!\"",
".",
"format",
"(",
"\"defaults_section\"",
"... | 32.25 | 15.75 |
def persons_significant_control(self, num, statements=False, **kwargs):
"""Search for a list of persons with significant control.
Searches for persons of significant control based on company number for
a specified company. Specify statements=True to only search for
officers with stateme... | [
"def",
"persons_significant_control",
"(",
"self",
",",
"num",
",",
"statements",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"baseuri",
"=",
"(",
"self",
".",
"_BASE_URI",
"+",
"'company/{}/persons-with-significant-control'",
".",
"format",
"(",
"num",
"... | 40.458333 | 21.541667 |
def inspect_signature_parameters(callable_, excluded=None):
"""Get the parameters of a callable.
Returns a list with the signature parameters of `callable_`.
Parameters contained in `excluded` tuple will not be included
in the result.
:param callable_: callable object
:param excluded: tuple wi... | [
"def",
"inspect_signature_parameters",
"(",
"callable_",
",",
"excluded",
"=",
"None",
")",
":",
"if",
"not",
"excluded",
":",
"excluded",
"=",
"(",
")",
"signature",
"=",
"inspect",
".",
"signature",
"(",
"callable_",
")",
"params",
"=",
"[",
"v",
"for",
... | 27.666667 | 20.571429 |
def restoreWidget(self, viewWidget, parent, xwidget):
"""
Creates the widget with the inputed parent based on the given xml type.
:param viewWidget | <XViewWidget>
parent | <QWidget>
xwidget | <xml.etree.Element>
:r... | [
"def",
"restoreWidget",
"(",
"self",
",",
"viewWidget",
",",
"parent",
",",
"xwidget",
")",
":",
"# create a new splitter",
"if",
"xwidget",
".",
"tag",
"==",
"'split'",
":",
"widget",
"=",
"XSplitter",
"(",
"parent",
")",
"if",
"(",
"xwidget",
".",
"get",... | 36.658228 | 15.949367 |
def build_wxsfile_default_gui(root):
""" This function adds a default GUI to the wxs file
"""
factory = Document()
Product = root.getElementsByTagName('Product')[0]
UIRef = factory.createElement('UIRef')
UIRef.attributes['Id'] = 'WixUI_Mondo'
Product.childNodes.append(UIRef)
UIRef ... | [
"def",
"build_wxsfile_default_gui",
"(",
"root",
")",
":",
"factory",
"=",
"Document",
"(",
")",
"Product",
"=",
"root",
".",
"getElementsByTagName",
"(",
"'Product'",
")",
"[",
"0",
"]",
"UIRef",
"=",
"factory",
".",
"createElement",
"(",
"'UIRef'",
")",
... | 33.230769 | 11.153846 |
def quit_all(editor, force=False):
"""
Quit all.
"""
quit(editor, all_=True, force=force) | [
"def",
"quit_all",
"(",
"editor",
",",
"force",
"=",
"False",
")",
":",
"quit",
"(",
"editor",
",",
"all_",
"=",
"True",
",",
"force",
"=",
"force",
")"
] | 20.2 | 6.6 |
def _define(self):
"""
gate sdg a { u1(-pi/2) a; }
"""
definition = []
q = QuantumRegister(1, "q")
rule = [
(U1Gate(-pi/2), [q[0]], [])
]
for inst in rule:
definition.append(inst)
self.definition = definition | [
"def",
"_define",
"(",
"self",
")",
":",
"definition",
"=",
"[",
"]",
"q",
"=",
"QuantumRegister",
"(",
"1",
",",
"\"q\"",
")",
"rule",
"=",
"[",
"(",
"U1Gate",
"(",
"-",
"pi",
"/",
"2",
")",
",",
"[",
"q",
"[",
"0",
"]",
"]",
",",
"[",
"]"... | 24.416667 | 10.75 |
def maybe_convert_objects(values, convert_dates=True, convert_numeric=True,
convert_timedeltas=True, copy=True):
""" if we have an object dtype, try to coerce dates and/or numbers """
# if we have passed in a list or scalar
if isinstance(values, (list, tuple)):
values = np... | [
"def",
"maybe_convert_objects",
"(",
"values",
",",
"convert_dates",
"=",
"True",
",",
"convert_numeric",
"=",
"True",
",",
"convert_timedeltas",
"=",
"True",
",",
"copy",
"=",
"True",
")",
":",
"# if we have passed in a list or scalar",
"if",
"isinstance",
"(",
"... | 34.04918 | 20.377049 |
def dbmax50years(self, value=None):
""" Corresponds to IDD Field `dbmax50years`
50-year return period values for maximum extreme dry-bulb temperature
Args:
value (float): value for IDD Field `dbmax50years`
Unit: C
if `value` is None it will not be ch... | [
"def",
"dbmax50years",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"float",
"(",
"value",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'value {} need to be of type f... | 36.428571 | 20.952381 |
def relexp_action(self, text, loc, arg):
"""Code executed after recognising a relexp expression (something relop something)"""
if DEBUG > 0:
print("REL_EXP:",arg)
if DEBUG == 2: self.symtab.display()
if DEBUG > 2: return
exshared.setpos(loc, text)
... | [
"def",
"relexp_action",
"(",
"self",
",",
"text",
",",
"loc",
",",
"arg",
")",
":",
"if",
"DEBUG",
">",
"0",
":",
"print",
"(",
"\"REL_EXP:\"",
",",
"arg",
")",
"if",
"DEBUG",
"==",
"2",
":",
"self",
".",
"symtab",
".",
"display",
"(",
")",
"if",... | 50.846154 | 13.615385 |
def mission_request_int_send(self, target_system, target_component, seq, force_mavlink1=False):
'''
Request the information of the mission item with the sequence number
seq. The response of the system to this message should
be a MISSION_ITEM_INT message.
... | [
"def",
"mission_request_int_send",
"(",
"self",
",",
"target_system",
",",
"target_component",
",",
"seq",
",",
"force_mavlink1",
"=",
"False",
")",
":",
"return",
"self",
".",
"send",
"(",
"self",
".",
"mission_request_int_encode",
"(",
"target_system",
",",
"t... | 55.846154 | 34.615385 |
def calculate_r_matrices(fine_states, reduced_matrix_elements, q=None,
numeric=True, convention=1):
ur"""Calculate the matrix elements of the electric dipole (in the helicity
basis).
We calculate all matrix elements for the D2 line in Rb 87.
>>> from sympy import symbols, ppri... | [
"def",
"calculate_r_matrices",
"(",
"fine_states",
",",
"reduced_matrix_elements",
",",
"q",
"=",
"None",
",",
"numeric",
"=",
"True",
",",
"convention",
"=",
"1",
")",
":",
"magnetic_states",
"=",
"make_list_of_states",
"(",
"fine_states",
",",
"'magnetic'",
",... | 53.423077 | 19.974359 |
def _retrieve_all_teams(self, year):
"""
Find and create Team instances for all teams in the given season.
For a given season, parses the specified NHL stats table and finds all
requested stats. Each team then has a Team instance created which
includes all requested stats and a ... | [
"def",
"_retrieve_all_teams",
"(",
"self",
",",
"year",
")",
":",
"if",
"not",
"year",
":",
"year",
"=",
"utils",
".",
"_find_year_for_season",
"(",
"'nhl'",
")",
"doc",
"=",
"pq",
"(",
"SEASON_PAGE_URL",
"%",
"year",
")",
"teams_list",
"=",
"utils",
"."... | 38.75 | 20.892857 |
def getlines(filename, module_globals=None):
"""Get the lines for a file from the cache.
Update the cache if it doesn't contain an entry for this file already."""
if filename in cache:
return cache[filename][2]
try:
return updatecache(filename, module_globals)
except MemoryError:
... | [
"def",
"getlines",
"(",
"filename",
",",
"module_globals",
"=",
"None",
")",
":",
"if",
"filename",
"in",
"cache",
":",
"return",
"cache",
"[",
"filename",
"]",
"[",
"2",
"]",
"try",
":",
"return",
"updatecache",
"(",
"filename",
",",
"module_globals",
"... | 28.833333 | 17.5 |
def process_vhwa_command(self, command, enm_cmd, from_guest):
"""Posts a Video HW Acceleration Command to the frame buffer for processing.
The commands used for 2D video acceleration (DDraw surface creation/destroying, blitting, scaling, color conversion, overlaying, etc.)
are posted from quest ... | [
"def",
"process_vhwa_command",
"(",
"self",
",",
"command",
",",
"enm_cmd",
",",
"from_guest",
")",
":",
"if",
"not",
"isinstance",
"(",
"command",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"\"command can only be an instance of type basestring\"",
")",... | 47.444444 | 25.925926 |
def get_rules(self, subreddit, bottom=False):
"""Return the json dictionary containing rules for a subreddit.
:param subreddit: The subreddit whose rules we will return.
"""
url = self.config['rules'].format(subreddit=six.text_type(subreddit))
return self.request_json(url) | [
"def",
"get_rules",
"(",
"self",
",",
"subreddit",
",",
"bottom",
"=",
"False",
")",
":",
"url",
"=",
"self",
".",
"config",
"[",
"'rules'",
"]",
".",
"format",
"(",
"subreddit",
"=",
"six",
".",
"text_type",
"(",
"subreddit",
")",
")",
"return",
"se... | 38.5 | 19 |
def get_rec_features(self, features=None):
"""
Returns a df of features for recalled items
"""
if features is None:
features = self.dist_funcs.keys()
elif not isinstance(features, list):
features = [features]
return self.rec.applymap(lambda x: {k:v... | [
"def",
"get_rec_features",
"(",
"self",
",",
"features",
"=",
"None",
")",
":",
"if",
"features",
"is",
"None",
":",
"features",
"=",
"self",
".",
"dist_funcs",
".",
"keys",
"(",
")",
"elif",
"not",
"isinstance",
"(",
"features",
",",
"list",
")",
":",... | 41.888889 | 12.555556 |
def findnextmatch(self, startkey, find_string, flags, search_result=True):
""" Returns a tuple with the position of the next match of find_string
Returns None if string not found.
Parameters:
-----------
startkey: Start position of search
find_string:String to be sear... | [
"def",
"findnextmatch",
"(",
"self",
",",
"startkey",
",",
"find_string",
",",
"flags",
",",
"search_result",
"=",
"True",
")",
":",
"assert",
"\"UP\"",
"in",
"flags",
"or",
"\"DOWN\"",
"in",
"flags",
"assert",
"not",
"(",
"\"UP\"",
"in",
"flags",
"and",
... | 34.847826 | 21.043478 |
def _set_load_balance_type(self, v, load=False):
"""
Setter method for load_balance_type, mapped from YANG variable /interface/port_channel/load_balance_type (enumeration)
If this variable is read-only (config: false) in the
source YANG file, then _set_load_balance_type is considered as a private
me... | [
"def",
"_set_load_balance_type",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",... | 94.363636 | 44.909091 |
def __correction(self,text):
"""
spell correction
"""
new_text = []
for i in text.split():
if len(i)>3:
low = i.lower()
new_text.append(i if WORDS[i] else correction(i))
else:new_text.append(i)
return " ".join(new_te... | [
"def",
"__correction",
"(",
"self",
",",
"text",
")",
":",
"new_text",
"=",
"[",
"]",
"for",
"i",
"in",
"text",
".",
"split",
"(",
")",
":",
"if",
"len",
"(",
"i",
")",
">",
"3",
":",
"low",
"=",
"i",
".",
"lower",
"(",
")",
"new_text",
".",
... | 28.454545 | 10.818182 |
def generate_sha1(string, salt=None):
"""
Generates a sha1 hash for supplied string. Doesn't need to be very secure
because it's not used for password checking. We got Django for that.
:param string:
The string that needs to be encrypted.
:param salt:
Optionally define your own sal... | [
"def",
"generate_sha1",
"(",
"string",
",",
"salt",
"=",
"None",
")",
":",
"if",
"not",
"salt",
":",
"salt",
"=",
"hashlib",
".",
"sha1",
"(",
"str",
"(",
"random",
".",
"random",
"(",
")",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
".",
"hexd... | 31.5 | 24 |
def to_dict_list_generic_type(df, int_col=None, binary_col=None):
"""Transform each row to dict, and put them into a list. And automatically
convert ``np.int64`` to ``int``, ``pandas.tslib.Timestamp`` to
``datetime.datetime``, ``np.nan`` to ``None``.
:param df: ``pandas.DataFrame`` instance.
:para... | [
"def",
"to_dict_list_generic_type",
"(",
"df",
",",
"int_col",
"=",
"None",
",",
"binary_col",
"=",
"None",
")",
":",
"# Pre-process int_col, binary_col and datetime_col",
"if",
"(",
"int_col",
"is",
"not",
"None",
")",
"and",
"(",
"not",
"isinstance",
"(",
"int... | 30.085714 | 19.014286 |
def _on_login(self, user):
"""
Callback called whenever the login or sign up process completes.
Returns the input user parameter.
"""
self._bot = bool(user.bot)
self._self_input_peer = utils.get_input_peer(user, allow_self=False)
self._authorized = True
... | [
"def",
"_on_login",
"(",
"self",
",",
"user",
")",
":",
"self",
".",
"_bot",
"=",
"bool",
"(",
"user",
".",
"bot",
")",
"self",
".",
"_self_input_peer",
"=",
"utils",
".",
"get_input_peer",
"(",
"user",
",",
"allow_self",
"=",
"False",
")",
"self",
"... | 29.181818 | 18.090909 |
def convert_cifar100(directory, output_directory,
output_filename='cifar100.hdf5'):
"""Converts the CIFAR-100 dataset to HDF5.
Converts the CIFAR-100 dataset to an HDF5 dataset compatible with
:class:`fuel.datasets.CIFAR100`. The converted dataset is saved as
'cifar100.hdf5'.
... | [
"def",
"convert_cifar100",
"(",
"directory",
",",
"output_directory",
",",
"output_filename",
"=",
"'cifar100.hdf5'",
")",
":",
"output_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"output_directory",
",",
"output_filename",
")",
"h5file",
"=",
"h5py",
".",
... | 36.716049 | 21.691358 |
def _place_ticks_horizontal(self):
"""Display the ticks for a horizontal scale."""
# first tick
tick = self.ticks[0]
label = self.ticklabels[0]
x = self.convert_to_pixels(tick)
half_width = label.winfo_reqwidth() / 2
if x - half_width < 0:
x = half_wid... | [
"def",
"_place_ticks_horizontal",
"(",
"self",
")",
":",
"# first tick",
"tick",
"=",
"self",
".",
"ticks",
"[",
"0",
"]",
"label",
"=",
"self",
".",
"ticklabels",
"[",
"0",
"]",
"x",
"=",
"self",
".",
"convert_to_pixels",
"(",
"tick",
")",
"half_width",... | 38.363636 | 9.5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.