text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def _get_serialize_func(self, name, spec):
""" Return the function that is used for serialization. """
func = getattr(self, 'serialize_' + name, None)
if func:
# this factory has a special serializer function for this field
return func
func = getattr(spec.fields[n... | [
"def",
"_get_serialize_func",
"(",
"self",
",",
"name",
",",
"spec",
")",
":",
"func",
"=",
"getattr",
"(",
"self",
",",
"'serialize_'",
"+",
"name",
",",
"None",
")",
"if",
"func",
":",
"# this factory has a special serializer function for this field",
"return",
... | 42.8 | 16.5 |
def contribute_to_class(self, cls, name, **kwargs):
"""
Called at class type creation. So, this method is called, when
metaclasses get created
"""
# TODO: Apply 3 edge cases when not to create an intermediary model
# specified in django.db.models.fields.related:1566
... | [
"def",
"contribute_to_class",
"(",
"self",
",",
"cls",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO: Apply 3 edge cases when not to create an intermediary model",
"# specified in django.db.models.fields.related:1566",
"# self.rel.through needs to be set prior to calling su... | 48.9375 | 18.375 |
def appendBlocks(self, blocks):
'''
appendBlocks - Append blocks to this element. A block can be a string (text node), or an AdvancedTag (tag node)
@param blocks list<str/AdvancedTag> - A list, in order to append, of blocks to add.
@return - #blocks
NOTE: To ad... | [
"def",
"appendBlocks",
"(",
"self",
",",
"blocks",
")",
":",
"for",
"block",
"in",
"blocks",
":",
"if",
"isinstance",
"(",
"block",
",",
"AdvancedTag",
")",
":",
"self",
".",
"appendNode",
"(",
"block",
")",
"else",
":",
"self",
".",
"appendText",
"(",... | 36.055556 | 28.944444 |
def correspondence(soup):
"""
Find the corresp tags included in author-notes
for primary correspondence
"""
correspondence = []
author_notes_nodes = raw_parser.author_notes(soup)
if author_notes_nodes:
corresp_nodes = raw_parser.corresp(author_notes_nodes)
for tag in corres... | [
"def",
"correspondence",
"(",
"soup",
")",
":",
"correspondence",
"=",
"[",
"]",
"author_notes_nodes",
"=",
"raw_parser",
".",
"author_notes",
"(",
"soup",
")",
"if",
"author_notes_nodes",
":",
"corresp_nodes",
"=",
"raw_parser",
".",
"corresp",
"(",
"author_not... | 25.666667 | 16.466667 |
def _neighbors(coordinate, radius):
"""
Returns coordinates around given coordinate, within given radius.
Includes given coordinate.
@param coordinate (numpy.array) N-dimensional integer coordinate
@param radius (int) Radius around `coordinate`
@return (numpy.array) List of coordinates
"""... | [
"def",
"_neighbors",
"(",
"coordinate",
",",
"radius",
")",
":",
"ranges",
"=",
"(",
"xrange",
"(",
"n",
"-",
"radius",
",",
"n",
"+",
"radius",
"+",
"1",
")",
"for",
"n",
"in",
"coordinate",
".",
"tolist",
"(",
")",
")",
"return",
"numpy",
".",
... | 36.583333 | 17.916667 |
def _parse(self, threshold):
"""
internal threshold string parser
arguments:
threshold: string describing the threshold
"""
match = re.search(r'^(@?)((~|\d*):)?(\d*)$', threshold)
if not match:
raise ValueError('Error parsing Threshold: {0}'.form... | [
"def",
"_parse",
"(",
"self",
",",
"threshold",
")",
":",
"match",
"=",
"re",
".",
"search",
"(",
"r'^(@?)((~|\\d*):)?(\\d*)$'",
",",
"threshold",
")",
"if",
"not",
"match",
":",
"raise",
"ValueError",
"(",
"'Error parsing Threshold: {0}'",
".",
"format",
"(",... | 27.275862 | 17.896552 |
def _vgg16_data_prep(batch):
"""
Takes images scaled to [0, 1] and returns them appropriately scaled and
mean-subtracted for VGG-16
"""
from mxnet import nd
mean = nd.array([123.68, 116.779, 103.939], ctx=batch.context)
return nd.broadcast_sub(255 * batch, mean.reshape((-1, 1, 1))) | [
"def",
"_vgg16_data_prep",
"(",
"batch",
")",
":",
"from",
"mxnet",
"import",
"nd",
"mean",
"=",
"nd",
".",
"array",
"(",
"[",
"123.68",
",",
"116.779",
",",
"103.939",
"]",
",",
"ctx",
"=",
"batch",
".",
"context",
")",
"return",
"nd",
".",
"broadca... | 37.875 | 15.625 |
def _read_state_variables(self):
"""
Reads the stateVariable information from the xml-file.
The information we like to extract are name and dataType so we
can assign them later on to FritzActionArgument-instances.
Returns a dictionary: key:value = name:dataType
"""
... | [
"def",
"_read_state_variables",
"(",
"self",
")",
":",
"nodes",
"=",
"self",
".",
"root",
".",
"iterfind",
"(",
"'.//ns:stateVariable'",
",",
"namespaces",
"=",
"{",
"'ns'",
":",
"self",
".",
"namespace",
"}",
")",
"for",
"node",
"in",
"nodes",
":",
"key... | 46 | 14.615385 |
def _has_valid_catchup_replies(self, seq_no: int, txns_to_process: List[Tuple[int, Any]]) -> Tuple[bool, str, int]:
"""
Transforms transactions for ledger!
Returns:
Whether catchup reply corresponding to seq_no
Name of node from which txns came
Number of tran... | [
"def",
"_has_valid_catchup_replies",
"(",
"self",
",",
"seq_no",
":",
"int",
",",
"txns_to_process",
":",
"List",
"[",
"Tuple",
"[",
"int",
",",
"Any",
"]",
"]",
")",
"->",
"Tuple",
"[",
"bool",
",",
"str",
",",
"int",
"]",
":",
"# TODO: Remove after sto... | 42.826923 | 22.75 |
def rooms_clean_history(self, room_id, latest, oldest, **kwargs):
"""Cleans up a room, removing messages from the provided time range."""
return self.__call_api_post('rooms.cleanHistory', roomId=room_id, latest=latest, oldest=oldest, kwargs=kwargs) | [
"def",
"rooms_clean_history",
"(",
"self",
",",
"room_id",
",",
"latest",
",",
"oldest",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"__call_api_post",
"(",
"'rooms.cleanHistory'",
",",
"roomId",
"=",
"room_id",
",",
"latest",
"=",
"latest",
... | 87.333333 | 34.333333 |
def add_abbreviation(self, new_abbreviation):
"""
Adds a new name variant to an author.
:param new_abbreviation: the abbreviation to be added
:return: `True` if the abbreviation is added, `False` otherwise (the abbreviation is a duplicate)
"""
try:
assert new... | [
"def",
"add_abbreviation",
"(",
"self",
",",
"new_abbreviation",
")",
":",
"try",
":",
"assert",
"new_abbreviation",
"not",
"in",
"self",
".",
"get_abbreviations",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"# TODO: raise a custom exception",
"logger",
".",
... | 52.333333 | 28.333333 |
def add_magic_table_from_data(self, dtype, data):
"""
Add a MagIC table to the contribution from a data list
Parameters
----------
dtype : str
MagIC table type, i.e. 'specimens'
data : list of dicts
data list with format [{'key1': 'val1', ...}, {'... | [
"def",
"add_magic_table_from_data",
"(",
"self",
",",
"dtype",
",",
"data",
")",
":",
"self",
".",
"tables",
"[",
"dtype",
"]",
"=",
"MagicDataFrame",
"(",
"dtype",
"=",
"dtype",
",",
"data",
"=",
"data",
")",
"if",
"dtype",
"==",
"'measurements'",
":",
... | 36.333333 | 16.466667 |
def visit_FunctionCall(self, node):
"""Visitor for `FunctionCall` AST node."""
call = self.memory[node.identifier.name]._node
args = [self.visit(parameter) for parameter in node.parameters]
if isinstance(call, AST):
current_scope = self.memory.stack.current.current
... | [
"def",
"visit_FunctionCall",
"(",
"self",
",",
"node",
")",
":",
"call",
"=",
"self",
".",
"memory",
"[",
"node",
".",
"identifier",
".",
"name",
"]",
".",
"_node",
"args",
"=",
"[",
"self",
".",
"visit",
"(",
"parameter",
")",
"for",
"parameter",
"i... | 33.961538 | 16.038462 |
def ascii_tree(self, no_types: bool = False, val_count: bool = False) -> str:
"""Generate ASCII art representation of the schema tree.
Args:
no_types: Suppress output of data type info.
val_count: Show accumulated validation counts.
Returns:
String with the ... | [
"def",
"ascii_tree",
"(",
"self",
",",
"no_types",
":",
"bool",
"=",
"False",
",",
"val_count",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"return",
"self",
".",
"schema",
".",
"_ascii_tree",
"(",
"\"\"",
",",
"no_types",
",",
"val_count",
")"
] | 36.090909 | 20.545455 |
def _update_targets(vesseldicts, environment_dict):
"""
<Purpose>
Connects to the nodes in the vesseldicts and adds them to the list
of valid targets.
<Arguments>
vesseldicts:
A list of vesseldicts obtained through
SeattleClearinghouseClient calls.
<Side Effects>
All valid targ... | [
"def",
"_update_targets",
"(",
"vesseldicts",
",",
"environment_dict",
")",
":",
"# Compile a list of the nodes that we need to check",
"nodelist",
"=",
"[",
"]",
"for",
"vesseldict",
"in",
"vesseldicts",
":",
"nodeip_port",
"=",
"vesseldict",
"[",
"'node_ip'",
"]",
"... | 28.278689 | 21.491803 |
def partial_regardless(self, fn, *a, **kw):
"""Like `partial`, but applies if callable is not annotated."""
if self.has_annotations(fn):
return self.partial(fn, *a, **kw)
else:
return functools.partial(fn, *a, **kw) | [
"def",
"partial_regardless",
"(",
"self",
",",
"fn",
",",
"*",
"a",
",",
"*",
"*",
"kw",
")",
":",
"if",
"self",
".",
"has_annotations",
"(",
"fn",
")",
":",
"return",
"self",
".",
"partial",
"(",
"fn",
",",
"*",
"a",
",",
"*",
"*",
"kw",
")",
... | 43 | 8.166667 |
def run(request, callable, *args, **kwargs):
'''Execute a python *callable*.'''
return callable(request.actor, *args, **kwargs) | [
"def",
"run",
"(",
"request",
",",
"callable",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"callable",
"(",
"request",
".",
"actor",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 44.333333 | 5.666667 |
def post(self, url, params={}, files=None):
"""
Issues a POST request against the API, allows for multipart data uploads
:param url: a string, the url you are requesting
:param params: a dict, the key-value of all the parameters needed
in the request
:para... | [
"def",
"post",
"(",
"self",
",",
"url",
",",
"params",
"=",
"{",
"}",
",",
"files",
"=",
"None",
")",
":",
"params",
".",
"update",
"(",
"{",
"'api_key'",
":",
"self",
".",
"api_key",
"}",
")",
"try",
":",
"response",
"=",
"requests",
".",
"post"... | 40.588235 | 17.411765 |
def set_terminate_listeners(stream):
"""Die on SIGTERM or SIGINT"""
def stop(signum, frame):
terminate(stream.listener)
# Installs signal handlers for handling SIGINT and SIGTERM
# gracefully.
signal.signal(signal.SIGINT, stop)
signal.signal(signal.SIGTERM, stop) | [
"def",
"set_terminate_listeners",
"(",
"stream",
")",
":",
"def",
"stop",
"(",
"signum",
",",
"frame",
")",
":",
"terminate",
"(",
"stream",
".",
"listener",
")",
"# Installs signal handlers for handling SIGINT and SIGTERM",
"# gracefully.",
"signal",
".",
"signal",
... | 28.8 | 15 |
def update_product_set(
self,
product_set,
location=None,
product_set_id=None,
update_mask=None,
project_id=None,
retry=None,
timeout=None,
metadata=None,
):
"""
For the documentation see:
:class:`~airflow.contrib.operat... | [
"def",
"update_product_set",
"(",
"self",
",",
"product_set",
",",
"location",
"=",
"None",
",",
"product_set_id",
"=",
"None",
",",
"update_mask",
"=",
"None",
",",
"project_id",
"=",
"None",
",",
"retry",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
... | 37.076923 | 22 |
def read_namespaced_replication_controller_dummy_scale(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_replication_controller_dummy_scale # noqa: E501
read scale of the specified ReplicationControllerDummy # noqa: E501
This method makes a synchronous HTTP request by default... | [
"def",
"read_namespaced_replication_controller_dummy_scale",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",... | 57.086957 | 29.695652 |
def guess_mime_file_mime (file_prog, filename):
"""Determine MIME type of filename with file(1) and --mime option.
@return: tuple (mime, encoding)
"""
mime, encoding = None, None
cmd = [file_prog, "--brief", "--mime-type", filename]
try:
mime = backtick(cmd).strip()
except OSError:
... | [
"def",
"guess_mime_file_mime",
"(",
"file_prog",
",",
"filename",
")",
":",
"mime",
",",
"encoding",
"=",
"None",
",",
"None",
"cmd",
"=",
"[",
"file_prog",
",",
"\"--brief\"",
",",
"\"--mime-type\"",
",",
"filename",
"]",
"try",
":",
"mime",
"=",
"backtic... | 33.714286 | 11.5 |
def select_best_candidate(candidate_models):
""" Select and return the best candidate model based on r-squared and
qualification.
Parameters
----------
candidate_models : :any:`list` of :any:`eemeter.CalTRACKUsagePerDayCandidateModel`
Candidate models to select from.
Returns
------... | [
"def",
"select_best_candidate",
"(",
"candidate_models",
")",
":",
"best_r_squared_adj",
"=",
"-",
"np",
".",
"inf",
"best_candidate",
"=",
"None",
"# CalTrack 3.4.3.3",
"for",
"candidate",
"in",
"candidate_models",
":",
"if",
"(",
"candidate",
".",
"status",
"=="... | 35.113636 | 23.613636 |
def block_username(username):
""" given the username block it. """
if not username:
# no reason to continue when there is no username
return
if config.DISABLE_USERNAME_LOCKOUT:
# no need to block, we disabled it.
return
key = get_username_blocked_cache_key(username)
i... | [
"def",
"block_username",
"(",
"username",
")",
":",
"if",
"not",
"username",
":",
"# no reason to continue when there is no username",
"return",
"if",
"config",
".",
"DISABLE_USERNAME_LOCKOUT",
":",
"# no need to block, we disabled it.",
"return",
"key",
"=",
"get_username_... | 34.5 | 12.785714 |
def fill_login_form(self, username, username_field, user_password,
user_password_field):
"""Fills form with login info
:param username: user login
:param username_field: name of field to fill with username
:param user_password: login password
:param user_... | [
"def",
"fill_login_form",
"(",
"self",
",",
"username",
",",
"username_field",
",",
"user_password",
",",
"user_password_field",
")",
":",
"self",
".",
"fill_form_field",
"(",
"username_field",
",",
"username",
")",
"# set username",
"self",
".",
"fill_form_field",
... | 46.727273 | 17.818182 |
def _is_actual_elif(self, node):
"""Check if the given node is an actual elif
This is a problem we're having with the builtin ast module,
which splits `elif` branches into a separate if statement.
Unfortunately we need to know the exact type in certain
cases.
"""
... | [
"def",
"_is_actual_elif",
"(",
"self",
",",
"node",
")",
":",
"if",
"isinstance",
"(",
"node",
".",
"parent",
",",
"astroid",
".",
"If",
")",
":",
"orelse",
"=",
"node",
".",
"parent",
".",
"orelse",
"# current if node must directly follow an \"else\"",
"if",
... | 40.666667 | 15.666667 |
def MAU(self):
'''Result of preconditioned operator to deflation space, i.e.,
:math:`MM_lAM_rU`.'''
if self._MAU is None:
self._MAU = self.linear_system.M * self.AU
return self._MAU | [
"def",
"MAU",
"(",
"self",
")",
":",
"if",
"self",
".",
"_MAU",
"is",
"None",
":",
"self",
".",
"_MAU",
"=",
"self",
".",
"linear_system",
".",
"M",
"*",
"self",
".",
"AU",
"return",
"self",
".",
"_MAU"
] | 36.666667 | 18 |
def box_score(game_id):
"""Gets the box score information for the game with matching id."""
# get data
data = mlbgame.data.get_box_score(game_id)
# parse data
parsed = etree.parse(data)
root = parsed.getroot()
linescore = root.find('linescore')
result = dict()
result['game_id'] = gam... | [
"def",
"box_score",
"(",
"game_id",
")",
":",
"# get data",
"data",
"=",
"mlbgame",
".",
"data",
".",
"get_box_score",
"(",
"game_id",
")",
"# parse data",
"parsed",
"=",
"etree",
".",
"parse",
"(",
"data",
")",
"root",
"=",
"parsed",
".",
"getroot",
"("... | 34.529412 | 12.352941 |
def render_template(template_in, file_out, context):
"""
_render_template_
Render a single template file, using the context provided
and write the file out to the location specified
#TODO: verify the template is completely rendered, no
missing values
"""
renderer = pystache.Rendere... | [
"def",
"render_template",
"(",
"template_in",
",",
"file_out",
",",
"context",
")",
":",
"renderer",
"=",
"pystache",
".",
"Renderer",
"(",
")",
"result",
"=",
"renderer",
".",
"render_path",
"(",
"template_in",
",",
"context",
")",
"with",
"open",
"(",
"f... | 32.235294 | 16.941176 |
def visit_keyword(self, node):
"""return an astroid.Keyword node as string"""
if node.arg is None:
return "**%s" % node.value.accept(self)
return "%s=%s" % (node.arg, node.value.accept(self)) | [
"def",
"visit_keyword",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
".",
"arg",
"is",
"None",
":",
"return",
"\"**%s\"",
"%",
"node",
".",
"value",
".",
"accept",
"(",
"self",
")",
"return",
"\"%s=%s\"",
"%",
"(",
"node",
".",
"arg",
",",
"no... | 44.6 | 10.6 |
def get_lead(self, lead_id):
"""
Get a specific lead saved on your account.
:param lead_id: Id of the lead to search. Must be defined.
:return: Lead found as a dict.
"""
params = self.base_params
endpoint = self.base_endpoint.format('leads/' + str(lead_id))
... | [
"def",
"get_lead",
"(",
"self",
",",
"lead_id",
")",
":",
"params",
"=",
"self",
".",
"base_params",
"endpoint",
"=",
"self",
".",
"base_endpoint",
".",
"format",
"(",
"'leads/'",
"+",
"str",
"(",
"lead_id",
")",
")",
"return",
"self",
".",
"_query_hunte... | 27.461538 | 19.769231 |
def obspy_3d_plot(inventory, catalog, size=(10.5, 7.5), **kwargs):
"""
Plot obspy Inventory and obspy Catalog classes in three dimensions.
:type inventory: obspy.core.inventory.inventory.Inventory
:param inventory: Obspy inventory class containing station metadata
:type catalog: obspy.core.event.ca... | [
"def",
"obspy_3d_plot",
"(",
"inventory",
",",
"catalog",
",",
"size",
"=",
"(",
"10.5",
",",
"7.5",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"nodes",
"=",
"[",
"]",
"for",
"ev",
"in",
"catalog",
":",
"nodes",
".",
"append",
"(",
"(",
"ev",
".",
... | 42.268657 | 20.835821 |
def post(self):
"""
Post processing for solved systems.
Store load, generation data on buses.
Store reactive power generation on PVs and slack generators.
Calculate series flows and area flows.
Returns
-------
None
"""
if not self.solved:... | [
"def",
"post",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"solved",
":",
"return",
"system",
"=",
"self",
".",
"system",
"exec",
"(",
"system",
".",
"call",
".",
"pfload",
")",
"system",
".",
"Bus",
".",
"Pl",
"=",
"system",
".",
"dae",
"."... | 26.382353 | 18.970588 |
def prompt_yn(stmt):
'''Prints the statement stmt to the terminal and wait for a Y or N answer.
Returns True for 'Y', False for 'N'.'''
print(stmt)
answer = ''
while answer not in ['Y', 'N']:
sys.stdout.write("$ ")
answer = sys.stdin.readline().upper().strip()
return answer ==... | [
"def",
"prompt_yn",
"(",
"stmt",
")",
":",
"print",
"(",
"stmt",
")",
"answer",
"=",
"''",
"while",
"answer",
"not",
"in",
"[",
"'Y'",
",",
"'N'",
"]",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"\"$ \"",
")",
"answer",
"=",
"sys",
".",
"stdin... | 35.111111 | 17.555556 |
def draw_rect(setter, x, y, w, h, color=None, aa=False):
"""Draw rectangle with top-left corner at x,y, width w and height h"""
_draw_fast_hline(setter, x, y, w, color, aa)
_draw_fast_hline(setter, x, y + h - 1, w, color, aa)
_draw_fast_vline(setter, x, y, h, color, aa)
_draw_fast_vline(setter, x + ... | [
"def",
"draw_rect",
"(",
"setter",
",",
"x",
",",
"y",
",",
"w",
",",
"h",
",",
"color",
"=",
"None",
",",
"aa",
"=",
"False",
")",
":",
"_draw_fast_hline",
"(",
"setter",
",",
"x",
",",
"y",
",",
"w",
",",
"color",
",",
"aa",
")",
"_draw_fast_... | 56.333333 | 10.666667 |
def preorder_iter(expression):
"""Iterate over the expression in preorder."""
yield expression
if isinstance(expression, Operation):
for operand in op_iter(expression):
yield from preorder_iter(operand) | [
"def",
"preorder_iter",
"(",
"expression",
")",
":",
"yield",
"expression",
"if",
"isinstance",
"(",
"expression",
",",
"Operation",
")",
":",
"for",
"operand",
"in",
"op_iter",
"(",
"expression",
")",
":",
"yield",
"from",
"preorder_iter",
"(",
"operand",
"... | 38.166667 | 6.5 |
def _start_payloads(self):
"""Start all queued payloads"""
with self._lock:
payloads = self._payloads.copy()
self._payloads.clear()
for subroutine in payloads:
thread = CapturingThread(target=subroutine)
thread.start()
self._threads.add... | [
"def",
"_start_payloads",
"(",
"self",
")",
":",
"with",
"self",
".",
"_lock",
":",
"payloads",
"=",
"self",
".",
"_payloads",
".",
"copy",
"(",
")",
"self",
".",
"_payloads",
".",
"clear",
"(",
")",
"for",
"subroutine",
"in",
"payloads",
":",
"thread"... | 36.272727 | 10.363636 |
def make_dataloader(data_train, data_val, data_test, args,
use_average_length=False, num_shards=0, num_workers=8):
"""Create data loaders for training/validation/test."""
data_train_lengths = get_data_lengths(data_train)
data_val_lengths = get_data_lengths(data_val)
data_test_lengths... | [
"def",
"make_dataloader",
"(",
"data_train",
",",
"data_val",
",",
"data_test",
",",
"args",
",",
"use_average_length",
"=",
"False",
",",
"num_shards",
"=",
"0",
",",
"num_workers",
"=",
"8",
")",
":",
"data_train_lengths",
"=",
"get_data_lengths",
"(",
"data... | 67.216667 | 29.6 |
def codes_get_api_version():
"""
Get the API version.
Returns the version of the API as a string in the format "major.minor.revision".
"""
ver = lib.codes_get_api_version()
patch = ver % 100
ver = ver // 100
minor = ver % 100
major = ver // 100
return "%d.%d.%d" % (major, minor... | [
"def",
"codes_get_api_version",
"(",
")",
":",
"ver",
"=",
"lib",
".",
"codes_get_api_version",
"(",
")",
"patch",
"=",
"ver",
"%",
"100",
"ver",
"=",
"ver",
"//",
"100",
"minor",
"=",
"ver",
"%",
"100",
"major",
"=",
"ver",
"//",
"100",
"return",
"\... | 24.307692 | 18.153846 |
def soft_kill(jid, state_id=None):
'''
Set up a state run to die before executing the given state id,
this instructs a running state to safely exit at a given
state id. This needs to pass in the jid of the running state.
If a state_id is not passed then the jid referenced will be safely exited
a... | [
"def",
"soft_kill",
"(",
"jid",
",",
"state_id",
"=",
"None",
")",
":",
"minion",
"=",
"salt",
".",
"minion",
".",
"MasterMinion",
"(",
"__opts__",
")",
"minion",
".",
"functions",
"[",
"'state.soft_kill'",
"]",
"(",
"jid",
",",
"state_id",
")"
] | 46 | 20.4 |
def write_multiple_registers(self, regs_addr, regs_value):
"""Modbus function WRITE_MULTIPLE_REGISTERS (0x10)
:param regs_addr: registers address (0 to 65535)
:type regs_addr: int
:param regs_value: registers values to write
:type regs_value: list
:returns: True if write... | [
"def",
"write_multiple_registers",
"(",
"self",
",",
"regs_addr",
",",
"regs_value",
")",
":",
"# number of registers to write",
"regs_nb",
"=",
"len",
"(",
"regs_value",
")",
"# check params",
"if",
"not",
"(",
"0x0000",
"<=",
"int",
"(",
"regs_addr",
")",
"<="... | 39.45614 | 15.964912 |
def nvmlDeviceGetPowerManagementMode(handle):
r"""
/**
* This API has been deprecated.
*
* Retrieves the power management mode associated with this device.
*
* For products from the Fermi family.
* - Requires \a NVML_INFOROM_POWER version 3.0 or higher.
*
* For from t... | [
"def",
"nvmlDeviceGetPowerManagementMode",
"(",
"handle",
")",
":",
"c_pcapMode",
"=",
"_nvmlEnableState_t",
"(",
")",
"fn",
"=",
"_nvmlGetFunctionPointer",
"(",
"\"nvmlDeviceGetPowerManagementMode\"",
")",
"ret",
"=",
"fn",
"(",
"handle",
",",
"byref",
"(",
"c_pcap... | 48.891892 | 29.72973 |
def update_variables(func):
"""
Use this decorator on Step.action implementation.
Your action method should always return variables, or
both variables and output.
This decorator will update variables with output.
"""
@wraps(func)
def wrapper(self, *args, **kwargs):
result = f... | [
"def",
"update_variables",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"func",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
... | 25.55 | 18.85 |
def fit(pointlist):
'''
Parameters
pointlist
[[x0,y0], [x1,y1], [x2,y2], ...]
Points [None, None] are allowed but ignored.
'''
# Separate x and y and clear Nones
is_num = lambda x: isinstance(x, Number)
pick_x = lambda x: x[0]
pick_y = lambda x: x[1]
xs =... | [
"def",
"fit",
"(",
"pointlist",
")",
":",
"# Separate x and y and clear Nones",
"is_num",
"=",
"lambda",
"x",
":",
"isinstance",
"(",
"x",
",",
"Number",
")",
"pick_x",
"=",
"lambda",
"x",
":",
"x",
"[",
"0",
"]",
"pick_y",
"=",
"lambda",
"x",
":",
"x"... | 28.125 | 17.75 |
def connection_lost(self, exception):
"""Called when the connection is lost or closed.
The argument is either an exception object or None. The latter means
a regular EOF is received, or the connection was aborted or closed by
this side of the connection.
"""
if exception... | [
"def",
"connection_lost",
"(",
"self",
",",
"exception",
")",
":",
"if",
"exception",
":",
"self",
".",
"logger",
".",
"exception",
"(",
"'Connection lost!'",
")",
"else",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Connection lost'",
")"
] | 38.818182 | 16.909091 |
def collect_conflicts_within(
context: ValidationContext,
conflicts: List[Conflict],
cached_fields_and_fragment_names: Dict,
compared_fragment_pairs: "PairSet",
field_map: NodeAndDefCollection,
) -> None:
"""Collect all Conflicts "within" one collection of fields."""
# A field map is a keyed... | [
"def",
"collect_conflicts_within",
"(",
"context",
":",
"ValidationContext",
",",
"conflicts",
":",
"List",
"[",
"Conflict",
"]",
",",
"cached_fields_and_fragment_names",
":",
"Dict",
",",
"compared_fragment_pairs",
":",
"\"PairSet\"",
",",
"field_map",
":",
"NodeAndD... | 45.83871 | 15.83871 |
def simple_cythonize(src, destdir=None, cwd=None, logger=None,
full_module_name=None, only_update=False,
**cy_kwargs):
"""
Generates a C file from a Cython source file.
Parameters
----------
src: path string
path to Cython source
destdir: path s... | [
"def",
"simple_cythonize",
"(",
"src",
",",
"destdir",
"=",
"None",
",",
"cwd",
"=",
"None",
",",
"logger",
"=",
"None",
",",
"full_module_name",
"=",
"None",
",",
"only_update",
"=",
"False",
",",
"*",
"*",
"cy_kwargs",
")",
":",
"from",
"Cython",
"."... | 32.591549 | 17.943662 |
def _get(self, url, params=None):
"""Used by every other method, it makes a GET request with the given params.
Args:
url (str): relative path of a specific service (account_info, ...).
params (:obj:`dict`, optional): contains parameters to be sent in the GET request.
Re... | [
"def",
"_get",
"(",
"self",
",",
"url",
",",
"params",
"=",
"None",
")",
":",
"if",
"not",
"params",
":",
"params",
"=",
"{",
"}",
"params",
".",
"update",
"(",
"{",
"'login'",
":",
"self",
".",
"login",
",",
"'key'",
":",
"self",
".",
"key",
"... | 32.631579 | 26.894737 |
def recv_all_filtered(self, keycheck, tab_key, timeout=0.5):
'''
Receive a all messages matching a filter, using the callable `keycheck` to filter received messages
for content.
This function will *ALWAY* block for at least `timeout` seconds.
If chromium is for some reason continuously streaming responses, ... | [
"def",
"recv_all_filtered",
"(",
"self",
",",
"keycheck",
",",
"tab_key",
",",
"timeout",
"=",
"0.5",
")",
":",
"self",
".",
"__check_open_socket",
"(",
"tab_key",
")",
"# First, check if the message has already been received.",
"ret",
"=",
"[",
"tmp",
"for",
"tmp... | 31.270833 | 28.729167 |
def _get_model_objs_to_sync(model_ids_to_sync, model_objs_map, sync_all):
"""
Given the model IDs to sync, fetch all model objects to sync
"""
model_objs_to_sync = {}
for ctype, model_ids_to_sync_for_ctype in model_ids_to_sync.items():
model_qset = entity_registry.entity_registry.get(ctype.m... | [
"def",
"_get_model_objs_to_sync",
"(",
"model_ids_to_sync",
",",
"model_objs_map",
",",
"sync_all",
")",
":",
"model_objs_to_sync",
"=",
"{",
"}",
"for",
"ctype",
",",
"model_ids_to_sync_for_ctype",
"in",
"model_ids_to_sync",
".",
"items",
"(",
")",
":",
"model_qset... | 40 | 25.875 |
def generate_clickable_map(self):
# type: () -> unicode
"""Generate clickable map tags if clickable item exists.
If not exists, this only returns empty string.
"""
if self.clickable:
return '\n'.join([self.content[0]] + self.clickable + [self.content[-1]])
el... | [
"def",
"generate_clickable_map",
"(",
"self",
")",
":",
"# type: () -> unicode",
"if",
"self",
".",
"clickable",
":",
"return",
"'\\n'",
".",
"join",
"(",
"[",
"self",
".",
"content",
"[",
"0",
"]",
"]",
"+",
"self",
".",
"clickable",
"+",
"[",
"self",
... | 33.6 | 17.7 |
def terms(cls, tags, minimum_match=None):
'''
A query that match on any (configurable) of the provided terms. This is a simpler syntax query for using a bool query with several term queries in the should clauses. For example:
{
"terms" : {
"tags" : [ "blue", "pill" ]... | [
"def",
"terms",
"(",
"cls",
",",
"tags",
",",
"minimum_match",
"=",
"None",
")",
":",
"instance",
"=",
"cls",
"(",
"terms",
"=",
"{",
"'tags'",
":",
"tags",
"}",
")",
"if",
"minimum_match",
"is",
"not",
"None",
":",
"instance",
"[",
"'terms'",
"]",
... | 38.642857 | 26.785714 |
def load_data(self, table_name, obj, database=None, **kwargs):
"""
Wraps the LOAD DATA DDL statement. Loads data into an MapD table by
physically moving data files.
Parameters
----------
table_name : string
obj: pandas.DataFrame or pyarrow.Table
database ... | [
"def",
"load_data",
"(",
"self",
",",
"table_name",
",",
"obj",
",",
"database",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"_database",
"=",
"self",
".",
"db_name",
"self",
".",
"set_database",
"(",
"database",
")",
"self",
".",
"con",
".",
"lo... | 34.133333 | 13.6 |
def visitInlineShapeOr(self, ctx: ShExDocParser.InlineShapeOrContext):
""" inlineShapeOr: inlineShapeAnd (KW_OR inlineShapeAnd)* """
if len(ctx.inlineShapeAnd()) > 1:
self.expr = ShapeOr(id=self.label, shapeExprs=[])
for sa in ctx.inlineShapeAnd():
sep = ShexShape... | [
"def",
"visitInlineShapeOr",
"(",
"self",
",",
"ctx",
":",
"ShExDocParser",
".",
"InlineShapeOrContext",
")",
":",
"if",
"len",
"(",
"ctx",
".",
"inlineShapeAnd",
"(",
")",
")",
">",
"1",
":",
"self",
".",
"expr",
"=",
"ShapeOr",
"(",
"id",
"=",
"self"... | 48.5 | 13.2 |
def as_command(self):
"""Return a find command document for this query.
Should be called *after* get_message.
"""
if '$explain' in self.spec:
self.name = 'explain'
return _gen_explain_command(
self.coll, self.spec, self.fields, self.ntoskip,
... | [
"def",
"as_command",
"(",
"self",
")",
":",
"if",
"'$explain'",
"in",
"self",
".",
"spec",
":",
"self",
".",
"name",
"=",
"'explain'",
"return",
"_gen_explain_command",
"(",
"self",
".",
"coll",
",",
"self",
".",
"spec",
",",
"self",
".",
"fields",
","... | 40.333333 | 12.066667 |
def proof_req_attr_referents(proof_req: dict) -> dict:
"""
Given a proof request with all requested attributes having cred def id restrictions,
return its attribute referents by cred def id and attribute.
The returned structure can be useful in populating the extra WQL query parameter
in the creden... | [
"def",
"proof_req_attr_referents",
"(",
"proof_req",
":",
"dict",
")",
"->",
"dict",
":",
"rv",
"=",
"{",
"}",
"for",
"uuid",
",",
"spec",
"in",
"proof_req",
"[",
"'requested_attributes'",
"]",
".",
"items",
"(",
")",
":",
"cd_id",
"=",
"None",
"for",
... | 31.455696 | 20.696203 |
def read_namespaced_pod(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_pod # noqa: E501
read the specified Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread ... | [
"def",
"read_namespaced_pod",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"s... | 53.44 | 27.64 |
def add_directories(names):
"""Git/Mercurial/zip files omit directories, let's add them back."""
res = list(names)
seen = set(names)
for name in names:
while True:
name = os.path.dirname(name)
if not name or name in seen:
break
res.append(name)... | [
"def",
"add_directories",
"(",
"names",
")",
":",
"res",
"=",
"list",
"(",
"names",
")",
"seen",
"=",
"set",
"(",
"names",
")",
"for",
"name",
"in",
"names",
":",
"while",
"True",
":",
"name",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"name",
... | 29.916667 | 12.75 |
def toXml(self, xparent=None):
"""
Converts this object to XML.
:param xparent | <xml.etree.ElementTree.Element> || None
:return <xml.etree.ElementTree.Element>
"""
if xparent is None:
xml = ElementTree.Element('object')
else:
xm... | [
"def",
"toXml",
"(",
"self",
",",
"xparent",
"=",
"None",
")",
":",
"if",
"xparent",
"is",
"None",
":",
"xml",
"=",
"ElementTree",
".",
"Element",
"(",
"'object'",
")",
"else",
":",
"xml",
"=",
"ElementTree",
".",
"SubElement",
"(",
"xparent",
",",
"... | 31.842105 | 16.052632 |
def add_translation_field(self, field, translation_field):
"""
Add a new translation field to both fields dicts.
"""
self.local_fields[field].add(translation_field)
self.fields[field].add(translation_field) | [
"def",
"add_translation_field",
"(",
"self",
",",
"field",
",",
"translation_field",
")",
":",
"self",
".",
"local_fields",
"[",
"field",
"]",
".",
"add",
"(",
"translation_field",
")",
"self",
".",
"fields",
"[",
"field",
"]",
".",
"add",
"(",
"translatio... | 40.166667 | 9.833333 |
def get_archiver(self, kind):
"""
Returns instance of archiver class specific to given kind
:param kind: archive kind
"""
archivers = {
'tar': TarArchiver,
'tbz2': Tbz2Archiver,
'tgz': TgzArchiver,
'zip': ZipArchiver,
}
return archivers[kind]() | [
"def",
"get_archiver",
"(",
"self",
",",
"kind",
")",
":",
"archivers",
"=",
"{",
"'tar'",
":",
"TarArchiver",
",",
"'tbz2'",
":",
"Tbz2Archiver",
",",
"'tgz'",
":",
"TgzArchiver",
",",
"'zip'",
":",
"ZipArchiver",
",",
"}",
"return",
"archivers",
"[",
"... | 19.533333 | 18.866667 |
def build_top_graph(self,tokens):
""" Build a Godot graph instance from parsed data.
"""
# Get basic graph information.
strict = tokens[0] == 'strict'
graphtype = tokens[1]
directed = graphtype == 'digraph'
graphname = tokens[2]
# Build the graph
g... | [
"def",
"build_top_graph",
"(",
"self",
",",
"tokens",
")",
":",
"# Get basic graph information.",
"strict",
"=",
"tokens",
"[",
"0",
"]",
"==",
"'strict'",
"graphtype",
"=",
"tokens",
"[",
"1",
"]",
"directed",
"=",
"graphtype",
"==",
"'digraph'",
"graphname",... | 38.727273 | 8.454545 |
def get_label(self, queryset, query_data):
"""
Gets option label for each datum. Can be used for type identification
of individual serialized objects
"""
if query_data.get('label', False):
return query_data['label']
try:
return queryset.model.__na... | [
"def",
"get_label",
"(",
"self",
",",
"queryset",
",",
"query_data",
")",
":",
"if",
"query_data",
".",
"get",
"(",
"'label'",
",",
"False",
")",
":",
"return",
"query_data",
"[",
"'label'",
"]",
"try",
":",
"return",
"queryset",
".",
"model",
".",
"__... | 33.416667 | 11.583333 |
def write_case_data(self, file):
""" Writes the header to file.
"""
case_sheet = self.book.add_sheet("Case")
case_sheet.write(0, 0, "Name")
case_sheet.write(0, 1, self.case.name)
case_sheet.write(1, 0, "base_mva")
case_sheet.write(1, 1, self.case.base_mva) | [
"def",
"write_case_data",
"(",
"self",
",",
"file",
")",
":",
"case_sheet",
"=",
"self",
".",
"book",
".",
"add_sheet",
"(",
"\"Case\"",
")",
"case_sheet",
".",
"write",
"(",
"0",
",",
"0",
",",
"\"Name\"",
")",
"case_sheet",
".",
"write",
"(",
"0",
... | 38.125 | 4.5 |
def get(self, historics_id=None, maximum=None, page=None, with_estimate=None):
""" Get the historics query with the given ID, if no ID is provided then get a list of historics queries.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsget
:param histor... | [
"def",
"get",
"(",
"self",
",",
"historics_id",
"=",
"None",
",",
"maximum",
"=",
"None",
",",
"page",
"=",
"None",
",",
"with_estimate",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'id'",
":",
"historics_id",
"}",
"if",
"maximum",
":",
"params",
"["... | 48.962963 | 23.333333 |
def Bernstein(n, k):
"""Bernstein polynomial.
"""
coeff = binom(n, k)
def _bpoly(x):
return coeff * x ** k * (1 - x) ** (n - k)
return _bpoly | [
"def",
"Bernstein",
"(",
"n",
",",
"k",
")",
":",
"coeff",
"=",
"binom",
"(",
"n",
",",
"k",
")",
"def",
"_bpoly",
"(",
"x",
")",
":",
"return",
"coeff",
"*",
"x",
"**",
"k",
"*",
"(",
"1",
"-",
"x",
")",
"**",
"(",
"n",
"-",
"k",
")",
... | 16.3 | 21.2 |
def make_step_rcont (transition):
"""Return a ufunc-like step function that is right-continuous. Returns 1 if
x >= transition, 0 otherwise.
"""
if not np.isfinite (transition):
raise ValueError ('"transition" argument must be finite number; got %r' % transition)
def step_rcont (x):
... | [
"def",
"make_step_rcont",
"(",
"transition",
")",
":",
"if",
"not",
"np",
".",
"isfinite",
"(",
"transition",
")",
":",
"raise",
"ValueError",
"(",
"'\"transition\" argument must be finite number; got %r'",
"%",
"transition",
")",
"def",
"step_rcont",
"(",
"x",
")... | 33.684211 | 19.157895 |
def context_processor(self, func: Callable, name: AppOrBlueprintKey=None) -> Callable:
"""Add a template context processor.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.context_processor
def update_context(context):
... | [
"def",
"context_processor",
"(",
"self",
",",
"func",
":",
"Callable",
",",
"name",
":",
"AppOrBlueprintKey",
"=",
"None",
")",
"->",
"Callable",
":",
"self",
".",
"template_context_processors",
"[",
"name",
"]",
".",
"append",
"(",
"ensure_coroutine",
"(",
... | 31.428571 | 22.785714 |
def _toc_fetch_finished(self):
"""Callback for when the TOC fetching is finished"""
self.cf.remove_port_callback(self.port, self._new_packet_cb)
logger.debug('[%d]: Done!', self.port)
self.finished_callback() | [
"def",
"_toc_fetch_finished",
"(",
"self",
")",
":",
"self",
".",
"cf",
".",
"remove_port_callback",
"(",
"self",
".",
"port",
",",
"self",
".",
"_new_packet_cb",
")",
"logger",
".",
"debug",
"(",
"'[%d]: Done!'",
",",
"self",
".",
"port",
")",
"self",
"... | 47.2 | 10.4 |
def _check_type(self, check_type, properties):
"""Decode a properties type looking for a specific type."""
if 'PrimitiveType' in properties:
return properties['PrimitiveType'] == check_type
if properties['Type'] == 'List':
if 'ItemType' in properties:
retu... | [
"def",
"_check_type",
"(",
"self",
",",
"check_type",
",",
"properties",
")",
":",
"if",
"'PrimitiveType'",
"in",
"properties",
":",
"return",
"properties",
"[",
"'PrimitiveType'",
"]",
"==",
"check_type",
"if",
"properties",
"[",
"'Type'",
"]",
"==",
"'List'"... | 45.8 | 11.7 |
def termination_check_md5(self):
# type: (Downloader) -> bool
"""Check if terminated from MD5 context
:param Downloader self: this
:rtype: bool
:return: if terminated from MD5 context
"""
with self._md5_meta_lock:
with self._transfer_lock:
... | [
"def",
"termination_check_md5",
"(",
"self",
")",
":",
"# type: (Downloader) -> bool",
"with",
"self",
".",
"_md5_meta_lock",
":",
"with",
"self",
".",
"_transfer_lock",
":",
"return",
"(",
"self",
".",
"_download_terminate",
"or",
"(",
"self",
".",
"_all_remote_f... | 39.846154 | 8.615385 |
def human_and_01(X, y, model_generator, method_name):
""" AND (false/true)
This tests how well a feature attribution method agrees with human intuition
for an AND operation combined with linear effects. This metric deals
specifically with the question of credit allocation for the following function
... | [
"def",
"human_and_01",
"(",
"X",
",",
"y",
",",
"model_generator",
",",
"method_name",
")",
":",
"return",
"_human_and",
"(",
"X",
",",
"model_generator",
",",
"method_name",
",",
"False",
",",
"True",
")"
] | 36.2 | 21.066667 |
def index_into(self, document, id) -> bool:
"""Index a single document into the index."""
try:
self.instance.index(index=self.index, doc_type=self.doc_type, body=json.dumps(document, ensure_ascii=False), id=id)
except RequestError as ex:
logging.error(ex)
retu... | [
"def",
"index_into",
"(",
"self",
",",
"document",
",",
"id",
")",
"->",
"bool",
":",
"try",
":",
"self",
".",
"instance",
".",
"index",
"(",
"index",
"=",
"self",
".",
"index",
",",
"doc_type",
"=",
"self",
".",
"doc_type",
",",
"body",
"=",
"json... | 39.777778 | 21.666667 |
def delete(self, key):
"""
Equals to setting the value to None
"""
validate_is_bytes(key)
self.root_hash = self._set(self.root_hash, encode_to_bin(key), b'') | [
"def",
"delete",
"(",
"self",
",",
"key",
")",
":",
"validate_is_bytes",
"(",
"key",
")",
"self",
".",
"root_hash",
"=",
"self",
".",
"_set",
"(",
"self",
".",
"root_hash",
",",
"encode_to_bin",
"(",
"key",
")",
",",
"b''",
")"
] | 27.428571 | 15.142857 |
def __caclulate_optimal_neighbor_cluster_score(self, index_cluster, difference):
"""!
@brief Calculates 'B' score for the specific object for the nearest cluster.
@param[in] index_point (uint): Index point from input data for which 'B' score should be calculated.
@param[in] index_c... | [
"def",
"__caclulate_optimal_neighbor_cluster_score",
"(",
"self",
",",
"index_cluster",
",",
"difference",
")",
":",
"optimal_score",
"=",
"float",
"(",
"'inf'",
")",
"for",
"index_neighbor_cluster",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"__clusters",
")",
... | 41.454545 | 27.227273 |
def new_session(self, zipkin_trace_v2, v2_ui=False):
"""Creates a new SchedulerSession for this Scheduler."""
return SchedulerSession(self, self._native.new_session(
self._scheduler, zipkin_trace_v2, v2_ui, multiprocessing.cpu_count())
) | [
"def",
"new_session",
"(",
"self",
",",
"zipkin_trace_v2",
",",
"v2_ui",
"=",
"False",
")",
":",
"return",
"SchedulerSession",
"(",
"self",
",",
"self",
".",
"_native",
".",
"new_session",
"(",
"self",
".",
"_scheduler",
",",
"zipkin_trace_v2",
",",
"v2_ui",... | 50.2 | 20.2 |
def get_events(self):
"""Send a HTTP request to the satellite (GET /_events)
Get monitoring events from the satellite.
:return: Broks list on success, [] on failure
:rtype: list
"""
res = self.con.get('_events', wait=False)
logger.debug("Got events from %s: %s", ... | [
"def",
"get_events",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"con",
".",
"get",
"(",
"'_events'",
",",
"wait",
"=",
"False",
")",
"logger",
".",
"debug",
"(",
"\"Got events from %s: %s\"",
",",
"self",
".",
"name",
",",
"res",
")",
"return",
... | 36.4 | 13.5 |
def load_hash_configuration(self, hash_name):
"""
Loads and returns hash configuration
"""
conf = self.redis_object.get(hash_name+'_conf')
return pickle.loads(conf) if conf is not None else None | [
"def",
"load_hash_configuration",
"(",
"self",
",",
"hash_name",
")",
":",
"conf",
"=",
"self",
".",
"redis_object",
".",
"get",
"(",
"hash_name",
"+",
"'_conf'",
")",
"return",
"pickle",
".",
"loads",
"(",
"conf",
")",
"if",
"conf",
"is",
"not",
"None",... | 32.714286 | 12.428571 |
def load_json_string(data):
"""
<Purpose>
Deserialize 'data' (JSON string) to a Python object.
<Arguments>
data:
A JSON string.
<Exceptions>
securesystemslib.exceptions.Error, if 'data' cannot be deserialized to a
Python object.
<Side Effects>
None.
<Returns>
Deserialized o... | [
"def",
"load_json_string",
"(",
"data",
")",
":",
"deserialized_object",
"=",
"None",
"try",
":",
"deserialized_object",
"=",
"json",
".",
"loads",
"(",
"data",
")",
"except",
"TypeError",
":",
"message",
"=",
"'Invalid JSON string: '",
"+",
"repr",
"(",
"data... | 20.457143 | 24.857143 |
def resolve_or_missing(self, key):
"""Resolves a variable like :meth:`resolve` but returns the
special `missing` value if it cannot be found.
"""
if self._legacy_resolve_mode:
rv = self.resolve(key)
if isinstance(rv, Undefined):
rv = missing
... | [
"def",
"resolve_or_missing",
"(",
"self",
",",
"key",
")",
":",
"if",
"self",
".",
"_legacy_resolve_mode",
":",
"rv",
"=",
"self",
".",
"resolve",
"(",
"key",
")",
"if",
"isinstance",
"(",
"rv",
",",
"Undefined",
")",
":",
"rv",
"=",
"missing",
"return... | 37.1 | 6.5 |
def _serialize(cls, data):
"""Serialize data to an frozen tuple."""
if hasattr(data, "__hash__") and callable(data.__hash__):
# If the data is already hashable (should be immutable) return it
return data
elif isinstance(data, list):
# Freeze the elements of th... | [
"def",
"_serialize",
"(",
"cls",
",",
"data",
")",
":",
"if",
"hasattr",
"(",
"data",
",",
"\"__hash__\"",
")",
"and",
"callable",
"(",
"data",
".",
"__hash__",
")",
":",
"# If the data is already hashable (should be immutable) return it",
"return",
"data",
"elif"... | 42.285714 | 15.904762 |
def channelModeModifyAcknowledge():
"""CHANNEL MODE MODIFY ACKNOWLEDGE Section 9.1.6"""
a = TpPd(pd=0x6)
b = MessageType(mesType=0x17) # 00010111
c = ChannelDescription2()
d = ChannelMode()
packet = a / b / c / d
return packet | [
"def",
"channelModeModifyAcknowledge",
"(",
")",
":",
"a",
"=",
"TpPd",
"(",
"pd",
"=",
"0x6",
")",
"b",
"=",
"MessageType",
"(",
"mesType",
"=",
"0x17",
")",
"# 00010111",
"c",
"=",
"ChannelDescription2",
"(",
")",
"d",
"=",
"ChannelMode",
"(",
")",
"... | 31 | 12.125 |
def get_initial_centroids(self):
'''Randomly choose k data points as initial centroids'''
if self.seed is not None: # useful for obtaining consistent results
np.random.seed(self.seed)
n = self.data.shape[0] # number of data points
# Pick K indices from range [0, N).
... | [
"def",
"get_initial_centroids",
"(",
"self",
")",
":",
"if",
"self",
".",
"seed",
"is",
"not",
"None",
":",
"# useful for obtaining consistent results",
"np",
".",
"random",
".",
"seed",
"(",
"self",
".",
"seed",
")",
"n",
"=",
"self",
".",
"data",
".",
... | 48.2 | 21.933333 |
def get_task_log(self, project, release_id, environment_id, release_deploy_phase_id, task_id, start_line=None, end_line=None, **kwargs):
"""GetTaskLog.
[Preview API] Gets the task log of a release as a plain text file.
:param str project: Project ID or project name
:param int release_id:... | [
"def",
"get_task_log",
"(",
"self",
",",
"project",
",",
"release_id",
",",
"environment_id",
",",
"release_deploy_phase_id",
",",
"task_id",
",",
"start_line",
"=",
"None",
",",
"end_line",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"route_values",
"="... | 56.512821 | 24.487179 |
def _build_environ(self) -> Dict[str, Optional[str]]:
"""
Build environment variables suitable for passing to the Model.
"""
d: Dict[str, Optional[str]] = {}
if self.__config__.case_insensitive:
env_vars = {k.lower(): v for k, v in os.environ.items()}
else:
... | [
"def",
"_build_environ",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"Optional",
"[",
"str",
"]",
"]",
":",
"d",
":",
"Dict",
"[",
"str",
",",
"Optional",
"[",
"str",
"]",
"]",
"=",
"{",
"}",
"if",
"self",
".",
"__config__",
".",
"case_insen... | 37.107143 | 19.178571 |
def getUserPassword(host='www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca'):
""""Getting the username/password for host from .netrc filie """
if os.access(os.path.join(os.environ.get('HOME','/'),".netrc"),os.R_OK):
auth=netrc.netrc().authenticators(host)
else:
auth=False
if not auth:
sys.st... | [
"def",
"getUserPassword",
"(",
"host",
"=",
"'www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca'",
")",
":",
"if",
"os",
".",
"access",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'HOME'",
",",
"'/'",
")",
",",
"\".netrc\"",
")",... | 37.428571 | 16.857143 |
def create_persistent_volume(self, body, **kwargs): # noqa: E501
"""create_persistent_volume # noqa: E501
create a PersistentVolume # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> threa... | [
"def",
"create_persistent_volume",
"(",
"self",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"c... | 58.041667 | 31.541667 |
def _load_properties(self):
"""Loads the properties from Flickr."""
method = 'flickr.groups.getInfo'
data = _doget(method, group_id=self.id)
self.__loaded = True
group = data.rsp.group
self.__name = photo.name.text
self.__members = photo.members.text
... | [
"def",
"_load_properties",
"(",
"self",
")",
":",
"method",
"=",
"'flickr.groups.getInfo'",
"data",
"=",
"_doget",
"(",
"method",
",",
"group_id",
"=",
"self",
".",
"id",
")",
"self",
".",
"__loaded",
"=",
"True",
"group",
"=",
"data",
".",
"rsp",
".",
... | 31.933333 | 11.466667 |
def get_timer(self, name=None):
'''Shortcut for getting a :class:`~statsd.timer.Timer` instance
:keyword name: See :func:`~statsd.client.Client.get_client`
:type name: str
'''
return self.get_client(name=name, class_=statsd.Timer) | [
"def",
"get_timer",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"return",
"self",
".",
"get_client",
"(",
"name",
"=",
"name",
",",
"class_",
"=",
"statsd",
".",
"Timer",
")"
] | 37.857143 | 25 |
def set_position(self, point, reset=False):
""" sets camera position to a point """
if isinstance(point, np.ndarray):
if point.ndim != 1:
point = point.ravel()
self.camera.SetPosition(point)
if reset:
self.reset_camera()
self.camera_set = T... | [
"def",
"set_position",
"(",
"self",
",",
"point",
",",
"reset",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"point",
",",
"np",
".",
"ndarray",
")",
":",
"if",
"point",
".",
"ndim",
"!=",
"1",
":",
"point",
"=",
"point",
".",
"ravel",
"(",
"... | 33.7 | 7.8 |
def import_module_with_exceptions(name, package=None):
"""Wrapper around importlib.import_module to import TimeSide subpackage
and ignoring ImportError if Aubio, Yaafe and Vamp Host are not available"""
from timeside.core import _WITH_AUBIO, _WITH_YAAFE, _WITH_VAMP
if name.count('.server.'):
#... | [
"def",
"import_module_with_exceptions",
"(",
"name",
",",
"package",
"=",
"None",
")",
":",
"from",
"timeside",
".",
"core",
"import",
"_WITH_AUBIO",
",",
"_WITH_YAAFE",
",",
"_WITH_VAMP",
"if",
"name",
".",
"count",
"(",
"'.server.'",
")",
":",
"# TODO:",
"... | 33.575758 | 18.424242 |
def remove(self):
"""
remove the gear from the cache and stop this actor
:return:
"""
LOGGER.debug("InjectorGearSkeleton.remove")
ret = self.cached_gear_actor.remove().get()
if self.actor_ref:
self.stop()
return ret | [
"def",
"remove",
"(",
"self",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"InjectorGearSkeleton.remove\"",
")",
"ret",
"=",
"self",
".",
"cached_gear_actor",
".",
"remove",
"(",
")",
".",
"get",
"(",
")",
"if",
"self",
".",
"actor_ref",
":",
"self",
".",
... | 28.2 | 14 |
def convert_nb(fname, dest_path='.'):
"Convert a notebook `fname` to html file in `dest_path`."
from .gen_notebooks import remove_undoc_cells, remove_code_cell_jupyter_widget_state_elem
nb = read_nb(fname)
nb['cells'] = remove_undoc_cells(nb['cells'])
nb['cells'] = remove_code_cell_jupyter_widget_st... | [
"def",
"convert_nb",
"(",
"fname",
",",
"dest_path",
"=",
"'.'",
")",
":",
"from",
".",
"gen_notebooks",
"import",
"remove_undoc_cells",
",",
"remove_code_cell_jupyter_widget_state_elem",
"nb",
"=",
"read_nb",
"(",
"fname",
")",
"nb",
"[",
"'cells'",
"]",
"=",
... | 55.846154 | 22.153846 |
def interrupt(self, interrupt):
"""Perform the shutdown of this server and save the exception."""
self._interrupt = True
self.stop()
self._interrupt = interrupt | [
"def",
"interrupt",
"(",
"self",
",",
"interrupt",
")",
":",
"self",
".",
"_interrupt",
"=",
"True",
"self",
".",
"stop",
"(",
")",
"self",
".",
"_interrupt",
"=",
"interrupt"
] | 37.6 | 9 |
def _get_live_streams(self, match):
"""
Get the live stream in a particular language
:param match:
:return:
"""
live_url = self._live_api_url.format(match.get("subdomain"))
live_res = self.session.http.json(self.session.http.get(live_url), schema=self._live_schema... | [
"def",
"_get_live_streams",
"(",
"self",
",",
"match",
")",
":",
"live_url",
"=",
"self",
".",
"_live_api_url",
".",
"format",
"(",
"match",
".",
"get",
"(",
"\"subdomain\"",
")",
")",
"live_res",
"=",
"self",
".",
"session",
".",
"http",
".",
"json",
... | 45.076923 | 29.230769 |
def who(self, target):
"""
Runs a WHO on a target
Required arguments:
* target - /WHO <target>
Returns a dictionary, with a nick as the key and -
the value is a list in the form of;
[0] - Username
[1] - Priv level
[2] - Real name
... | [
"def",
"who",
"(",
"self",
",",
"target",
")",
":",
"with",
"self",
".",
"lock",
":",
"self",
".",
"send",
"(",
"'WHO %s'",
"%",
"target",
")",
"who_lst",
"=",
"{",
"}",
"while",
"self",
".",
"readable",
"(",
")",
":",
"msg",
"=",
"self",
".",
... | 40.977778 | 12.222222 |
def is_tablet_tool(self):
"""Macro to check if this event is
a :class:`~libinput.event.TabletToolEvent`.
"""
if self in {type(self).TABLET_TOOL_AXIS, type(self).TABLET_TOOL_BUTTON,
type(self).TABLET_TOOL_PROXIMITY, type(self).TABLET_TOOL_TIP}:
return True
else:
return False | [
"def",
"is_tablet_tool",
"(",
"self",
")",
":",
"if",
"self",
"in",
"{",
"type",
"(",
"self",
")",
".",
"TABLET_TOOL_AXIS",
",",
"type",
"(",
"self",
")",
".",
"TABLET_TOOL_BUTTON",
",",
"type",
"(",
"self",
")",
".",
"TABLET_TOOL_PROXIMITY",
",",
"type"... | 28.5 | 20.2 |
def mean(x):
"""
Return a numpy array of column mean.
It does not affect if the array is one dimension
Parameters
----------
x : ndarray
A numpy array instance
Returns
-------
ndarray
A 1 x n numpy array instance of column mean
Examples
--------
>>> a =... | [
"def",
"mean",
"(",
"x",
")",
":",
"if",
"x",
".",
"ndim",
">",
"1",
"and",
"len",
"(",
"x",
"[",
"0",
"]",
")",
">",
"1",
":",
"return",
"np",
".",
"mean",
"(",
"x",
",",
"axis",
"=",
"1",
")",
"return",
"x"
] | 20.214286 | 20.428571 |
def COOKIES(self):
""" Cookies parsed into a dictionary. Signed cookies are NOT decoded
automatically. See :meth:`get_cookie` for details.
"""
raw_dict = SimpleCookie(self.headers.get('Cookie',''))
cookies = {}
for cookie in six.itervalues(raw_dict):
cooki... | [
"def",
"COOKIES",
"(",
"self",
")",
":",
"raw_dict",
"=",
"SimpleCookie",
"(",
"self",
".",
"headers",
".",
"get",
"(",
"'Cookie'",
",",
"''",
")",
")",
"cookies",
"=",
"{",
"}",
"for",
"cookie",
"in",
"six",
".",
"itervalues",
"(",
"raw_dict",
")",
... | 40.444444 | 13 |
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
... | [
"def",
"version",
"(",
"*",
"names",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"names",
")",
"==",
"1",
":",
"vers",
"=",
"__proxy__",
"[",
"'dummy.package_status'",
"]",
"(",
"names",
"[",
"0",
"]",
")",
"return",
"vers",
"[",
"names",
... | 29.318182 | 22.318182 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.