text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def listLastFires(self, *args, **kwargs):
"""
Get information about recent hook fires
This endpoint will return information about the the last few times this hook has been
fired, including whether the hook was fired successfully or not
This method gives output: ``v1/list-lastFi... | [
"def",
"listLastFires",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_makeApiCall",
"(",
"self",
".",
"funcinfo",
"[",
"\"listLastFires\"",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 35.692308 | 0.008403 |
def errcat(self):
'''
List the posts to be modified.
'''
post_recs = MPost.query_random(limit=1000)
outrecs = []
errrecs = []
idx = 0
for postinfo in post_recs:
if idx > 16:
break
cat = MPost2Catalog.get_first_catego... | [
"def",
"errcat",
"(",
"self",
")",
":",
"post_recs",
"=",
"MPost",
".",
"query_random",
"(",
"limit",
"=",
"1000",
")",
"outrecs",
"=",
"[",
"]",
"errrecs",
"=",
"[",
"]",
"idx",
"=",
"0",
"for",
"postinfo",
"in",
"post_recs",
":",
"if",
"idx",
">"... | 31.766667 | 0.002037 |
def number_independent_conservation_relations(model):
"""
Return the number of conserved metabolite pools.
This number is given by the left null space of the stoichiometric matrix.
Parameters
----------
model : cobra.Model
The metabolic model under investigation.
"""
s_matrix,... | [
"def",
"number_independent_conservation_relations",
"(",
"model",
")",
":",
"s_matrix",
",",
"_",
",",
"_",
"=",
"con_helpers",
".",
"stoichiometry_matrix",
"(",
"model",
".",
"metabolites",
",",
"model",
".",
"reactions",
")",
"ln_matrix",
"=",
"con_helpers",
"... | 27.882353 | 0.002041 |
def virtual_memory():
'''
.. versionadded:: 2014.7.0
Return a dict that describes statistics about system memory usage.
.. note::
This function is only available in psutil version 0.6.0 and above.
CLI Example:
.. code-block:: bash
salt '*' ps.virtual_memory
'''
if p... | [
"def",
"virtual_memory",
"(",
")",
":",
"if",
"psutil",
".",
"version_info",
"<",
"(",
"0",
",",
"6",
",",
"0",
")",
":",
"msg",
"=",
"'virtual_memory is only available in psutil 0.6.0 or greater'",
"raise",
"CommandExecutionError",
"(",
"msg",
")",
"return",
"d... | 25 | 0.001927 |
def pad(x, paddings, dim_name, name=None):
"""Slice operation.
Args:
x: a list of Tensors
paddings: list of integers of size 2, padding size before and after for dim.
dim_name: string, name for the padding dim
name: an optional string
Returns:
a Tensor with shape extended by output_shape for ... | [
"def",
"pad",
"(",
"x",
",",
"paddings",
",",
"dim_name",
",",
"name",
"=",
"None",
")",
":",
"return",
"PadOperation",
"(",
"x",
",",
"paddings",
",",
"dim_name",
",",
"name",
"=",
"name",
")",
".",
"outputs",
"[",
"0",
"]"
] | 30.923077 | 0.009662 |
def run(cli_args):
"""
Split the functionality into 2 methods.
One for parsing the cli and one that runs the application.
"""
from .core import Core
c = Core(
source_file=cli_args["--data-file"],
schema_files=cli_args["--schema-file"],
extensions=cli_args['--extension']... | [
"def",
"run",
"(",
"cli_args",
")",
":",
"from",
".",
"core",
"import",
"Core",
"c",
"=",
"Core",
"(",
"source_file",
"=",
"cli_args",
"[",
"\"--data-file\"",
"]",
",",
"schema_files",
"=",
"cli_args",
"[",
"\"--schema-file\"",
"]",
",",
"extensions",
"=",... | 30.315789 | 0.001684 |
def issues(self, start=None):
"""Get the issues from pagination"""
payload = self.__build_payload(size=self.items_per_page, operation=True, startdate=start)
path = self.__get_url_project()
return self.__fetch_items(path=path, payload=payload) | [
"def",
"issues",
"(",
"self",
",",
"start",
"=",
"None",
")",
":",
"payload",
"=",
"self",
".",
"__build_payload",
"(",
"size",
"=",
"self",
".",
"items_per_page",
",",
"operation",
"=",
"True",
",",
"startdate",
"=",
"start",
")",
"path",
"=",
"self",... | 45 | 0.010909 |
def is_objective_required(self, objective_id=None, required_objective_id=None):
"""Tests if an objective is required before proceeding with an
objective.
arg: objective_id (osid.id.Id): Id of the dependent Objective
arg: required_objective_id (osid.id.Id): Id of the required
... | [
"def",
"is_objective_required",
"(",
"self",
",",
"objective_id",
"=",
"None",
",",
"required_objective_id",
"=",
"None",
")",
":",
"if",
"objective_id",
"is",
"None",
"or",
"required_objective_id",
"is",
"None",
":",
"raise",
"NullArgument",
"(",
")",
"requisit... | 48.772727 | 0.001828 |
def resource(self):
"""
:class:`~zhmcclient.BaseResource`: The Python resource object of the
resource these metric values apply to.
Raises:
:exc:`~zhmcclient.NotFound`: No resource found for this URI in the
management scope of the HMC.
"""
if sel... | [
"def",
"resource",
"(",
"self",
")",
":",
"if",
"self",
".",
"_resource",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_resource",
"resource_class",
"=",
"self",
".",
"metric_group_definition",
".",
"resource_class",
"resource_uri",
"=",
"self",
".",
"r... | 35.571429 | 0.000782 |
def flip_flip(self, point):
"""
Sometimes we 'flipped' the X/Y coordinates of the image during processing. This function takes an
(x,y) location from the processing pipeline and returns the x/y location relative to the original
reference frame. (Correctly checks if the coordinate is f... | [
"def",
"flip_flip",
"(",
"self",
",",
"point",
")",
":",
"x",
",",
"y",
"=",
"point",
"if",
"self",
".",
"reading",
".",
"compute_inverted",
"(",
")",
":",
"naxis1",
"=",
"self",
".",
"reading",
".",
"obs",
".",
"header",
".",
"get",
"(",
"self",
... | 47.814815 | 0.009112 |
def changed_locations(a, include_first):
"""
Compute indices of values in ``a`` that differ from the previous value.
Parameters
----------
a : np.ndarray
The array on which to indices of change.
include_first : bool
Whether or not to consider the first index of the array as "cha... | [
"def",
"changed_locations",
"(",
"a",
",",
"include_first",
")",
":",
"if",
"a",
".",
"ndim",
">",
"1",
":",
"raise",
"ValueError",
"(",
"\"indices_of_changed_values only supports 1D arrays.\"",
")",
"indices",
"=",
"flatnonzero",
"(",
"diff",
"(",
"a",
")",
"... | 27.642857 | 0.001248 |
def get_orders_info(self,
symbol,
states:list,
types:list=None,
start_date=None,
end_date=None,
_from=None,
direct=None,
size=No... | [
"def",
"get_orders_info",
"(",
"self",
",",
"symbol",
",",
"states",
":",
"list",
",",
"types",
":",
"list",
"=",
"None",
",",
"start_date",
"=",
"None",
",",
"end_date",
"=",
"None",
",",
"_from",
"=",
"None",
",",
"direct",
"=",
"None",
",",
"size"... | 34.404762 | 0.01144 |
def handle(self, *args, **options):
"""Handle the management command."""
if mon is None:
sys.stderr.write(MISSING)
else:
mon.run(**options) | [
"def",
"handle",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"if",
"mon",
"is",
"None",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"MISSING",
")",
"else",
":",
"mon",
".",
"run",
"(",
"*",
"*",
"options",
")"
] | 30.333333 | 0.010695 |
def export_context(cls, context):
""" Export the specified context to be capable context transferring
:param context: context to export
:return: tuple
"""
if context is None:
return
result = [(x.context_name(), x.context_value()) for x in context]
result.reverse()
return tuple(result) | [
"def",
"export_context",
"(",
"cls",
",",
"context",
")",
":",
"if",
"context",
"is",
"None",
":",
"return",
"result",
"=",
"[",
"(",
"x",
".",
"context_name",
"(",
")",
",",
"x",
".",
"context_value",
"(",
")",
")",
"for",
"x",
"in",
"context",
"]... | 26.818182 | 0.036066 |
def delete(collection_name, spec, safe,
last_error_args, opts, flags=0):
"""Get a **delete** message.
`opts` is a CodecOptions. `flags` is a bit vector that may contain
the SingleRemove flag or not:
http://docs.mongodb.org/meta-driver/latest/legacy/mongodb-wire-protocol/#op-delete
"""
... | [
"def",
"delete",
"(",
"collection_name",
",",
"spec",
",",
"safe",
",",
"last_error_args",
",",
"opts",
",",
"flags",
"=",
"0",
")",
":",
"data",
"=",
"_ZERO_32",
"data",
"+=",
"bson",
".",
"_make_c_string",
"(",
"collection_name",
")",
"data",
"+=",
"st... | 40.590909 | 0.001094 |
def basic_color(code):
"""
16 colors supported
"""
def inner(text, rl=False):
""" Every raw_input with color sequences should be called with
rl=True to avoid readline messed up the length calculation
"""
c = code
if rl:
return "\001\033[%sm\002%s\001\0... | [
"def",
"basic_color",
"(",
"code",
")",
":",
"def",
"inner",
"(",
"text",
",",
"rl",
"=",
"False",
")",
":",
"\"\"\" Every raw_input with color sequences should be called with\n rl=True to avoid readline messed up the length calculation\n \"\"\"",
"c",
"=",
"code"... | 29.357143 | 0.002358 |
def twilio_SMS(self, from_, to, body):
"""
Send an SMS message from your `twilio`_ account.
.. _twilio: https://www.twilio.com/
Login will be performed using stored credentials.
* *stored credential name: TWILIO_ACCOUNT_SID*
* *stored credential name: TWILIO_AU... | [
"def",
"twilio_SMS",
"(",
"self",
",",
"from_",
",",
"to",
",",
"body",
")",
":",
"logging",
".",
"debug",
"(",
"'Texting from Twilio'",
")",
"client",
"=",
"TwilioRestClient",
"(",
"self",
".",
"_credentials",
"[",
"'TWILIO_ACCOUNT_SID'",
"]",
",",
"self",
... | 41.166667 | 0.01088 |
def regress(self, method = 'lstsq'):
"""regress performs linear least squares regression of the designmatrix on the data.
:param method: method, or backend to be used for the regression analysis.
:type method: string, one of ['lstsq', 'sm_ols']
:returns: instance variables ... | [
"def",
"regress",
"(",
"self",
",",
"method",
"=",
"'lstsq'",
")",
":",
"if",
"method",
"is",
"'lstsq'",
":",
"self",
".",
"betas",
",",
"residuals_sum",
",",
"rank",
",",
"s",
"=",
"LA",
".",
"lstsq",
"(",
"self",
".",
"design_matrix",
".",
"T",
"... | 64.956522 | 0.011873 |
def build_highlight_objects(html, highlights, uniformize_html=True):
'''converts a dict of pretty_name --> [tuple(string, score), ...] to
`Highlight` objects as specified above.
'''
if uniformize_html:
try:
html = uniform_html(html.encode('utf-8')).decode('utf-8')
except Exc... | [
"def",
"build_highlight_objects",
"(",
"html",
",",
"highlights",
",",
"uniformize_html",
"=",
"True",
")",
":",
"if",
"uniformize_html",
":",
"try",
":",
"html",
"=",
"uniform_html",
"(",
"html",
".",
"encode",
"(",
"'utf-8'",
")",
")",
".",
"decode",
"("... | 34.84375 | 0.000873 |
def _brace_key(self, key):
"""
key: 'x' -> '{x}'
"""
if isinstance(key, six.integer_types):
t = str
key = t(key)
else:
t = type(key)
return t(u'{') + key + t(u'}') | [
"def",
"_brace_key",
"(",
"self",
",",
"key",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"six",
".",
"integer_types",
")",
":",
"t",
"=",
"str",
"key",
"=",
"t",
"(",
"key",
")",
"else",
":",
"t",
"=",
"type",
"(",
"key",
")",
"return",
"t"... | 23.8 | 0.008097 |
def execute(self, triple_map, output, **kwargs):
"""Method executes mapping between CSV source and
output RDF
args:
triple_map(SimpleNamespace): Triple Map
"""
subject = self.generate_term(term_map=triple_map.subjectMap,
**kwargs)... | [
"def",
"execute",
"(",
"self",
",",
"triple_map",
",",
"output",
",",
"*",
"*",
"kwargs",
")",
":",
"subject",
"=",
"self",
".",
"generate_term",
"(",
"term_map",
"=",
"triple_map",
".",
"subjectMap",
",",
"*",
"*",
"kwargs",
")",
"start_size",
"=",
"l... | 41.878049 | 0.002277 |
def _UpdateProcessStatus(
self, process_status, identifier, status, pid, used_memory, display_name,
number_of_consumed_sources, number_of_produced_sources,
number_of_consumed_events, number_of_produced_events,
number_of_consumed_event_tags, number_of_produced_event_tags,
number_of_consumed... | [
"def",
"_UpdateProcessStatus",
"(",
"self",
",",
"process_status",
",",
"identifier",
",",
"status",
",",
"pid",
",",
"used_memory",
",",
"display_name",
",",
"number_of_consumed_sources",
",",
"number_of_produced_sources",
",",
"number_of_consumed_events",
",",
"number... | 44.967742 | 0.001053 |
def nlmsg_type(self, value):
"""Message content setter."""
self.bytearray[self._get_slicers(1)] = bytearray(c_uint16(value or 0)) | [
"def",
"nlmsg_type",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"bytearray",
"[",
"self",
".",
"_get_slicers",
"(",
"1",
")",
"]",
"=",
"bytearray",
"(",
"c_uint16",
"(",
"value",
"or",
"0",
")",
")"
] | 47.666667 | 0.013793 |
def to_local_time(timestamp):
"""Convert a datatime object from UTC time to local time.
Adopted from:
http://stackoverflow.com/questions/4770297/python-convert-utc-datetime-string-to-local-datetime
Parameters
----------
timestamp : string
Default string representation of timestamps exp... | [
"def",
"to_local_time",
"(",
"timestamp",
")",
":",
"utc",
"=",
"dt",
".",
"datetime",
".",
"strptime",
"(",
"timestamp",
",",
"'%Y-%m-%dT%H:%M:%S.%f'",
")",
"# Get UTC and local time zone",
"from_zone",
"=",
"tz",
".",
"gettz",
"(",
"'UTC'",
")",
"to_zone",
"... | 27.148148 | 0.001318 |
def _guess(kwargs):
"""
Adds types, actions, etc. to given argument specification.
For example, ``default=3`` implies ``type=int``.
:param arg: a :class:`argh.utils.Arg` instance
"""
guessed = {}
# Parser actions that accept argument 'type'
TYPE_AWARE_ACTIONS = 'store', 'append'
#... | [
"def",
"_guess",
"(",
"kwargs",
")",
":",
"guessed",
"=",
"{",
"}",
"# Parser actions that accept argument 'type'",
"TYPE_AWARE_ACTIONS",
"=",
"'store'",
",",
"'append'",
"# guess type/action from default value",
"value",
"=",
"kwargs",
".",
"get",
"(",
"'default'",
"... | 35.766667 | 0.000907 |
def retrieve_token(self, token):
"""
Retrieve Token details for a specific Token.
Args:
token: The identifier of the token.
Returns:
"""
headers = self.client._get_private_headers()
endpoint = '/tokens/{}'.format(token)
return self.client._... | [
"def",
"retrieve_token",
"(",
"self",
",",
"token",
")",
":",
"headers",
"=",
"self",
".",
"client",
".",
"_get_private_headers",
"(",
")",
"endpoint",
"=",
"'/tokens/{}'",
".",
"format",
"(",
"token",
")",
"return",
"self",
".",
"client",
".",
"_get",
"... | 25.714286 | 0.008043 |
def _calculate_sun_vector(self):
"""Calculate sun vector for this sun."""
z_axis = Vector3(0., 0., -1.)
x_axis = Vector3(1., 0., 0.)
north_vector = Vector3(0., 1., 0.)
# rotate north vector based on azimuth, altitude, and north
_sun_vector = north_vector \
.r... | [
"def",
"_calculate_sun_vector",
"(",
"self",
")",
":",
"z_axis",
"=",
"Vector3",
"(",
"0.",
",",
"0.",
",",
"-",
"1.",
")",
"x_axis",
"=",
"Vector3",
"(",
"1.",
",",
"0.",
",",
"0.",
")",
"north_vector",
"=",
"Vector3",
"(",
"0.",
",",
"1.",
",",
... | 36.954545 | 0.002398 |
def pre_filter(self):
""" Return rTorrent condition to speed up data transfer.
"""
if self._name in self.PRE_FILTER_FIELDS:
return '"{}={},value={}"'.format(
self._rt_cmp, self.PRE_FILTER_FIELDS[self._name], int(self._value))
return '' | [
"def",
"pre_filter",
"(",
"self",
")",
":",
"if",
"self",
".",
"_name",
"in",
"self",
".",
"PRE_FILTER_FIELDS",
":",
"return",
"'\"{}={},value={}\"'",
".",
"format",
"(",
"self",
".",
"_rt_cmp",
",",
"self",
".",
"PRE_FILTER_FIELDS",
"[",
"self",
".",
"_na... | 41.714286 | 0.010067 |
def _generate_union_serializer(self, union):
"""Emits the serialize method for the serialization object for the given union."""
union_name = fmt_class_prefix(union)
with self.block_func(
func='serialize',
args=fmt_func_args_declaration([('valueObj',
... | [
"def",
"_generate_union_serializer",
"(",
"self",
",",
"union",
")",
":",
"union_name",
"=",
"fmt_class_prefix",
"(",
"union",
")",
"with",
"self",
".",
"block_func",
"(",
"func",
"=",
"'serialize'",
",",
"args",
"=",
"fmt_func_args_declaration",
"(",
"[",
"("... | 43.236111 | 0.00157 |
def _dotify(cls, data):
"""Add dots."""
return ''.join(char if char in cls.PRINTABLE_DATA else '.' for char in data) | [
"def",
"_dotify",
"(",
"cls",
",",
"data",
")",
":",
"return",
"''",
".",
"join",
"(",
"char",
"if",
"char",
"in",
"cls",
".",
"PRINTABLE_DATA",
"else",
"'.'",
"for",
"char",
"in",
"data",
")"
] | 40.666667 | 0.016129 |
def get_dates(feed: "Feed", *, as_date_obj: bool = False) -> List[str]:
"""
Return a list of dates for which the given "Feed" is valid, which
could be the empty list if the "Feed" has no calendar information.
Parameters
----------
feed : "Feed"
as_date_obj : boolean
If ``True``, the... | [
"def",
"get_dates",
"(",
"feed",
":",
"\"Feed\"",
",",
"*",
",",
"as_date_obj",
":",
"bool",
"=",
"False",
")",
"->",
"List",
"[",
"str",
"]",
":",
"dates",
"=",
"[",
"]",
"if",
"feed",
".",
"calendar",
"is",
"not",
"None",
"and",
"not",
"feed",
... | 32.977273 | 0.000669 |
def upload(self, force=False):
"""
Uploads a notebook
:param force: True/False
:returns {}
"""
self.package and self.release
try:
return self.aserver_api.upload(self.username, self.project, self.version,
basename(... | [
"def",
"upload",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"self",
".",
"package",
"and",
"self",
".",
"release",
"try",
":",
"return",
"self",
".",
"aserver_api",
".",
"upload",
"(",
"self",
".",
"username",
",",
"self",
".",
"project",
","... | 42.1 | 0.010453 |
def authorization_code(self, request, data, client):
"""
Handle ``grant_type=authorization_code`` requests as defined in
:rfc:`4.1.3`.
"""
grant = self.get_authorization_code_grant(request, request.POST,
client)
if constants.SINGLE_ACCESS_TOKEN:
... | [
"def",
"authorization_code",
"(",
"self",
",",
"request",
",",
"data",
",",
"client",
")",
":",
"grant",
"=",
"self",
".",
"get_authorization_code_grant",
"(",
"request",
",",
"request",
".",
"POST",
",",
"client",
")",
"if",
"constants",
".",
"SINGLE_ACCESS... | 39.176471 | 0.010264 |
def _run_seq(self, size):
"""
Send the contents of self['SEQ'] to the chip and wait until it finishes.
"""
# Write the sequence to the sequence generator (hw driver)
self['SEQ'].write(size) #write pattern to memory
self['SEQ'].set_size(size) # set size... | [
"def",
"_run_seq",
"(",
"self",
",",
"size",
")",
":",
"# Write the sequence to the sequence generator (hw driver)",
"self",
"[",
"'SEQ'",
"]",
".",
"write",
"(",
"size",
")",
"#write pattern to memory",
"self",
"[",
"'SEQ'",
"]",
".",
"set_size",
"(",
"size",
"... | 32.470588 | 0.019366 |
def _update_lhs(lhs, xCore, zCore, new_lhs):
""" Function to be called from the project()"""
# TODO: Use intermediate variable to use 5 nested loops instead of 6.
r_old_x, n, r_x = xCore.shape
num_obj, r_old_z, n, r_z = zCore.shape
for idx in range(num_obj):
for val in range(n):
... | [
"def",
"_update_lhs",
"(",
"lhs",
",",
"xCore",
",",
"zCore",
",",
"new_lhs",
")",
":",
"# TODO: Use intermediate variable to use 5 nested loops instead of 6.",
"r_old_x",
",",
"n",
",",
"r_x",
"=",
"xCore",
".",
"shape",
"num_obj",
",",
"r_old_z",
",",
"n",
","... | 52.866667 | 0.001239 |
def gen_all_voltages_for_injections(self, injections_raw):
"""For a given set of current injections AB, generate all possible
unique potential measurements.
After Noel and Xu, 1991, for N electrodes, the number of possible
voltage dipoles for a given current dipole is :math:`(N - 2)(N -... | [
"def",
"gen_all_voltages_for_injections",
"(",
"self",
",",
"injections_raw",
")",
":",
"injections",
"=",
"injections_raw",
".",
"astype",
"(",
"int",
")",
"N",
"=",
"self",
".",
"nr_electrodes",
"all_quadpoles",
"=",
"[",
"]",
"for",
"idipole",
"in",
"inject... | 35.951613 | 0.00131 |
def submit(self, timestamp):
"""Internal instance method to submit this task for running immediately.
Does not handle any iteration, end-date, etc., processing."""
Channel(RUN_TASK_CHANNEL).send({'id':self.pk, 'ts': timestamp.timestamp()}) | [
"def",
"submit",
"(",
"self",
",",
"timestamp",
")",
":",
"Channel",
"(",
"RUN_TASK_CHANNEL",
")",
".",
"send",
"(",
"{",
"'id'",
":",
"self",
".",
"pk",
",",
"'ts'",
":",
"timestamp",
".",
"timestamp",
"(",
")",
"}",
")"
] | 65 | 0.019011 |
def reset_globals(version=None, loop=None):
""" Reinitialize the global singletons with a given API version.
:param version: 1 or 2. If `None`, pulled from the `useProtocolApiV2`
advanced setting.
"""
global containers
global instruments
global labware
global robot
g... | [
"def",
"reset_globals",
"(",
"version",
"=",
"None",
",",
"loop",
"=",
"None",
")",
":",
"global",
"containers",
"global",
"instruments",
"global",
"labware",
"global",
"robot",
"global",
"reset",
"global",
"modules",
"global",
"hardware",
"robot",
",",
"reset... | 29.125 | 0.002079 |
def convert_convolution(node, **kwargs):
"""Map MXNet's convolution operator attributes to onnx's Conv operator
and return the created node.
"""
name, input_nodes, attrs = get_inputs(node, kwargs)
kernel_dims = list(parse_helper(attrs, "kernel"))
stride_dims = list(parse_helper(attrs, "stride",... | [
"def",
"convert_convolution",
"(",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
",",
"input_nodes",
",",
"attrs",
"=",
"get_inputs",
"(",
"node",
",",
"kwargs",
")",
"kernel_dims",
"=",
"list",
"(",
"parse_helper",
"(",
"attrs",
",",
"\"kernel\"",
... | 29.555556 | 0.001214 |
def count_unique_sequences(
allele_reads,
max_prefix_size=None,
max_suffix_size=None):
"""
Given a list of AlleleRead objects, extracts all unique
(prefix, allele, suffix) sequences and associate each with the number
of reads that contain that sequence.
"""
groups = group... | [
"def",
"count_unique_sequences",
"(",
"allele_reads",
",",
"max_prefix_size",
"=",
"None",
",",
"max_suffix_size",
"=",
"None",
")",
":",
"groups",
"=",
"group_unique_sequences",
"(",
"allele_reads",
",",
"max_prefix_size",
"=",
"max_prefix_size",
",",
"max_suffix_siz... | 31.411765 | 0.001818 |
def get_summary(content):
"""Gets the summary of a license from tldrlegal.com"""
soup = BeautifulSoup(content, "html.parser")
summary = soup.find_all(attrs={
'class': re.compile(r".*\bsummary-content\b.*")})
if summary[0].p.string is None:
return summary[0].p.p.getText()
return summary[0].p.getText... | [
"def",
"get_summary",
"(",
"content",
")",
":",
"soup",
"=",
"BeautifulSoup",
"(",
"content",
",",
"\"html.parser\"",
")",
"summary",
"=",
"soup",
".",
"find_all",
"(",
"attrs",
"=",
"{",
"'class'",
":",
"re",
".",
"compile",
"(",
"r\".*\\bsummary-content\\b... | 34.888889 | 0.018634 |
def ProgChunks(list_, chunksize, nInput=None, **kwargs):
"""
Yeilds an iterator in chunks and computes progress
Progress version of ut.ichunks
Args:
list_ (list):
chunksize (?):
nInput (None): (default = None)
Kwargs:
length, freq
Returns:
ProgressIter:... | [
"def",
"ProgChunks",
"(",
"list_",
",",
"chunksize",
",",
"nInput",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"nInput",
"is",
"None",
":",
"nInput",
"=",
"len",
"(",
"list_",
")",
"n_chunks",
"=",
"get_num_chunks",
"(",
"nInput",
",",
"ch... | 27.309524 | 0.000842 |
def delete_source(self, id, **kwargs): # noqa: E501
"""Delete metadata (description and tags) for a specific source # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread ... | [
"def",
"delete_source",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"delete_source_... | 41.857143 | 0.002225 |
def update(self, reseed):
"""
Update that snowflake!
:param reseed: Whether we are in the normal reseed cycle or not.
"""
self._screen.print_at(" ", self._x, self._y)
cell = None
for _ in range(self._rate):
self._y += 1
cell = self._screen... | [
"def",
"update",
"(",
"self",
",",
"reseed",
")",
":",
"self",
".",
"_screen",
".",
"print_at",
"(",
"\" \"",
",",
"self",
".",
"_x",
",",
"self",
".",
"_y",
")",
"cell",
"=",
"None",
"for",
"_",
"in",
"range",
"(",
"self",
".",
"_rate",
")",
"... | 39.090909 | 0.002269 |
def __get_libpath(self):
'''Return the absolute path to the MeCab library.
On Windows, the path to the system dictionary is used to deduce the
path to libmecab.dll.
Otherwise, mecab-config is used find the libmecab shared object or
dynamic library (*NIX or Mac OS, respec... | [
"def",
"__get_libpath",
"(",
"self",
")",
":",
"libp",
"=",
"os",
".",
"getenv",
"(",
"self",
".",
"MECAB_PATH",
")",
"if",
"libp",
":",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"libp",
")",
"else",
":",
"plat",
"=",
"sys",
".",
"platform"... | 40.6 | 0.00074 |
def next(self):
"""Iterator protocol: get next item or raise StopIteration."""
if self._fut is None:
self._fut = self._iter.getq()
try:
try:
# The future result is set by this class's _extended_callback
# method.
# pylint: disable=unpacking-non-sequence
(ent,
... | [
"def",
"next",
"(",
"self",
")",
":",
"if",
"self",
".",
"_fut",
"is",
"None",
":",
"self",
".",
"_fut",
"=",
"self",
".",
"_iter",
".",
"getq",
"(",
")",
"try",
":",
"try",
":",
"# The future result is set by this class's _extended_callback",
"# method.",
... | 28.789474 | 0.00885 |
def url(self, var, default=NOTSET):
"""
:rtype: urlparse.ParseResult
"""
return self.get_value(var, cast=urlparse, default=default, parse_default=True) | [
"def",
"url",
"(",
"self",
",",
"var",
",",
"default",
"=",
"NOTSET",
")",
":",
"return",
"self",
".",
"get_value",
"(",
"var",
",",
"cast",
"=",
"urlparse",
",",
"default",
"=",
"default",
",",
"parse_default",
"=",
"True",
")"
] | 35.8 | 0.016393 |
def from_string(contents):
"""
Creates GaussianInput from a string.
Args:
contents: String representing an Gaussian input file.
Returns:
GaussianInput object
"""
lines = [l.strip() for l in contents.split("\n")]
link0_patt = re.compile(r... | [
"def",
"from_string",
"(",
"contents",
")",
":",
"lines",
"=",
"[",
"l",
".",
"strip",
"(",
")",
"for",
"l",
"in",
"contents",
".",
"split",
"(",
"\"\\n\"",
")",
"]",
"link0_patt",
"=",
"re",
".",
"compile",
"(",
"r\"^(%.+)\\s*=\\s*(.+)\"",
")",
"link0... | 35.507937 | 0.001305 |
def time_report(self, include_overhead=False, header=None,
include_server=True, digits=4):
"""
Returns a str table of the times for this api call
:param include_overhead: bool if True include information from
overhead, such as the time for... | [
"def",
"time_report",
"(",
"self",
",",
"include_overhead",
"=",
"False",
",",
"header",
"=",
"None",
",",
"include_server",
"=",
"True",
",",
"digits",
"=",
"4",
")",
":",
"try",
":",
"self",
".",
"_timestamps",
".",
"setdefault",
"(",
"'report'",
",",
... | 48.064935 | 0.001324 |
async def create_vm(self, preset_name: str, image: str, flavor: str, security_groups: List=None,
userdata: Dict=None, key_name: str=None, availability_zone: str=None,
subnets: List=None) -> Any:
"""
Create (boot) a new server.
:arg string preset_n... | [
"async",
"def",
"create_vm",
"(",
"self",
",",
"preset_name",
":",
"str",
",",
"image",
":",
"str",
",",
"flavor",
":",
"str",
",",
"security_groups",
":",
"List",
"=",
"None",
",",
"userdata",
":",
"Dict",
"=",
"None",
",",
"key_name",
":",
"str",
"... | 48.285714 | 0.017408 |
def _process_incoming_iq(self, stanza_obj):
"""
Process an incoming IQ stanza `stanza_obj`. Calls the response handler,
spawns a request handler coroutine or drops the stanza while logging a
warning if no handler can be found.
"""
self._logger.debug("incoming iq: %r", sta... | [
"def",
"_process_incoming_iq",
"(",
"self",
",",
"stanza_obj",
")",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"incoming iq: %r\"",
",",
"stanza_obj",
")",
"if",
"stanza_obj",
".",
"type_",
".",
"is_response",
":",
"# iq response",
"self",
".",
"_logger... | 41.679487 | 0.000601 |
def manage_file_analysis(args: argparse.Namespace, filename: str, data: object) -> None:
"""
Take care of the analysis of a datafile
"""
key = DataStore.hashfile(filename)
print('Analyzing {} --> {}'.format(filename, key))
if data.check_key(key): # if exists in database, prepopulate
fit... | [
"def",
"manage_file_analysis",
"(",
"args",
":",
"argparse",
".",
"Namespace",
",",
"filename",
":",
"str",
",",
"data",
":",
"object",
")",
"->",
"None",
":",
"key",
"=",
"DataStore",
".",
"hashfile",
"(",
"filename",
")",
"print",
"(",
"'Analyzing {} -->... | 40.666667 | 0.002288 |
def create(self, context, request):
"""/@@API/create: Create new object.
Required parameters:
- obj_type = portal_type of new object.
- obj_path = path of new object, from plone site root. - Not required for
obj_type=AnalysisRequest
Optionally:
... | [
"def",
"create",
"(",
"self",
",",
"context",
",",
"request",
")",
":",
"savepoint",
"=",
"transaction",
".",
"savepoint",
"(",
")",
"self",
".",
"context",
"=",
"context",
"self",
".",
"request",
"=",
"request",
"self",
".",
"unused",
"=",
"[",
"x",
... | 39.976331 | 0.001589 |
def _set_fields(self, json_dict):
""" Set this object's attributes specified in json_dict """
for key, value in json_dict.items():
if not key.startswith("_"):
setattr(self, key, value) | [
"def",
"_set_fields",
"(",
"self",
",",
"json_dict",
")",
":",
"for",
"key",
",",
"value",
"in",
"json_dict",
".",
"items",
"(",
")",
":",
"if",
"not",
"key",
".",
"startswith",
"(",
"\"_\"",
")",
":",
"setattr",
"(",
"self",
",",
"key",
",",
"valu... | 44.8 | 0.008772 |
def reset(self):
"""Reset stacks and instruction pointer."""
self.data_stack = stack.Stack()
self.return_stack = stack.Stack()
self.instruction_pointer = 0
return self | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"data_stack",
"=",
"stack",
".",
"Stack",
"(",
")",
"self",
".",
"return_stack",
"=",
"stack",
".",
"Stack",
"(",
")",
"self",
".",
"instruction_pointer",
"=",
"0",
"return",
"self"
] | 33.666667 | 0.009662 |
def post_user_bookmarks_save(self, id, **data):
"""
POST /users/:id/bookmarks/save/
Adds a new bookmark for the user. Returns ``{"created": true}``.
A user is only authorized to save his/her own events.
"""
return self.post("/users/{0}/bookmarks/save/".format(id)... | [
"def",
"post_user_bookmarks_save",
"(",
"self",
",",
"id",
",",
"*",
"*",
"data",
")",
":",
"return",
"self",
".",
"post",
"(",
"\"/users/{0}/bookmarks/save/\"",
".",
"format",
"(",
"id",
")",
",",
"data",
"=",
"data",
")"
] | 40.625 | 0.009036 |
def transform(self, X):
"""Computes the row principal coordinates of a dataset.
Same as calling `row_coordinates`. In most cases you should be using the same
dataset as you did when calling the `fit` method. You might however also want to included
supplementary data.
"""
... | [
"def",
"transform",
"(",
"self",
",",
"X",
")",
":",
"utils",
".",
"validation",
".",
"check_is_fitted",
"(",
"self",
",",
"'s_'",
")",
"if",
"self",
".",
"check_input",
":",
"utils",
".",
"check_array",
"(",
"X",
")",
"return",
"self",
".",
"row_coord... | 41.454545 | 0.008584 |
def _index_entities(self):
''' Sets current instance's entities based on the existing index.
Note: Only entity key/value pairs common to all rows in all contained
Variables are returned. E.g., if a Collection contains Variables
extracted from runs 1, 2 and 3 from subject '01', t... | [
"def",
"_index_entities",
"(",
"self",
")",
":",
"all_ents",
"=",
"pd",
".",
"DataFrame",
".",
"from_records",
"(",
"[",
"v",
".",
"entities",
"for",
"v",
"in",
"self",
".",
"variables",
".",
"values",
"(",
")",
"]",
")",
"constant",
"=",
"all_ents",
... | 49 | 0.002225 |
def call(self, tag_name: str, *args, **kwargs):
"""Convenience method for calling methods with walker."""
if hasattr(self, tag_name):
getattr(self, tag_name)(*args, **kwargs) | [
"def",
"call",
"(",
"self",
",",
"tag_name",
":",
"str",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"tag_name",
")",
":",
"getattr",
"(",
"self",
",",
"tag_name",
")",
"(",
"*",
"args",
",",
"*",
"*"... | 49.75 | 0.009901 |
def _get_longest_hl(self, highlights):
"""
Given a list of highlighted text, returns the
longest highlight
For example:
[
"<em>Muscle</em> <em>atrophy</em>, generalized",
"Generalized <em>muscle</em> degeneration",
"Diffuse skeletal <em>">muscl... | [
"def",
"_get_longest_hl",
"(",
"self",
",",
"highlights",
")",
":",
"len_dict",
"=",
"OrderedDict",
"(",
")",
"for",
"hl",
"in",
"highlights",
":",
"# dummy tags to make it valid xml",
"dummy_xml",
"=",
"\"<p>\"",
"+",
"hl",
"+",
"\"</p>\"",
"try",
":",
"eleme... | 33.774194 | 0.001857 |
def confidences(cluster, condensed_distances, d):
'''
We calculate a per record score that is similar to a standard
deviation. The main reason is that these record scores can be
used to calculate the standard deviation of an entire cluster,
which is a reasonable metric for clusters.
'''
sc... | [
"def",
"confidences",
"(",
"cluster",
",",
"condensed_distances",
",",
"d",
")",
":",
"scores",
"=",
"dict",
".",
"fromkeys",
"(",
"cluster",
",",
"0.0",
")",
"squared_distances",
"=",
"condensed_distances",
"**",
"2",
"for",
"i",
",",
"j",
"in",
"itertool... | 40.35 | 0.001211 |
def create_model(
self,
parent,
model,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a model. Returns a Model in the ``response`` field when it
completes. When you ... | [
"def",
"create_model",
"(",
"self",
",",
"parent",
",",
"model",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",... | 40.340426 | 0.002059 |
def write_fpga_reg(self, fpga_num, addr, value, cabinet, frame, board):
"""Write the value of an FPGA (SPI) register.
See the SpI/O project's spinnaker_fpga design's `README`_ for a listing
of FPGA registers. The SpI/O project can be found on GitHub at:
https://github.com/SpiNNakerManch... | [
"def",
"write_fpga_reg",
"(",
"self",
",",
"fpga_num",
",",
"addr",
",",
"value",
",",
"cabinet",
",",
"frame",
",",
"board",
")",
":",
"arg1",
"=",
"addr",
"&",
"(",
"~",
"0x3",
")",
"arg2",
"=",
"4",
"# Write a 32-bit value",
"arg3",
"=",
"fpga_num",... | 41.961538 | 0.001792 |
def serve_file(load, fnd):
'''
Return a chunk from a file based on the data received
'''
if 'env' in load:
# "env" is not supported; Use "saltenv".
load.pop('env')
ret = {'data': '',
'dest': ''}
if 'path' not in load or 'loc' not in load or 'saltenv' not in load:
... | [
"def",
"serve_file",
"(",
"load",
",",
"fnd",
")",
":",
"if",
"'env'",
"in",
"load",
":",
"# \"env\" is not supported; Use \"saltenv\".",
"load",
".",
"pop",
"(",
"'env'",
")",
"ret",
"=",
"{",
"'data'",
":",
"''",
",",
"'dest'",
":",
"''",
"}",
"if",
... | 29.702703 | 0.001762 |
def createAlignment(self, resultFormat=dict):
"""
Run the alignment algorithm.
@param resultFormat: Either C{dict} or C{str}, giving the desired
result format.
@return: If C{resultFormat} is C{dict}, a C{dict} containing
information about the match (or C{None}) i... | [
"def",
"createAlignment",
"(",
"self",
",",
"resultFormat",
"=",
"dict",
")",
":",
"table",
"=",
"self",
".",
"_initialise",
"(",
")",
"alignment",
"=",
"self",
".",
"_fillAndTraceback",
"(",
"table",
")",
"output",
"=",
"alignment",
"[",
"0",
"]",
"if",... | 40.655172 | 0.001657 |
def save_file(self, filename, text):
"""Save the given text under the given condition filename and the
current path.
If the current directory is not defined explicitly, the directory
name is constructed with the actual simulation end date. If
such an directory does not exist, i... | [
"def",
"save_file",
"(",
"self",
",",
"filename",
",",
"text",
")",
":",
"_defaultdir",
"=",
"self",
".",
"DEFAULTDIR",
"try",
":",
"if",
"not",
"filename",
".",
"endswith",
"(",
"'.py'",
")",
":",
"filename",
"+=",
"'.py'",
"try",
":",
"self",
".",
... | 39.692308 | 0.001892 |
def dfa_complementation(dfa: dict) -> dict:
""" Returns a DFA that accepts any word but he ones accepted
by the input DFA.
Let A be a completed DFA, :math:`Ā = (Σ, S, s_0 , ρ, S − F )`
is the DFA that runs A but accepts whatever word A does not.
:param dict dfa: input DFA.
:return: *(dict)* re... | [
"def",
"dfa_complementation",
"(",
"dfa",
":",
"dict",
")",
"->",
"dict",
":",
"dfa_complement",
"=",
"dfa_completion",
"(",
"deepcopy",
"(",
"dfa",
")",
")",
"dfa_complement",
"[",
"'accepting_states'",
"]",
"=",
"dfa_complement",
"[",
"'states'",
"]",
".",
... | 39.857143 | 0.001751 |
def p_simple_list(p):
'''simple_list : simple_list1
| simple_list1 AMPERSAND
| simple_list1 SEMICOLON'''
tok = p.lexer
heredoc.gatherheredocuments(tok)
if len(p) == 3 or len(p[1]) > 1:
parts = p[1]
if len(p) == 3:
parts.append(ast.node(k... | [
"def",
"p_simple_list",
"(",
"p",
")",
":",
"tok",
"=",
"p",
".",
"lexer",
"heredoc",
".",
"gatherheredocuments",
"(",
"tok",
")",
"if",
"len",
"(",
"p",
")",
"==",
"3",
"or",
"len",
"(",
"p",
"[",
"1",
"]",
")",
">",
"1",
":",
"parts",
"=",
... | 33.65 | 0.001445 |
def current_kv_names(self):
"""Return set of string names of current available Splunk KV collections"""
return current_kv_names(self.sci, self.username, self.appname, request=self._request) | [
"def",
"current_kv_names",
"(",
"self",
")",
":",
"return",
"current_kv_names",
"(",
"self",
".",
"sci",
",",
"self",
".",
"username",
",",
"self",
".",
"appname",
",",
"request",
"=",
"self",
".",
"_request",
")"
] | 67.666667 | 0.019512 |
def create_session(self, session_id, register=True):
"""Creates new session object and returns it.
`request`
Request that created the session. Will be used to get query string
parameters and cookies
`register`
Should be session registered in a storage. Websoc... | [
"def",
"create_session",
"(",
"self",
",",
"session_id",
",",
"register",
"=",
"True",
")",
":",
"# TODO: Possible optimization here for settings.get",
"s",
"=",
"self",
".",
"_session_kls",
"(",
"self",
".",
"_connection",
",",
"self",
",",
"session_id",
",",
"... | 33.095238 | 0.008392 |
def quokka_bounding_boxes(size=None, extract=None):
"""
Returns example bounding boxes on the standard example quokke image.
Currently only a single bounding box is returned that covers the quokka.
Parameters
----------
size : None or float or tuple of int or tuple of float, optional
S... | [
"def",
"quokka_bounding_boxes",
"(",
"size",
"=",
"None",
",",
"extract",
"=",
"None",
")",
":",
"# TODO get rid of this deferred import",
"from",
"imgaug",
".",
"augmentables",
".",
"bbs",
"import",
"BoundingBox",
",",
"BoundingBoxesOnImage",
"left",
",",
"top",
... | 34.686275 | 0.002199 |
def split_conditional (property):
""" If 'property' is conditional property, returns
condition and the property, e.g
<variant>debug,<toolset>gcc:<inlining>full will become
<variant>debug,<toolset>gcc <inlining>full.
Otherwise, returns empty string.
"""
assert isinstance(prope... | [
"def",
"split_conditional",
"(",
"property",
")",
":",
"assert",
"isinstance",
"(",
"property",
",",
"basestring",
")",
"m",
"=",
"__re_split_conditional",
".",
"match",
"(",
"property",
")",
"if",
"m",
":",
"return",
"(",
"m",
".",
"group",
"(",
"1",
")... | 31.928571 | 0.01087 |
def cells_to_series(cells, args):
"""Convert a CellImpl into a Series.
`args` must be a sequence of argkeys.
`args` can be longer or shorter then the number of cell's parameters.
If shorter, then defaults are filled if any, else raise error.
If longer, then redundant args are ignored.
"""
... | [
"def",
"cells_to_series",
"(",
"cells",
",",
"args",
")",
":",
"paramlen",
"=",
"len",
"(",
"cells",
".",
"formula",
".",
"parameters",
")",
"is_multidx",
"=",
"paramlen",
">",
"1",
"if",
"len",
"(",
"cells",
".",
"data",
")",
"==",
"0",
":",
"data",... | 28.145161 | 0.001107 |
def print_roi(self, loglevel=logging.INFO):
"""Print information about the spectral and spatial properties
of the ROI (sources, diffuse components)."""
self.logger.log(loglevel, '\n' + str(self.roi)) | [
"def",
"print_roi",
"(",
"self",
",",
"loglevel",
"=",
"logging",
".",
"INFO",
")",
":",
"self",
".",
"logger",
".",
"log",
"(",
"loglevel",
",",
"'\\n'",
"+",
"str",
"(",
"self",
".",
"roi",
")",
")"
] | 55 | 0.008969 |
def _alarms_present(name, alarms, alarms_from_pillar, region, key, keyid, profile):
'''helper method for present. ensure that cloudwatch_alarms are set'''
current = __salt__['config.option'](alarms_from_pillar, {})
if alarms:
current = salt.utils.dictupdate.update(current, alarms)
ret = {'name'... | [
"def",
"_alarms_present",
"(",
"name",
",",
"alarms",
",",
"alarms_from_pillar",
",",
"region",
",",
"key",
",",
"keyid",
",",
"profile",
")",
":",
"current",
"=",
"__salt__",
"[",
"'config.option'",
"]",
"(",
"alarms_from_pillar",
",",
"{",
"}",
")",
"if"... | 46.740741 | 0.002329 |
def unsubscribe_all(self):
# type: () -> None
"""Unsubscribe from all topics."""
topics = list(self.topics.keys())
for topic in topics:
self.unsubscribe(topic) | [
"def",
"unsubscribe_all",
"(",
"self",
")",
":",
"# type: () -> None",
"topics",
"=",
"list",
"(",
"self",
".",
"topics",
".",
"keys",
"(",
")",
")",
"for",
"topic",
"in",
"topics",
":",
"self",
".",
"unsubscribe",
"(",
"topic",
")"
] | 33 | 0.014778 |
def generate_random(self, bits_len=None):
"""Generates a random value.
:param int bits_len:
:rtype: int
"""
bits_len = bits_len or self._bits_random
return random().getrandbits(bits_len) | [
"def",
"generate_random",
"(",
"self",
",",
"bits_len",
"=",
"None",
")",
":",
"bits_len",
"=",
"bits_len",
"or",
"self",
".",
"_bits_random",
"return",
"random",
"(",
")",
".",
"getrandbits",
"(",
"bits_len",
")"
] | 28.5 | 0.008511 |
def from_raw(self, raw: RawScalar) -> Optional[bytes]:
"""Override superclass method."""
try:
return base64.b64decode(raw, validate=True)
except TypeError:
return None | [
"def",
"from_raw",
"(",
"self",
",",
"raw",
":",
"RawScalar",
")",
"->",
"Optional",
"[",
"bytes",
"]",
":",
"try",
":",
"return",
"base64",
".",
"b64decode",
"(",
"raw",
",",
"validate",
"=",
"True",
")",
"except",
"TypeError",
":",
"return",
"None"
] | 35 | 0.009302 |
def transform_coords(self, width, height):
"""Return the current absolute (x, y) coordinates of
the tablet tool event, transformed to screen coordinates and
whether they have changed in this event.
Note:
On some devices, returned value may be negative or larger than
the width of the device. See `Out-of-b... | [
"def",
"transform_coords",
"(",
"self",
",",
"width",
",",
"height",
")",
":",
"x",
"=",
"self",
".",
"_libinput",
".",
"libinput_event_tablet_tool_get_x_transformed",
"(",
"self",
".",
"_handle",
",",
"width",
")",
"y",
"=",
"self",
".",
"_libinput",
".",
... | 38.346154 | 0.024462 |
def figure_grid(figures_grid,
row_heights=None,
column_widths=None,
row_spacing=0.15,
column_spacing=0.15,
share_xaxis=False,
share_yaxis=False):
"""
Construct a figure from a 2D grid of sub-figures
Parameters
... | [
"def",
"figure_grid",
"(",
"figures_grid",
",",
"row_heights",
"=",
"None",
",",
"column_widths",
"=",
"None",
",",
"row_spacing",
"=",
"0.15",
",",
"column_spacing",
"=",
"0.15",
",",
"share_xaxis",
"=",
"False",
",",
"share_yaxis",
"=",
"False",
")",
":",
... | 35.932584 | 0.000304 |
def scaled_data(self, data_class, x_range=None, y_range=None):
"""Scale `self.data` as appropriate for the given data encoding
(data_class) and return it.
An optional `y_range` -- a 2-tuple (lower, upper) -- can be
given to specify the y-axis bounds. If not given, the range is
i... | [
"def",
"scaled_data",
"(",
"self",
",",
"data_class",
",",
"x_range",
"=",
"None",
",",
"y_range",
"=",
"None",
")",
":",
"self",
".",
"scaled_data_class",
"=",
"data_class",
"# Determine the x-axis range for scaling.",
"if",
"x_range",
"is",
"None",
":",
"x_ran... | 38.212766 | 0.001086 |
def _mouse_pointer_moved(self, x, y):
'''GUI callback for mouse moved'''
self._namespace['MOUSEX'] = x
self._namespace['MOUSEY'] = y | [
"def",
"_mouse_pointer_moved",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"self",
".",
"_namespace",
"[",
"'MOUSEX'",
"]",
"=",
"x",
"self",
".",
"_namespace",
"[",
"'MOUSEY'",
"]",
"=",
"y"
] | 38.25 | 0.012821 |
def model_fields(model, allow_pk=False, only=None, exclude=None,
field_args=None, converter=None):
"""
Generate a dictionary of fields for a given Peewee model.
See `model_form` docstring for description of parameters.
"""
converter = converter or ModelConverter()
field_args = ... | [
"def",
"model_fields",
"(",
"model",
",",
"allow_pk",
"=",
"False",
",",
"only",
"=",
"None",
",",
"exclude",
"=",
"None",
",",
"field_args",
"=",
"None",
",",
"converter",
"=",
"None",
")",
":",
"converter",
"=",
"converter",
"or",
"ModelConverter",
"("... | 29.571429 | 0.00117 |
def map_model(self, new):
""" Maps a domain model to the diagram """
logger.debug("Mapping the domain model!")
dot = Dot()
self.diagram.clear_canvas()
for node_mapping in self.nodes:
ct = node_mapping.containment_trait
logger.debug("Mapping elements con... | [
"def",
"map_model",
"(",
"self",
",",
"new",
")",
":",
"logger",
".",
"debug",
"(",
"\"Mapping the domain model!\"",
")",
"dot",
"=",
"Dot",
"(",
")",
"self",
".",
"diagram",
".",
"clear_canvas",
"(",
")",
"for",
"node_mapping",
"in",
"self",
".",
"nodes... | 40.95082 | 0.002346 |
def clean_up(self):
"""Do clean-up before returning buffer"""
self.action_buffer = []
self.sources = {}
self.doc_to_get = {}
self.doc_to_update = [] | [
"def",
"clean_up",
"(",
"self",
")",
":",
"self",
".",
"action_buffer",
"=",
"[",
"]",
"self",
".",
"sources",
"=",
"{",
"}",
"self",
".",
"doc_to_get",
"=",
"{",
"}",
"self",
".",
"doc_to_update",
"=",
"[",
"]"
] | 30.5 | 0.010638 |
def usernames(
self
):
"""
This function returns the list of unique usernames corresponding to the
tweets stored in self.
"""
try:
return list(set([tweet.username for tweet in self]))
except:
log.error("error -- possibly a problem w... | [
"def",
"usernames",
"(",
"self",
")",
":",
"try",
":",
"return",
"list",
"(",
"set",
"(",
"[",
"tweet",
".",
"username",
"for",
"tweet",
"in",
"self",
"]",
")",
")",
"except",
":",
"log",
".",
"error",
"(",
"\"error -- possibly a problem with tweets stored... | 29.909091 | 0.00885 |
def parser():
"""Parse command line arguments, validate them, and return them."""
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('-r', '--read-only', action='store_true',
help='open notmuch database in read-only mode')
parser.add_argument('-c', '--config', m... | [
"def",
"parser",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"add_help",
"=",
"False",
")",
"parser",
".",
"add_argument",
"(",
"'-r'",
",",
"'--read-only'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'open notmuch datab... | 53.719298 | 0.000321 |
def check_collections_are_supported(saved_model_handler, supported):
"""Checks that SavedModelHandler only uses supported collections."""
for meta_graph in saved_model_handler.meta_graphs:
used_collection_keys = set(meta_graph.collection_def.keys())
unsupported = used_collection_keys - supported
if unsu... | [
"def",
"check_collections_are_supported",
"(",
"saved_model_handler",
",",
"supported",
")",
":",
"for",
"meta_graph",
"in",
"saved_model_handler",
".",
"meta_graphs",
":",
"used_collection_keys",
"=",
"set",
"(",
"meta_graph",
".",
"collection_def",
".",
"keys",
"(",... | 58.666667 | 0.009328 |
def reorder_sonos_playlist(self, sonos_playlist, tracks, new_pos,
update_id=0):
"""Reorder and/or Remove tracks in a Sonos playlist.
The underlying call is quite complex as it can both move a track
within the list or delete a track from the playlist. All of this
... | [
"def",
"reorder_sonos_playlist",
"(",
"self",
",",
"sonos_playlist",
",",
"tracks",
",",
"new_pos",
",",
"update_id",
"=",
"0",
")",
":",
"# allow either a string 'SQ:10' or an object with item_id attribute.",
"object_id",
"=",
"getattr",
"(",
"sonos_playlist",
",",
"'i... | 46.043103 | 0.00055 |
def industry_code(self):
"""
[str] 国民经济行业分类代码,具体可参考“Industry列表” (股票专用)
"""
try:
return self.__dict__["industry_code"]
except (KeyError, ValueError):
raise AttributeError(
"Instrument(order_book_id={}) has no attribute 'industry_code' ".form... | [
"def",
"industry_code",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"__dict__",
"[",
"\"industry_code\"",
"]",
"except",
"(",
"KeyError",
",",
"ValueError",
")",
":",
"raise",
"AttributeError",
"(",
"\"Instrument(order_book_id={}) has no attribute 'ind... | 34.7 | 0.008427 |
def change_active_widget(self, index):
"""
This is implemented for handling negative values in index for
3d arrays, to give the same behavior as slicing
"""
string_index = [':']*3
string_index[self.last_dim] = '<font color=red>%i</font>'
self.slicing_label.... | [
"def",
"change_active_widget",
"(",
"self",
",",
"index",
")",
":",
"string_index",
"=",
"[",
"':'",
"]",
"*",
"3",
"string_index",
"[",
"self",
".",
"last_dim",
"]",
"=",
"'<font color=red>%i</font>'",
"self",
".",
"slicing_label",
".",
"setText",
"(",
"(",... | 44.37037 | 0.002451 |
def _TerminateProcessByPid(self, pid):
"""Terminate a process that's monitored by the engine.
Args:
pid (int): process identifier (PID).
Raises:
KeyError: if the process is not registered with and monitored by the
engine.
"""
self._RaiseIfNotRegistered(pid)
process = sel... | [
"def",
"_TerminateProcessByPid",
"(",
"self",
",",
"pid",
")",
":",
"self",
".",
"_RaiseIfNotRegistered",
"(",
"pid",
")",
"process",
"=",
"self",
".",
"_processes_per_pid",
"[",
"pid",
"]",
"self",
".",
"_TerminateProcess",
"(",
"process",
")",
"self",
".",... | 25.5 | 0.002364 |
def inverted(self):
"""
Returns an inverted copy of this query.
:return <orb.Query>
"""
out = self.copy()
out.setInverted(not self.isInverted())
return out | [
"def",
"inverted",
"(",
"self",
")",
":",
"out",
"=",
"self",
".",
"copy",
"(",
")",
"out",
".",
"setInverted",
"(",
"not",
"self",
".",
"isInverted",
"(",
")",
")",
"return",
"out"
] | 23.111111 | 0.009259 |
def get_interfaces(impls):
"""Get interfaces from their implementations."""
if impls is None:
return None
elif isinstance(impls, OrderMixin):
result = OrderedDict()
for name in impls.order:
result[name] = impls[name].interface
return result
elif isinstance(i... | [
"def",
"get_interfaces",
"(",
"impls",
")",
":",
"if",
"impls",
"is",
"None",
":",
"return",
"None",
"elif",
"isinstance",
"(",
"impls",
",",
"OrderMixin",
")",
":",
"result",
"=",
"OrderedDict",
"(",
")",
"for",
"name",
"in",
"impls",
".",
"order",
":... | 26.894737 | 0.00189 |
def attrdict(prev, attr_names):
"""attrdict pipe can extract attribute values of object into a dict.
The argument attr_names can be a list or a dict.
If attr_names is a list and its item is not a valid attribute of
prev's object. It will be excluded from yielded dict.
If attr_names is dict and th... | [
"def",
"attrdict",
"(",
"prev",
",",
"attr_names",
")",
":",
"if",
"isinstance",
"(",
"attr_names",
",",
"dict",
")",
":",
"for",
"obj",
"in",
"prev",
":",
"attr_values",
"=",
"dict",
"(",
")",
"for",
"name",
"in",
"attr_names",
".",
"keys",
"(",
")"... | 35.787879 | 0.000824 |
def valid_email(emailaddress, domains=GENERIC_DOMAINS):
"""Checks for a syntactically valid email address."""
# Email address must be at least 6 characters in total.
# Assuming noone may have addresses of the type a@com
if len(emailaddress) < 6:
return False # Address too short.
# Split u... | [
"def",
"valid_email",
"(",
"emailaddress",
",",
"domains",
"=",
"GENERIC_DOMAINS",
")",
":",
"# Email address must be at least 6 characters in total.",
"# Assuming noone may have addresses of the type a@com",
"if",
"len",
"(",
"emailaddress",
")",
"<",
"6",
":",
"return",
"... | 32.821429 | 0.001057 |
def xpointerNewRange(self, startindex, end, endindex):
"""Create a new xmlXPathObjectPtr of type range """
if end is None: end__o = None
else: end__o = end._o
ret = libxml2mod.xmlXPtrNewRange(self._o, startindex, end__o, endindex)
if ret is None:raise treeError('xmlXPtrNewRange()... | [
"def",
"xpointerNewRange",
"(",
"self",
",",
"startindex",
",",
"end",
",",
"endindex",
")",
":",
"if",
"end",
"is",
"None",
":",
"end__o",
"=",
"None",
"else",
":",
"end__o",
"=",
"end",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlXPtrNewRange",
"("... | 51.142857 | 0.016484 |
def population_counts(
self,
population_size,
weighted=True,
include_missing=False,
include_transforms_for_dims=None,
prune=False,
):
"""Return counts scaled in proportion to overall population.
The return value is a numpy.ndarray object. Count values... | [
"def",
"population_counts",
"(",
"self",
",",
"population_size",
",",
"weighted",
"=",
"True",
",",
"include_missing",
"=",
"False",
",",
"include_transforms_for_dims",
"=",
"None",
",",
"prune",
"=",
"False",
",",
")",
":",
"population_counts",
"=",
"[",
"sli... | 31.931818 | 0.002072 |
def _needs_update(self):
'Returns whether the ProgressBar should redraw the line.'
if self.poll_interval:
delta = timeit.default_timer() - self._last_update_timer
poll_status = delta > self.poll_interval.total_seconds()
else:
delta = 0
poll_status... | [
"def",
"_needs_update",
"(",
"self",
")",
":",
"if",
"self",
".",
"poll_interval",
":",
"delta",
"=",
"timeit",
".",
"default_timer",
"(",
")",
"-",
"self",
".",
"_last_update_timer",
"poll_status",
"=",
"delta",
">",
"self",
".",
"poll_interval",
".",
"to... | 35.166667 | 0.002307 |
def expand_benchmark_name(bm_name, bench_groups):
"""Recursively expand name benchmark names.
Args:
bm_name: string naming a benchmark or benchmark group.
Yields:
Names of actual benchmarks, with all group names fully expanded.
"""
expansion = bench_groups.get(bm_name)
if expan... | [
"def",
"expand_benchmark_name",
"(",
"bm_name",
",",
"bench_groups",
")",
":",
"expansion",
"=",
"bench_groups",
".",
"get",
"(",
"bm_name",
")",
"if",
"expansion",
":",
"for",
"name",
"in",
"expansion",
":",
"for",
"name",
"in",
"expand_benchmark_name",
"(",
... | 29.1875 | 0.002075 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.