text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def hugoniot_rho_single(p, rho0, c0, s, min_strain=0.01):
"""
calculate density in g/cm^3 from a hugoniot curve
:param p: pressure in GPa
:param rho0: density at 1 bar in g/cm^3
:param c0: velocity at 1 bar in km/s
:param s: slope of the velocity change
:param min_strain: defining minimum v... | [
"def",
"hugoniot_rho_single",
"(",
"p",
",",
"rho0",
",",
"c0",
",",
"s",
",",
"min_strain",
"=",
"0.01",
")",
":",
"if",
"p",
"<=",
"1.e-5",
":",
"return",
"rho0",
"def",
"f_diff",
"(",
"rho",
")",
":",
"return",
"hugoniot_p",
"(",
"rho",
",",
"rh... | 30.333333 | 0.001776 |
def cmd_generate(args):
"""Generate text.
Parameters
----------
args : `argparse.Namespace`
Command arguments.
"""
if args.start:
if args.end or args.reply:
raise ValueError('multiple input arguments')
args.reply_to = args.start
args.reply_mode = Rep... | [
"def",
"cmd_generate",
"(",
"args",
")",
":",
"if",
"args",
".",
"start",
":",
"if",
"args",
".",
"end",
"or",
"args",
".",
"reply",
":",
"raise",
"ValueError",
"(",
"'multiple input arguments'",
")",
"args",
".",
"reply_to",
"=",
"args",
".",
"start",
... | 25.956522 | 0.000807 |
def is_entailed_by(self, other):
"""
Other is more specific than self. Other is bounded within self.
"""
other = self.coerce(other)
to_i = self.to_i
return to_i(other.low) >= to_i(self.low) and \
to_i(other.high) <= to_i(self.high) | [
"def",
"is_entailed_by",
"(",
"self",
",",
"other",
")",
":",
"other",
"=",
"self",
".",
"coerce",
"(",
"other",
")",
"to_i",
"=",
"self",
".",
"to_i",
"return",
"to_i",
"(",
"other",
".",
"low",
")",
">=",
"to_i",
"(",
"self",
".",
"low",
")",
"... | 36.25 | 0.010101 |
def update_number(self, number, payload_number_modification, **kwargs): # noqa: E501
"""Assign number # noqa: E501
With this API call you will be able to assign a specific number to a specific account (one of your members). # noqa: E501
This method makes a synchronous HTTP request by default... | [
"def",
"update_number",
"(",
"self",
",",
"number",
",",
"payload_number_modification",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"ret... | 50.954545 | 0.001751 |
def channels_voice_greeting_delete(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/voice-api/greetings#delete-greeting"
api_path = "/api/v2/channels/voice/greetings/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, method="DELETE", **kwargs) | [
"def",
"channels_voice_greeting_delete",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/channels/voice/greetings/{id}.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"id",
"=",
"id",
")",
"return",
"self",
".",
... | 61.8 | 0.009585 |
def set_connection(connection=defaults.sqlalchemy_connection_string_default):
"""Set the connection string for SQLAlchemy
:param str connection: SQLAlchemy connection string
"""
cfp = defaults.config_file_path
config = RawConfigParser()
if not os.path.exists(cfp):
with open(cfp, 'w') a... | [
"def",
"set_connection",
"(",
"connection",
"=",
"defaults",
".",
"sqlalchemy_connection_string_default",
")",
":",
"cfp",
"=",
"defaults",
".",
"config_file_path",
"config",
"=",
"RawConfigParser",
"(",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
... | 37.833333 | 0.001433 |
def _write_exports(exports, edict):
'''
Write an exports file to disk
If multiple shares were initially configured per line, like:
/media/storage /media/data *(ro,sync,no_subtree_check)
...then they will be saved to disk with only one share per line:
/media/storage *(ro,sync,no_subtr... | [
"def",
"_write_exports",
"(",
"exports",
",",
"edict",
")",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"exports",
",",
"'w'",
")",
"as",
"efh",
":",
"for",
"export",
"in",
"edict",
":",
"line",
"=",
"salt",
".",
"utils",
".... | 35.238095 | 0.001316 |
def mail_session(self, name, host, username, mail_from, props):
"""
Domain mail session.
:param str name:
Mail session name.
:param str host:
Mail host.
:param str username:
Mail username.
:param str mail_from:
Mail "from" address.
:param dict props:
Extra properties.
:rtyp... | [
"def",
"mail_session",
"(",
"self",
",",
"name",
",",
"host",
",",
"username",
",",
"mail_from",
",",
"props",
")",
":",
"return",
"MailSession",
"(",
"self",
".",
"__endpoint",
",",
"name",
",",
"host",
",",
"username",
",",
"mail_from",
",",
"props",
... | 19.52381 | 0.074419 |
def __calculate_links(self, cluster1, cluster2):
"""!
@brief Returns number of link between two clusters.
@details Link between objects (points) exists only if distance between them less than connectivity radius.
@param[in] cluster1 (list): The first cluster.
@par... | [
"def",
"__calculate_links",
"(",
"self",
",",
"cluster1",
",",
"cluster2",
")",
":",
"number_links",
"=",
"0",
"for",
"index1",
"in",
"cluster1",
":",
"for",
"index2",
"in",
"cluster2",
":",
"number_links",
"+=",
"self",
".",
"__adjacency_matrix",
"[",
"inde... | 35.736842 | 0.018651 |
def schedule_ping_frequency(self): # pragma: no cover
"Send a ping message to slack every 20 seconds"
ping = crontab('* * * * * */20', func=self.send_ping, start=False)
ping.start() | [
"def",
"schedule_ping_frequency",
"(",
"self",
")",
":",
"# pragma: no cover",
"ping",
"=",
"crontab",
"(",
"'* * * * * */20'",
",",
"func",
"=",
"self",
".",
"send_ping",
",",
"start",
"=",
"False",
")",
"ping",
".",
"start",
"(",
")"
] | 50.75 | 0.009709 |
def load_config(filename=None, section_option_dict={}):
"""
This function returns a Bunch object from the stated config file.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
NOTE:
The values are not evaluated by default.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!... | [
"def",
"load_config",
"(",
"filename",
"=",
"None",
",",
"section_option_dict",
"=",
"{",
"}",
")",
":",
"config",
"=",
"ConfigParser",
"(",
")",
"config",
".",
"read",
"(",
"filename",
")",
"working_dict",
"=",
"_prepare_working_dict",
"(",
"config",
",",
... | 30.408163 | 0.00065 |
def get_article_status(self, url=None, article_id=None):
"""
Send a HEAD request to the `parser` endpoint to the parser API to
get the articles status.
Returned is a `requests.Response` object. The id and status for the
article can be extracted from the `X-Article-Id` and `X-Art... | [
"def",
"get_article_status",
"(",
"self",
",",
"url",
"=",
"None",
",",
"article_id",
"=",
"None",
")",
":",
"query_params",
"=",
"{",
"}",
"if",
"url",
"is",
"not",
"None",
":",
"query_params",
"[",
"'url'",
"]",
"=",
"url",
"if",
"article_id",
"is",
... | 40.727273 | 0.002181 |
def prod_fac_massgrid_A_1(self,weighted=True,log=True,runs=[],isotopes=[],elements=[],cycles=[],plot_set_diagram=True,color=['r','b','g','k'],marker_type=['o','p','s','D'],line_style=['--','-','-.',':'],markersize=[6,6,6,6],line_width=[14,14,14,14],title='',withlabel=True,label='',plot_lines=True,exp_only=False,pre_exp... | [
"def",
"prod_fac_massgrid_A_1",
"(",
"self",
",",
"weighted",
"=",
"True",
",",
"log",
"=",
"True",
",",
"runs",
"=",
"[",
"]",
",",
"isotopes",
"=",
"[",
"]",
",",
"elements",
"=",
"[",
"]",
",",
"cycles",
"=",
"[",
"]",
",",
"plot_set_diagram",
"... | 33.918079 | 0.058576 |
def compare_config(self):
"""Compare candidate config with running."""
diff = self.device.cu.diff()
if diff is None:
return ''
else:
return diff.strip() | [
"def",
"compare_config",
"(",
"self",
")",
":",
"diff",
"=",
"self",
".",
"device",
".",
"cu",
".",
"diff",
"(",
")",
"if",
"diff",
"is",
"None",
":",
"return",
"''",
"else",
":",
"return",
"diff",
".",
"strip",
"(",
")"
] | 25.25 | 0.009569 |
def init_postgresql_db(username, host, database, port='', password='', initTime=False):
"""
Initialize PostgreSQL Database
.. note:: psycopg2 or similar driver required
Args:
username(str): Database username.
host(str): Database host URL.
database(str): Database name.
... | [
"def",
"init_postgresql_db",
"(",
"username",
",",
"host",
",",
"database",
",",
"port",
"=",
"''",
",",
"password",
"=",
"''",
",",
"initTime",
"=",
"False",
")",
":",
"postgresql_base_url",
"=",
"'postgresql://'",
"if",
"password",
"!=",
"''",
":",
"pass... | 30.309091 | 0.01104 |
def gen_columns(obj) -> Generator[Tuple[str, Column], None, None]:
"""
Asks a SQLAlchemy ORM object: "what are your SQLAlchemy columns?"
Yields tuples of ``(attr_name, Column)`` from an SQLAlchemy ORM object
instance. Also works with the corresponding SQLAlchemy ORM class. Examples:
.. code-block:... | [
"def",
"gen_columns",
"(",
"obj",
")",
"->",
"Generator",
"[",
"Tuple",
"[",
"str",
",",
"Column",
"]",
",",
"None",
",",
"None",
"]",
":",
"mapper",
"=",
"obj",
".",
"__mapper__",
"# type: Mapper",
"assert",
"mapper",
",",
"\"gen_columns called on {!r} whic... | 33.628571 | 0.000826 |
def reset_package(self):
"""Resets the builder's state in order to build new packages."""
# FIXME: this state does not make sense
self.package_set = False
self.package_vers_set = False
self.package_file_name_set = False
self.package_supplier_set = False
self.packa... | [
"def",
"reset_package",
"(",
"self",
")",
":",
"# FIXME: this state does not make sense",
"self",
".",
"package_set",
"=",
"False",
"self",
".",
"package_vers_set",
"=",
"False",
"self",
".",
"package_file_name_set",
"=",
"False",
"self",
".",
"package_supplier_set",
... | 42.052632 | 0.002448 |
def register_classes():
"""Register these classes with the `LinkFactory` """
Gtlink_select.register_class()
Gtlink_bin.register_class()
Gtlink_expcube2.register_class()
Gtlink_scrmaps.register_class()
Gtlink_mktime.register_class()
Gtlink_ltcube.register_class()
Link_FermipyCoadd.registe... | [
"def",
"register_classes",
"(",
")",
":",
"Gtlink_select",
".",
"register_class",
"(",
")",
"Gtlink_bin",
".",
"register_class",
"(",
")",
"Gtlink_expcube2",
".",
"register_class",
"(",
")",
"Gtlink_scrmaps",
".",
"register_class",
"(",
")",
"Gtlink_mktime",
".",
... | 35.722222 | 0.001515 |
def DOM_node_to_XML(tree, xml_declaration=True):
"""
Prints a DOM tree to its Unicode representation.
:param tree: the input DOM tree
:type tree: an ``xml.etree.ElementTree.Element`` object
:param xml_declaration: if ``True`` (default) prints a leading XML
declaration line
:type xml_dec... | [
"def",
"DOM_node_to_XML",
"(",
"tree",
",",
"xml_declaration",
"=",
"True",
")",
":",
"result",
"=",
"ET",
".",
"tostring",
"(",
"tree",
",",
"encoding",
"=",
"'utf8'",
",",
"method",
"=",
"'xml'",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"if",
"not",
... | 34.8125 | 0.001748 |
def p_labelled_statement(self, p):
"""labelled_statement : identifier COLON statement"""
p[0] = ast.Label(identifier=p[1], statement=p[3]) | [
"def",
"p_labelled_statement",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"ast",
".",
"Label",
"(",
"identifier",
"=",
"p",
"[",
"1",
"]",
",",
"statement",
"=",
"p",
"[",
"3",
"]",
")"
] | 50.666667 | 0.012987 |
def Deserializer(stream_or_string, **options):
"""
Deserialize a stream or string of CSV data.
"""
def process_item(item):
m = _LIST_RE.match(item)
if m:
contents = m.group(1)
if not contents:
item = []
else:
item = proc... | [
"def",
"Deserializer",
"(",
"stream_or_string",
",",
"*",
"*",
"options",
")",
":",
"def",
"process_item",
"(",
"item",
")",
":",
"m",
"=",
"_LIST_RE",
".",
"match",
"(",
"item",
")",
"if",
"m",
":",
"contents",
"=",
"m",
".",
"group",
"(",
"1",
")... | 30.178571 | 0.000573 |
def sonify_clicks(audio, clicks, out_file, fs, offset=0):
"""Sonifies the estimated times into the output file.
Parameters
----------
audio: np.array
Audio samples of the input track.
clicks: np.array
Click positions in seconds.
out_file: str
Path to the output file.
... | [
"def",
"sonify_clicks",
"(",
"audio",
",",
"clicks",
",",
"out_file",
",",
"fs",
",",
"offset",
"=",
"0",
")",
":",
"# Generate clicks (this should be done by mir_eval, but its",
"# latest release is not compatible with latest numpy)",
"times",
"=",
"clicks",
"+",
"offset... | 33.028571 | 0.00084 |
def serial_udb_extra_f2_b_encode(self, sue_time, sue_pwm_input_1, sue_pwm_input_2, sue_pwm_input_3, sue_pwm_input_4, sue_pwm_input_5, sue_pwm_input_6, sue_pwm_input_7, sue_pwm_input_8, sue_pwm_input_9, sue_pwm_input_10, sue_pwm_output_1, sue_pwm_output_2, sue_pwm_output_3, sue_pwm_output_4, sue_pwm_output_5, sue_pwm_ou... | [
"def",
"serial_udb_extra_f2_b_encode",
"(",
"self",
",",
"sue_time",
",",
"sue_pwm_input_1",
",",
"sue_pwm_input_2",
",",
"sue_pwm_input_3",
",",
"sue_pwm_input_4",
",",
"sue_pwm_input_5",
",",
"sue_pwm_input_6",
",",
"sue_pwm_input_7",
",",
"sue_pwm_input_8",
",",
"sue... | 108.875 | 0.008193 |
def sevenths_inv(reference_labels, estimated_labels):
"""Compare chords along MIREX 'sevenths' rules. Chords with qualities
outside [maj, maj7, 7, min, min7, N] are ignored.
Examples
--------
>>> (ref_intervals,
... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab')
>>> (est_inter... | [
"def",
"sevenths_inv",
"(",
"reference_labels",
",",
"estimated_labels",
")",
":",
"validate",
"(",
"reference_labels",
",",
"estimated_labels",
")",
"seventh_qualities",
"=",
"[",
"'maj'",
",",
"'min'",
",",
"'maj7'",
",",
"'7'",
",",
"'min7'",
",",
"''",
"]"... | 42.224138 | 0.000399 |
def joint_min(mu, var, with_derivatives=False, **kwargs):
"""
Computes the probability of every given point to be the minimum
based on the EPMGP[1] algorithm.
[1] Cunningham, P. Hennig, and S. Lacoste-Julien.
Gaussian probabilities and expectation propagation.
under review. Preprint at arXiv, No... | [
"def",
"joint_min",
"(",
"mu",
",",
"var",
",",
"with_derivatives",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"logP",
"=",
"np",
".",
"zeros",
"(",
"mu",
".",
"shape",
")",
"D",
"=",
"mu",
".",
"shape",
"[",
"0",
"]",
"if",
"with_derivativ... | 31.893939 | 0.000461 |
def estimate_rate_matrix(C, dt=1.0, method='KL', sparsity=None,
t_agg=None, pi=None, tol=1.0E7, K0=None,
maxiter=100000, on_error='raise'):
r"""Estimate a reversible rate matrix from a count matrix.
Parameters
----------
C : (N,N) ndarray
count ... | [
"def",
"estimate_rate_matrix",
"(",
"C",
",",
"dt",
"=",
"1.0",
",",
"method",
"=",
"'KL'",
",",
"sparsity",
"=",
"None",
",",
"t_agg",
"=",
"None",
",",
"pi",
"=",
"None",
",",
"tol",
"=",
"1.0E7",
",",
"K0",
"=",
"None",
",",
"maxiter",
"=",
"1... | 43.686131 | 0.001797 |
def _retrieve(self):
"""Query Apache Tomcat Server Status Page in XML format and return
the result as an ElementTree object.
@return: ElementTree object of Status Page XML.
"""
url = "%s://%s:%d/manager/status" % (self._proto, self._host, self._port)
pa... | [
"def",
"_retrieve",
"(",
"self",
")",
":",
"url",
"=",
"\"%s://%s:%d/manager/status\"",
"%",
"(",
"self",
".",
"_proto",
",",
"self",
".",
"_host",
",",
"self",
".",
"_port",
")",
"params",
"=",
"{",
"}",
"params",
"[",
"'XML'",
"]",
"=",
"'true'",
"... | 37.076923 | 0.012146 |
def set_subnet_name(name):
'''
Set the local subnet name
:param str name: The new local subnet name
.. note::
Spaces are changed to dashes. Other special characters are removed.
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
... | [
"def",
"set_subnet_name",
"(",
"name",
")",
":",
"cmd",
"=",
"'systemsetup -setlocalsubnetname \"{0}\"'",
".",
"format",
"(",
"name",
")",
"__utils__",
"[",
"'mac_utils.execute_return_success'",
"]",
"(",
"cmd",
")",
"return",
"__utils__",
"[",
"'mac_utils.confirm_upd... | 23.5 | 0.001572 |
def plain_text_iter(fname: str, text_type: str, data_side: str) -> Iterable[str]:
"""
Extract plain text from file as iterable. Also take steps to ensure that
whitespace characters (including unicode newlines) are normalized and
outputs are line-parallel with inputs considering ASCII newlines only.
... | [
"def",
"plain_text_iter",
"(",
"fname",
":",
"str",
",",
"text_type",
":",
"str",
",",
"data_side",
":",
"str",
")",
"->",
"Iterable",
"[",
"str",
"]",
":",
"if",
"text_type",
"in",
"(",
"TEXT_UTF8_RAW",
",",
"TEXT_UTF8_TOKENIZED",
")",
":",
"with",
"thi... | 47.604651 | 0.000957 |
def list(context, sort, limit, where, verbose):
"""list(context, sort, limit. where. verbose)
List all topics.
>>> dcictl topic-list
:param string sort: Field to apply sort
:param integer limit: Max number of rows to return
:param string where: An optional filter criteria
:param boolean v... | [
"def",
"list",
"(",
"context",
",",
"sort",
",",
"limit",
",",
"where",
",",
"verbose",
")",
":",
"topics",
"=",
"topic",
".",
"list",
"(",
"context",
",",
"sort",
"=",
"sort",
",",
"limit",
"=",
"limit",
",",
"where",
"=",
"where",
")",
"utils",
... | 34.285714 | 0.002028 |
def create_insight(self, project_key, **kwargs):
"""Create a new insight
:param project_key: Project identifier, in the form of
projectOwner/projectid
:type project_key: str
:param title: Insight title
:type title: str
:param description: Insight description.
... | [
"def",
"create_insight",
"(",
"self",
",",
"project_key",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
"=",
"self",
".",
"__build_insight_obj",
"(",
"lambda",
":",
"_swagger",
".",
"InsightCreateRequest",
"(",
"title",
"=",
"kwargs",
".",
"get",
"(",
"'ti... | 41.259259 | 0.000877 |
def render_template_string(source, **context):
"""Renders a template from the given template source string
with the given context.
:param source: the sourcecode of the template to be
rendered
:param context: the variables that should be available in the
context of... | [
"def",
"render_template_string",
"(",
"source",
",",
"*",
"*",
"context",
")",
":",
"ctx",
"=",
"_app_ctx_stack",
".",
"top",
"ctx",
".",
"app",
".",
"update_template_context",
"(",
"context",
")",
"return",
"_render",
"(",
"ctx",
".",
"app",
".",
"jinja_e... | 38.384615 | 0.001957 |
def Message(self, Id=0):
"""Queries a chat message object.
:Parameters:
Id : int
Message Id.
:return: A chat message object.
:rtype: `ChatMessage`
"""
o = ChatMessage(self, Id)
o.Status # Test if such an id is known.
return o | [
"def",
"Message",
"(",
"self",
",",
"Id",
"=",
"0",
")",
":",
"o",
"=",
"ChatMessage",
"(",
"self",
",",
"Id",
")",
"o",
".",
"Status",
"# Test if such an id is known.",
"return",
"o"
] | 23.153846 | 0.009585 |
def _validate_compute_chunk_params(self,
graph,
dates,
sids,
initial_workspace):
"""
Verify that the values passed to compute_chunk are well-formed.... | [
"def",
"_validate_compute_chunk_params",
"(",
"self",
",",
"graph",
",",
"dates",
",",
"sids",
",",
"initial_workspace",
")",
":",
"root",
"=",
"self",
".",
"_root_mask_term",
"clsname",
"=",
"type",
"(",
"self",
")",
".",
"__name__",
"# Writing this out explici... | 47.316456 | 0.001572 |
def krylovMethod(self,tol=1e-8):
"""
We obtain ``pi`` by using the :func:``gmres`` solver for the system of linear equations.
It searches in Krylov subspace for a vector with minimal residual. The result is stored in the class attribute ``pi``.
Example
-------
>>> P... | [
"def",
"krylovMethod",
"(",
"self",
",",
"tol",
"=",
"1e-8",
")",
":",
"P",
"=",
"self",
".",
"getIrreducibleTransitionMatrix",
"(",
")",
"#if P consists of one element, then set self.pi = 1.0",
"if",
"P",
".",
"shape",
"==",
"(",
"1",
",",
"1",
")",
":",
"s... | 36.585366 | 0.018182 |
def show_instance(name, call=None):
'''
Show the details from Parallels concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
items = query(action='ve', command=name)
ret = {}
... | [
"def",
"show_instance",
"(",
"name",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The show_instance action must be called with -a or --action.'",
")",
"items",
"=",
"query",
"(",
"action",
"=",
"'v... | 27.692308 | 0.001342 |
def copy_file_clipboard(self, fnames=None):
"""Copy file(s)/folders(s) to clipboard."""
if fnames is None:
fnames = self.get_selected_filenames()
if not isinstance(fnames, (tuple, list)):
fnames = [fnames]
try:
file_content = QMimeData()
... | [
"def",
"copy_file_clipboard",
"(",
"self",
",",
"fnames",
"=",
"None",
")",
":",
"if",
"fnames",
"is",
"None",
":",
"fnames",
"=",
"self",
".",
"get_selected_filenames",
"(",
")",
"if",
"not",
"isinstance",
"(",
"fnames",
",",
"(",
"tuple",
",",
"list",
... | 47.941176 | 0.002407 |
async def authenticate_with_macaroon(url, insecure=False):
"""Login via macaroons and generate and return new API keys."""
executor = futures.ThreadPoolExecutor(max_workers=1)
def get_token():
client = httpbakery.Client()
resp = client.request(
'POST', '{}/account/?op=create_aut... | [
"async",
"def",
"authenticate_with_macaroon",
"(",
"url",
",",
"insecure",
"=",
"False",
")",
":",
"executor",
"=",
"futures",
".",
"ThreadPoolExecutor",
"(",
"max_workers",
"=",
"1",
")",
"def",
"get_token",
"(",
")",
":",
"client",
"=",
"httpbakery",
".",
... | 45.428571 | 0.001027 |
def import_files(self, path, timeoutSecs=180):
'''
Import a file or files into h2o. The 'file' parameter accepts a directory or a single file.
192.168.0.37:54323/ImportFiles.html?file=%2Fhome%2F0xdiag%2Fdatasets
'''
a = self.do_json_request('3/ImportFiles.json',
timeout=timeoutSecs,
... | [
"def",
"import_files",
"(",
"self",
",",
"path",
",",
"timeoutSecs",
"=",
"180",
")",
":",
"a",
"=",
"self",
".",
"do_json_request",
"(",
"'3/ImportFiles.json'",
",",
"timeout",
"=",
"timeoutSecs",
",",
"params",
"=",
"{",
"\"path\"",
":",
"path",
"}",
"... | 37.583333 | 0.010823 |
def parse(self):
"""
Parse a Pipfile (as seen in pipenv)
:return:
"""
try:
data = toml.loads(self.obj.content, _dict=OrderedDict)
if data:
for package_type in ['packages', 'dev-packages']:
if package_type in data:
... | [
"def",
"parse",
"(",
"self",
")",
":",
"try",
":",
"data",
"=",
"toml",
".",
"loads",
"(",
"self",
".",
"obj",
".",
"content",
",",
"_dict",
"=",
"OrderedDict",
")",
"if",
"data",
":",
"for",
"package_type",
"in",
"[",
"'packages'",
",",
"'dev-packag... | 42.884615 | 0.001754 |
def mean_first_passage_time(adjacency):
"""
Calculates mean first passage time of `adjacency`
The first passage time from i to j is the expected number of steps it takes
a random walker starting at node i to arrive for the first time at node j.
The mean first passage time is not a symmetric measure... | [
"def",
"mean_first_passage_time",
"(",
"adjacency",
")",
":",
"P",
"=",
"np",
".",
"linalg",
".",
"solve",
"(",
"np",
".",
"diag",
"(",
"np",
".",
"sum",
"(",
"adjacency",
",",
"axis",
"=",
"1",
")",
")",
",",
"adjacency",
")",
"n",
"=",
"len",
"... | 29 | 0.001308 |
def __build_lxml(target, source, env):
"""
General XSLT builder (HTML/FO), using the lxml module.
"""
from lxml import etree
xslt_ac = etree.XSLTAccessControl(read_file=True,
write_file=True,
create_dir=True,
... | [
"def",
"__build_lxml",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"from",
"lxml",
"import",
"etree",
"xslt_ac",
"=",
"etree",
".",
"XSLTAccessControl",
"(",
"read_file",
"=",
"True",
",",
"write_file",
"=",
"True",
",",
"create_dir",
"=",
"True",
... | 31.1 | 0.008316 |
def _create_dag_op(self, name, params, qargs):
"""
Create a DAG node out of a parsed AST op node.
Args:
name (str): operation name to apply to the dag.
params (list): op parameters
qargs (list(QuantumRegister, int)): qubits to attach to
Raises:
... | [
"def",
"_create_dag_op",
"(",
"self",
",",
"name",
",",
"params",
",",
"qargs",
")",
":",
"if",
"name",
"==",
"\"u0\"",
":",
"op_class",
"=",
"U0Gate",
"elif",
"name",
"==",
"\"u1\"",
":",
"op_class",
"=",
"U1Gate",
"elif",
"name",
"==",
"\"u2\"",
":",... | 28.916667 | 0.000929 |
def sndrcv(pks, pkt, timeout=None, inter=0, verbose=None, chainCC=False,
retry=0, multi=False, rcv_pks=None, store_unanswered=True,
process=None, prebuild=False):
"""Scapy raw function to send a packet and receive its answer.
WARNING: This is an internal function. Using sr/srp/sr1/srp is
... | [
"def",
"sndrcv",
"(",
"pks",
",",
"pkt",
",",
"timeout",
"=",
"None",
",",
"inter",
"=",
"0",
",",
"verbose",
"=",
"None",
",",
"chainCC",
"=",
"False",
",",
"retry",
"=",
"0",
",",
"multi",
"=",
"False",
",",
"rcv_pks",
"=",
"None",
",",
"store_... | 33.782609 | 0.000625 |
def add_months(self, value: int) -> datetime:
""" Add a number of months to the given date """
self.value = self.value + relativedelta(months=value)
return self.value | [
"def",
"add_months",
"(",
"self",
",",
"value",
":",
"int",
")",
"->",
"datetime",
":",
"self",
".",
"value",
"=",
"self",
".",
"value",
"+",
"relativedelta",
"(",
"months",
"=",
"value",
")",
"return",
"self",
".",
"value"
] | 46.75 | 0.010526 |
def look_up_and_get(cellpy_file_name, table_name):
"""Extracts table from cellpy hdf5-file."""
# infoname = '/CellpyData/info'
# dataname = '/CellpyData/dfdata'
# summaryname = '/CellpyData/dfsummary'
# fidname = '/CellpyData/fidtable'
# stepname = '/CellpyData/step_table'
root = '/CellpyD... | [
"def",
"look_up_and_get",
"(",
"cellpy_file_name",
",",
"table_name",
")",
":",
"# infoname = '/CellpyData/info'",
"# dataname = '/CellpyData/dfdata'",
"# summaryname = '/CellpyData/dfsummary'",
"# fidname = '/CellpyData/fidtable'",
"# stepname = '/CellpyData/step_table'",
"root",
"=",
... | 31.764706 | 0.001799 |
def reverse_dict(dict_obj):
"""Reverse a dict, so each value in it maps to a sorted list of its keys.
Parameters
----------
dict_obj : dict
A key-value dict.
Returns
-------
dict
A dict where each value maps to a sorted list of all the unique keys
that mapped to it.... | [
"def",
"reverse_dict",
"(",
"dict_obj",
")",
":",
"new_dict",
"=",
"{",
"}",
"for",
"key",
"in",
"dict_obj",
":",
"add_to_dict_val_set",
"(",
"dict_obj",
"=",
"new_dict",
",",
"key",
"=",
"dict_obj",
"[",
"key",
"]",
",",
"val",
"=",
"key",
")",
"for",... | 25.038462 | 0.001479 |
def top_path(sources, sinks, net_flux):
"""
Use the Dijkstra algorithm for finding the shortest path
connecting a set of source states from a set of sink states.
Parameters
----------
sources : array_like, int
One-dimensional list of nodes to define the source states.
sinks : array_... | [
"def",
"top_path",
"(",
"sources",
",",
"sinks",
",",
"net_flux",
")",
":",
"sources",
"=",
"np",
".",
"array",
"(",
"sources",
",",
"dtype",
"=",
"np",
".",
"int",
")",
".",
"reshape",
"(",
"(",
"-",
"1",
",",
")",
")",
"sinks",
"=",
"np",
"."... | 37.269565 | 0.002045 |
def get_default_value(self):
"""
Return the default value for the parameter. If here is no default value, return None
"""
if ('default_value' in self.attributes and
bool(self.attributes['default_value'].strip())):
return self.attributes['default_value']
... | [
"def",
"get_default_value",
"(",
"self",
")",
":",
"if",
"(",
"'default_value'",
"in",
"self",
".",
"attributes",
"and",
"bool",
"(",
"self",
".",
"attributes",
"[",
"'default_value'",
"]",
".",
"strip",
"(",
")",
")",
")",
":",
"return",
"self",
".",
... | 38.111111 | 0.008547 |
def _run_and_measure(self, quil_program, qubits, trials, random_seed) -> np.ndarray:
"""
Run a Forest ``run_and_measure`` job.
Users should use :py:func:`WavefunctionSimulator.run_and_measure` instead of calling
this directly.
"""
payload = run_and_measure_payload(quil_p... | [
"def",
"_run_and_measure",
"(",
"self",
",",
"quil_program",
",",
"qubits",
",",
"trials",
",",
"random_seed",
")",
"->",
"np",
".",
"ndarray",
":",
"payload",
"=",
"run_and_measure_payload",
"(",
"quil_program",
",",
"qubits",
",",
"trials",
",",
"random_seed... | 47.1 | 0.0125 |
def jvm_dependency_map(self):
"""A map of each JvmTarget in the context to the set of JvmTargets it depends on "directly".
"Directly" is in quotes here because it isn't quite the same as its normal use, which would be
filter(self._is_jvm_target, target.dependencies).
For this method, we define the set... | [
"def",
"jvm_dependency_map",
"(",
"self",
")",
":",
"jvm_deps",
"=",
"self",
".",
"_unfiltered_jvm_dependency_map",
"(",
")",
"return",
"{",
"target",
":",
"deps",
"for",
"target",
",",
"deps",
"in",
"jvm_deps",
".",
"items",
"(",
")",
"if",
"deps",
"and",... | 55.439024 | 0.008214 |
def sigfig_str(number, sigfig):
"""
References:
http://stackoverflow.com/questions/2663612/nicely-repr-float-in-python
"""
assert(sigfig > 0)
try:
d = decimal.Decimal(number)
except TypeError:
d = float_to_decimal(float(number))
sign, digits, exponent = d.as_tuple()
... | [
"def",
"sigfig_str",
"(",
"number",
",",
"sigfig",
")",
":",
"assert",
"(",
"sigfig",
">",
"0",
")",
"try",
":",
"d",
"=",
"decimal",
".",
"Decimal",
"(",
"number",
")",
"except",
"TypeError",
":",
"d",
"=",
"float_to_decimal",
"(",
"float",
"(",
"nu... | 31.263158 | 0.000816 |
def pt_on_bezier_curve(P=[(0.0, 0.0)], t=0.5):
'''Return point at t on bezier curve defined by control points P.
'''
assert isinstance(P, list)
assert len(P) > 0
for p in P:
assert isinstance(p, tuple)
for i in p:
assert len(p) > 1
assert isinstance(i, float)
... | [
"def",
"pt_on_bezier_curve",
"(",
"P",
"=",
"[",
"(",
"0.0",
",",
"0.0",
")",
"]",
",",
"t",
"=",
"0.5",
")",
":",
"assert",
"isinstance",
"(",
"P",
",",
"list",
")",
"assert",
"len",
"(",
"P",
")",
">",
"0",
"for",
"p",
"in",
"P",
":",
"asse... | 28.416667 | 0.009929 |
def parse_ref(self, field: Field) -> str:
"""
Parse the reference type for nested fields, if any.
"""
ref_name = type_name(name_for(field.schema))
return f"#/definitions/{ref_name}" | [
"def",
"parse_ref",
"(",
"self",
",",
"field",
":",
"Field",
")",
"->",
"str",
":",
"ref_name",
"=",
"type_name",
"(",
"name_for",
"(",
"field",
".",
"schema",
")",
")",
"return",
"f\"#/definitions/{ref_name}\""
] | 30.857143 | 0.009009 |
def close_multicast_socket(sock, address):
"""
Cleans up the given multicast socket.
Unregisters it of the multicast group.
Parameters should be the result of create_multicast_socket
:param sock: A multicast socket
:param address: The multicast address used by the socket
"""
if sock is... | [
"def",
"close_multicast_socket",
"(",
"sock",
",",
"address",
")",
":",
"if",
"sock",
"is",
"None",
":",
"return",
"if",
"address",
":",
"# Prepare the mreq structure to join the group",
"mreq",
"=",
"make_mreq",
"(",
"sock",
".",
"family",
",",
"address",
")",
... | 27.75 | 0.001244 |
def document_frequencies(self, hashes):
'''Get document frequencies for a list of hashes.
This will return all zeros unless the index was written with
`hash_frequencies` set. If :data:`DOCUMENT_HASH_KEY` is
included in `hashes`, that value will be returned with the
total number... | [
"def",
"document_frequencies",
"(",
"self",
",",
"hashes",
")",
":",
"result",
"=",
"{",
"}",
"for",
"(",
"k",
",",
"v",
")",
"in",
"self",
".",
"client",
".",
"get",
"(",
"HASH_FREQUENCY_TABLE",
",",
"*",
"[",
"(",
"h",
",",
")",
"for",
"h",
"in... | 38 | 0.002334 |
def branch(self, newname, subsamples=None, infile=None):
"""
Returns a copy of the Assembly object. Does not allow Assembly
object names to be replicated in namespace or path.
"""
## subsample by removal or keeping.
remove = 0
## is there a better way to ask if i... | [
"def",
"branch",
"(",
"self",
",",
"newname",
",",
"subsamples",
"=",
"None",
",",
"infile",
"=",
"None",
")",
":",
"## subsample by removal or keeping.",
"remove",
"=",
"0",
"## is there a better way to ask if it already exists?",
"if",
"(",
"newname",
"==",
"self"... | 38.645161 | 0.00814 |
def value(dtype, arg):
"""Validates that the given argument is a Value with a particular datatype
Parameters
----------
dtype : DataType subclass or DataType instance
arg : python literal or an ibis expression
If a python literal is given the validator tries to coerce it to an ibis
lite... | [
"def",
"value",
"(",
"dtype",
",",
"arg",
")",
":",
"if",
"not",
"isinstance",
"(",
"arg",
",",
"ir",
".",
"Expr",
")",
":",
"# coerce python literal to ibis literal",
"arg",
"=",
"ir",
".",
"literal",
"(",
"arg",
")",
"if",
"not",
"isinstance",
"(",
"... | 33.902439 | 0.000699 |
def write(file, data, samplerate, subtype=None, endian=None, format=None,
closefd=True):
"""Write data to a sound file.
.. note:: If `file` exists, it will be truncated and overwritten!
Parameters
----------
file : str or int or file-like object
The file to write to. See :class:... | [
"def",
"write",
"(",
"file",
",",
"data",
",",
"samplerate",
",",
"subtype",
"=",
"None",
",",
"endian",
"=",
"None",
",",
"format",
"=",
"None",
",",
"closefd",
"=",
"True",
")",
":",
"import",
"numpy",
"as",
"np",
"data",
"=",
"np",
".",
"asarray... | 34.796296 | 0.000518 |
def write_gds(self, outfile, cells=None, timestamp=None):
"""
Write the GDSII library to a file.
The dimensions actually written on the GDSII file will be the
dimensions of the objects created times the ratio
``unit/precision``. For example, if a circle with radius 1.5 is
... | [
"def",
"write_gds",
"(",
"self",
",",
"outfile",
",",
"cells",
"=",
"None",
",",
"timestamp",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"outfile",
",",
"basestring",
")",
":",
"outfile",
"=",
"open",
"(",
"outfile",
",",
"'wb'",
")",
"close",
"... | 43.096154 | 0.000873 |
def load_seit_data(directory, frequency_file='frequencies.dat',
data_prefix='volt_', **kwargs):
"""Load sEIT data from data directory. This function loads data previously
exported from reda using reda.exporters.crtomo.write_files_to_directory
Parameters
----------
directory : str... | [
"def",
"load_seit_data",
"(",
"directory",
",",
"frequency_file",
"=",
"'frequencies.dat'",
",",
"data_prefix",
"=",
"'volt_'",
",",
"*",
"*",
"kwargs",
")",
":",
"frequencies",
"=",
"np",
".",
"loadtxt",
"(",
"directory",
"+",
"os",
".",
"sep",
"+",
"freq... | 36.642857 | 0.000633 |
def search(self, q):
"""Search tweets by keyword.
Args:
q: keyword
Returns:
list: tweet list
"""
results = self._api.search(q=q)
return results | [
"def",
"search",
"(",
"self",
",",
"q",
")",
":",
"results",
"=",
"self",
".",
"_api",
".",
"search",
"(",
"q",
"=",
"q",
")",
"return",
"results"
] | 17.25 | 0.009174 |
def update_user(cls, username, email, password):
""" Edit user info """
if cls._check_email_changed(username, email):
# if we try to set the email to whatever it is already on SeAT, we get a HTTP422 error
logger.debug("Updating SeAT username %s with email %s and password" % (user... | [
"def",
"update_user",
"(",
"cls",
",",
"username",
",",
"email",
",",
"password",
")",
":",
"if",
"cls",
".",
"_check_email_changed",
"(",
"username",
",",
"email",
")",
":",
"# if we try to set the email to whatever it is already on SeAT, we get a HTTP422 error",
"logg... | 57 | 0.00863 |
def marker(self):
"""Return environment marker."""
if not self._marker:
assert markers, 'Package packaging is needed for environment markers'
self._marker = markers.Marker(self.raw)
return self._marker | [
"def",
"marker",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_marker",
":",
"assert",
"markers",
",",
"'Package packaging is needed for environment markers'",
"self",
".",
"_marker",
"=",
"markers",
".",
"Marker",
"(",
"self",
".",
"raw",
")",
"return",
... | 40.666667 | 0.012048 |
def set_bit_order(self, order):
"""Set order of bits to be read/written over serial lines. Should be
either MSBFIRST for most-significant first, or LSBFIRST for
least-signifcant first.
"""
# Set self._mask to the bitmask which points at the appropriate bit to
# read or w... | [
"def",
"set_bit_order",
"(",
"self",
",",
"order",
")",
":",
"# Set self._mask to the bitmask which points at the appropriate bit to",
"# read or write, and appropriate left/right shift operator function for",
"# reading/writing.",
"if",
"order",
"==",
"MSBFIRST",
":",
"self",
".",... | 43.555556 | 0.002497 |
def _normalize_params(image, width, height, crop):
"""
Normalize params and calculate aspect.
"""
if width is None and height is None:
raise ValueError("Either width or height must be set. Otherwise "
"resizing is useless.")
if width is None or height is None:
... | [
"def",
"_normalize_params",
"(",
"image",
",",
"width",
",",
"height",
",",
"crop",
")",
":",
"if",
"width",
"is",
"None",
"and",
"height",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Either width or height must be set. Otherwise \"",
"\"resizing is useless.\"... | 32.904762 | 0.001406 |
def format_timedelta(dt: timedelta) -> str:
"""
Formats timedelta to readable format, e.g. 1h30min.
:param dt: timedelta
:return: str
"""
seconds = int(dt.total_seconds())
days, remainder = divmod(seconds, 86400)
hours, remainder = divmod(remainder, 3600)
minutes, seconds = divmod(re... | [
"def",
"format_timedelta",
"(",
"dt",
":",
"timedelta",
")",
"->",
"str",
":",
"seconds",
"=",
"int",
"(",
"dt",
".",
"total_seconds",
"(",
")",
")",
"days",
",",
"remainder",
"=",
"divmod",
"(",
"seconds",
",",
"86400",
")",
"hours",
",",
"remainder",... | 26 | 0.001855 |
def get_first_edge_id_by_node_ids(self, node_a, node_b):
"""Returns the first (and possibly only) edge connecting node_a and node_b."""
ret = self.get_edge_ids_by_node_ids(node_a, node_b)
if not ret:
return None
else:
return ret[0] | [
"def",
"get_first_edge_id_by_node_ids",
"(",
"self",
",",
"node_a",
",",
"node_b",
")",
":",
"ret",
"=",
"self",
".",
"get_edge_ids_by_node_ids",
"(",
"node_a",
",",
"node_b",
")",
"if",
"not",
"ret",
":",
"return",
"None",
"else",
":",
"return",
"ret",
"[... | 40.142857 | 0.010453 |
def toLinear(self):
"""
NAME:
toLinear
PURPOSE:
convert a 3D orbit into a 1D orbit (z)
INPUT:
(none)
OUTPUT:
linear Orbit
HISTORY:
2010-11-30 - Written - Bovy (NYU)
"""
orbSetupKwargs= {'ro':... | [
"def",
"toLinear",
"(",
"self",
")",
":",
"orbSetupKwargs",
"=",
"{",
"'ro'",
":",
"None",
",",
"'vo'",
":",
"None",
",",
"'zo'",
":",
"self",
".",
"_orb",
".",
"_zo",
",",
"'solarmotion'",
":",
"self",
".",
"_orb",
".",
"_solarmotion",
"}",
"if",
... | 24.083333 | 0.014412 |
def sparkline_display_value_type(self, sparkline_display_value_type):
"""Sets the sparkline_display_value_type of this ChartSettings.
For the single stat view, whether to display the name of the query or the value of query # noqa: E501
:param sparkline_display_value_type: The sparkline_displa... | [
"def",
"sparkline_display_value_type",
"(",
"self",
",",
"sparkline_display_value_type",
")",
":",
"allowed_values",
"=",
"[",
"\"VALUE\"",
",",
"\"LABEL\"",
"]",
"# noqa: E501",
"if",
"sparkline_display_value_type",
"not",
"in",
"allowed_values",
":",
"raise",
"ValueEr... | 50.125 | 0.002448 |
def connect_get_node_proxy(self, name, **kwargs): # noqa: E501
"""connect_get_node_proxy # noqa: E501
connect GET requests to proxy of Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>... | [
"def",
"connect_get_node_proxy",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"con... | 46.545455 | 0.001914 |
def _update_services_instant_gratification(sdp_target_state: str):
"""For demonstration purposes only.
This instantly updates the services current state with the
target state, rather than wait on them or schedule random delays
in bringing them back up.
"""
service_states = get_service_state_lis... | [
"def",
"_update_services_instant_gratification",
"(",
"sdp_target_state",
":",
"str",
")",
":",
"service_states",
"=",
"get_service_state_list",
"(",
")",
"# Set the target state of services",
"for",
"service",
"in",
"service_states",
":",
"if",
"service",
".",
"current_s... | 41 | 0.00159 |
def setAutoRangeOn(self, axisNumber):
""" Sets the auto-range of the axis on.
:param axisNumber: 0 (X-axis), 1 (Y-axis), 2, (Both X and Y axes).
"""
setXYAxesAutoRangeOn(self, self.xAxisRangeCti, self.yAxisRangeCti, axisNumber) | [
"def",
"setAutoRangeOn",
"(",
"self",
",",
"axisNumber",
")",
":",
"setXYAxesAutoRangeOn",
"(",
"self",
",",
"self",
".",
"xAxisRangeCti",
",",
"self",
".",
"yAxisRangeCti",
",",
"axisNumber",
")"
] | 43.166667 | 0.011364 |
def validate_request_certificate(headers, data):
"""Ensure that the certificate and signature specified in the
request headers are truely from Amazon and correctly verify.
Returns True if certificate verification succeeds, False otherwise.
:param headers: Dictionary (or sufficiently dictionary-like) m... | [
"def",
"validate_request_certificate",
"(",
"headers",
",",
"data",
")",
":",
"# Make sure we have the appropriate headers.",
"if",
"'SignatureCertChainUrl'",
"not",
"in",
"headers",
"or",
"'Signature'",
"not",
"in",
"headers",
":",
"log",
".",
"error",
"(",
"'invalid... | 30.1875 | 0.002006 |
def _check_unpack_options(extensions, function, extra_args):
"""Checks what gets registered as an unpacker."""
# first make sure no other unpacker is registered for this extension
existing_extensions = {}
for name, info in _UNPACK_FORMATS.items():
for ext in info[0]:
existing_extensi... | [
"def",
"_check_unpack_options",
"(",
"extensions",
",",
"function",
",",
"extra_args",
")",
":",
"# first make sure no other unpacker is registered for this extension",
"existing_extensions",
"=",
"{",
"}",
"for",
"name",
",",
"info",
"in",
"_UNPACK_FORMATS",
".",
"items"... | 43.8125 | 0.001397 |
def markCollapsed( self, direction, sizes ):
"""
Updates the interface to reflect that the splitter is collapsed.
:param direction | <XSplitterHandle.CollapseDirection>
sizes | [<int>, ..]
"""
self._collapsed = True
self._storedSizes ... | [
"def",
"markCollapsed",
"(",
"self",
",",
"direction",
",",
"sizes",
")",
":",
"self",
".",
"_collapsed",
"=",
"True",
"self",
".",
"_storedSizes",
"=",
"sizes",
"[",
":",
"]",
"if",
"(",
"direction",
"==",
"XSplitterHandle",
".",
"CollapseDirection",
".",... | 44.541667 | 0.025641 |
def drinkAdmins(self, objects=False):
""" Returns a list of drink admins uids
"""
admins = self.group('drink', objects=objects)
return admins | [
"def",
"drinkAdmins",
"(",
"self",
",",
"objects",
"=",
"False",
")",
":",
"admins",
"=",
"self",
".",
"group",
"(",
"'drink'",
",",
"objects",
"=",
"objects",
")",
"return",
"admins"
] | 33.8 | 0.011561 |
def rotateX(self, angle):
""" Rotates the point around the X axis by the given angle in degrees. """
rad = angle * math.pi / 180
cosa = math.cos(rad)
sina = math.sin(rad)
y = self.y * cosa - self.z * sina
z = self.y * sina + self.z * cosa
return Point3D(self.x, y,... | [
"def",
"rotateX",
"(",
"self",
",",
"angle",
")",
":",
"rad",
"=",
"angle",
"*",
"math",
".",
"pi",
"/",
"180",
"cosa",
"=",
"math",
".",
"cos",
"(",
"rad",
")",
"sina",
"=",
"math",
".",
"sin",
"(",
"rad",
")",
"y",
"=",
"self",
".",
"y",
... | 39.5 | 0.009288 |
def get_mappings(cls, index_name, doc_type):
""" fetch mapped-items structure from cache """
return cache.get(cls.get_cache_item_name(index_name, doc_type), {}) | [
"def",
"get_mappings",
"(",
"cls",
",",
"index_name",
",",
"doc_type",
")",
":",
"return",
"cache",
".",
"get",
"(",
"cls",
".",
"get_cache_item_name",
"(",
"index_name",
",",
"doc_type",
")",
",",
"{",
"}",
")"
] | 58 | 0.011364 |
def worker_thread(context):
"""The worker thread routines."""
queue = context.task_queue
parameters = context.worker_parameters
if parameters.initializer is not None:
if not run_initializer(parameters.initializer, parameters.initargs):
context.state = ERROR
return
f... | [
"def",
"worker_thread",
"(",
"context",
")",
":",
"queue",
"=",
"context",
".",
"task_queue",
"parameters",
"=",
"context",
".",
"worker_parameters",
"if",
"parameters",
".",
"initializer",
"is",
"not",
"None",
":",
"if",
"not",
"run_initializer",
"(",
"parame... | 32.461538 | 0.002304 |
def create_sky_plot(observation_table, outfile):
"""Given a VOTable that describes the observation coverage provide a PDF of the skycoverge.
observation_table: vostable.arrary
outfile: name of file to write results to.
"""
# camera dimensions
width = 0.98
height = 0.98
ax = None
i... | [
"def",
"create_sky_plot",
"(",
"observation_table",
",",
"outfile",
")",
":",
"# camera dimensions",
"width",
"=",
"0.98",
"height",
"=",
"0.98",
"ax",
"=",
"None",
"if",
"outfile",
"[",
"0",
":",
"4",
"]",
"==",
"'vos:'",
":",
"temp_file",
"=",
"tempfile"... | 37.141026 | 0.002017 |
def vectorize_damping(params, damping=1.0, increase_list=[['psf-', 1e4]]):
"""
Returns a non-constant damping vector, allowing certain parameters to be
more strongly damped than others.
Parameters
----------
params : List
The list of parameter names, in order.
damping : ... | [
"def",
"vectorize_damping",
"(",
"params",
",",
"damping",
"=",
"1.0",
",",
"increase_list",
"=",
"[",
"[",
"'psf-'",
",",
"1e4",
"]",
"]",
")",
":",
"damp_vec",
"=",
"np",
".",
"ones",
"(",
"len",
"(",
"params",
")",
")",
"*",
"damping",
"for",
"n... | 34.538462 | 0.001083 |
def check_fastq(self, input_files, output_files, paired_end):
"""
Returns a follow sanity-check function to be run after a fastq conversion.
Run following a command that will produce the fastq files.
This function will make sure any input files have the same number of reads as the
... | [
"def",
"check_fastq",
"(",
"self",
",",
"input_files",
",",
"output_files",
",",
"paired_end",
")",
":",
"# Define a temporary function which we will return, to be called by the",
"# pipeline.",
"# Must define default parameters here based on the parameters passed in. This locks",
"# t... | 43.45614 | 0.002369 |
def calc_clusters(returns, n=None, plot=False):
"""
Calculates the clusters based on k-means
clustering.
Args:
* returns (pd.DataFrame): DataFrame of returns
* n (int): Specify # of clusters. If None, this
will be automatically determined
* plot (bool): Show plot?
... | [
"def",
"calc_clusters",
"(",
"returns",
",",
"n",
"=",
"None",
",",
"plot",
"=",
"False",
")",
":",
"# calculate correlation",
"corr",
"=",
"returns",
".",
"corr",
"(",
")",
"# calculate dissimilarity matrix",
"diss",
"=",
"1",
"-",
"corr",
"# scale down to 2 ... | 28.123288 | 0.000471 |
def PushPopItem(obj, key, value):
'''
A context manager to replace and restore a value using a getter and setter.
:param object obj: The object to replace/restore.
:param object key: The key to replace/restore in the object.
:param object value: The value to replace.
Example::
with Push... | [
"def",
"PushPopItem",
"(",
"obj",
",",
"key",
",",
"value",
")",
":",
"if",
"key",
"in",
"obj",
":",
"old_value",
"=",
"obj",
"[",
"key",
"]",
"obj",
"[",
"key",
"]",
"=",
"value",
"yield",
"value",
"obj",
"[",
"key",
"]",
"=",
"old_value",
"else... | 24.833333 | 0.001616 |
def add_channel(self, chname, workspace=None,
num_images=None, settings=None,
settings_template=None,
settings_share=None, share_keylist=None):
"""Create a new Ginga channel.
Parameters
----------
chname : str
The n... | [
"def",
"add_channel",
"(",
"self",
",",
"chname",
",",
"workspace",
"=",
"None",
",",
"num_images",
"=",
"None",
",",
"settings",
"=",
"None",
",",
"settings_template",
"=",
"None",
",",
"settings_share",
"=",
"None",
",",
"share_keylist",
"=",
"None",
")"... | 39.789916 | 0.001648 |
def evaluate_F(self, F):
"""
Given a fixed policy F, with the interpretation :math:`u = -F x`, this
function computes the matrix :math:`P_F` and constant :math:`d_F`
associated with discounted cost :math:`J_F(x) = x' P_F x + d_F`
Parameters
----------
F : array_l... | [
"def",
"evaluate_F",
"(",
"self",
",",
"F",
")",
":",
"# == Simplify names == #",
"Q",
",",
"R",
",",
"A",
",",
"B",
",",
"C",
"=",
"self",
".",
"Q",
",",
"self",
".",
"R",
",",
"self",
".",
"A",
",",
"self",
".",
"B",
",",
"self",
".",
"C",
... | 33.522727 | 0.001976 |
def proximal(self):
"""Return the proximal operator.
Raises
------
NotImplementedError
if ``outer_exp`` is not 1 or ``singular_vector_exp`` is not 1, 2 or
infinity
"""
if self.outernorm.exponent != 1:
raise NotImplementedError('`proxim... | [
"def",
"proximal",
"(",
"self",
")",
":",
"if",
"self",
".",
"outernorm",
".",
"exponent",
"!=",
"1",
":",
"raise",
"NotImplementedError",
"(",
"'`proximal` only implemented for '",
"'`outer_exp==1`'",
")",
"if",
"self",
".",
"pwisenorm",
".",
"exponent",
"not",... | 38.890244 | 0.000612 |
def _get_repo_details(saltenv):
'''
Return repo details for the specified saltenv as a namedtuple
'''
contextkey = 'winrepo._get_repo_details.{0}'.format(saltenv)
if contextkey in __context__:
(winrepo_source_dir, local_dest, winrepo_file) = __context__[contextkey]
else:
winrepo... | [
"def",
"_get_repo_details",
"(",
"saltenv",
")",
":",
"contextkey",
"=",
"'winrepo._get_repo_details.{0}'",
".",
"format",
"(",
"saltenv",
")",
"if",
"contextkey",
"in",
"__context__",
":",
"(",
"winrepo_source_dir",
",",
"local_dest",
",",
"winrepo_file",
")",
"=... | 37.948052 | 0.001668 |
def main(argv=None):
"""Run Nutch command using REST API."""
global Verbose, Mock
if argv is None:
argv = sys.argv
if len(argv) < 5: die('Bad args')
try:
opts, argv = getopt.getopt(argv[1:], 'hs:p:mv',
['help', 'server=', 'port=', 'mock', 'verbose'])
except getopt.Geto... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"global",
"Verbose",
",",
"Mock",
"if",
"argv",
"is",
"None",
":",
"argv",
"=",
"sys",
".",
"argv",
"if",
"len",
"(",
"argv",
")",
"<",
"5",
":",
"die",
"(",
"'Bad args'",
")",
"try",
":",
"opt... | 32.264706 | 0.012389 |
def _customized_loader(container, loader=Loader, mapping_tag=_MAPPING_TAG):
"""
Create or update loader with making given callble 'container' to make
mapping objects such as dict and OrderedDict, used to construct python
object from yaml mapping node internally.
:param container: Set container used... | [
"def",
"_customized_loader",
"(",
"container",
",",
"loader",
"=",
"Loader",
",",
"mapping_tag",
"=",
"_MAPPING_TAG",
")",
":",
"def",
"construct_mapping",
"(",
"loader",
",",
"node",
",",
"deep",
"=",
"False",
")",
":",
"\"\"\"Construct python object from yaml ma... | 38.085106 | 0.000545 |
def quantity(*args):
"""Create a quantity. This can be from a scalar or vector.
Example::
q1 = quantity(1.0, "km/s")
q2 = quantity("1km/s")
q1 = quantity([1.0,2.0], "km/s")
"""
if len(args) == 1:
if isinstance(args[0], str):
# use copy constructor to create quant... | [
"def",
"quantity",
"(",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"1",
":",
"if",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"str",
")",
":",
"# use copy constructor to create quantity from string",
"return",
"Quantity",
"(",
"from_st... | 31.571429 | 0.001098 |
def breakfast(self, message="Breakfast is ready", shout: bool = False):
"""Say something in the morning"""
return self.helper.output(message, shout) | [
"def",
"breakfast",
"(",
"self",
",",
"message",
"=",
"\"Breakfast is ready\"",
",",
"shout",
":",
"bool",
"=",
"False",
")",
":",
"return",
"self",
".",
"helper",
".",
"output",
"(",
"message",
",",
"shout",
")"
] | 54 | 0.012195 |
def encode(self, splitchars=';, \t', maxlinelen=None, linesep='\n'):
r"""Encode a message header into an RFC-compliant format.
There are many issues involved in converting a given string for use in
an email header. Only certain character sets are readable in most
email clients, and as ... | [
"def",
"encode",
"(",
"self",
",",
"splitchars",
"=",
"';, \\t'",
",",
"maxlinelen",
"=",
"None",
",",
"linesep",
"=",
"'\\n'",
")",
":",
"self",
".",
"_normalize",
"(",
")",
"if",
"maxlinelen",
"is",
"None",
":",
"maxlinelen",
"=",
"self",
".",
"_maxl... | 51.475 | 0.000715 |
def datagram_received(self, data, addr):
"""Datagram received callback."""
#_LOGGER.debug(data)
if not self.box_ip or self.box_ip == addr[0]:
self.responses(MediaroomNotify(addr, data)) | [
"def",
"datagram_received",
"(",
"self",
",",
"data",
",",
"addr",
")",
":",
"#_LOGGER.debug(data)",
"if",
"not",
"self",
".",
"box_ip",
"or",
"self",
".",
"box_ip",
"==",
"addr",
"[",
"0",
"]",
":",
"self",
".",
"responses",
"(",
"MediaroomNotify",
"(",... | 43.4 | 0.013575 |
def weird_log_graph(self, stream):
''' Build up a graph (nodes and edges from a Bro weird.log) '''
weird_log = list(stream)
print 'Entering weird_log_graph...(%d rows)' % len(weird_log)
# Here we're just going to capture that something weird
# happened between two hosts
... | [
"def",
"weird_log_graph",
"(",
"self",
",",
"stream",
")",
":",
"weird_log",
"=",
"list",
"(",
"stream",
")",
"print",
"'Entering weird_log_graph...(%d rows)'",
"%",
"len",
"(",
"weird_log",
")",
"# Here we're just going to capture that something weird",
"# happened betwe... | 34.806452 | 0.001803 |
def lookup(self, hostname):
"""
Find a hostkey entry for a given hostname or IP. If no entry is found,
``None`` is returned. Otherwise a dictionary of keytype to key is
returned. The keytype will be either ``"ssh-rsa"`` or ``"ssh-dss"``.
:param str hostname: the hostname (or ... | [
"def",
"lookup",
"(",
"self",
",",
"hostname",
")",
":",
"class",
"SubDict",
"(",
"MutableMapping",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"hostname",
",",
"entries",
",",
"hostkeys",
")",
":",
"self",
".",
"_hostname",
"=",
"hostname",
"self",
... | 33.430769 | 0.000894 |
def validate_accounting_equation(cls):
"""Check that all accounts sum to 0"""
balances = [account.balance(raw=True) for account in Account.objects.root_nodes()]
if sum(balances, Balance()) != 0:
raise exceptions.AccountingEquationViolationError(
"Account balances do n... | [
"def",
"validate_accounting_equation",
"(",
"cls",
")",
":",
"balances",
"=",
"[",
"account",
".",
"balance",
"(",
"raw",
"=",
"True",
")",
"for",
"account",
"in",
"Account",
".",
"objects",
".",
"root_nodes",
"(",
")",
"]",
"if",
"sum",
"(",
"balances",... | 54.428571 | 0.010336 |
def _two_func_initializer(freqs, signal):
"""
This is a helper function for heuristic estimation of the initial parameters
used in fitting dual peak functions
_do_two_lorentzian_fit
_do_two_gaussian_fit
"""
# Use the signal for a rough estimate of the parameters for initialization:
r_signal = n... | [
"def",
"_two_func_initializer",
"(",
"freqs",
",",
"signal",
")",
":",
"# Use the signal for a rough estimate of the parameters for initialization:",
"r_signal",
"=",
"np",
".",
"real",
"(",
"signal",
")",
"# The local maxima have a zero-crossing in their derivative, so we start by... | 37.75 | 0.020121 |
def _logger_stream(self):
"""Add stream logging handler."""
sh = logging.StreamHandler()
sh.set_name('sh')
sh.setLevel(logging.INFO)
sh.setFormatter(self._logger_formatter)
self.log.addHandler(sh) | [
"def",
"_logger_stream",
"(",
"self",
")",
":",
"sh",
"=",
"logging",
".",
"StreamHandler",
"(",
")",
"sh",
".",
"set_name",
"(",
"'sh'",
")",
"sh",
".",
"setLevel",
"(",
"logging",
".",
"INFO",
")",
"sh",
".",
"setFormatter",
"(",
"self",
".",
"_log... | 34 | 0.008197 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.