text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def retrieve_handle_record(self, handle, handlerecord_json=None):
'''
Retrieve a handle record from the Handle server as a dict. If there
is several entries of the same type, only the first one is
returned. Values of complex types (such as HS_ADMIN) are
transformed to strings.
... | [
"def",
"retrieve_handle_record",
"(",
"self",
",",
"handle",
",",
"handlerecord_json",
"=",
"None",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'retrieve_handle_record...'",
")",
"handlerecord_json",
"=",
"self",
".",
"__get_handle_record_if_necessary",
"(",
"handle",
"... | 47.107143 | 0.002972 |
def conditional_loss_ratio(loss_ratios, poes, probability):
"""
Return the loss ratio corresponding to the given PoE (Probability
of Exceendance). We can have four cases:
1. If `probability` is in `poes` it takes the bigger
corresponding loss_ratios.
2. If it is in `(poe1, poe2)` wher... | [
"def",
"conditional_loss_ratio",
"(",
"loss_ratios",
",",
"poes",
",",
"probability",
")",
":",
"assert",
"len",
"(",
"loss_ratios",
")",
">=",
"3",
",",
"loss_ratios",
"rpoes",
"=",
"poes",
"[",
":",
":",
"-",
"1",
"]",
"if",
"probability",
">",
"poes",... | 37.916667 | 0.000536 |
def find_by_b64id(self, _id, **kwargs):
"""
Pass me a base64-encoded ObjectId
"""
return self.find_one({"_id": ObjectId(base64.b64decode(_id))}, **kwargs) | [
"def",
"find_by_b64id",
"(",
"self",
",",
"_id",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"find_one",
"(",
"{",
"\"_id\"",
":",
"ObjectId",
"(",
"base64",
".",
"b64decode",
"(",
"_id",
")",
")",
"}",
",",
"*",
"*",
"kwargs",
")"
] | 30.333333 | 0.016043 |
def images(cam):
"""Extract images from input stream to jpg files.
Args:
cam: Input stream of raw rosbag messages.
Returns:
File instances for images of input stream.
"""
# Set output stream title and pull first message
yield marv.set_header(title=cam.topic)
# Fetch and pr... | [
"def",
"images",
"(",
"cam",
")",
":",
"# Set output stream title and pull first message",
"yield",
"marv",
".",
"set_header",
"(",
"title",
"=",
"cam",
".",
"topic",
")",
"# Fetch and process first 20 image messages",
"name_template",
"=",
"'%s-{}.jpg'",
"%",
"cam",
... | 30.533333 | 0.001058 |
def manipulate_multiproc_safe(traj):
""" Target function that manipulates the trajectory.
Stores the current name of the process into the trajectory and
**overwrites** previous settings.
:param traj:
Trajectory container with multiprocessing safe storage service
"""
# Manipulate the... | [
"def",
"manipulate_multiproc_safe",
"(",
"traj",
")",
":",
"# Manipulate the data in the trajectory",
"traj",
".",
"last_process_name",
"=",
"mp",
".",
"current_process",
"(",
")",
".",
"name",
"# Store the manipulated data",
"traj",
".",
"results",
".",
"f_store",
"(... | 28.4375 | 0.002128 |
def parse(self, fo):
"""
Convert MDmodule output to motifs
Parameters
----------
fo : file-like
File object containing MDmodule output.
Returns
-------
motifs : list
List of Motif instances.
"""
motifs = []... | [
"def",
"parse",
"(",
"self",
",",
"fo",
")",
":",
"motifs",
"=",
"[",
"]",
"nucs",
"=",
"{",
"\"A\"",
":",
"0",
",",
"\"C\"",
":",
"1",
",",
"\"G\"",
":",
"2",
",",
"\"T\"",
":",
"3",
"}",
"p",
"=",
"re",
".",
"compile",
"(",
"r'(\\d+)\\s+(\\... | 30.142857 | 0.010327 |
def diff(a, b, presorted=False, buffersize=None, tempdir=None, cache=True,
strict=False):
"""
Find the difference between rows in two tables. Returns a pair of tables.
E.g.::
>>> import petl as etl
>>> a = [['foo', 'bar', 'baz'],
... ['A', 1, True],
... ['... | [
"def",
"diff",
"(",
"a",
",",
"b",
",",
"presorted",
"=",
"False",
",",
"buffersize",
"=",
"None",
",",
"tempdir",
"=",
"None",
",",
"cache",
"=",
"True",
",",
"strict",
"=",
"False",
")",
":",
"if",
"not",
"presorted",
":",
"a",
"=",
"sort",
"("... | 33.081967 | 0.000481 |
def rm_alias(alias):
'''
Remove an entry from the aliases file
CLI Example:
.. code-block:: bash
salt '*' aliases.rm_alias alias
'''
if not get_target(alias):
return True
lines = __parse_aliases()
out = []
for (line_alias, line_target, line_comment) in lines:
... | [
"def",
"rm_alias",
"(",
"alias",
")",
":",
"if",
"not",
"get_target",
"(",
"alias",
")",
":",
"return",
"True",
"lines",
"=",
"__parse_aliases",
"(",
")",
"out",
"=",
"[",
"]",
"for",
"(",
"line_alias",
",",
"line_target",
",",
"line_comment",
")",
"in... | 20.857143 | 0.002183 |
def reload(self):
'''
Clear plugin manager state and reload plugins.
This method will make use of :meth:`clear` and :meth:`load_plugin`,
so all internal state will be cleared, and all plugins defined in
:data:`self.app.config['plugin_modules']` will be loaded.
'''
... | [
"def",
"reload",
"(",
"self",
")",
":",
"self",
".",
"clear",
"(",
")",
"for",
"plugin",
"in",
"self",
".",
"app",
".",
"config",
".",
"get",
"(",
"'plugin_modules'",
",",
"(",
")",
")",
":",
"self",
".",
"load_plugin",
"(",
"plugin",
")"
] | 38.727273 | 0.004587 |
def sharded_filenames(filename_prefix, num_shards):
"""Sharded filenames given prefix and number of shards."""
shard_suffix = "%05d-of-%05d"
return [
"%s-%s" % (filename_prefix, shard_suffix % (i, num_shards))
for i in range(num_shards)
] | [
"def",
"sharded_filenames",
"(",
"filename_prefix",
",",
"num_shards",
")",
":",
"shard_suffix",
"=",
"\"%05d-of-%05d\"",
"return",
"[",
"\"%s-%s\"",
"%",
"(",
"filename_prefix",
",",
"shard_suffix",
"%",
"(",
"i",
",",
"num_shards",
")",
")",
"for",
"i",
"in"... | 36 | 0.015504 |
def _git_command(params, cwd):
"""
Executes a git command, returning the output
:param params:
A list of the parameters to pass to git
:param cwd:
The working directory to execute git in
:return:
A 2-element tuple of (stdout, stderr)
"""
proc = subprocess.Popen(
... | [
"def",
"_git_command",
"(",
"params",
",",
"cwd",
")",
":",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"'git'",
"]",
"+",
"params",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
",",
"cwd",
"=... | 23 | 0.001546 |
def _normWidth(self, w, maxw):
"""
Helper for calculating percentages
"""
if type(w) == type(""):
w = ((maxw / 100.0) * float(w[: - 1]))
elif (w is None) or (w == "*"):
w = maxw
return min(w, maxw) | [
"def",
"_normWidth",
"(",
"self",
",",
"w",
",",
"maxw",
")",
":",
"if",
"type",
"(",
"w",
")",
"==",
"type",
"(",
"\"\"",
")",
":",
"w",
"=",
"(",
"(",
"maxw",
"/",
"100.0",
")",
"*",
"float",
"(",
"w",
"[",
":",
"-",
"1",
"]",
")",
")",... | 29 | 0.011152 |
def tange_grun(v, v0, gamma0, a, b):
"""
calculate Gruneisen parameter for the Tange equation
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param gamma0: Gruneisen parameter at 1 bar
:param a: volume-independent adjustable parameters
:param b: volume-indepen... | [
"def",
"tange_grun",
"(",
"v",
",",
"v0",
",",
"gamma0",
",",
"a",
",",
"b",
")",
":",
"x",
"=",
"v",
"/",
"v0",
"return",
"gamma0",
"*",
"(",
"1.",
"+",
"a",
"*",
"(",
"np",
".",
"power",
"(",
"x",
",",
"b",
")",
"-",
"1.",
")",
")"
] | 34.076923 | 0.002198 |
def exchange_delete(self, exchange, if_unused=False,
nowait=False, ticket=None):
"""
delete an exchange
This method deletes an exchange. When an exchange is deleted
all queue bindings on the exchange are cancelled.
PARAMETERS:
exchange: shortstr
... | [
"def",
"exchange_delete",
"(",
"self",
",",
"exchange",
",",
"if_unused",
"=",
"False",
",",
"nowait",
"=",
"False",
",",
"ticket",
"=",
"None",
")",
":",
"args",
"=",
"AMQPWriter",
"(",
")",
"if",
"ticket",
"is",
"not",
"None",
":",
"args",
".",
"wr... | 30.671642 | 0.001414 |
def datetime(self):
"""
Returns a datetime object of the month, day, year, and time the game
was played.
"""
date_string = '%s %s' % (self._date, self._year)
date_string = re.sub(r' \(\d+\)', '', date_string)
return datetime.strptime(date_string, '%A, %b %d %Y') | [
"def",
"datetime",
"(",
"self",
")",
":",
"date_string",
"=",
"'%s %s'",
"%",
"(",
"self",
".",
"_date",
",",
"self",
".",
"_year",
")",
"date_string",
"=",
"re",
".",
"sub",
"(",
"r' \\(\\d+\\)'",
",",
"''",
",",
"date_string",
")",
"return",
"datetim... | 38.875 | 0.006289 |
def _convert_timedelta_to_seconds(timedelta):
"""Returns the total seconds calculated from the supplied timedelta.
(Function provided to enable running on Python 2.6 which lacks timedelta.total_seconds()).
"""
days_in_seconds = timedelta.days * 24 * 3600
return int((timedelta.microseconds + (ti... | [
"def",
"_convert_timedelta_to_seconds",
"(",
"timedelta",
")",
":",
"days_in_seconds",
"=",
"timedelta",
".",
"days",
"*",
"24",
"*",
"3600",
"return",
"int",
"(",
"(",
"timedelta",
".",
"microseconds",
"+",
"(",
"timedelta",
".",
"seconds",
"+",
"days_in_seco... | 46.125 | 0.007979 |
def from_cells(cls, cells):
"""
Creates a MOC from a numpy array representing the HEALPix cells.
Parameters
----------
cells : `numpy.ndarray`
Must be a numpy structured array (See https://docs.scipy.org/doc/numpy-1.15.0/user/basics.rec.html).
The structu... | [
"def",
"from_cells",
"(",
"cls",
",",
"cells",
")",
":",
"shift",
"=",
"(",
"AbstractMOC",
".",
"HPY_MAX_NORDER",
"-",
"cells",
"[",
"\"depth\"",
"]",
")",
"<<",
"1",
"p1",
"=",
"cells",
"[",
"\"ipix\"",
"]",
"p2",
"=",
"cells",
"[",
"\"ipix\"",
"]",... | 30.185185 | 0.003567 |
def plot_calibration_curve(y_true, probas_list, clf_names=None, n_bins=10,
title='Calibration plots (Reliability Curves)',
ax=None, figsize=None, cmap='nipy_spectral',
title_fontsize="large", text_fontsize="medium"):
"""Plots calibrati... | [
"def",
"plot_calibration_curve",
"(",
"y_true",
",",
"probas_list",
",",
"clf_names",
"=",
"None",
",",
"n_bins",
"=",
"10",
",",
"title",
"=",
"'Calibration plots (Reliability Curves)'",
",",
"ax",
"=",
"None",
",",
"figsize",
"=",
"None",
",",
"cmap",
"=",
... | 42.522727 | 0.000348 |
def make_close_message(code=1000, message=b''):
"""Close the websocket, sending the specified code and message."""
return _make_frame(struct.pack('!H%ds' % len(message), code, message),
opcode=OPCODE_CLOSE) | [
"def",
"make_close_message",
"(",
"code",
"=",
"1000",
",",
"message",
"=",
"b''",
")",
":",
"return",
"_make_frame",
"(",
"struct",
".",
"pack",
"(",
"'!H%ds'",
"%",
"len",
"(",
"message",
")",
",",
"code",
",",
"message",
")",
",",
"opcode",
"=",
"... | 58.5 | 0.004219 |
def read_mda(attribute):
"""Read HDFEOS metadata and return a dict with all the key/value pairs."""
lines = attribute.split('\n')
mda = {}
current_dict = mda
path = []
prev_line = None
for line in lines:
if not line:
continue
... | [
"def",
"read_mda",
"(",
"attribute",
")",
":",
"lines",
"=",
"attribute",
".",
"split",
"(",
"'\\n'",
")",
"mda",
"=",
"{",
"}",
"current_dict",
"=",
"mda",
"path",
"=",
"[",
"]",
"prev_line",
"=",
"None",
"for",
"line",
"in",
"lines",
":",
"if",
"... | 31.47619 | 0.002201 |
def get_manifest(self, repo_name, digest=None, version="v1"):
'''
get_manifest should return an image manifest
for a particular repo and tag. The image details
are extracted when the client is generated.
Parameters
==========
repo_name: reference to the <username>/<reposi... | [
"def",
"get_manifest",
"(",
"self",
",",
"repo_name",
",",
"digest",
"=",
"None",
",",
"version",
"=",
"\"v1\"",
")",
":",
"accepts",
"=",
"{",
"'config'",
":",
"\"application/vnd.docker.container.image.v1+json\"",
",",
"'v1'",
":",
"\"application/vnd.docker.distrib... | 32.733333 | 0.003956 |
def send_highspeed(self, data, progress_callback):
"""Send a script to a device at highspeed, reporting progress.
This method takes a binary blob and downloads it to the device as fast
as possible, calling the passed progress_callback periodically with
updates on how far it has gotten.
... | [
"def",
"send_highspeed",
"(",
"self",
",",
"data",
",",
"progress_callback",
")",
":",
"if",
"not",
"self",
".",
"connected",
":",
"raise",
"HardwareError",
"(",
"\"Cannot send a script if we are not in a connected state\"",
")",
"if",
"isinstance",
"(",
"data",
","... | 43.607143 | 0.005609 |
def _sanity_check_registered_locations_parent_locations(query_metadata_table):
"""Assert that all registered locations' parent locations are also registered."""
for location, location_info in query_metadata_table.registered_locations:
if (location != query_metadata_table.root_location and
... | [
"def",
"_sanity_check_registered_locations_parent_locations",
"(",
"query_metadata_table",
")",
":",
"for",
"location",
",",
"location_info",
"in",
"query_metadata_table",
".",
"registered_locations",
":",
"if",
"(",
"location",
"!=",
"query_metadata_table",
".",
"root_loca... | 70.75 | 0.006975 |
def use_federated_gradebook_view(self):
"""Pass through to provider GradeSystemLookupSession.use_federated_gradebook_view"""
self._gradebook_view = FEDERATED
# self._get_provider_session('grade_system_lookup_session') # To make sure the session is tracked
for session in self._get_provide... | [
"def",
"use_federated_gradebook_view",
"(",
"self",
")",
":",
"self",
".",
"_gradebook_view",
"=",
"FEDERATED",
"# self._get_provider_session('grade_system_lookup_session') # To make sure the session is tracked",
"for",
"session",
"in",
"self",
".",
"_get_provider_sessions",
"(",... | 50.333333 | 0.008677 |
def rebalance_brokers(self):
"""Rebalance partition-count across brokers within each replication-group."""
for rg in six.itervalues(self.cluster_topology.rgs):
rg.rebalance_brokers() | [
"def",
"rebalance_brokers",
"(",
"self",
")",
":",
"for",
"rg",
"in",
"six",
".",
"itervalues",
"(",
"self",
".",
"cluster_topology",
".",
"rgs",
")",
":",
"rg",
".",
"rebalance_brokers",
"(",
")"
] | 51.75 | 0.014286 |
def code(self, value):
"""
Set the code of the message.
:type value: Codes
:param value: the code
:raise AttributeError: if value is not a valid code
"""
if value not in list(defines.Codes.LIST.keys()) and value is not None:
raise AttributeError
... | [
"def",
"code",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"not",
"in",
"list",
"(",
"defines",
".",
"Codes",
".",
"LIST",
".",
"keys",
"(",
")",
")",
"and",
"value",
"is",
"not",
"None",
":",
"raise",
"AttributeError",
"self",
".",
"_code"... | 30.090909 | 0.005865 |
def postinit(self, exc=None, cause=None):
"""Do some setup after initialisation.
:param exc: What is being raised.
:type exc: NodeNG or None
:param cause: The exception being used to raise this one.
:type cause: NodeNG or None
"""
self.exc = exc
self.cau... | [
"def",
"postinit",
"(",
"self",
",",
"exc",
"=",
"None",
",",
"cause",
"=",
"None",
")",
":",
"self",
".",
"exc",
"=",
"exc",
"self",
".",
"cause",
"=",
"cause"
] | 29.090909 | 0.006061 |
def clean(outputdir, drivers=None):
"""Remove driver executables from the specified outputdir.
drivers can be a list of drivers to filter which executables
to remove. Specify a version using an equal sign i.e.: 'chrome=2.2'
"""
if drivers:
# Generate a list of tuples: [(driver_name, request... | [
"def",
"clean",
"(",
"outputdir",
",",
"drivers",
"=",
"None",
")",
":",
"if",
"drivers",
":",
"# Generate a list of tuples: [(driver_name, requested_version)]",
"# If driver string does not contain a version, the second element",
"# of the tuple is None.",
"# Example:",
"# [('driv... | 40.365854 | 0.00059 |
def build_arg_parser2():
"""
Build an argument parser using optparse. Use it when python version is 2.5 or 2.6.
"""
usage_str = "Smatch calculator -- arguments"
parser = optparse.OptionParser(usage=usage_str)
parser.add_option("-f", "--files", nargs=2, dest="f", type="string",
... | [
"def",
"build_arg_parser2",
"(",
")",
":",
"usage_str",
"=",
"\"Smatch calculator -- arguments\"",
"parser",
"=",
"optparse",
".",
"OptionParser",
"(",
"usage",
"=",
"usage_str",
")",
"parser",
".",
"add_option",
"(",
"\"-f\"",
",",
"\"--files\"",
",",
"nargs",
... | 65.965517 | 0.007213 |
def tie_break(sorted_list, results, prop_key, ndecoys):
"""
When finding the best ensemble, using "find_best_ensemble," in the event of a tie, we break it by looking at
enrichment factors at successively larger FPF values, beginning with the smallest FPF not trained on.
:param sorted_list:
:param re... | [
"def",
"tie_break",
"(",
"sorted_list",
",",
"results",
",",
"prop_key",
",",
"ndecoys",
")",
":",
"# Generate a list of the number of decoys that correspond to the FPF",
"# values at which enrichment factors were determined, not including ndecoys, the training value",
"ndecoys_list",
... | 53.09375 | 0.008092 |
def _reduce(self, op, name, axis=0, skipna=True, numeric_only=None,
filter_type=None, **kwds):
""" perform the reduction type operation if we can """
func = getattr(self, name, None)
if func is None:
raise TypeError("{klass} cannot perform the operation {op}".format(
... | [
"def",
"_reduce",
"(",
"self",
",",
"op",
",",
"name",
",",
"axis",
"=",
"0",
",",
"skipna",
"=",
"True",
",",
"numeric_only",
"=",
"None",
",",
"filter_type",
"=",
"None",
",",
"*",
"*",
"kwds",
")",
":",
"func",
"=",
"getattr",
"(",
"self",
","... | 53 | 0.006961 |
def execute(self, context):
"""Upload a file to Azure Blob Storage."""
hook = WasbHook(wasb_conn_id=self.wasb_conn_id)
self.log.info(
'Uploading %s to wasb://%s '
'as %s'.format(self.file_path, self.container_name, self.blob_name)
)
hook.load_file(self.fil... | [
"def",
"execute",
"(",
"self",
",",
"context",
")",
":",
"hook",
"=",
"WasbHook",
"(",
"wasb_conn_id",
"=",
"self",
".",
"wasb_conn_id",
")",
"self",
".",
"log",
".",
"info",
"(",
"'Uploading %s to wasb://%s '",
"'as %s'",
".",
"format",
"(",
"self",
".",
... | 44.444444 | 0.004902 |
def _split_line(self,data_list,line_num,text):
"""Builds list of text lines by splitting text lines at wrap point
This function will determine if the input text line needs to be
wrapped (split) into separate lines. If so, the first wrap point
will be determined and the first line appen... | [
"def",
"_split_line",
"(",
"self",
",",
"data_list",
",",
"line_num",
",",
"text",
")",
":",
"# if blank line or context separator, just add it to the output list",
"if",
"not",
"line_num",
":",
"data_list",
".",
"append",
"(",
"(",
"line_num",
",",
"text",
")",
"... | 35.740741 | 0.005547 |
def feed_forward(self, input_data, prediction=False):
"""Propagate forward through the layer
**Parameters:**
input_data : ``GPUArray``
Input data to compute activations for.
prediction : bool, optional
Whether to use prediction model. Only relevant when using
... | [
"def",
"feed_forward",
"(",
"self",
",",
"input_data",
",",
"prediction",
"=",
"False",
")",
":",
"if",
"input_data",
".",
"shape",
"[",
"1",
"]",
"!=",
"self",
".",
"W",
".",
"shape",
"[",
"0",
"]",
":",
"raise",
"ValueError",
"(",
"'Number of outputs... | 33.405405 | 0.003931 |
def path(self, name):
"""
Look for files in subdirectory of MEDIA_ROOT using the tenant's
domain_url value as the specifier.
"""
if name is None:
name = ''
try:
location = safe_join(self.location, connection.tenant.domain_url)
except Attrib... | [
"def",
"path",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"''",
"try",
":",
"location",
"=",
"safe_join",
"(",
"self",
".",
"location",
",",
"connection",
".",
"tenant",
".",
"domain_url",
")",
"except",
"Attrib... | 33.588235 | 0.003407 |
def set_up_logging(logger, level, should_be_quiet):
"""
Sets up logging for pepe.
:param logger:
The logger object to update.
:param level:
Logging level specified at command line.
:param should_be_quiet:
Boolean value for the -q option.
:return:
logging level ``... | [
"def",
"set_up_logging",
"(",
"logger",
",",
"level",
",",
"should_be_quiet",
")",
":",
"LOGGING_LEVELS",
"=",
"{",
"'DEBUG'",
":",
"logging",
".",
"DEBUG",
",",
"'INFO'",
":",
"logging",
".",
"INFO",
",",
"'WARNING'",
":",
"logging",
".",
"WARNING",
",",
... | 28.27027 | 0.000924 |
def register_lcformat(formatkey,
fileglob,
timecols,
magcols,
errcols,
readerfunc_module,
readerfunc,
readerfunc_kwargs=None,
normfunc_module=No... | [
"def",
"register_lcformat",
"(",
"formatkey",
",",
"fileglob",
",",
"timecols",
",",
"magcols",
",",
"errcols",
",",
"readerfunc_module",
",",
"readerfunc",
",",
"readerfunc_kwargs",
"=",
"None",
",",
"normfunc_module",
"=",
"None",
",",
"normfunc",
"=",
"None",... | 42.264574 | 0.002073 |
def answer(self, c, details):
"""Answer will provide all necessary feedback for the caller
Args:
c (int): HTTP Code
details (dict): Response payload
Returns:
dict: Response payload
Raises:
ErrAtlasBadRequest
... | [
"def",
"answer",
"(",
"self",
",",
"c",
",",
"details",
")",
":",
"if",
"c",
"in",
"[",
"Settings",
".",
"SUCCESS",
",",
"Settings",
".",
"CREATED",
",",
"Settings",
".",
"ACCEPTED",
"]",
":",
"return",
"details",
"elif",
"c",
"==",
"Settings",
".",
... | 33.324324 | 0.004728 |
def get_original_field_value(self, name):
"""
Returns original field value or None
"""
name = self.get_real_name(name)
try:
value = self.__original_data__[name]
except KeyError:
return None
try:
return value.export_original_da... | [
"def",
"get_original_field_value",
"(",
"self",
",",
"name",
")",
":",
"name",
"=",
"self",
".",
"get_real_name",
"(",
"name",
")",
"try",
":",
"value",
"=",
"self",
".",
"__original_data__",
"[",
"name",
"]",
"except",
"KeyError",
":",
"return",
"None",
... | 24.4 | 0.005263 |
def _val_pt_xml(self):
"""
The unicode XML snippet containing the ``<c:pt>`` elements containing
the values for this series.
"""
xml = ''
for idx, value in enumerate(self._series.values):
if value is None:
continue
xml += (
... | [
"def",
"_val_pt_xml",
"(",
"self",
")",
":",
"xml",
"=",
"''",
"for",
"idx",
",",
"value",
"in",
"enumerate",
"(",
"self",
".",
"_series",
".",
"values",
")",
":",
"if",
"value",
"is",
"None",
":",
"continue",
"xml",
"+=",
"(",
"' <c:pt ... | 32.277778 | 0.003344 |
def T(self, ID, sign):
""" Returns the term of an object in a sign. """
lon = self.terms[sign][ID]
ID = 'T_%s_%s' % (ID, sign)
return self.G(ID, 0, lon) | [
"def",
"T",
"(",
"self",
",",
"ID",
",",
"sign",
")",
":",
"lon",
"=",
"self",
".",
"terms",
"[",
"sign",
"]",
"[",
"ID",
"]",
"ID",
"=",
"'T_%s_%s'",
"%",
"(",
"ID",
",",
"sign",
")",
"return",
"self",
".",
"G",
"(",
"ID",
",",
"0",
",",
... | 36 | 0.01087 |
def volume(self, vol, clim=None, method='mip', threshold=None,
cmap='grays'):
"""Show a 3D volume
Parameters
----------
vol : ndarray
Volume to render.
clim : tuple of two floats | None
The contrast limits. The values in the volume are mapp... | [
"def",
"volume",
"(",
"self",
",",
"vol",
",",
"clim",
"=",
"None",
",",
"method",
"=",
"'mip'",
",",
"threshold",
"=",
"None",
",",
"cmap",
"=",
"'grays'",
")",
":",
"self",
".",
"_configure_3d",
"(",
")",
"volume",
"=",
"scene",
".",
"Volume",
"(... | 31.942857 | 0.002604 |
def update(self, t_obj):
"""[update table]
Arguments:
t_obj {[objs of DeclarativeMeta]} -- [update the table]
"""
if isinstance(t_obj, Iterable):
self._session.add_all(t_obj)
else:
self._session.add(t_obj) | [
"def",
"update",
"(",
"self",
",",
"t_obj",
")",
":",
"if",
"isinstance",
"(",
"t_obj",
",",
"Iterable",
")",
":",
"self",
".",
"_session",
".",
"add_all",
"(",
"t_obj",
")",
"else",
":",
"self",
".",
"_session",
".",
"add",
"(",
"t_obj",
")"
] | 24.818182 | 0.007067 |
def isOnSilicon(self, ra_deg, dec_deg, padding_pix=DEFAULT_PADDING):
"""Returns True if the given location is observable with a science CCD.
Parameters
----------
ra_deg : float
Right Ascension (J2000) in decimal degrees.
dec_deg : float
Declination (J20... | [
"def",
"isOnSilicon",
"(",
"self",
",",
"ra_deg",
",",
"dec_deg",
",",
"padding_pix",
"=",
"DEFAULT_PADDING",
")",
":",
"ch",
",",
"col",
",",
"row",
"=",
"self",
".",
"getChannelColRow",
"(",
"ra_deg",
",",
"dec_deg",
")",
"# Modules 3 and 7 are no longer ope... | 39.307692 | 0.00191 |
def betacf(a, b, x):
"""
This function evaluates the continued fraction form of the incomplete
Beta function, betai. (Adapted from: Numerical Recipies in C.)
Usage: lbetacf(a,b,x)
"""
ITMAX = 200
EPS = 3.0e-7
bm = az = am = 1.0
qab = a + b
qap = a + 1.0
qam = a - 1.0
... | [
"def",
"betacf",
"(",
"a",
",",
"b",
",",
"x",
")",
":",
"ITMAX",
"=",
"200",
"EPS",
"=",
"3.0e-7",
"bm",
"=",
"az",
"=",
"am",
"=",
"1.0",
"qab",
"=",
"a",
"+",
"b",
"qap",
"=",
"a",
"+",
"1.0",
"qam",
"=",
"a",
"-",
"1.0",
"bz",
"=",
... | 26.5625 | 0.001135 |
def click_event(event):
"""On click, bring the cell under the cursor to Life"""
grid_x_coord = int(divmod(event.x, cell_size)[0])
grid_y_coord = int(divmod(event.y, cell_size)[0])
world[grid_x_coord][grid_y_coord].value = True
color = world[x][y].color_alive.get_as_hex()
canvas.itemconfig(canvas... | [
"def",
"click_event",
"(",
"event",
")",
":",
"grid_x_coord",
"=",
"int",
"(",
"divmod",
"(",
"event",
".",
"x",
",",
"cell_size",
")",
"[",
"0",
"]",
")",
"grid_y_coord",
"=",
"int",
"(",
"divmod",
"(",
"event",
".",
"y",
",",
"cell_size",
")",
"[... | 51.428571 | 0.002732 |
def extract_params(params):
"""
Extracts the values of a set of parameters, recursing into nested dictionaries.
"""
values = []
if isinstance(params, dict):
for key, value in params.items():
values.extend(extract_params(value))
elif isinstance(params, list):
for value... | [
"def",
"extract_params",
"(",
"params",
")",
":",
"values",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"params",
",",
"dict",
")",
":",
"for",
"key",
",",
"value",
"in",
"params",
".",
"items",
"(",
")",
":",
"values",
".",
"extend",
"(",
"extract_param... | 30.357143 | 0.004566 |
def out_8(library, session, space, offset, data, extended=False):
"""Write in an 8-bit value from the specified memory space and offset.
Corresponds to viOut8* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
... | [
"def",
"out_8",
"(",
"library",
",",
"session",
",",
"space",
",",
"offset",
",",
"data",
",",
"extended",
"=",
"False",
")",
":",
"if",
"extended",
":",
"return",
"library",
".",
"viOut8Ex",
"(",
"session",
",",
"space",
",",
"offset",
",",
"data",
... | 45.055556 | 0.002415 |
def _get_brokerclient(self, node_id):
"""
Get a broker client.
:param int node_id: Broker node ID
:raises KeyError: for an unknown node ID
:returns: :class:`_KafkaBrokerClient`
"""
if self._closing:
raise ClientError("Cannot get broker client for node... | [
"def",
"_get_brokerclient",
"(",
"self",
",",
"node_id",
")",
":",
"if",
"self",
".",
"_closing",
":",
"raise",
"ClientError",
"(",
"\"Cannot get broker client for node_id={}: {} has been closed\"",
".",
"format",
"(",
"node_id",
",",
"self",
")",
")",
"if",
"node... | 41.666667 | 0.003911 |
def dtypes(self):
"""
Return the dtypes in the DataFrame.
This returns a Series with the data type of each column.
The result's index is the original DataFrame's columns. Columns
with mixed types are stored with the ``object`` dtype. See
:ref:`the User Guide <basics.dtyp... | [
"def",
"dtypes",
"(",
"self",
")",
":",
"from",
"pandas",
"import",
"Series",
"return",
"Series",
"(",
"self",
".",
"_data",
".",
"get_dtypes",
"(",
")",
",",
"index",
"=",
"self",
".",
"_info_axis",
",",
"dtype",
"=",
"np",
".",
"object_",
")"
] | 31.735294 | 0.001799 |
def pos(self, element = None):
''' Tries to decide about the part of speech. '''
tags = []
if element:
if re.search('[\w|\s]+ [m|f]\.', element, re.U):
tags.append('NN')
if '[VERB]' in element:
tags.append('VB')
if 'adj.' in element and re.search('([\w|\s]+, [\w|\s]+)', element, re.U):
tags.... | [
"def",
"pos",
"(",
"self",
",",
"element",
"=",
"None",
")",
":",
"tags",
"=",
"[",
"]",
"if",
"element",
":",
"if",
"re",
".",
"search",
"(",
"'[\\w|\\s]+ [m|f]\\.'",
",",
"element",
",",
"re",
".",
"U",
")",
":",
"tags",
".",
"append",
"(",
"'N... | 28.25 | 0.053533 |
def key_from_dict(**kwargs):
"""
Return a unique string representation of a dict as quickly as possible.
Used to generated deduplication keys from a request.
"""
out = []
stack = [kwargs]
while stack:
obj = stack.pop()
if isinstance(obj, dict):
stack.extend(sorted... | [
"def",
"key_from_dict",
"(",
"*",
"*",
"kwargs",
")",
":",
"out",
"=",
"[",
"]",
"stack",
"=",
"[",
"kwargs",
"]",
"while",
"stack",
":",
"obj",
"=",
"stack",
".",
"pop",
"(",
")",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"stack",
... | 29.0625 | 0.002083 |
def mmGetMetricStabilityConfusion(self):
"""
For each iteration that doesn't follow a reset, looks at every other
iteration for the same world that doesn't follow a reset, and computes the
number of bits that show up in one or the other set of active cells for
that iteration, but not both. This metr... | [
"def",
"mmGetMetricStabilityConfusion",
"(",
"self",
")",
":",
"self",
".",
"_mmComputeSequenceRepresentationData",
"(",
")",
"numbers",
"=",
"self",
".",
"_mmData",
"[",
"\"stabilityConfusion\"",
"]",
"return",
"Metric",
"(",
"self",
",",
"\"stability confusion\"",
... | 43.615385 | 0.001727 |
def fetch(self):
"""
Retrieves the remote design document content and populates the locally
cached DesignDocument dictionary. View content is stored either as
View or QueryIndexView objects which are extensions of the ``dict``
type. All other design document data are stored dir... | [
"def",
"fetch",
"(",
"self",
")",
":",
"super",
"(",
"DesignDocument",
",",
"self",
")",
".",
"fetch",
"(",
")",
"if",
"self",
".",
"views",
":",
"for",
"view_name",
",",
"view_def",
"in",
"iteritems_",
"(",
"self",
".",
"get",
"(",
"'views'",
",",
... | 43.032258 | 0.002199 |
def list_themes(directory=None):
"""Gets a list of the installed themes."""
repo = require_repo(directory)
path = os.path.join(repo, themes_dir)
return os.listdir(path) if os.path.isdir(path) else None | [
"def",
"list_themes",
"(",
"directory",
"=",
"None",
")",
":",
"repo",
"=",
"require_repo",
"(",
"directory",
")",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"repo",
",",
"themes_dir",
")",
"return",
"os",
".",
"listdir",
"(",
"path",
")",
"if... | 42.6 | 0.004608 |
def push(self):
""" create a github repo and push the local repo into it
"""
self.github_repo.create_and_push()
self._repo = self.github_repo.repo
return self._repo | [
"def",
"push",
"(",
"self",
")",
":",
"self",
".",
"github_repo",
".",
"create_and_push",
"(",
")",
"self",
".",
"_repo",
"=",
"self",
".",
"github_repo",
".",
"repo",
"return",
"self",
".",
"_repo"
] | 33.166667 | 0.009804 |
def merge_section(self, section, filter_func=None):
"""
Add section.checks to self, if not skipped by self._add_check_callback.
order, description, etc. are not updated.
"""
for check in section.checks:
if filter_func and not filter_func(check):
continue
self.add_check(check) | [
"def",
"merge_section",
"(",
"self",
",",
"section",
",",
"filter_func",
"=",
"None",
")",
":",
"for",
"check",
"in",
"section",
".",
"checks",
":",
"if",
"filter_func",
"and",
"not",
"filter_func",
"(",
"check",
")",
":",
"continue",
"self",
".",
"add_c... | 34.222222 | 0.009494 |
def sync_with_handlers(self, handlers=()):
'''
Sync the stored log records to the provided log handlers.
'''
if not handlers:
return
while self.__messages:
record = self.__messages.pop(0)
for handler in handlers:
if handler.lev... | [
"def",
"sync_with_handlers",
"(",
"self",
",",
"handlers",
"=",
"(",
")",
")",
":",
"if",
"not",
"handlers",
":",
"return",
"while",
"self",
".",
"__messages",
":",
"record",
"=",
"self",
".",
"__messages",
".",
"pop",
"(",
"0",
")",
"for",
"handler",
... | 35.466667 | 0.003663 |
def _compare_match(dict1, dict2):
'''
Compare two dictionaries and return a boolean value if their values match.
'''
for karg, warg in six.iteritems(dict1):
if karg in dict2 and dict2[karg] != warg:
return False
return True | [
"def",
"_compare_match",
"(",
"dict1",
",",
"dict2",
")",
":",
"for",
"karg",
",",
"warg",
"in",
"six",
".",
"iteritems",
"(",
"dict1",
")",
":",
"if",
"karg",
"in",
"dict2",
"and",
"dict2",
"[",
"karg",
"]",
"!=",
"warg",
":",
"return",
"False",
"... | 32 | 0.003802 |
def htmlReadDoc(cur, URL, encoding, options):
"""parse an XML in-memory document and build a tree. """
ret = libxml2mod.htmlReadDoc(cur, URL, encoding, options)
if ret is None:raise treeError('htmlReadDoc() failed')
return xmlDoc(_obj=ret) | [
"def",
"htmlReadDoc",
"(",
"cur",
",",
"URL",
",",
"encoding",
",",
"options",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"htmlReadDoc",
"(",
"cur",
",",
"URL",
",",
"encoding",
",",
"options",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
... | 50.2 | 0.011765 |
def register(*paths, methods=None, name=None, handler=None):
"""Mark Handler.method to aiohttp handler.
It uses when registration of the handler with application is postponed.
::
class AwesomeHandler(Handler):
def get(self, request):
return "I'm awesome!"
... | [
"def",
"register",
"(",
"*",
"paths",
",",
"methods",
"=",
"None",
",",
"name",
"=",
"None",
",",
"handler",
"=",
"None",
")",
":",
"def",
"wrapper",
"(",
"method",
")",
":",
"\"\"\"Store route params into method.\"\"\"",
"method",
"=",
"to_coroutine",
"(",
... | 30.708333 | 0.001316 |
def _build_cache_key(self, uri):
"""
Build sha1 hex cache key to handle key length and whitespace to be compatible with Memcached
"""
key = uri.clone(ext=None, version=None)
if six.PY3:
key = key.encode('utf-8')
return sha1(key).hexdigest() | [
"def",
"_build_cache_key",
"(",
"self",
",",
"uri",
")",
":",
"key",
"=",
"uri",
".",
"clone",
"(",
"ext",
"=",
"None",
",",
"version",
"=",
"None",
")",
"if",
"six",
".",
"PY3",
":",
"key",
"=",
"key",
".",
"encode",
"(",
"'utf-8'",
")",
"return... | 29.3 | 0.009934 |
def fitNorm_v2(self, specVals):
"""Fit the normalization given a set of spectral values
that define a spectral shape.
This version uses `scipy.optimize.fmin`.
Parameters
----------
specVals : an array of (nebin values that define a spectral shape
xlims : f... | [
"def",
"fitNorm_v2",
"(",
"self",
",",
"specVals",
")",
":",
"from",
"scipy",
".",
"optimize",
"import",
"fmin",
"def",
"fToMin",
"(",
"x",
")",
":",
"return",
"self",
".",
"__call__",
"(",
"specVals",
"*",
"x",
")",
"result",
"=",
"fmin",
"(",
"fToM... | 28.52381 | 0.006462 |
def _set_get_nameserver_detail(self, v, load=False):
"""
Setter method for get_nameserver_detail, mapped from YANG variable /brocade_nameserver_rpc/get_nameserver_detail (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_get_nameserver_detail is considered as a privat... | [
"def",
"_set_get_nameserver_detail",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
... | 78.16 | 0.005561 |
def execute(self):
"""Run selected module generator."""
if self._cli_arguments['cfn']:
generate_sample_cfn_module(self.env_root)
elif self._cli_arguments['sls']:
generate_sample_sls_module(self.env_root)
elif self._cli_arguments['sls-tsc']:
generate_sa... | [
"def",
"execute",
"(",
"self",
")",
":",
"if",
"self",
".",
"_cli_arguments",
"[",
"'cfn'",
"]",
":",
"generate_sample_cfn_module",
"(",
"self",
".",
"env_root",
")",
"elif",
"self",
".",
"_cli_arguments",
"[",
"'sls'",
"]",
":",
"generate_sample_sls_module",
... | 46.777778 | 0.002328 |
def validate(self, columns=None):
"""
Validates the current record object to make sure it is ok to commit to the database. If
the optional override dictionary is passed in, then it will use the given values vs. the one
stored with this record object which can be useful to check to see i... | [
"def",
"validate",
"(",
"self",
",",
"columns",
"=",
"None",
")",
":",
"schema",
"=",
"self",
".",
"schema",
"(",
")",
"if",
"not",
"columns",
":",
"ignore_flags",
"=",
"orb",
".",
"Column",
".",
"Flags",
".",
"Virtual",
"|",
"orb",
".",
"Column",
... | 35.625 | 0.00427 |
def save_config(self, cmd="save config", confirm=True, confirm_response="y"):
"""Saves Config."""
self.enable()
if confirm:
output = self.send_command_timing(command_string=cmd)
if confirm_response:
output += self.send_command_timing(confirm_response)
... | [
"def",
"save_config",
"(",
"self",
",",
"cmd",
"=",
"\"save config\"",
",",
"confirm",
"=",
"True",
",",
"confirm_response",
"=",
"\"y\"",
")",
":",
"self",
".",
"enable",
"(",
")",
"if",
"confirm",
":",
"output",
"=",
"self",
".",
"send_command_timing",
... | 42.428571 | 0.003295 |
def get_tectonic_regionalisation(self, regionalisation, region_type=None):
'''
Defines the tectonic region and updates the shear modulus,
magnitude scaling relation and displacement to length ratio using
the regional values, if not previously defined for the fault
:param regiona... | [
"def",
"get_tectonic_regionalisation",
"(",
"self",
",",
"regionalisation",
",",
"region_type",
"=",
"None",
")",
":",
"if",
"region_type",
":",
"self",
".",
"trt",
"=",
"region_type",
"if",
"not",
"self",
".",
"trt",
"in",
"regionalisation",
".",
"key_list",
... | 45.540541 | 0.001743 |
def resolve_dep_from_path(self, depname):
""" If we can find the dep in the PATH, then we consider it to
be a system dependency that we should not bundle in the package """
if is_system_dep(depname):
return True
for d in self._path:
name = os.path.join(d, depname... | [
"def",
"resolve_dep_from_path",
"(",
"self",
",",
"depname",
")",
":",
"if",
"is_system_dep",
"(",
"depname",
")",
":",
"return",
"True",
"for",
"d",
"in",
"self",
".",
"_path",
":",
"name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"d",
",",
"depnam... | 33.083333 | 0.004902 |
def detect_components(args, distro):
"""
Since the package split, now there are various different Ceph components to
install like:
* ceph
* ceph-mon
* ceph-mgr
* ceph-osd
* ceph-mds
This helper function should parse the args that may contain specifics about
these flags and retu... | [
"def",
"detect_components",
"(",
"args",
",",
"distro",
")",
":",
"# the flag that prevents all logic here is the `--repo` flag which is used",
"# when no packages should be installed, just the repo files, so check for",
"# that here and return an empty list (which is equivalent to say 'no",
"... | 31.854839 | 0.000491 |
def _init_kws(self, **kws_usr):
"""Return a dict containing user-specified plotting options."""
kws_self = {}
user_keys = set(kws_usr)
for objname, expset in self.exp_keys.items():
usrkeys_curr = user_keys.intersection(expset)
kws_self[objname] = get_kwargs(kws_us... | [
"def",
"_init_kws",
"(",
"self",
",",
"*",
"*",
"kws_usr",
")",
":",
"kws_self",
"=",
"{",
"}",
"user_keys",
"=",
"set",
"(",
"kws_usr",
")",
"for",
"objname",
",",
"expset",
"in",
"self",
".",
"exp_keys",
".",
"items",
"(",
")",
":",
"usrkeys_curr",... | 46.7 | 0.004202 |
def combine(files: List[str], output_file: str, key: str = None, file_attrs: Dict[str, str] = None, batch_size: int = 1000, convert_attrs: bool = False) -> None:
"""
Combine two or more loom files and save as a new loom file
Args:
files (list of str): the list of input files (full paths)
output_file (str): ... | [
"def",
"combine",
"(",
"files",
":",
"List",
"[",
"str",
"]",
",",
"output_file",
":",
"str",
",",
"key",
":",
"str",
"=",
"None",
",",
"file_attrs",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
"=",
"None",
",",
"batch_size",
":",
"int",
"=",
"1000... | 44.045455 | 0.024735 |
def wait_for_interrupt(self, check_interval=1.0, max_time=None):
"""Run the event loop until we receive a ctrl-c interrupt or max_time passes.
This method will wake up every 1 second by default to check for any
interrupt signals or if the maximum runtime has expired. This can be
set lo... | [
"def",
"wait_for_interrupt",
"(",
"self",
",",
"check_interval",
"=",
"1.0",
",",
"max_time",
"=",
"None",
")",
":",
"self",
".",
"start",
"(",
")",
"wait",
"=",
"max",
"(",
"check_interval",
",",
"0.01",
")",
"accum",
"=",
"0",
"try",
":",
"while",
... | 39.121212 | 0.003023 |
def smear(idx, factor):
"""
This function will take as input an array of indexes and return every
unique index within the specified factor of the inputs.
E.g.: smear([5,7,100],2) = [3,4,5,6,7,8,9,98,99,100,101,102]
Parameters
-----------
idx : numpy.array of ints
The indexes to be ... | [
"def",
"smear",
"(",
"idx",
",",
"factor",
")",
":",
"s",
"=",
"[",
"idx",
"]",
"for",
"i",
"in",
"range",
"(",
"factor",
"+",
"1",
")",
":",
"a",
"=",
"i",
"-",
"factor",
"/",
"2",
"s",
"+=",
"[",
"idx",
"+",
"a",
"]",
"return",
"numpy",
... | 24 | 0.003082 |
def send_msg(name,
recipient,
subject,
sender=None,
profile=None,
use_ssl='True',
attachments=None):
'''
Send a message via SMTP
.. code-block:: yaml
server-warning-message:
smtp.send_msg:
- name: '... | [
"def",
"send_msg",
"(",
"name",
",",
"recipient",
",",
"subject",
",",
"sender",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"use_ssl",
"=",
"'True'",
",",
"attachments",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'change... | 27.676923 | 0.002147 |
def post_notification(self, ntype, sender, *args, **kwargs):
"""Post notification to all registered observers.
The registered callback will be called as::
callback(ntype, sender, *args, **kwargs)
Parameters
----------
ntype : hashable
The notification t... | [
"def",
"post_notification",
"(",
"self",
",",
"ntype",
",",
"sender",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"(",
"ntype",
"==",
"None",
"or",
"sender",
"==",
"None",
")",
":",
"raise",
"NotificationError",
"(",
"\"Notification type a... | 34 | 0.004515 |
def tree_statistics(tree):
"""
prints the types and counts of elements present in a SaltDocument tree,
e.g.::
layers: 3
sDocument: 1
nodes: 252
labels: 2946
edges: 531
"""
all_elements = tree.findall('//')
tag_counter = defaultdict(int)
for element i... | [
"def",
"tree_statistics",
"(",
"tree",
")",
":",
"all_elements",
"=",
"tree",
".",
"findall",
"(",
"'//'",
")",
"tag_counter",
"=",
"defaultdict",
"(",
"int",
")",
"for",
"element",
"in",
"all_elements",
":",
"tag_counter",
"[",
"element",
".",
"tag",
"]",... | 24.833333 | 0.002155 |
def _get_or_convert_magnitude(self, mag_letter):
""" Takes input of the magnitude letter and ouputs the magnitude fetched from the catalogue or a converted value
:return:
"""
allowed_mags = "UBVJIHKLMN"
catalogue_mags = 'BVIJHK'
if mag_letter not in allowed_mags or not l... | [
"def",
"_get_or_convert_magnitude",
"(",
"self",
",",
"mag_letter",
")",
":",
"allowed_mags",
"=",
"\"UBVJIHKLMN\"",
"catalogue_mags",
"=",
"'BVIJHK'",
"if",
"mag_letter",
"not",
"in",
"allowed_mags",
"or",
"not",
"len",
"(",
"mag_letter",
")",
"==",
"1",
":",
... | 49.827586 | 0.005431 |
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 v_Us_B(self):
"""
returns the implications {v:Us} based on B
This is L=∪ min L_i in [1]_
"""
Bg = reduce(lambda x,y:x&y,(B(g,self.width-1) for g in self))
gw = self.width
return v_Us_dict(Bg, gw) | [
"def",
"v_Us_B",
"(",
"self",
")",
":",
"Bg",
"=",
"reduce",
"(",
"lambda",
"x",
",",
"y",
":",
"x",
"&",
"y",
",",
"(",
"B",
"(",
"g",
",",
"self",
".",
"width",
"-",
"1",
")",
"for",
"g",
"in",
"self",
")",
")",
"gw",
"=",
"self",
".",
... | 31 | 0.027451 |
def maf_iterator(fn, index_friendly=False,
yield_class=MultipleSequenceAlignment, yield_kw_args={},
verbose=False):
"""
Iterate of MAF format file and yield <yield_class> objects for each block.
MAF files are arranged in blocks. Each block is a multiple alignment. Within
a blo... | [
"def",
"maf_iterator",
"(",
"fn",
",",
"index_friendly",
"=",
"False",
",",
"yield_class",
"=",
"MultipleSequenceAlignment",
",",
"yield_kw_args",
"=",
"{",
"}",
",",
"verbose",
"=",
"False",
")",
":",
"try",
":",
"fh",
"=",
"open",
"(",
"fn",
")",
"exce... | 40.077922 | 0.006958 |
def make_withitem(queue, stack):
"""
Make an ast.withitem node.
"""
context_expr = make_expr(stack)
# This is a POP_TOP for just "with <expr>:".
# This is a STORE_NAME(name) for "with <expr> as <name>:".
as_instr = queue.popleft()
if isinstance(as_instr, (instrs.STORE_FAST,
... | [
"def",
"make_withitem",
"(",
"queue",
",",
"stack",
")",
":",
"context_expr",
"=",
"make_expr",
"(",
"stack",
")",
"# This is a POP_TOP for just \"with <expr>:\".",
"# This is a STORE_NAME(name) for \"with <expr> as <name>:\".",
"as_instr",
"=",
"queue",
".",
"popleft",
"("... | 37.454545 | 0.001183 |
def rfc3339(self):
"""Return an RFC 3339-compliant timestamp.
Returns:
(str): Timestamp string according to RFC 3339 spec.
"""
if self._nanosecond == 0:
return to_rfc3339(self)
nanos = str(self._nanosecond).rjust(9, '0').rstrip("0")
return "{}.{}Z... | [
"def",
"rfc3339",
"(",
"self",
")",
":",
"if",
"self",
".",
"_nanosecond",
"==",
"0",
":",
"return",
"to_rfc3339",
"(",
"self",
")",
"nanos",
"=",
"str",
"(",
"self",
".",
"_nanosecond",
")",
".",
"rjust",
"(",
"9",
",",
"'0'",
")",
".",
"rstrip",
... | 36.3 | 0.005376 |
def from_dict(cls, tx):
"""Transforms a Python dictionary to a Transaction object.
Args:
tx_body (dict): The Transaction to be transformed.
Returns:
:class:`~bigchaindb.common.transaction.Transaction`
"""
inputs = [Input.from_dict(input_)... | [
"def",
"from_dict",
"(",
"cls",
",",
"tx",
")",
":",
"inputs",
"=",
"[",
"Input",
".",
"from_dict",
"(",
"input_",
")",
"for",
"input_",
"in",
"tx",
"[",
"'inputs'",
"]",
"]",
"outputs",
"=",
"[",
"Output",
".",
"from_dict",
"(",
"output",
")",
"fo... | 41.769231 | 0.003604 |
def delete_topics(self, topics, timeout_ms=None):
"""Delete topics from the cluster.
:param topics: A list of topic name strings.
:param timeout_ms: Milliseconds to wait for topics to be deleted
before the broker returns.
:return: Appropriate version of DeleteTopicsResponse ... | [
"def",
"delete_topics",
"(",
"self",
",",
"topics",
",",
"timeout_ms",
"=",
"None",
")",
":",
"version",
"=",
"self",
".",
"_matching_api_version",
"(",
"DeleteTopicsRequest",
")",
"timeout_ms",
"=",
"self",
".",
"_validate_timeout",
"(",
"timeout_ms",
")",
"i... | 41.142857 | 0.003394 |
def _wait_for_tasks(tasks, service_instance):
'''
Wait for tasks created via the VSAN API
'''
log.trace('Waiting for vsan tasks: {0}',
', '.join([six.text_type(t) for t in tasks]))
try:
vsanapiutils.WaitForTasks(tasks, service_instance)
except vim.fault.NoPermission as exc:... | [
"def",
"_wait_for_tasks",
"(",
"tasks",
",",
"service_instance",
")",
":",
"log",
".",
"trace",
"(",
"'Waiting for vsan tasks: {0}'",
",",
"', '",
".",
"join",
"(",
"[",
"six",
".",
"text_type",
"(",
"t",
")",
"for",
"t",
"in",
"tasks",
"]",
")",
")",
... | 39.1 | 0.001248 |
def associate_psds_to_single_ifo_segments(opt, fd_segments, gwstrain, flen,
delta_f, flow, ifo,
dyn_range_factor=1., precision=None):
"""
Associate PSDs to segments for a single ifo when using the multi-detector
CLI
"""
... | [
"def",
"associate_psds_to_single_ifo_segments",
"(",
"opt",
",",
"fd_segments",
",",
"gwstrain",
",",
"flen",
",",
"delta_f",
",",
"flow",
",",
"ifo",
",",
"dyn_range_factor",
"=",
"1.",
",",
"precision",
"=",
"None",
")",
":",
"single_det_opt",
"=",
"copy_opt... | 52.181818 | 0.003425 |
def extract_feature(self, image, layer):
"""
Passes image to a deepnet and extracts from the specified layer
:param image: opencv image
:param layer: network layer name
:return: extracted features
"""
img = image.astype(np.float32)
# Substracting... | [
"def",
"extract_feature",
"(",
"self",
",",
"image",
",",
"layer",
")",
":",
"img",
"=",
"image",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"# Substracting Image mean value",
"img",
"-=",
"np",
".",
"array",
"(",
"(",
"104.00698793",
",",
"116.6687676... | 30.692308 | 0.003645 |
def _index_document(self, identifier, force=False):
""" Adds identifier document to the index. """
writer = self.index.writer()
all_names = set([x['name'] for x in self.index.searcher().documents()])
if identifier['name'] not in all_names:
writer.add_document(**identifier)
... | [
"def",
"_index_document",
"(",
"self",
",",
"identifier",
",",
"force",
"=",
"False",
")",
":",
"writer",
"=",
"self",
".",
"index",
".",
"writer",
"(",
")",
"all_names",
"=",
"set",
"(",
"[",
"x",
"[",
"'name'",
"]",
"for",
"x",
"in",
"self",
".",... | 48.428571 | 0.005797 |
def get(ns, dburl=None):
'''
Get a default dones object for ns. If no dones object exists for ns yet,
a DbDones object will be created, cached, and returned.
'''
if dburl is None:
dburl = DONES_DB_URL
cache_key = (ns, dburl)
if ns not in DONES_CACHE:
dones_ns = 'dones_{}'.f... | [
"def",
"get",
"(",
"ns",
",",
"dburl",
"=",
"None",
")",
":",
"if",
"dburl",
"is",
"None",
":",
"dburl",
"=",
"DONES_DB_URL",
"cache_key",
"=",
"(",
"ns",
",",
"dburl",
")",
"if",
"ns",
"not",
"in",
"DONES_CACHE",
":",
"dones_ns",
"=",
"'dones_{}'",
... | 29.857143 | 0.00232 |
def in_file(string, search_file):
"""Looks in a file for a string."""
handle = open(search_file, 'r')
for line in handle.readlines():
if string in line:
return True
return False | [
"def",
"in_file",
"(",
"string",
",",
"search_file",
")",
":",
"handle",
"=",
"open",
"(",
"search_file",
",",
"'r'",
")",
"for",
"line",
"in",
"handle",
".",
"readlines",
"(",
")",
":",
"if",
"string",
"in",
"line",
":",
"return",
"True",
"return",
... | 25.875 | 0.004673 |
def docs(recreate, gen_index, run_doctests):
# type: (bool, bool, bool) -> None
""" Build the documentation for the project.
Args:
recreate (bool):
If set to **True**, the build and output directories will be cleared
prior to generating the docs.
gen_index (bool):
... | [
"def",
"docs",
"(",
"recreate",
",",
"gen_index",
",",
"run_doctests",
")",
":",
"# type: (bool, bool, bool) -> None",
"build_dir",
"=",
"conf",
".",
"get_path",
"(",
"'build_dir'",
",",
"'.build'",
")",
"docs_dir",
"=",
"conf",
".",
"get_path",
"(",
"'docs.path... | 36.862069 | 0.001367 |
def _destroy(cls, cdata):
"""Destroy some cdata"""
# Leptonica API uses double-pointers for its destroy APIs to prevent
# dangling pointers. This means we need to put our single pointer,
# cdata, in a temporary CDATA**.
pp = ffi.new('{} **'.format(cls.LEPTONICA_TYPENAME), cdata)
... | [
"def",
"_destroy",
"(",
"cls",
",",
"cdata",
")",
":",
"# Leptonica API uses double-pointers for its destroy APIs to prevent",
"# dangling pointers. This means we need to put our single pointer,",
"# cdata, in a temporary CDATA**.",
"pp",
"=",
"ffi",
".",
"new",
"(",
"'{} **'",
"... | 49 | 0.005731 |
def sync_imports( self, quiet = False ):
"""Return a context manager to control imports onto all the engines
in the underlying cluster. This method is used within a ``with`` statement.
Any imports should be done with no experiments running, otherwise the
method will block until the clus... | [
"def",
"sync_imports",
"(",
"self",
",",
"quiet",
"=",
"False",
")",
":",
"self",
".",
"open",
"(",
")",
"return",
"self",
".",
"_client",
"[",
":",
"]",
".",
"sync_imports",
"(",
"quiet",
"=",
"quiet",
")"
] | 50.857143 | 0.013793 |
def match(self, abstract_consonant: AbstractConsonant) -> bool:
"""
A real consonant matches an abstract consonant if and only if the required features of the abstract consonant
are also features of the real consonant.
:param abstract_consonant: AbstractConsonant
:return: bool
... | [
"def",
"match",
"(",
"self",
",",
"abstract_consonant",
":",
"AbstractConsonant",
")",
"->",
"bool",
":",
"if",
"isinstance",
"(",
"abstract_consonant",
",",
"AbstractConsonant",
")",
":",
"res",
"=",
"True",
"if",
"abstract_consonant",
".",
"place",
"is",
"no... | 46.5 | 0.002874 |
def space_search(args):
""" Search for workspaces matching certain criteria """
r = fapi.list_workspaces()
fapi._check_response_code(r, 200)
# Parse the JSON for workspace + namespace; then filter by
# search terms: each term is treated as a regular expression
workspaces = r.json()
extra_te... | [
"def",
"space_search",
"(",
"args",
")",
":",
"r",
"=",
"fapi",
".",
"list_workspaces",
"(",
")",
"fapi",
".",
"_check_response_code",
"(",
"r",
",",
"200",
")",
"# Parse the JSON for workspace + namespace; then filter by",
"# search terms: each term is treated as a regul... | 35.653846 | 0.00105 |
def sectionsPDF(self,walkTrace=tuple(),case=None,element=None,doc=None):
"""Prepares section for PDF output.
"""
import pylatex as pl
if case == 'sectionmain':
if self.settings['clearpage']: doc.append(pl.utils.NoEscape(r'\clearpage'))
with doc.create(pl.Section(s... | [
"def",
"sectionsPDF",
"(",
"self",
",",
"walkTrace",
"=",
"tuple",
"(",
")",
",",
"case",
"=",
"None",
",",
"element",
"=",
"None",
",",
"doc",
"=",
"None",
")",
":",
"import",
"pylatex",
"as",
"pl",
"if",
"case",
"==",
"'sectionmain'",
":",
"if",
... | 50.333333 | 0.009171 |
def select_segment(self, segs, segs_tips, segs_undecided) -> Tuple[int, int]:
"""Out of a list of line segments, choose segment that has the most
distant second data point.
Assume the distance matrix Ddiff is sorted according to seg_idcs.
Compute all the distances.
Returns
... | [
"def",
"select_segment",
"(",
"self",
",",
"segs",
",",
"segs_tips",
",",
"segs_undecided",
")",
"->",
"Tuple",
"[",
"int",
",",
"int",
"]",
":",
"scores_tips",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"segs",
")",
",",
"4",
")",
")",
"allind... | 52.052632 | 0.003721 |
def csv(
self,
filepath=None
):
"""*Render the data in CSV format*
**Key Arguments:**
- ``filepath`` -- path to the file to write the csv content to. Default *None*
**Return:**
- ``renderedData`` -- the data rendered in csv format
**Usage:**... | [
"def",
"csv",
"(",
"self",
",",
"filepath",
"=",
"None",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'starting the ``csv`` method'",
")",
"renderedData",
"=",
"self",
".",
"_list_of_dictionaries_to_csv",
"(",
"\"machine\"",
")",
"if",
"filepath",
"and",
... | 26.571429 | 0.002963 |
def list_database(db):
"""Print credential as a table"""
credentials = db.credentials()
if credentials:
table = Table(
db.config['headers'],
table_format=db.config['table_format'],
colors=db.config['colors'],
hidden=db.config['hidden'],
hid... | [
"def",
"list_database",
"(",
"db",
")",
":",
"credentials",
"=",
"db",
".",
"credentials",
"(",
")",
"if",
"credentials",
":",
"table",
"=",
"Table",
"(",
"db",
".",
"config",
"[",
"'headers'",
"]",
",",
"table_format",
"=",
"db",
".",
"config",
"[",
... | 33.583333 | 0.002415 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.