text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def _dict_to_map_str_str(self, d):
"""
Thrift requires the params and headers dict values to only contain str values.
"""
return dict(map(
lambda (k, v): (k, str(v).lower() if isinstance(v, bool) else str(v)),
d.iteritems()
)) | [
"def",
"_dict_to_map_str_str",
"(",
"self",
",",
"d",
")",
":",
"return",
"dict",
"(",
"map",
"(",
"lambda",
"(",
"k",
",",
"v",
")",
":",
"(",
"k",
",",
"str",
"(",
"v",
")",
".",
"lower",
"(",
")",
"if",
"isinstance",
"(",
"v",
",",
"bool",
... | 35.375 | 19.375 |
def down_host(trg_queue, host, user=None, group=None, mode=None):
''' Down a host queue by creating a down file in the host queue
directory '''
down(trg_queue, user=user, group=group, mode=mode, host=host) | [
"def",
"down_host",
"(",
"trg_queue",
",",
"host",
",",
"user",
"=",
"None",
",",
"group",
"=",
"None",
",",
"mode",
"=",
"None",
")",
":",
"down",
"(",
"trg_queue",
",",
"user",
"=",
"user",
",",
"group",
"=",
"group",
",",
"mode",
"=",
"mode",
... | 54.5 | 24 |
def Stichlmair_wet(Vg, Vl, rhog, rhol, mug, voidage, specific_area, C1, C2, C3, H=1):
r'''Calculates dry pressure drop across a packed column, using the
Stichlmair [1]_ correlation. Uses three regressed constants for each
type of packing, and voidage and specific area. This model is for irrigated
column... | [
"def",
"Stichlmair_wet",
"(",
"Vg",
",",
"Vl",
",",
"rhog",
",",
"rhol",
",",
"mug",
",",
"voidage",
",",
"specific_area",
",",
"C1",
",",
"C2",
",",
"C3",
",",
"H",
"=",
"1",
")",
":",
"dp",
"=",
"6.0",
"*",
"(",
"1.0",
"-",
"voidage",
")",
... | 33.638095 | 24.438095 |
def get(self, sid):
"""
Constructs a ParticipantContext
:param sid: The sid
:returns: twilio.rest.video.v1.room.room_participant.ParticipantContext
:rtype: twilio.rest.video.v1.room.room_participant.ParticipantContext
"""
return ParticipantContext(self._version,... | [
"def",
"get",
"(",
"self",
",",
"sid",
")",
":",
"return",
"ParticipantContext",
"(",
"self",
".",
"_version",
",",
"room_sid",
"=",
"self",
".",
"_solution",
"[",
"'room_sid'",
"]",
",",
"sid",
"=",
"sid",
",",
")"
] | 35.9 | 24.7 |
def create_query_index(
self,
design_document_id=None,
index_name=None,
index_type='json',
partitioned=False,
**kwargs
):
"""
Creates either a JSON or a text query index in the remote database.
:param str index_type: Th... | [
"def",
"create_query_index",
"(",
"self",
",",
"design_document_id",
"=",
"None",
",",
"index_name",
"=",
"None",
",",
"index_type",
"=",
"'json'",
",",
"partitioned",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"index_type",
"==",
"JSON_INDEX_TYP... | 52.25 | 24.903846 |
def execute(self, X):
"""Execute the program according to X.
Parameters
----------
X : {array-like}, shape = [n_samples, n_features]
Training vectors, where n_samples is the number of samples and
n_features is the number of features.
Returns
----... | [
"def",
"execute",
"(",
"self",
",",
"X",
")",
":",
"# Check for single-node programs",
"node",
"=",
"self",
".",
"program",
"[",
"0",
"]",
"if",
"isinstance",
"(",
"node",
",",
"float",
")",
":",
"return",
"np",
".",
"repeat",
"(",
"node",
",",
"X",
... | 33.702128 | 18.106383 |
def mapred(self, inputs, query, timeout=None):
"""
Run a MapReduce query.
"""
# Construct the job, optionally set the timeout...
content = self._construct_mapred_json(inputs, query, timeout)
# Do the request...
url = self.mapred_path()
headers = {'Content... | [
"def",
"mapred",
"(",
"self",
",",
"inputs",
",",
"query",
",",
"timeout",
"=",
"None",
")",
":",
"# Construct the job, optionally set the timeout...",
"content",
"=",
"self",
".",
"_construct_mapred_json",
"(",
"inputs",
",",
"query",
",",
"timeout",
")",
"# Do... | 35.55 | 18.15 |
def parseUnits(self, inp):
"""Carries out a conversion (represented as a string) and returns the
result as a human-readable string.
Args:
inp (str): Text representing a unit conversion, which should
include a magnitude, a description of the initial units,
... | [
"def",
"parseUnits",
"(",
"self",
",",
"inp",
")",
":",
"quantity",
"=",
"self",
".",
"convert",
"(",
"inp",
")",
"units",
"=",
"' '",
".",
"join",
"(",
"str",
"(",
"quantity",
".",
"units",
")",
".",
"split",
"(",
"' '",
")",
"[",
"1",
":",
"]... | 41.588235 | 21.705882 |
def _get_intercepts(self):
"""
Concatenate all intercepts of the classifier.
"""
temp_arr = self.temp('arr')
for layer in self.intercepts:
inter = ', '.join([self.repr(b) for b in layer])
yield temp_arr.format(inter) | [
"def",
"_get_intercepts",
"(",
"self",
")",
":",
"temp_arr",
"=",
"self",
".",
"temp",
"(",
"'arr'",
")",
"for",
"layer",
"in",
"self",
".",
"intercepts",
":",
"inter",
"=",
"', '",
".",
"join",
"(",
"[",
"self",
".",
"repr",
"(",
"b",
")",
"for",
... | 34.125 | 6.875 |
def configure_logging(level=logging.DEBUG):
'''Configures the root logger for command line applications.
A stream handler will be added to the logger that directs
messages to the standard error stream.
By default, *no* messages will be filtered out: set a higher
level on derived/child loggers to a... | [
"def",
"configure_logging",
"(",
"level",
"=",
"logging",
".",
"DEBUG",
")",
":",
"fmt",
"=",
"'%(asctime)s | %(levelname)-8s | %(name)-40s | %(message)s'",
"datefmt",
"=",
"'%Y-%m-%d %H:%M:%S'",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"fmt",
"=",
"fmt",
... | 34.92 | 22.12 |
def insert_bucket_acl(self, bucket_name, entity, role, user_project=None):
"""
Creates a new ACL entry on the specified bucket_name.
See: https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls/insert
:param bucket_name: Name of a bucket_name.
:type bucket_name: s... | [
"def",
"insert_bucket_acl",
"(",
"self",
",",
"bucket_name",
",",
"entity",
",",
"role",
",",
"user_project",
"=",
"None",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'Creating a new ACL entry in bucket: %s'",
",",
"bucket_name",
")",
"client",
"=",
"self... | 48.931034 | 23.551724 |
def _set_gre_source(self, v, load=False):
"""
Setter method for gre_source, mapped from YANG variable /interface/tunnel/gre_source (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_gre_source is considered as a private
method. Backends looking to populate t... | [
"def",
"_set_gre_source",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"bas... | 76.318182 | 35.318182 |
def create_process(cmd, root_helper=None, addl_env=None, log_output=True):
"""Create a process object for the given command.
The return value will be a tuple of the process object and the
list of command arguments used to create it.
"""
if root_helper:
cmd = shlex.split(root_helper) + cmd
... | [
"def",
"create_process",
"(",
"cmd",
",",
"root_helper",
"=",
"None",
",",
"addl_env",
"=",
"None",
",",
"log_output",
"=",
"True",
")",
":",
"if",
"root_helper",
":",
"cmd",
"=",
"shlex",
".",
"split",
"(",
"root_helper",
")",
"+",
"cmd",
"cmd",
"=",
... | 34.473684 | 20.052632 |
def _prepare(self, kwargs=None):
"""
Updates the function arguments and creates a :class:`asyncio.Task`
from the Action.
*kwargs* is an optional dictionnary of additional arguments to pass to
the Action function.
.. warning::
*kwargs* will overwrite existing... | [
"def",
"_prepare",
"(",
"self",
",",
"kwargs",
"=",
"None",
")",
":",
"if",
"kwargs",
"is",
"not",
"None",
":",
"# Note: This will overwrite existing keys in self.args.",
"# This is the wanted behavior.",
"self",
".",
"args",
".",
"update",
"(",
"kwargs",
")",... | 36.0625 | 21.6875 |
def output_domain(gandi, domain, output_keys, justify=12):
""" Helper to output a domain information."""
if 'nameservers' in domain:
domain['nameservers'] = format_list(domain['nameservers'])
if 'services' in domain:
domain['services'] = format_list(domain['services'])
if 'tags' in dom... | [
"def",
"output_domain",
"(",
"gandi",
",",
"domain",
",",
"output_keys",
",",
"justify",
"=",
"12",
")",
":",
"if",
"'nameservers'",
"in",
"domain",
":",
"domain",
"[",
"'nameservers'",
"]",
"=",
"format_list",
"(",
"domain",
"[",
"'nameservers'",
"]",
")"... | 35.076923 | 20.576923 |
def vesting(ctx, account):
""" List accounts vesting balances
"""
account = Account(account, full=True)
t = [["vesting_id", "claimable"]]
for vest in account["vesting_balances"]:
vesting = Vesting(vest)
t.append([vesting["id"], str(vesting.claimable)])
print_table(t) | [
"def",
"vesting",
"(",
"ctx",
",",
"account",
")",
":",
"account",
"=",
"Account",
"(",
"account",
",",
"full",
"=",
"True",
")",
"t",
"=",
"[",
"[",
"\"vesting_id\"",
",",
"\"claimable\"",
"]",
"]",
"for",
"vest",
"in",
"account",
"[",
"\"vesting_bala... | 33.222222 | 7.777778 |
def post(self, request, provider=None):
"""
method called on POST request
:param django.http.HttpRequest request: The current request object
:param unicode provider: Optional parameter. The user provider suffix.
"""
# if settings.CAS_FEDERATE is not True redi... | [
"def",
"post",
"(",
"self",
",",
"request",
",",
"provider",
"=",
"None",
")",
":",
"# if settings.CAS_FEDERATE is not True redirect to the login page",
"if",
"not",
"settings",
".",
"CAS_FEDERATE",
":",
"logger",
".",
"warning",
"(",
"\"CAS_FEDERATE is False, set it to... | 48 | 19.209302 |
def sleep(self, seconds):
"""
Sleep in simulated time.
"""
start = self.time()
while (self.time() - start < seconds and
not self.need_to_stop.is_set()):
self.need_to_stop.wait(self.sim_time) | [
"def",
"sleep",
"(",
"self",
",",
"seconds",
")",
":",
"start",
"=",
"self",
".",
"time",
"(",
")",
"while",
"(",
"self",
".",
"time",
"(",
")",
"-",
"start",
"<",
"seconds",
"and",
"not",
"self",
".",
"need_to_stop",
".",
"is_set",
"(",
")",
")"... | 31.25 | 7.5 |
def from_params(cls, params: Iterable[Tuple[str, Params]] = ()) -> Optional['RegularizerApplicator']:
"""
Converts a List of pairs (regex, params) into an RegularizerApplicator.
This list should look like
[["regex1", {"type": "l2", "alpha": 0.01}], ["regex2", "l1"]]
where each ... | [
"def",
"from_params",
"(",
"cls",
",",
"params",
":",
"Iterable",
"[",
"Tuple",
"[",
"str",
",",
"Params",
"]",
"]",
"=",
"(",
")",
")",
"->",
"Optional",
"[",
"'RegularizerApplicator'",
"]",
":",
"if",
"not",
"params",
":",
"return",
"None",
"instanti... | 47.783784 | 28.918919 |
def destination(self, bearing, distance):
"""Calculate destination locations for given distance and bearings.
Args:
bearing (float): Bearing to move on in degrees
distance (float): Distance in kilometres
Returns:
list of list of Point: Groups of points shift... | [
"def",
"destination",
"(",
"self",
",",
"bearing",
",",
"distance",
")",
":",
"return",
"(",
"segment",
".",
"destination",
"(",
"bearing",
",",
"distance",
")",
"for",
"segment",
"in",
"self",
")"
] | 37.25 | 20.083333 |
def get_grade_entry_form_for_update(self, grade_entry_id):
"""Gets the grade entry form for updating an existing entry.
A new grade entry form should be requested for each update
transaction.
arg: grade_entry_id (osid.id.Id): the ``Id`` of the
``GradeEntry``
... | [
"def",
"get_grade_entry_form_for_update",
"(",
"self",
",",
"grade_entry_id",
")",
":",
"collection",
"=",
"JSONClientValidated",
"(",
"'grading'",
",",
"collection",
"=",
"'GradeEntry'",
",",
"runtime",
"=",
"self",
".",
"_runtime",
")",
"if",
"not",
"isinstance"... | 46.117647 | 21.911765 |
def upload_aws(target_filepath, metadata, access_token, base_url=OH_BASE_URL,
remote_file_info=None, project_member_id=None,
max_bytes=MAX_FILE_DEFAULT):
"""
Upload a file from a local filepath using the "direct upload" API.
Equivalent to upload_file. To learn more about this A... | [
"def",
"upload_aws",
"(",
"target_filepath",
",",
"metadata",
",",
"access_token",
",",
"base_url",
"=",
"OH_BASE_URL",
",",
"remote_file_info",
"=",
"None",
",",
"project_member_id",
"=",
"None",
",",
"max_bytes",
"=",
"MAX_FILE_DEFAULT",
")",
":",
"return",
"u... | 57.375 | 25.875 |
def stream(self, flags=0, devpath=None):
"Control streaming reports from the daemon,"
if flags & WATCH_DISABLE:
arg = '?WATCH={"enable":false'
if flags & WATCH_JSON:
arg += ',"json":false'
if flags & WATCH_NMEA:
arg += ',"nmea":false'
... | [
"def",
"stream",
"(",
"self",
",",
"flags",
"=",
"0",
",",
"devpath",
"=",
"None",
")",
":",
"if",
"flags",
"&",
"WATCH_DISABLE",
":",
"arg",
"=",
"'?WATCH={\"enable\":false'",
"if",
"flags",
"&",
"WATCH_JSON",
":",
"arg",
"+=",
"',\"json\":false'",
"if",
... | 36.939394 | 4.515152 |
def time_range(self, start, end):
"""Add a request for a time range to the query.
This modifies the query in-place, but returns `self` so that multiple queries
can be chained together on one line.
This replaces any existing temporal queries that have been set.
Parameters
... | [
"def",
"time_range",
"(",
"self",
",",
"start",
",",
"end",
")",
":",
"self",
".",
"_set_query",
"(",
"self",
".",
"time_query",
",",
"time_start",
"=",
"self",
".",
"_format_time",
"(",
"start",
")",
",",
"time_end",
"=",
"self",
".",
"_format_time",
... | 31 | 21.083333 |
def percent_point(self, U):
"""Given a cdf value, returns a value in original space.
Args:
U: `int` or `float` cdf value in [0,1]
Returns:
float: value in original space
"""
self.check_fit()
if not 0 < U < 1:
raise ValueError('cdf va... | [
"def",
"percent_point",
"(",
"self",
",",
"U",
")",
":",
"self",
".",
"check_fit",
"(",
")",
"if",
"not",
"0",
"<",
"U",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"'cdf value must be in [0,1]'",
")",
"return",
"scipy",
".",
"optimize",
".",
"brentq",
... | 28.2 | 22.533333 |
def exception(self, timeout=None):
"""Wait for the async function to complete and return its exception.
If the function did not raise an exception this returns ``None``.
"""
if not self._done.wait(timeout):
raise Timeout('timeout waiting for future')
if self._state =... | [
"def",
"exception",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_done",
".",
"wait",
"(",
"timeout",
")",
":",
"raise",
"Timeout",
"(",
"'timeout waiting for future'",
")",
"if",
"self",
".",
"_state",
"==",
"self",
"... | 40.333333 | 11.777778 |
def image_name (txt):
"""Return the alt part of the first <img alt=""> tag in txt."""
mo = imgtag_re.search(txt)
if mo:
name = strformat.unquote(mo.group('name').strip())
return _unquote(name)
return u'' | [
"def",
"image_name",
"(",
"txt",
")",
":",
"mo",
"=",
"imgtag_re",
".",
"search",
"(",
"txt",
")",
"if",
"mo",
":",
"name",
"=",
"strformat",
".",
"unquote",
"(",
"mo",
".",
"group",
"(",
"'name'",
")",
".",
"strip",
"(",
")",
")",
"return",
"_un... | 32.857143 | 16.142857 |
def contextMenuEvent(self, event):
"""
Add menu action:
* 'Show line numbers'
* 'Save to file'
"""
menu = QtWidgets.QPlainTextEdit.createStandardContextMenu(self)
mg = self.getGlobalsMenu()
a0 = menu.actions()[0]
menu.insertMenu(a0, mg)
me... | [
"def",
"contextMenuEvent",
"(",
"self",
",",
"event",
")",
":",
"menu",
"=",
"QtWidgets",
".",
"QPlainTextEdit",
".",
"createStandardContextMenu",
"(",
"self",
")",
"mg",
"=",
"self",
".",
"getGlobalsMenu",
"(",
")",
"a0",
"=",
"menu",
".",
"actions",
"(",... | 29.740741 | 15.518519 |
def asarray(self, file=None, out=None, **kwargs):
"""Read image data from files and return as numpy array.
The kwargs parameters are passed to the imread function.
Raise IndexError or ValueError if image shapes do not match.
"""
if file is not None:
if isinstance(f... | [
"def",
"asarray",
"(",
"self",
",",
"file",
"=",
"None",
",",
"out",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"file",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"file",
",",
"int",
")",
":",
"return",
"self",
".",
"imread",
... | 38.75 | 17.208333 |
def CreateVertices(self, points):
"""
Returns a dictionary object with keys that are 2tuples
represnting a point.
"""
gr = digraph()
for z, x, Q in points:
node = (z, x, Q)
gr.add_nodes([node])
return gr | [
"def",
"CreateVertices",
"(",
"self",
",",
"points",
")",
":",
"gr",
"=",
"digraph",
"(",
")",
"for",
"z",
",",
"x",
",",
"Q",
"in",
"points",
":",
"node",
"=",
"(",
"z",
",",
"x",
",",
"Q",
")",
"gr",
".",
"add_nodes",
"(",
"[",
"node",
"]",... | 22.833333 | 16 |
def get_other_answers(pool, seeded_answers, get_student_item_dict, algo, options):
"""
Select other student's answers from answer pool or seeded answers based on the selection algorithm
Args:
pool (dict): answer pool, format:
{
option1_index: {
studen... | [
"def",
"get_other_answers",
"(",
"pool",
",",
"seeded_answers",
",",
"get_student_item_dict",
",",
"algo",
",",
"options",
")",
":",
"# \"#\" means the number of responses returned should be the same as the number of options.",
"num_responses",
"=",
"len",
"(",
"options",
")"... | 40.648649 | 24.162162 |
def Hooper2K(Di, Re, name=None, K1=None, Kinfty=None):
r'''Returns loss coefficient for any various fittings, depending
on the name input. Alternatively, the Hooper constants K1, Kinfty
may be provided and used instead. Source of data is [1]_.
Reviews of this model are favorable less favorable than the ... | [
"def",
"Hooper2K",
"(",
"Di",
",",
"Re",
",",
"name",
"=",
"None",
",",
"K1",
"=",
"None",
",",
"Kinfty",
"=",
"None",
")",
":",
"if",
"name",
":",
"if",
"name",
"in",
"Hooper",
":",
"d",
"=",
"Hooper",
"[",
"name",
"]",
"K1",
",",
"Kinfty",
... | 32.078125 | 23.921875 |
def remove(self, uid, filename=None):
"""Removes an address to the Abook addressbook
uid -- UID of the entry to remove
"""
book = ConfigParser(default_section='format')
with self._lock:
book.read(self._filename)
del book[uid.split('@')[0]]
with... | [
"def",
"remove",
"(",
"self",
",",
"uid",
",",
"filename",
"=",
"None",
")",
":",
"book",
"=",
"ConfigParser",
"(",
"default_section",
"=",
"'format'",
")",
"with",
"self",
".",
"_lock",
":",
"book",
".",
"read",
"(",
"self",
".",
"_filename",
")",
"... | 38.2 | 4.9 |
def normalize_curves_eb(curves):
"""
A more sophisticated version of normalize_curves, used in the event
based calculator.
:param curves: a list of pairs (losses, poes)
:returns: first losses, all_poes
"""
# we assume non-decreasing losses, so losses[-1] is the maximum loss
non_zero_cur... | [
"def",
"normalize_curves_eb",
"(",
"curves",
")",
":",
"# we assume non-decreasing losses, so losses[-1] is the maximum loss",
"non_zero_curves",
"=",
"[",
"(",
"losses",
",",
"poes",
")",
"for",
"losses",
",",
"poes",
"in",
"curves",
"if",
"losses",
"[",
"-",
"1",
... | 42.96 | 15.2 |
def decode_key(cls, pubkey_content):
"""Decode base64 coded part of the key."""
try:
decoded_key = base64.b64decode(pubkey_content.encode("ascii"))
except (TypeError, binascii.Error):
raise MalformedDataError("Unable to decode the key")
return decoded_key | [
"def",
"decode_key",
"(",
"cls",
",",
"pubkey_content",
")",
":",
"try",
":",
"decoded_key",
"=",
"base64",
".",
"b64decode",
"(",
"pubkey_content",
".",
"encode",
"(",
"\"ascii\"",
")",
")",
"except",
"(",
"TypeError",
",",
"binascii",
".",
"Error",
")",
... | 43.571429 | 15.285714 |
def _build_tree(value_and_gradients_fn,
current_state,
current_target_log_prob,
current_grads_target_log_prob,
current_momentum,
direction,
depth,
step_size,
log_slice_sample,
... | [
"def",
"_build_tree",
"(",
"value_and_gradients_fn",
",",
"current_state",
",",
"current_target_log_prob",
",",
"current_grads_target_log_prob",
",",
"current_momentum",
",",
"direction",
",",
"depth",
",",
"step_size",
",",
"log_slice_sample",
",",
"max_simulation_error",
... | 40.865217 | 19.53913 |
def writeColorLUT2(config,
outfile=None, isochrone=None, distance_modulus_array=None,
delta_mag=None, mag_err_array=None,
mass_steps=10000, plot=False):
"""
Precompute a 4-dimensional signal color probability look-up table to speed up the likelihood evaluati... | [
"def",
"writeColorLUT2",
"(",
"config",
",",
"outfile",
"=",
"None",
",",
"isochrone",
"=",
"None",
",",
"distance_modulus_array",
"=",
"None",
",",
"delta_mag",
"=",
"None",
",",
"mag_err_array",
"=",
"None",
",",
"mass_steps",
"=",
"10000",
",",
"plot",
... | 50.012579 | 29.748428 |
def validate(config):
'''
Validate the beacon configuration
'''
VALID_ITEMS = [
'type', 'bytes_sent', 'bytes_recv', 'packets_sent',
'packets_recv', 'errin', 'errout', 'dropin',
'dropout'
]
# Configuration for load beacon should be a list of dicts
if not isinstance(c... | [
"def",
"validate",
"(",
"config",
")",
":",
"VALID_ITEMS",
"=",
"[",
"'type'",
",",
"'bytes_sent'",
",",
"'bytes_recv'",
",",
"'packets_sent'",
",",
"'packets_recv'",
",",
"'errin'",
",",
"'errout'",
",",
"'dropin'",
",",
"'dropout'",
"]",
"# Configuration for l... | 35.392857 | 24.321429 |
def get_order_detail(self, code):
"""
查询A股Level 2权限下提供的委托明细
:param code: 股票代码,例如:'HK.02318'
:return: (ret, data)
ret == RET_OK data为1个dict,包含以下数据
ret != RET_OK data为错误字符串
{‘code’: 股票代码
‘Ask’:[ order_num, [order_volume1, ... | [
"def",
"get_order_detail",
"(",
"self",
",",
"code",
")",
":",
"if",
"code",
"is",
"None",
"or",
"is_str",
"(",
"code",
")",
"is",
"False",
":",
"error_str",
"=",
"ERROR_STR_PREFIX",
"+",
"\"the type of code param is wrong\"",
"return",
"RET_ERROR",
",",
"erro... | 30.8 | 21.885714 |
def plot(self, flip=False, ax_channels=None, ax=None, *args, **kwargs):
"""
{_gate_plot_doc}
"""
for gate in self.gates:
gate.plot(flip=flip, ax_channels=ax_channels, ax=ax, *args, **kwargs) | [
"def",
"plot",
"(",
"self",
",",
"flip",
"=",
"False",
",",
"ax_channels",
"=",
"None",
",",
"ax",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"gate",
"in",
"self",
".",
"gates",
":",
"gate",
".",
"plot",
"(",
"flip... | 38.166667 | 16.166667 |
def init(policy_file=None, rules=None, default_rule=None, use_conf=True):
"""Init an Enforcer class.
:param policy_file: Custom policy file to use, if none is specified,
`CONF.policy_file` will be used.
:param rules: Default dictionary / Rules to use. It will be
... | [
"def",
"init",
"(",
"policy_file",
"=",
"None",
",",
"rules",
"=",
"None",
",",
"default_rule",
"=",
"None",
",",
"use_conf",
"=",
"True",
")",
":",
"global",
"_ENFORCER",
"global",
"saved_file_rules",
"if",
"not",
"_ENFORCER",
":",
"_ENFORCER",
"=",
"poli... | 43.193548 | 19.548387 |
def _GetVSSStoreIdentifiers(self, scan_node):
"""Determines the VSS store identifiers.
Args:
scan_node (dfvfs.SourceScanNode): scan node.
Returns:
list[str]: VSS store identifiers.
Raises:
SourceScannerError: if the format of or within the source is not
supported or the sc... | [
"def",
"_GetVSSStoreIdentifiers",
"(",
"self",
",",
"scan_node",
")",
":",
"if",
"not",
"scan_node",
"or",
"not",
"scan_node",
".",
"path_spec",
":",
"raise",
"errors",
".",
"SourceScannerError",
"(",
"'Invalid scan node.'",
")",
"volume_system",
"=",
"vshadow_vol... | 31.659574 | 21.12766 |
def set_constant(self, name, value):
"""
Set constant of name to value.
:param name: may be a str or a sympy.Symbol
:param value: must be an int
"""
assert isinstance(name, str) or isinstance(name, sympy.Symbol), \
"constant name needs to be of type str, unic... | [
"def",
"set_constant",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"assert",
"isinstance",
"(",
"name",
",",
"str",
")",
"or",
"isinstance",
"(",
"name",
",",
"sympy",
".",
"Symbol",
")",
",",
"\"constant name needs to be of type str, unicode or a sympy.Sy... | 40 | 15.142857 |
def create_pending_tasks(self):
"""
Creates pending task results in a dict on self.result with task string as key. It will also
create a list on self.tasks that is used to make sure the serialization of the results
creates a correctly ordered list.
"""
for task in self.se... | [
"def",
"create_pending_tasks",
"(",
"self",
")",
":",
"for",
"task",
"in",
"self",
".",
"settings",
".",
"services",
":",
"task",
"=",
"self",
".",
"create_service_command",
"(",
"task",
")",
"self",
".",
"service_tasks",
".",
"append",
"(",
"task",
")",
... | 41.555556 | 15.222222 |
def scompressed2ibytes(stream):
"""
:param stream: SOMETHING WITH read() METHOD TO GET MORE BYTES
:return: GENERATOR OF UNCOMPRESSED BYTES
"""
def more():
try:
while True:
bytes_ = stream.read(4096)
if not bytes_:
return
... | [
"def",
"scompressed2ibytes",
"(",
"stream",
")",
":",
"def",
"more",
"(",
")",
":",
"try",
":",
"while",
"True",
":",
"bytes_",
"=",
"stream",
".",
"read",
"(",
"4096",
")",
"if",
"not",
"bytes_",
":",
"return",
"yield",
"bytes_",
"except",
"Exception"... | 28.736842 | 13.894737 |
def pool_list(call=None):
'''
Get a list of Resource Pools
.. code-block:: bash
salt-cloud -f pool_list myxen
'''
if call == 'action':
raise SaltCloudSystemExit(
'This function must be called with -f, --function argument.'
)
ret = {}
session = _get_sess... | [
"def",
"pool_list",
"(",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'This function must be called with -f, --function argument.'",
")",
"ret",
"=",
"{",
"}",
"session",
"=",
"_get_session",
"(",
")",
... | 24.9 | 21.4 |
def pil_image3d(input, size=(800, 600), pcb_rotate=(0, 0, 0), timeout=20, showgui=False):
'''
same as export_image3d, but there is no output file, PIL object is returned instead
'''
f = tempfile.NamedTemporaryFile(suffix='.png', prefix='eagexp_')
output = f.name
export_image3d(input, output=out... | [
"def",
"pil_image3d",
"(",
"input",
",",
"size",
"=",
"(",
"800",
",",
"600",
")",
",",
"pcb_rotate",
"=",
"(",
"0",
",",
"0",
",",
"0",
")",
",",
"timeout",
"=",
"20",
",",
"showgui",
"=",
"False",
")",
":",
"f",
"=",
"tempfile",
".",
"NamedTe... | 36.916667 | 31.416667 |
def get_default_config_help(self):
"""
Returns the help text for the configuration options for this handler
"""
config = super(rmqHandler, self).get_default_config_help()
config.update({
'server': '',
'rmq_exchange': '',
})
return config | [
"def",
"get_default_config_help",
"(",
"self",
")",
":",
"config",
"=",
"super",
"(",
"rmqHandler",
",",
"self",
")",
".",
"get_default_config_help",
"(",
")",
"config",
".",
"update",
"(",
"{",
"'server'",
":",
"''",
",",
"'rmq_exchange'",
":",
"''",
",",... | 28 | 18 |
def exit(self, result=0, msg=None, *args, **kwargs):
"""Exit the runtime."""
if self._finalizer:
try:
self._finalizer()
except Exception as e:
try:
NailgunProtocol.send_stderr(
self._socket,
'\nUnexpected exception in finalizer: {!r}\n'.format(e)
... | [
"def",
"exit",
"(",
"self",
",",
"result",
"=",
"0",
",",
"msg",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_finalizer",
":",
"try",
":",
"self",
".",
"_finalizer",
"(",
")",
"except",
"Exception",
"as",... | 28.538462 | 20.038462 |
def run():
"""
Runs the linter and tests
:return:
A bool - if the linter and tests ran successfully
"""
print('Python ' + sys.version.replace('\n', ''))
try:
oscrypto_tests_module_info = imp.find_module('tests', [os.path.join(build_root, 'oscrypto')])
oscrypto_tests = ... | [
"def",
"run",
"(",
")",
":",
"print",
"(",
"'Python '",
"+",
"sys",
".",
"version",
".",
"replace",
"(",
"'\\n'",
",",
"''",
")",
")",
"try",
":",
"oscrypto_tests_module_info",
"=",
"imp",
".",
"find_module",
"(",
"'tests'",
",",
"[",
"os",
".",
"pat... | 26.257143 | 22.2 |
def FqdnUrl(v):
"""Verify that the value is a Fully qualified domain name URL.
>>> s = Schema(FqdnUrl())
>>> with raises(MultipleInvalid, 'expected a Fully qualified domain name URL'):
... s("http://localhost/")
>>> s('http://w3.org')
'http://w3.org'
"""
try:
parsed_url = _url... | [
"def",
"FqdnUrl",
"(",
"v",
")",
":",
"try",
":",
"parsed_url",
"=",
"_url_validation",
"(",
"v",
")",
"if",
"\".\"",
"not",
"in",
"parsed_url",
".",
"netloc",
":",
"raise",
"UrlInvalid",
"(",
"\"must have a domain name in URL\"",
")",
"return",
"v",
"except... | 29.8125 | 17.875 |
def parse_partition(rule):
'''
Parse the partition line
'''
parser = argparse.ArgumentParser()
rules = shlex.split(rule)
rules.pop(0)
parser.add_argument('mntpoint')
parser.add_argument('--size', dest='size', action='store')
parser.add_argument('--grow', dest='grow', action='store_tr... | [
"def",
"parse_partition",
"(",
"rule",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"rules",
"=",
"shlex",
".",
"split",
"(",
"rule",
")",
"rules",
".",
"pop",
"(",
"0",
")",
"parser",
".",
"add_argument",
"(",
"'mntpoint'",
")... | 51.1 | 25.9 |
def _update_input_func_list(self):
"""
Update sources list from receiver.
Internal method which updates sources list of receiver after getting
sources and potential renaming information from receiver.
"""
# Get all sources and renaming information from receiver
#... | [
"def",
"_update_input_func_list",
"(",
"self",
")",
":",
"# Get all sources and renaming information from receiver",
"# For structural information of the variables please see the methods",
"receiver_sources",
"=",
"self",
".",
"_get_receiver_sources",
"(",
")",
"if",
"not",
"receiv... | 45.637363 | 19.197802 |
def register(cls, *args, **kwargs):
"""Register view to handler."""
if cls.app is None:
return register(*args, handler=cls, **kwargs)
return cls.app.register(*args, handler=cls, **kwargs) | [
"def",
"register",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"cls",
".",
"app",
"is",
"None",
":",
"return",
"register",
"(",
"*",
"args",
",",
"handler",
"=",
"cls",
",",
"*",
"*",
"kwargs",
")",
"return",
"cls",
"... | 43.8 | 11.2 |
def make_file_read_only(file_path):
"""
Removes the write permissions for the given file for owner, groups and others.
:param file_path: The file whose privileges are revoked.
:raise FileNotFoundError: If the given file does not exist.
"""
old_permissions = os.stat(file_path).st_mode
os.chm... | [
"def",
"make_file_read_only",
"(",
"file_path",
")",
":",
"old_permissions",
"=",
"os",
".",
"stat",
"(",
"file_path",
")",
".",
"st_mode",
"os",
".",
"chmod",
"(",
"file_path",
",",
"old_permissions",
"&",
"~",
"WRITE_PERMISSIONS",
")"
] | 40.333333 | 17.666667 |
def followers(self):
""" :class:`Feed <pypump.models.feed.Feed>` with all
:class:`Person <pypump.models.person.Person>` objects following the person.
Example:
>>> alice = pump.Person('alice@example.org')
>>> for follower in alice.followers[:2]:
... print(... | [
"def",
"followers",
"(",
"self",
")",
":",
"if",
"self",
".",
"_followers",
"is",
"None",
":",
"self",
".",
"_followers",
"=",
"Followers",
"(",
"self",
".",
"links",
"[",
"'followers'",
"]",
",",
"pypump",
"=",
"self",
".",
"_pump",
")",
"return",
"... | 37.666667 | 16.933333 |
def lazy_load_modules(*modules):
"""
Decorator to load module to perform related operation for specific function
and delete the module from imports once the task is done. GC frees the memory
related to module during clean-up.
"""
def decorator(function):
def wrapper(*args, **kwargs):
... | [
"def",
"lazy_load_modules",
"(",
"*",
"modules",
")",
":",
"def",
"decorator",
"(",
"function",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"module_dict",
"=",
"{",
"}",
"for",
"module_string",
"in",
"modules",
":",... | 36.933333 | 18.466667 |
def add_experiment_choice(experiment, choice):
"""Adds an experiment choice"""
redis = oz.redis.create_connection()
oz.bandit.Experiment(redis, experiment).add_choice(choice) | [
"def",
"add_experiment_choice",
"(",
"experiment",
",",
"choice",
")",
":",
"redis",
"=",
"oz",
".",
"redis",
".",
"create_connection",
"(",
")",
"oz",
".",
"bandit",
".",
"Experiment",
"(",
"redis",
",",
"experiment",
")",
".",
"add_choice",
"(",
"choice"... | 45.75 | 7 |
def pause_unit(assess_status_func, services=None, ports=None,
charm_func=None):
"""Pause a unit by stopping the services and setting 'unit-paused'
in the local kv() store.
Also checks that the services have stopped and ports are no longer
being listened to.
An optional charm_func() ... | [
"def",
"pause_unit",
"(",
"assess_status_func",
",",
"services",
"=",
"None",
",",
"ports",
"=",
"None",
",",
"charm_func",
"=",
"None",
")",
":",
"_",
",",
"messages",
"=",
"manage_payload_services",
"(",
"'pause'",
",",
"services",
"=",
"services",
",",
... | 37.02439 | 19.146341 |
def get_agent_requirement_line(check, version):
"""
Compose a text line to be used in a requirements.txt file to install a check
pinned to a specific version.
"""
package_name = get_package_name(check)
# no manifest
if check in ('datadog_checks_base', 'datadog_checks_downloader'):
r... | [
"def",
"get_agent_requirement_line",
"(",
"check",
",",
"version",
")",
":",
"package_name",
"=",
"get_package_name",
"(",
"check",
")",
"# no manifest",
"if",
"check",
"in",
"(",
"'datadog_checks_base'",
",",
"'datadog_checks_downloader'",
")",
":",
"return",
"'{}=... | 41.172414 | 22.689655 |
def read(self, n):
"""Read data from file segs.
Args:
n: max bytes to read. Must be positive.
Returns:
some bytes. May be smaller than n bytes. "" when no more data is left.
"""
if self._EOF:
return ""
while self._seg_index <= self._last_seg_index:
result = self._read_... | [
"def",
"read",
"(",
"self",
",",
"n",
")",
":",
"if",
"self",
".",
"_EOF",
":",
"return",
"\"\"",
"while",
"self",
".",
"_seg_index",
"<=",
"self",
".",
"_last_seg_index",
":",
"result",
"=",
"self",
".",
"_read_from_seg",
"(",
"n",
")",
"if",
"resul... | 20.428571 | 22.47619 |
def set_attributes_all(target, attributes, discard_others=True):
""" Set Attributes in bulk and optionally discard others.
Sets each Attribute in turn (modifying it in place if possible if it
is already present) and optionally discarding all other Attributes
not explicitly set. This function yields muc... | [
"def",
"set_attributes_all",
"(",
"target",
",",
"attributes",
",",
"discard_others",
"=",
"True",
")",
":",
"attrs",
"=",
"target",
".",
"attrs",
"existing",
"=",
"dict",
"(",
"attrs",
".",
"items",
"(",
")",
")",
"# Generate special dtype for string arrays.",
... | 37.920635 | 18.206349 |
def parse_command_line():
""" Parse CLI args."""
## create the parser
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
* Example command-line usage:
## push test branch to conda --label=conda-test for travis CI
./versioner.py -p toyt... | [
"def",
"parse_command_line",
"(",
")",
":",
"## create the parser",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"formatter_class",
"=",
"argparse",
".",
"RawDescriptionHelpFormatter",
",",
"epilog",
"=",
"\"\"\"\n * Example command-line usage: \n\n ## push test b... | 26.354839 | 19.387097 |
def __driver_stub(self, text, state):
"""Display help messages or invoke the proper completer.
The interface of helper methods and completer methods are documented in
the helper() decorator method and the completer() decorator method,
respectively.
Arguments:
text: ... | [
"def",
"__driver_stub",
"(",
"self",
",",
"text",
",",
"state",
")",
":",
"origline",
"=",
"readline",
".",
"get_line_buffer",
"(",
")",
"line",
"=",
"origline",
".",
"lstrip",
"(",
")",
"if",
"line",
"and",
"line",
"[",
"-",
"1",
"]",
"==",
"'?'",
... | 40.413793 | 21.827586 |
def push(args):
"""
%prog push unitig{version}.{partID}.{unitigID}
For example, `%prog push unitig5.530` will push the modified `unitig530`
and replace the one in the tigStore
"""
p = OptionParser(push.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.p... | [
"def",
"push",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"push",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
":",
"sys",
".",
"exit",
"(",
"not",... | 25.272727 | 20.090909 |
def search_regexp(self):
"""
Define the regexp used for the search
"""
if ((self.season == "") and (self.episode == "")):
# Find serie
try:
print("%s has %s seasons (the serie is %s)" % (self.tvdb.data['seriesname'], self.tvdb.get_season_number(), ... | [
"def",
"search_regexp",
"(",
"self",
")",
":",
"if",
"(",
"(",
"self",
".",
"season",
"==",
"\"\"",
")",
"and",
"(",
"self",
".",
"episode",
"==",
"\"\"",
")",
")",
":",
"# Find serie",
"try",
":",
"print",
"(",
"\"%s has %s seasons (the serie is %s)\"",
... | 48 | 32.296296 |
def args_to_props(target: Target, builder: Builder, args: list, kwargs: dict):
"""Convert build file `args` and `kwargs` to `target` props.
Use builder signature to validate builder usage in build-file, raising
appropriate exceptions on signature-mismatches.
Use builder signature default values to ass... | [
"def",
"args_to_props",
"(",
"target",
":",
"Target",
",",
"builder",
":",
"Builder",
",",
"args",
":",
"list",
",",
"kwargs",
":",
"dict",
")",
":",
"if",
"len",
"(",
"args",
")",
">",
"len",
"(",
"builder",
".",
"sig",
")",
":",
"# too many positio... | 52.017241 | 21.931034 |
def transactional(func):
"""
Decorate a function call with a commit/rollback and pass the session as the first arg.
"""
@wraps(func)
def wrapper(*args, **kwargs):
with transaction():
return func(*args, **kwargs)
return wrapper | [
"def",
"transactional",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"transaction",
"(",
")",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs... | 26.2 | 17.2 |
def zscan(self, name, cursor='0', match=None, count=10):
"""Emulate zscan."""
def value_function():
values = self.zrange(name, 0, -1, withscores=True)
values.sort(key=lambda x: x[1]) # sort for consistent order
return values
return self._common_scan(value_fun... | [
"def",
"zscan",
"(",
"self",
",",
"name",
",",
"cursor",
"=",
"'0'",
",",
"match",
"=",
"None",
",",
"count",
"=",
"10",
")",
":",
"def",
"value_function",
"(",
")",
":",
"values",
"=",
"self",
".",
"zrange",
"(",
"name",
",",
"0",
",",
"-",
"1... | 54.428571 | 23.571429 |
def get_forecast_sites(self):
"""
This function returns a list of Site object.
"""
time_now = time()
if (time_now - self.forecast_sites_last_update) > self.forecast_sites_update_time or self.forecast_sites_last_request is None:
data = self.__call_api("sitelist/")
... | [
"def",
"get_forecast_sites",
"(",
"self",
")",
":",
"time_now",
"=",
"time",
"(",
")",
"if",
"(",
"time_now",
"-",
"self",
".",
"forecast_sites_last_update",
")",
">",
"self",
".",
"forecast_sites_update_time",
"or",
"self",
".",
"forecast_sites_last_request",
"... | 34.4 | 20.15 |
def soft_bounce(self, unique_id, configs=None):
""" Performs a soft bounce (stop and start) for the specified process
:Parameter unique_id: the name of the process
"""
self.stop(unique_id, configs)
self.start(unique_id, configs) | [
"def",
"soft_bounce",
"(",
"self",
",",
"unique_id",
",",
"configs",
"=",
"None",
")",
":",
"self",
".",
"stop",
"(",
"unique_id",
",",
"configs",
")",
"self",
".",
"start",
"(",
"unique_id",
",",
"configs",
")"
] | 34.714286 | 9.857143 |
def is_inbound_presence_filter(cb):
"""
Return true if `cb` has been decorated with
:func:`inbound_presence_filter`.
"""
try:
handlers = get_magic_attr(cb)
except AttributeError:
return False
hs = HandlerSpec(
(_apply_inbound_presence_filter, ())
)
return h... | [
"def",
"is_inbound_presence_filter",
"(",
"cb",
")",
":",
"try",
":",
"handlers",
"=",
"get_magic_attr",
"(",
"cb",
")",
"except",
"AttributeError",
":",
"return",
"False",
"hs",
"=",
"HandlerSpec",
"(",
"(",
"_apply_inbound_presence_filter",
",",
"(",
")",
")... | 19.875 | 17.375 |
def pdf_lognormal(d, d_characteristic, s):
r'''Calculates the probability density function of a lognormal particle
distribution given a particle diameter `d`, characteristic particle
diameter `d_characteristic`, and distribution standard deviation `s`.
.. math::
q(d) = \frac{1}{ds\sqrt{2\pi... | [
"def",
"pdf_lognormal",
"(",
"d",
",",
"d_characteristic",
",",
"s",
")",
":",
"try",
":",
"log_term",
"=",
"log",
"(",
"d",
"/",
"d_characteristic",
")",
"/",
"s",
"except",
"ValueError",
":",
"return",
"0.0",
"return",
"1.",
"/",
"(",
"d",
"*",
"s"... | 34.137931 | 25.896552 |
def set_led(self, colorcode):
""" Set the LED Color of Herkulex
Args:
colorcode (int): The code for colors
(0x00-OFF
0x02-BLUE
0x03-CYAN
0x04-RED
... | [
"def",
"set_led",
"(",
"self",
",",
"colorcode",
")",
":",
"data",
"=",
"[",
"]",
"data",
".",
"append",
"(",
"0x0A",
")",
"data",
".",
"append",
"(",
"self",
".",
"servoid",
")",
"data",
".",
"append",
"(",
"RAM_WRITE_REQ",
")",
"data",
".",
"appe... | 30.238095 | 9.190476 |
def _get_wv(sentence, ignore=False):
'''
get word2vec data by sentence
sentence is segmented string.
'''
global _vectors
vectors = []
for y in sentence:
y_ = any2unicode(y).strip()
if y_ not in _stopwords:
syns = nearby(y_)[0]
# print("sentence %s word... | [
"def",
"_get_wv",
"(",
"sentence",
",",
"ignore",
"=",
"False",
")",
":",
"global",
"_vectors",
"vectors",
"=",
"[",
"]",
"for",
"y",
"in",
"sentence",
":",
"y_",
"=",
"any2unicode",
"(",
"y",
")",
".",
"strip",
"(",
")",
"if",
"y_",
"not",
"in",
... | 39.416667 | 18.694444 |
def Kerr_factor(final_mass, distance):
"""Return the factor final_mass/distance (in dimensionless units) for Kerr
ringdowns
"""
# Convert solar masses to meters
mass = final_mass * lal.MSUN_SI * lal.G_SI / lal.C_SI**2
# Convert Mpc to meters
dist = distance * 1e6 * lal.PC_SI
return mas... | [
"def",
"Kerr_factor",
"(",
"final_mass",
",",
"distance",
")",
":",
"# Convert solar masses to meters",
"mass",
"=",
"final_mass",
"*",
"lal",
".",
"MSUN_SI",
"*",
"lal",
".",
"G_SI",
"/",
"lal",
".",
"C_SI",
"**",
"2",
"# Convert Mpc to meters",
"dist",
"=",
... | 28.909091 | 15.181818 |
def InitUI(self):
"""
Build the mainframe
"""
menubar = pmag_gui_menu.MagICMenu(self, data_model_num=self.data_model_num)
self.SetMenuBar(menubar)
#pnl = self.panel
#---sizer logo ----
#start_image = wx.Image("/Users/ronshaar/PmagPy/images/logo2.png")
... | [
"def",
"InitUI",
"(",
"self",
")",
":",
"menubar",
"=",
"pmag_gui_menu",
".",
"MagICMenu",
"(",
"self",
",",
"data_model_num",
"=",
"self",
".",
"data_model_num",
")",
"self",
".",
"SetMenuBar",
"(",
"menubar",
")",
"#pnl = self.panel",
"#---sizer logo ----",
... | 42.719101 | 25.797753 |
def get_authorization_url(self,
signin_with_twitter=False,
access_type=None):
"""Get the authorization URL to redirect the user"""
try:
if signin_with_twitter:
url = self._get_oauth_url('authenticate')
... | [
"def",
"get_authorization_url",
"(",
"self",
",",
"signin_with_twitter",
"=",
"False",
",",
"access_type",
"=",
"None",
")",
":",
"try",
":",
"if",
"signin_with_twitter",
":",
"url",
"=",
"self",
".",
"_get_oauth_url",
"(",
"'authenticate'",
")",
"if",
"access... | 43.133333 | 14.2 |
def cmp_private_numbers(pn1, pn2):
"""
Compare 2 sets of private numbers. This is for comparing 2
private RSA keys.
:param pn1: The set of values belonging to the 1st key
:param pn2: The set of values belonging to the 2nd key
:return: True is the sets are the same otherwise False.
"""
i... | [
"def",
"cmp_private_numbers",
"(",
"pn1",
",",
"pn2",
")",
":",
"if",
"not",
"cmp_public_numbers",
"(",
"pn1",
".",
"public_numbers",
",",
"pn2",
".",
"public_numbers",
")",
":",
"return",
"False",
"for",
"param",
"in",
"[",
"'d'",
",",
"'p'",
",",
"'q'"... | 32.625 | 18.375 |
def ref_context_from_geoloc(geoloc):
"""Return a RefContext object given a geoloc entry."""
text = geoloc.get('text')
geoid = geoloc.get('geoID')
rc = RefContext(name=text, db_refs={'GEOID': geoid})
return rc | [
"def",
"ref_context_from_geoloc",
"(",
"geoloc",
")",
":",
"text",
"=",
"geoloc",
".",
"get",
"(",
"'text'",
")",
"geoid",
"=",
"geoloc",
".",
"get",
"(",
"'geoID'",
")",
"rc",
"=",
"RefContext",
"(",
"name",
"=",
"text",
",",
"db_refs",
"=",
"{",
"'... | 37.166667 | 11.166667 |
def patch_file_open(): # pragma: no cover
"""A Monkey patch to log opening and closing of files, which is useful for
debugging file descriptor exhaustion."""
openfiles = set()
oldfile = builtins.file
class newfile(oldfile):
def __init__(self, *args, **kwargs):
self.x = args[0]
... | [
"def",
"patch_file_open",
"(",
")",
":",
"# pragma: no cover",
"openfiles",
"=",
"set",
"(",
")",
"oldfile",
"=",
"builtins",
".",
"file",
"class",
"newfile",
"(",
"oldfile",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"k... | 28.896552 | 18.689655 |
def stats(self, **kwargs):
"""
Stream statistics for this container. Similar to the
``docker stats`` command.
Args:
decode (bool): If set to true, stream will be decoded into dicts
on the fly. Only applicable if ``stream`` is True.
False by de... | [
"def",
"stats",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"client",
".",
"api",
".",
"stats",
"(",
"self",
".",
"id",
",",
"*",
"*",
"kwargs",
")"
] | 36.941176 | 19.176471 |
def set_basic_params(
self, spawn_on_request=None,
cheaper_algo=None, workers_min=None, workers_startup=None, workers_step=None):
"""
:param bool spawn_on_request: Spawn workers only after the first request.
:param Algo cheaper_algo: The algorithm object to be used used ... | [
"def",
"set_basic_params",
"(",
"self",
",",
"spawn_on_request",
"=",
"None",
",",
"cheaper_algo",
"=",
"None",
",",
"workers_min",
"=",
"None",
",",
"workers_startup",
"=",
"None",
",",
"workers_step",
"=",
"None",
")",
":",
"self",
".",
"_set",
"(",
"'ch... | 39.029412 | 29.676471 |
def readFILTERLIST(self):
""" Read a length-prefixed list of FILTERs """
number = self.readUI8()
return [self.readFILTER() for _ in range(number)] | [
"def",
"readFILTERLIST",
"(",
"self",
")",
":",
"number",
"=",
"self",
".",
"readUI8",
"(",
")",
"return",
"[",
"self",
".",
"readFILTER",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"number",
")",
"]"
] | 41.75 | 10.25 |
def GetEntries(self, parser_mediator, top_level=None, **unused_kwargs):
"""Simple method to exact date values from a Plist.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
top_level (dict[str, object]): plist t... | [
"def",
"GetEntries",
"(",
"self",
",",
"parser_mediator",
",",
"top_level",
"=",
"None",
",",
"*",
"*",
"unused_kwargs",
")",
":",
"for",
"root",
",",
"key",
",",
"datetime_value",
"in",
"interface",
".",
"RecurseKey",
"(",
"top_level",
")",
":",
"if",
"... | 39.894737 | 22 |
def handle(self, locale, app=None, **options):
""" command execution """
translation.activate(settings.LANGUAGE_CODE)
if app:
unpack = app.split('.')
if len(unpack) == 2:
models = [get_model(unpack[0], unpack[1])]
elif len(unpack) == 1:
... | [
"def",
"handle",
"(",
"self",
",",
"locale",
",",
"app",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"translation",
".",
"activate",
"(",
"settings",
".",
"LANGUAGE_CODE",
")",
"if",
"app",
":",
"unpack",
"=",
"app",
".",
"split",
"(",
"'.'",
... | 49.621622 | 23.810811 |
def connect(self):
"Initiate the connection to a proxying hub"
log.info("connecting")
# don't have the connection attempt reconnects, because when it goes
# down we are going to cycle to the next potential peer from the Client
self._peer = connection.Peer(
None, ... | [
"def",
"connect",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"\"connecting\"",
")",
"# don't have the connection attempt reconnects, because when it goes",
"# down we are going to cycle to the next potential peer from the Client",
"self",
".",
"_peer",
"=",
"connection",
"... | 42.9 | 20.7 |
def is_excluded(root, excludes):
# type: (unicode, List[unicode]) -> bool
"""Check if the directory is in the exclude list.
Note: by having trailing slashes, we avoid common prefix issues, like
e.g. an exlude "foo" also accidentally excluding "foobar".
"""
for exclude in excludes:
... | [
"def",
"is_excluded",
"(",
"root",
",",
"excludes",
")",
":",
"# type: (unicode, List[unicode]) -> bool",
"for",
"exclude",
"in",
"excludes",
":",
"if",
"fnmatch",
"(",
"root",
",",
"exclude",
")",
":",
"return",
"True",
"return",
"False"
] | 34.363636 | 15.636364 |
def add(self, a, b):
"""
Parameters:
- a
- b
"""
self.send_add(a, b)
return self.recv_add() | [
"def",
"add",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"self",
".",
"send_add",
"(",
"a",
",",
"b",
")",
"return",
"self",
".",
"recv_add",
"(",
")"
] | 17.75 | 15 |
def watch_log_for_alive(self, nodes, from_mark=None, timeout=720, filename='system.log'):
"""
Watch the log of this node until it detects that the provided other
nodes are marked UP. This method works similarly to watch_log_for_death.
We want to provide a higher default timeout when thi... | [
"def",
"watch_log_for_alive",
"(",
"self",
",",
"nodes",
",",
"from_mark",
"=",
"None",
",",
"timeout",
"=",
"720",
",",
"filename",
"=",
"'system.log'",
")",
":",
"super",
"(",
"DseNode",
",",
"self",
")",
".",
"watch_log_for_alive",
"(",
"nodes",
",",
... | 57.125 | 34.375 |
def GetDevicePath(device_handle):
"""Obtains the unique path for the device.
Args:
device_handle: reference to the device
Returns:
A unique path for the device, obtained from the IO Registry
"""
# Obtain device path from IO Registry
io_service_obj = iokit.IOHIDDeviceGetService(device_handle)
st... | [
"def",
"GetDevicePath",
"(",
"device_handle",
")",
":",
"# Obtain device path from IO Registry",
"io_service_obj",
"=",
"iokit",
".",
"IOHIDDeviceGetService",
"(",
"device_handle",
")",
"str_buffer",
"=",
"ctypes",
".",
"create_string_buffer",
"(",
"DEVICE_PATH_BUFFER_SIZE"... | 29.625 | 22.3125 |
def _is_noop_block(arch, block):
"""
Check if the block is a no-op block by checking VEX statements.
:param block: The VEX block instance.
:return: True if the entire block is a single-byte or multi-byte nop instruction, False otherwise.
:rtype: bool
"""
if arch... | [
"def",
"_is_noop_block",
"(",
"arch",
",",
"block",
")",
":",
"if",
"arch",
".",
"name",
"==",
"\"MIPS32\"",
":",
"if",
"arch",
".",
"memory_endness",
"==",
"\"Iend_BE\"",
":",
"MIPS32_BE_NOOPS",
"=",
"{",
"b\"\\x00\\x20\\x08\\x25\"",
",",
"# move $at, $at",
"... | 35.916667 | 22.583333 |
def Process(self, parser_mediator, registry_key, **kwargs):
"""Processes a Windows Registry key or value.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
registry_key (dfwinreg.WinRegistryKey): Windows Registry... | [
"def",
"Process",
"(",
"self",
",",
"parser_mediator",
",",
"registry_key",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"registry_key",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Windows Registry key is not set.'",
")",
"# This will raise if unhandled keyword argum... | 37.777778 | 24.888889 |
def get_function_call_str(fn, args, kwargs):
"""Converts method call (function and its arguments) to a str(...)-like string."""
def str_converter(v):
try:
return str(v)
except Exception:
try:
return repr(v)
except Exception:
re... | [
"def",
"get_function_call_str",
"(",
"fn",
",",
"args",
",",
"kwargs",
")",
":",
"def",
"str_converter",
"(",
"v",
")",
":",
"try",
":",
"return",
"str",
"(",
"v",
")",
"except",
"Exception",
":",
"try",
":",
"return",
"repr",
"(",
"v",
")",
"except"... | 25.392857 | 17.25 |
def get_all(self, type_name, base_fields=None, the_filter=None,
nested_fields=None):
"""Get the resource by resource id.
:param nested_fields: nested resource fields
:param base_fields: fields of this resource
:param the_filter: dictionary of filter like `{'name': 'abc'}... | [
"def",
"get_all",
"(",
"self",
",",
"type_name",
",",
"base_fields",
"=",
"None",
",",
"the_filter",
"=",
"None",
",",
"nested_fields",
"=",
"None",
")",
":",
"fields",
"=",
"self",
".",
"get_fields",
"(",
"type_name",
",",
"base_fields",
",",
"nested_fiel... | 42.681818 | 19.772727 |
def add_emission(self, chunksize=2**19, comp_filter=default_compression,
overwrite=False, params=dict(), chunkslice='bytes'):
"""Add the `emission` array in '/trajectories'.
"""
nparams = self.numeric_params
num_particles = nparams['np']
return self.add_traj... | [
"def",
"add_emission",
"(",
"self",
",",
"chunksize",
"=",
"2",
"**",
"19",
",",
"comp_filter",
"=",
"default_compression",
",",
"overwrite",
"=",
"False",
",",
"params",
"=",
"dict",
"(",
")",
",",
"chunkslice",
"=",
"'bytes'",
")",
":",
"nparams",
"=",... | 52.076923 | 20.230769 |
def rowCount(self, parent):
"""Reimplemented from QtCore.QAbstractItemModel"""
if not parent.isValid():
v = self._conf
else:
v = self.get_value(parent)
if isinstance(v, Section):
return len(v.keys())
else:
return 0 | [
"def",
"rowCount",
"(",
"self",
",",
"parent",
")",
":",
"if",
"not",
"parent",
".",
"isValid",
"(",
")",
":",
"v",
"=",
"self",
".",
"_conf",
"else",
":",
"v",
"=",
"self",
".",
"get_value",
"(",
"parent",
")",
"if",
"isinstance",
"(",
"v",
",",... | 29.3 | 12.5 |
def get_SZ(self, psd, geometry):
"""
Compute the scattering matrices for the given PSD and geometries.
Returns:
The new amplitude (S) and phase (Z) matrices.
"""
if (self._S_table is None) or (self._Z_table is None):
raise AttributeError(
... | [
"def",
"get_SZ",
"(",
"self",
",",
"psd",
",",
"geometry",
")",
":",
"if",
"(",
"self",
".",
"_S_table",
"is",
"None",
")",
"or",
"(",
"self",
".",
"_Z_table",
"is",
"None",
")",
":",
"raise",
"AttributeError",
"(",
"\"Initialize or load the scattering tab... | 34.8 | 18.96 |
def merge(self, services):
"""Merge extended host information into services
:param services: services list, to look for a specific one
:type services: alignak.objects.service.Services
:return: None
"""
for extinfo in self:
if hasattr(extinfo, 'register') and ... | [
"def",
"merge",
"(",
"self",
",",
"services",
")",
":",
"for",
"extinfo",
"in",
"self",
":",
"if",
"hasattr",
"(",
"extinfo",
",",
"'register'",
")",
"and",
"not",
"getattr",
"(",
"extinfo",
",",
"'register'",
")",
":",
"# We don't have to merge template",
... | 44.055556 | 17.777778 |
def resize_move(self, title, xOrigin=-1, yOrigin=-1, width=-1, height=-1, matchClass=False):
"""
Resize and/or move the specified window
Usage: C{window.close(title, xOrigin=-1, yOrigin=-1, width=-1, height=-1, matchClass=False)}
Leaving and of the position/dimension values as ... | [
"def",
"resize_move",
"(",
"self",
",",
"title",
",",
"xOrigin",
"=",
"-",
"1",
",",
"yOrigin",
"=",
"-",
"1",
",",
"width",
"=",
"-",
"1",
",",
"height",
"=",
"-",
"1",
",",
"matchClass",
"=",
"False",
")",
":",
"mvArgs",
"=",
"[",
"\"0\"",
",... | 46.954545 | 26.409091 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.