text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def get_urls(self):
""" Extend the admin urls for the CompetitionEntryAdmin model
to be able to invoke a CSV export view on the admin model """
urls = super(CompetitionEntryAdmin, self).get_urls()
csv_urls = patterns('',
url(
r'^exportcsv/$',
... | 0.006397 |
def prepare_weighted_spans(targets, # type: List[TargetExplanation]
preserve_density=None, # type: Optional[bool]
):
# type: (...) -> List[Optional[List[PreparedWeightedSpans]]]
""" Return weighted spans prepared for rendering.
Calculate a separate wei... | 0.002009 |
def kube_node_status_ready(self, metric, scraper_config):
""" The ready status of a cluster node (legacy)"""
service_check_name = scraper_config['namespace'] + '.node.ready'
for sample in metric.samples:
node_tag = self._label_to_tag("node", sample[self.SAMPLE_LABELS], scraper_config... | 0.005386 |
def perform_command(self):
"""
Perform command and return the appropriate exit code.
:rtype: int
"""
if len(self.actual_arguments) < 4:
return self.print_help()
text_format = gf.safe_unicode(self.actual_arguments[0])
if text_format == u"list":
... | 0.003794 |
def _regular_gate(self, gate, lines, ctrl_lines, used_lines):
"""
Draw a regular gate.
:param string gate: Gate to draw.
:param lines: Lines the gate acts on.
:type: list[int]
:param int ctrl_lines: Control lines.
:param int used_lines: The lines that are actuall... | 0.004582 |
def _handle_return(state: GlobalState) -> None:
"""
Adds all the annotations into the state which correspond to the
locations in the memory returned by RETURN opcode.
:param state: The Global State
"""
stack = state.mstate.stack
try:
offset, length = g... | 0.004073 |
def _FracInt(x,y,z,a,b,c,tau,n):
"""Returns
1 x^2 y^2 z^2
-------------------------- (1 - ------- - ------- - -------)^n
sqrt(tau+a)(tau+b)(tau+c)) tau+a tau+b tau+c
"""
denom = np.sqrt((a + tau)*(b + tau)*(c + tau))
return (1. - x**2... | 0.021277 |
def get_action(self, action=None):
""" Returns action to take after call """
if action:
self.action = action
if self.action not in AjaxResponseAction.choices:
raise ValueError(
"Invalid action selected: '{}'".format(self.action))
return self.acti... | 0.006211 |
def update_link(self):
"""
redirects all links to self (the new linked object)
"""
name = repr(self)
if not name:
return self
l = self.__class__._get_links()
to_be_changed = list()
if name in l:
for wal in l[name]:
... | 0.005495 |
async def replace_dialog(self, dialog_id: str, options: object = None) -> DialogTurnResult:
"""
Ends the active dialog and starts a new dialog in its place. This is particularly useful
for creating loops or redirecting to another dialog.
:param dialog_id: ID of the dialog to search for.
... | 0.007704 |
def get_credentials():
"""
Returns the user's stored API key if a valid credentials file is found.
Raises CredentialsError if no valid credentials file is found.
"""
try:
netrc_path = netrc.path()
auths = netrc(netrc_path).authenticators(
urlparse(solvebio.api_host).netlo... | 0.001721 |
def get_managed(
name,
template,
source,
source_hash,
source_hash_name,
user,
group,
mode,
attrs,
saltenv,
context,
defaults,
skip_verify=False,
**kwargs):
'''
Return the managed file data for file.ma... | 0.00092 |
def delete(self, *args, **kwargs):
"""
Delete the image, along with any generated thumbnails.
"""
source_cache = self.get_source_cache()
# First, delete any related thumbnails.
self.delete_thumbnails(source_cache)
# Next, delete the source image.
super(Thu... | 0.003929 |
def walkdirs(self, pattern=None, errors='strict'):
""" D.walkdirs() -> iterator over subdirs, recursively.
With the optional `pattern` argument, this yields only
directories whose names match the given pattern. For
example, ``mydir.walkdirs('*test')`` yields only directories
wi... | 0.001474 |
def parsebam(self):
"""
Parse the dictionaries of the sorted bam files extracted using pysam
"""
# Threading is actually the worst - need multiprocessing to make this work at all
logging.info('Parsing BAM files')
# The sample objects are too big to get pickled. To hack ou... | 0.006019 |
def user_deleted_from_site_event(event):
""" Remove deleted user from all the workspaces where he
is a member """
userid = event.principal
catalog = api.portal.get_tool('portal_catalog')
query = {'object_provides': WORKSPACE_INTERFACE}
query['workspace_members'] = userid
workspaces = [
... | 0.001972 |
def join(self, other, how='left', lsuffix='', rsuffix=''):
"""
Join items with other Panel either on major and minor axes column.
Parameters
----------
other : Panel or list of Panels
Index should be similar to one of the columns in this one
how : {'left', 'r... | 0.001024 |
def _upload_code(s3_conn, bucket, prefix, name, contents, content_hash,
payload_acl):
"""Upload a ZIP file to S3 for use by Lambda.
The key used for the upload will be unique based on the checksum of the
contents. No changes will be made if the contents in S3 already match the
expected... | 0.000583 |
def load_module(self, name):
"""
Load the ``pygal.maps.name`` module from the previously
loaded plugin
"""
if name not in sys.modules:
sys.modules[name] = getattr(maps, name.split('.')[2])
return sys.modules[name] | 0.007326 |
def model(self) -> 'modeltools.Model':
"""The |Model| object handled by the actual |Element| object.
Directly after their initialisation, elements do not know
which model they require:
>>> from hydpy import Element
>>> hland = Element('hland', outlets='outlet')
>>> hlan... | 0.00073 |
def get(self, session):
'''taobao.aftersale.get 查询用户售后服务模板
查询用户设置的售后服务模板,仅返回标题和id'''
request = TOPRequest('taobao.aftersale.get')
self.create(self.execute(request, session))
return self.after_sales | 0.012195 |
def parse(self, buffer, inlineparent = None):
'''
Compatible to Parser.parse()
'''
size = 0
v = []
for i in range(0, self.size): # @UnusedVariable
r = self.innerparser.parse(buffer[size:], None)
if r is None:
return None
... | 0.010363 |
def compute_trans(expnums, ccd, version, prefix=None, default="WCS"):
"""
Pull the astrometric header for each image, compute an x/y transform and compare to trans.jmp
this one overides trans.jmp if they are very different.
@param expnums:
@param ccd:
@param version:
@param prefix:
@ret... | 0.007187 |
def parse_panel_app_panel(panel_info, hgnc_map, institute='cust000', panel_type='clinical'):
"""Parse a PanelApp panel
Args:
panel_info(dict)
hgnc_map(dict): Map from symbol to hgnc ids
institute(str)
panel_type(str)
Returns:
gene_panel(dict)
"""
dat... | 0.009772 |
def compute_and_save_video_metrics(
output_dirs, problem_name, video_length, frame_shape):
"""Compute and saves the video metrics."""
statistics, all_results = compute_video_metrics_from_png_files(
output_dirs, problem_name, video_length, frame_shape)
for results, output_dir in zip(all_results, output_d... | 0.015873 |
def get_blocks(self, block_structure=None):
"""For a reducible circuit, get a sequence of subblocks that when
concatenated again yield the original circuit. The block structure
given has to be compatible with the circuits actual block structure,
i.e. it can only be more coarse-grained.
... | 0.002188 |
def well(self, well_x=1, well_y=1):
"""ScanWellData of specific well.
Parameters
----------
well_x : int
well_y : int
Returns
-------
lxml.objectify.ObjectifiedElement
"""
xpath = './ScanWellData'
xpath += _xpath_attrib('WellX', w... | 0.004435 |
def style(text, fg=None, bg=None, bold=None, dim=None, underline=None,
blink=None, reverse=None, reset=True):
"""Styles a text with ANSI styles and returns the new string. By
default the styling is self contained which means that at the end
of the string a reset code is issued. This can be preve... | 0.000384 |
def _format_data(self, data):
"""
Sort the data in blue wavelengths to red, and ignore any spectra that
have entirely non-finite or negative fluxes.
"""
return [spectrum for spectrum in \
sorted(data if isinstance(data, (list, tuple)) else [data],
key=... | 0.010554 |
def delete(cls, uuid):
"""Delete a workflow."""
to_delete = Workflow.query.get(uuid)
db.session.delete(to_delete) | 0.014599 |
def _node_to_msg(store_load, node):
"""Maps a given node and a store_load constant to the message that is understood by
the storage service.
"""
if node.v_is_leaf:
if store_load == STORE:
return pypetconstants.LEAF
elif store_load == LOAD:
... | 0.004298 |
def update_primary(hdu_in, hdu=None):
""" 'Update' a primary HDU
This checks hdu exists and creates it from hdu_in if it does not.
If hdu does exist, this adds the data in hdu_in to hdu
"""
if hdu is None:
hdu = fits.PrimaryHDU(data=hdu_in.data, header=hdu_in.header)
else:
hdu.d... | 0.002833 |
def parse_translation(f, lineno):
"""Read a single translation entry from the file F and return a
tuple with the comments, msgid and msgstr. The comments is returned
as a list of lines which do not end in new-lines. The msgid and
msgstr are strings, possibly with embedded newlines"""
line = f... | 0.002542 |
def inputs(form_args):
"""
Creates list of input elements
"""
element = []
for name, value in form_args.items():
element.append(
'<input type="hidden" name="{}" value="{}"/>'.format(name, value))
return "\n".join(element) | 0.003774 |
def push_to_registry(image, repository, tag, project):
"""
:param image: DockerImage, image to push
:param repository: str, new name of image
:param tag: str, new tag of image
:param project: str, oc project
:return: DockerImage, new docker image
"""
return image.push("%s/%s/%s" % (get_i... | 0.005362 |
def delete_unused_subjects():
"""Delete any unused subjects from the database.
This is not strictly required as any unused subjects will automatically be reused if
needed in the future.
"""
# This causes Django to create a single join (check with query.query)
query = d1_gmn.app.models.Subject.... | 0.002509 |
def build_signature(self, user_api_key, user_secret, request):
"""Return the signature for the request."""
path = request.get_full_path()
sent_signature = request.META.get(
self.header_canonical('Authorization'))
signature_headers = self.get_headers_from_signature(sent_signat... | 0.00289 |
def update_H(self, mean_field, l):
"""Updates the spin hamiltonian and recalculates its eigenbasis"""
self.H_s = self.spin_hamiltonian(mean_field, l)
try:
self.eig_energies, self.eig_states = diagonalize(self.H_s)
except np.linalg.linalg.LinAlgError:
np.savez('er... | 0.005607 |
def read_cluster_role_binding(self, name, **kwargs):
"""
read the specified ClusterRoleBinding
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_cluster_role_binding(name, async_req=True... | 0.004149 |
def build_columns(self, X, verbose=False):
"""construct the model matrix columns for the term
Parameters
----------
X : array-like
Input dataset with n rows
verbose : bool
whether to show warnings
Returns
-------
scipy sparse arr... | 0.002188 |
def _loc_to_features(loc):
"""Converts a location string "{Half}, {YardLine}" into a tuple of those
values, the second being an int.
:l: The string from the play by play table representing location.
:returns: A tuple that separates out the values, making them missing
(np.nan) when necessary.
"... | 0.001408 |
def set_default_symbols(self):
"""Set self.symbols based on self.numbers and the periodic table."""
self.symbols = tuple(periodic[n].symbol for n in self.numbers) | 0.011236 |
def knapsack_iterative(items, maxweight):
# Knapsack requires integral weights
weights = [t[1] for t in items]
max_exp = max([number_of_decimals(w_) for w_ in weights])
coeff = 10 ** max_exp
# Adjust weights to be integral
int_maxweight = int(maxweight * coeff)
int_items = [(v, int(w * coeff... | 0.002088 |
def traverse(self, traverser, **kwargs):
"""
Implementation of mandatory interface for traversing the whole rule tree.
This method will call the implementation of :py:func:`pynspect.rules.RuleTreeTraverser.function`
method with reference to ``self`` instance as first argument and with th... | 0.009688 |
def _handle_sigusr2(self, signum: int, frame: Any) -> None:
"""Drop current task."""
logger.warning("Catched SIGUSR2")
if self.current_task:
logger.warning("Dropping current task...")
raise Discard | 0.008163 |
def check_time_coordinate(self, ds):
'''
Check variables defining time are valid under CF
CF §4.4 Variables representing time must always explicitly include the
units attribute; there is no default value.
The units attribute takes a string value formatted as per the
rec... | 0.00076 |
def _node_errors(builder, env, tlist, slist):
"""Validate that the lists of target and source nodes are
legal for this builder and environment. Raise errors or
issue warnings as appropriate.
"""
# First, figure out if there are any errors in the way the targets
# were specified.
for t in t... | 0.006121 |
def ver_cmp(ver1, ver2):
"""
Compare lago versions
Args:
ver1(str): version string
ver2(str): version string
Returns:
Return negative if ver1<ver2, zero if ver1==ver2, positive if
ver1>ver2.
"""
return cmp(
pkg_resources.parse_version(ver1), pkg_resourc... | 0.002874 |
def get_cluster_nodes(self):
"""
return list with all nodes in cluster
"""
if not hasattr(self, '_cluster_nodes_cache'):
server, port = self._servers[0].split(':')
try:
self._cluster_nodes_cache = (
get_cluster_info(server, port... | 0.003135 |
def save_to_object(self):
"""Saves the current model state to a Python object. It also
saves to disk but does not return the checkpoint path.
Returns:
Object holding checkpoint data.
"""
tmpdir = tempfile.mkdtemp("save_to_object", dir=self.logdir)
checkpoint... | 0.001889 |
def task_log(self):
"""Get task log.
:rtype: str
:returns: The task log as a string.
"""
if self.task_id is None:
raise ValueError('task_id is None')
return self.get_task_log(self.task_id, self.session, self.request_kwargs) | 0.010526 |
def user_loc_value_to_instance_string(axis_tag, user_loc):
"""Return the Glyphs UI string (from the instance dropdown) that is
closest to the provided user location.
>>> user_loc_value_to_instance_string('wght', 430)
'Normal'
>>> user_loc_value_to_instance_string('wdth', 150)
'Extra Expanded'
... | 0.002801 |
def create_agent_signer(user_id):
"""Sign digest with existing GPG keys using gpg-agent tool."""
sock = connect_to_agent(env=os.environ)
keygrip = get_keygrip(user_id)
def sign(digest):
"""Sign the digest and return an ECDSA/RSA/DSA signature."""
return sign_digest(sock=sock, keygrip=ke... | 0.002793 |
def esinw(b, orbit, solve_for=None, **kwargs):
"""
Create a constraint for esinw in an orbit.
If 'esinw' does not exist in the orbit, it will be created
:parameter b: the :class:`phoebe.frontend.bundle.Bundle`
:parameter str orbit: the label of the orbit in which this
constraint should be ... | 0.003408 |
def eli_hanley(T, MW, Tc, Vc, Zc, omega, Cvm):
r'''Estimates the thermal conductivity of a gas as a function of
temperature using the reference fluid method of Eli and Hanley [1]_ as
shown in [2]_.
.. math::
\lambda = \lambda^* + \frac{\eta^*}{MW}(1.32)\left(C_v - \frac{3R}{2}\right)
T... | 0.002161 |
def required_validator(validator, req, instance, schema):
"""Swagger 1.2 expects `required` to be a bool in the Parameter object, but
a list of properties in a Model object.
"""
if schema.get('paramType'):
if req is True and not instance:
return [ValidationError("%s is required" % sc... | 0.002353 |
def _read_section(self):
"""Read and return an entire section"""
lines = [self._last[self._last.find(":")+1:]]
self._last = self._f.readline()
while len(self._last) > 0 and len(self._last[0].strip()) == 0:
lines.append(self._last)
self._last = self._f.readline()
... | 0.0059 |
def _json_to_term_model(term_data):
"""
Returns a term model created from the passed json data.
param: term_data loaded json data
"""
strptime = datetime.strptime
day_format = "%Y-%m-%d"
datetime_format = "%Y-%m-%dT%H:%M:%S"
term = TermModel()
term.year = term_data["Year"]
term... | 0.000221 |
def get_firmware_version(self):
"""Call PN532 GetFirmwareVersion function and return a tuple with the IC,
Ver, Rev, and Support values.
"""
response = self.call_function(PN532_COMMAND_GETFIRMWAREVERSION, 4)
if response is None:
raise RuntimeError('Failed to detect the... | 0.006861 |
def format_sensor(self, sensor):
""" Format a sensor value. If pango is enabled color is per sensor. """
current_val = sensor.current
if self.pango_enabled:
percentage = self.percentage(sensor.current, sensor.critical)
if self.dynamic_color:
color = self.c... | 0.004651 |
def _write_dihedral_information(gsd_file, structure):
"""Write the dihedrals in the system.
Parameters
----------
gsd_file :
The file object of the GSD file being written
structure : parmed.Structure
Parmed structure object holding system information
"""
gsd_file.dihedrals... | 0.001225 |
def _calc_inst_pmf(self):
"""Calculate the epsilon-greedy instrumental distribution"""
# Easy vars
t = self.t_
epsilon = self.epsilon
alpha = self.alpha
preds = self._preds_avg_in_strata
weights = self.strata.weights_[:,np.newaxis]
p1 = self._BB_model.thet... | 0.00687 |
def parse_coach_bsites_inf(infile):
"""Parse the Bsites.inf output file of COACH and return a list of rank-ordered binding site predictions
Bsites.inf contains the summary of COACH clustering results after all other prediction algorithms have finished
For each site (cluster), there are three lines:
... | 0.004916 |
def _is_autocomplete_valid(cur_commands, alias_command):
"""
Determine whether autocomplete can be performed at the current state.
Args:
parser: The current CLI parser.
cur_commands: The current commands typed in the console.
alias_command: The alias command.
Returns:
T... | 0.003812 |
def unlock(self, pwd):
""" Unlock the wallet database
"""
if self.store.is_encrypted():
return self.store.unlock(pwd) | 0.013072 |
def azimuth(self, point):
"""
Compute the azimuth (in decimal degrees) between this point
and the given point.
:param point:
Destination point.
:type point:
Instance of :class:`Point`
:returns:
The azimuth, value in a range ``[0, 360)`... | 0.004032 |
def update(self, iterations=10):
""" Iterates the graph layout and updates node positions.
"""
# The graph fades in when initially constructed.
self.alpha += 0.05
self.alpha = min(self.alpha, 1.0)
# Iterates over the graph's layout.
# Each s... | 0.007246 |
def lookup_type(storable_type):
"""
Look for the Python type that corresponds to a storable type name.
"""
if storable_type.startswith('Python'):
_, module_name = storable_type.split('.', 1)
else:
module_name = storable_type
#type_name, module_name = \
names = [ _name[::-1] f... | 0.005747 |
def get_actns(learn, hook:Hook, dl:DataLoader, pool=AdaptiveConcatPool2d, pool_dim:int=4, **kwargs):
"Gets activations at the layer specified by `hook`, applies `pool` of dim `pool_dim` and concatenates"
print('Getting activations...')
actns = []
learn.model.eval()
with torch.no... | 0.0208 |
def input_file(self):
"""Returns the input file name, with a default relative path
"""
return path.join(path.dirname(__file__), 'data', 'tgs{:s}.tsv'.format(self.number)) | 0.015464 |
def get_url(self, agent_id, media_id):
"""
获取永久素材下载地址
详情请参考
https://qydev.weixin.qq.com/wiki/index.php?title=%E8%8E%B7%E5%8F%96%E6%B0%B8%E4%B9%85%E7%B4%A0%E6%9D%90
:param agent_id: 企业应用的id
:param media_id: 媒体文件 ID
:return: 临时素材下载地址
"""
parts = (
... | 0.00346 |
def detach(self):
"""
Detaches this volume from any device it may be attached to. If it
is not attached, nothing happens.
"""
attachments = self.attachments
if not attachments:
# Not attached; no error needed, just return
return
# A volume ... | 0.002782 |
def parse(self, xmp):
"""Run parser and return a dictionary of all the parsed metadata."""
tree = etree.fromstring(xmp)
rdf_tree = tree.find(RDF_NS + 'RDF')
meta = defaultdict(dict)
for desc in rdf_tree.findall(RDF_NS + 'Description'):
for el in desc.getchildren():
... | 0.004228 |
def generate_csr(self, domain='', r=None):
"""
Creates a certificate signing request to be submitted to a formal
certificate authority to generate a certificate.
Note, the provider may say the CSR must be created on the target server,
but this is not necessary.
"""
... | 0.006677 |
def __tableStringParser(self, tableString):
"""
Will parse and check tableString parameter for any invalid strings.
Args:
tableString (str): Standard table string with header and decisions.
Raises:
ValueError: tableString is empty.
ValueError: One of the header element is not unique.
ValueError: M... | 0.037216 |
def log_startup_info():
"""Log info about the current environment."""
LOG.always("Starting mongo-connector version: %s", __version__)
if "dev" in __version__:
LOG.warning(
"This is a development version (%s) of mongo-connector", __version__
)
LOG.always("Python version: %s", ... | 0.002119 |
def setDefaultApplicationForMimeType(self, pchAppKey, pchMimeType):
"""Adds this mime-type to the list of supported mime types for this application"""
fn = self.function_table.setDefaultApplicationForMimeType
result = fn(pchAppKey, pchMimeType)
return result | 0.010309 |
def draw_edges(self):
"""
Draws edges to screen.
"""
if self.backend == "matplotlib":
for i, (n1, n2) in enumerate(self.edges):
x1, y1 = self.locs[n1]
x2, y2 = self.locs[n2]
color = self.edge_colors[i]
line = Lin... | 0.001918 |
def read_csv(filename, keys=None, convert_types=False, **kwargs):
'''
Read a CSV in canonical form: ::
<agent_id, t_step, key, value, value_type>
'''
df = pd.read_csv(filename)
if convert_types:
df = convert_types_slow(df)
if keys:
df = df[df['key'].isin(keys)]
df =... | 0.002857 |
def unflatten(self, obj):
"""
Translate substitutions dictionary into objects.
"""
obj.substitutions = [
dict(from_id=key, to_id=value)
for key, value in getattr(obj, "substitutions", {}).items()
] | 0.007634 |
def get_dataset(self, key, info):
"""Read data from file and return the corresponding projectables."""
if key.name in ['longitude', 'latitude']:
logger.debug('Reading coordinate arrays.')
if self.lons is None or self.lats is None:
self.lons, self.lats = self.get_... | 0.00313 |
def evaluate(self, data, env):
"""
Evaluate statement
Parameters
----------
data : pandas.DataFrame
Data in whose namespace the statement will be
evaluated. Typically, this is a group dataframe.
Returns
-------
out : object
... | 0.001514 |
def get_variable(name, temp_s):
'''
Get variable by name.
'''
return tf.Variable(tf.zeros(temp_s), name=name) | 0.008 |
def block_code(self):
inputs = self._get_all_input_values()
outputs = {}
"""
self.f = self.user_function(**inputs)
try:
outputs = self.f.send(inputs)
except StopIteration:
self.terminate()
"""
if self.first_time:
self.f ... | 0.003538 |
def solve_T(self, P, V, quick=True):
r'''Method to calculate `T` from a specified `P` and `V` for the PRSV
EOS. Uses `Tc`, `a`, `b`, `kappa0` and `kappa` as well, obtained from
the class's namespace.
Parameters
----------
P : float
Pressure, [Pa]
V... | 0.006394 |
def _internal_request(self, request_obj, url, method, **kwargs):
""" Internal handling of requests. Handles Exceptions.
:param request_obj: a requests session.
:param str url: url to send request to
:param str method: type of request (get/put/post/patch/delete)
:param kwargs: ex... | 0.001379 |
def do_thread(self, arg):
"""th(read) [threadnumber]
Without argument, display a summary of all active threads.
The summary prints for each thread:
1. the thread number assigned by pdb
2. the thread name
3. the python thread identifier
4. the current s... | 0.001275 |
def getDone(self, done):
"""
:desc: Fetches a list of all the done ToDs
:param bool done: done or undone?
:returns: A list of matching IDs
:rval: list
"""
doneItems = self.noteDB['todo'] \
.find({"done": done}) \
... | 0.00464 |
def add_dataset(self, name=None, label=None,
x_column_label=None, y_column_label=None, index=None, control=False):
"""Add a dataset to a specific plot.
This method adds a dataset to a plot. Its functional use is imperative
to the plot generation. It handles adding new files ... | 0.002782 |
def get_lexer_for_mimetype(_mime, **options):
"""Get a lexer for a mimetype.
Raises ClassNotFound if not found.
"""
for modname, name, _, _, mimetypes in itervalues(LEXERS):
if _mime in mimetypes:
if name not in _lexer_cache:
_load_lexers(modname)
return ... | 0.001919 |
def compute_dprime(n_Hit=None, n_Miss=None, n_FA=None, n_CR=None):
"""
Computes the d', beta, aprime, b''d and c parameters based on the signal detection theory (SDT). **Feel free to help me expand the documentation of this function with details and interpretation guides.**
Parameters
----------
n_... | 0.00435 |
def _parse_snapshot_hits(self, file_obj):
"""Parse and store snapshot hits."""
for _ in range(self.n_snapshot_hits):
dom_id, pmt_id = unpack('<ib', file_obj.read(5))
tdc_time = unpack('>I', file_obj.read(4))[0]
tot = unpack('<b', file_obj.read(1))[0]
self.... | 0.005362 |
def set_exception(self, exc_class, exc_info, exc_stack):
"""Set an exception as the result of this operation.
Args:
exc_class (object): The exception type """
if self.is_finished():
raise InternalError("set_exception called on finished AsynchronousResponse",
... | 0.006383 |
def inverse(self):
"""Invert all instructions."""
for index, instruction in enumerate(self.instructions):
self.instructions[index] = instruction.inverse()
return self | 0.009901 |
def save(self, commit=True):
"""
Save the model instance with the correct Auth Group based on the user_level question
"""
instance = super(UserCreationForm, self).save(commit=commit)
random_password = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(32... | 0.006645 |
def build(values):
"""Build a tree from `list representation`_ and return its root node.
.. _list representation:
https://en.wikipedia.org/wiki/Binary_tree#Arrays
:param values: List representation of the binary tree, which is a list of
node values in breadth-first order starting from the ... | 0.000537 |
def to_molden(cartesian_list, buf=None, sort_index=True,
overwrite=True, float_format='{:.6f}'.format):
"""Write a list of Cartesians into a molden file.
.. note:: Since it permamently writes a file, this function
is strictly speaking **not sideeffect free**.
The list to be writte... | 0.000502 |
def get_border_phase(self, idn=0, idr=0):
"""Return one of nine border fields
Parameters
----------
idn: int
Index for refractive index.
One of -1 (left), 0 (center), 1 (right)
idr: int
Index for radius.
One of -1 (left), 0 (center... | 0.001241 |
def imagetransformer_sep_channels_12l_16h_imagenet_large():
"""separate rgb embeddings."""
hparams = imagetransformer_sep_channels_8l_8h()
hparams.num_hidden_layers = 12
hparams.batch_size = 1
hparams.filter_size = 2048
hparams.num_heads = 16
hparams.learning_rate_warmup_steps = 16000
hparams.sampling_m... | 0.028721 |
def prepare_worker_options(self):
"""
Prepare (and return as a dict) all options to be passed to the worker
"""
worker_options = dict()
for option_name in (self.options.worker_class.parameters):
option = getattr(self.options, option_name)
if option is not ... | 0.004902 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.