content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def getNames(xml):
"""
get person, organization and place tags from PageXML.
"""
content = re.sub("<\?xml version.*?>", "", xml)
try:
root = et.fromstring(content)
except Exception as e:
print(e)
return {"XMLERROR":"XMLERROR"}
pagename = root.find(".//{http://schema.p... | 70,700 |
def test_ct_i005_ct_i005_v(mode, save_output, output_format):
"""
TEST :Syntax Checking for top level complexType Declaration :
complexType with attribute final = '' , derived complexType by
extension
"""
assert_bindings(
schema="msData/complexType/ctI005.xsd",
instance="msData/c... | 70,701 |
def get_xls(es_result, column_mapping):
"""
Creates a stream with the Excel file, the column headers, and the result rows
:param es_result: The result of the ElasticSearch search
:param column_mapping (dict): A dict mapping the column names in the original data, to the desired column headers
for th... | 70,702 |
def average(numbers):
"""
:param list[float] numbers: a list of numbers
:returns: the average of the given number sequence. an empty list returns 0.
:rtype: float
"""
return float(sum(numbers)) / max(len(numbers), 1) | 70,703 |
def _IsIdentityTypeMapping(type_mappings):
"""\
An identity type mapping is a special case where each of the input types
matches the output type.
"""
for input_type, output_types in six.iteritems(type_mappings):
if output_types != [input_type]:
return False
return... | 70,704 |
def inv_rotate(vec: Vector3, quat: Quaternion):
"""Rotates a vector by the inverse of a unit quaternion.
Args:
vec: (3,) a vector
quat: (4,) a quaternion
Returns:
A vector rotated by quat^{-1}
"""
return rotate(vec, quat_inv(quat)) | 70,705 |
def play_manche_joueur():
"""
cette fonction propose au joueur de jouier une manche si il fauit 1 , son score est annulé et la fonction retourne -1
Returns:
le total de la cagnote
"""
cagnote=0
if input("voulez vous lancer un dé ? (y pour relancer, ou anykey pour arréter)\n")=="y":
... | 70,706 |
def kn_logprob(inp='../data/vrex_1week_long_text.queries',
outp='../data/vrex_1week_with_probability.queries',
fdfile='../data/fdist_kn.pickle',
minlen=4,
length_normalized=True):
"""
Calculates the log probability of every query from the input file ac... | 70,707 |
def test_s3():
"""from talk 'Groebner basis and applications', by Hillar
find the defining equation over the rationals for the algebraic number z
defined as the solution to
p(z)=z^5 + sqrt(2)*z^3 - a^2*z + a = 0
where a is a solution to a^3 + a - 1 = 0
z^30 -2*z^26 +2*z^22 +6*z^21 +2*z^20 -6*z^18 +14*z^17 +... | 70,708 |
def crossProduct(u, v):
"""
Calculates the cross product of two 3d vectors (as 1-d arrays).
"""
return np.cross(u, v) | 70,709 |
def selbest(ctx, n, s):
"""Select best parameter"""
from train.get_best_parameters import get_best
import pandas as pd
if not n:
n = 1
else:
n = int(n)
# select best method
df, save_path = get_best(common_n=n)
print_msg = df[['percent_detected', 'false_... | 70,710 |
def vgg13_bn(backbone='vgg13_bn', pretrained=False, **kwargs):
"""VGG 13-layer model (configuration "B") with batch normalization
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
kwargs['cfg_key'] = 'B'
kwargs['batch_norm'] = True
kwargs['backbone'] = "vgg13... | 70,711 |
def get_resource_type_by_url(url: str):
"""Get the resource type definition from a resource URL."""
url_parts = urlparse(url)
url_path = url_parts.path
resource_type = sub(r'/(core|rest|identity|auth|product-metadata)/v\d+/([^/]+)/?.*', r'\2', url_path)
if resource_type == "download-urls.json":
... | 70,712 |
def general_pool_fn(x):
"""
x[0]: function to call
x[1] to x[n]: arguments of the function
"""
return x[0](*x[1:]) | 70,713 |
def getfullname(val):
"""Get the module-qualified name of type or function val."""
return (val.__module__ or '<UNKNOWN_MODULE>') + '.' + getqualname(val) | 70,714 |
def saveFile(fName, data, savePolicy, magic):
"""Saves the NBT data to the disk.
:fName: str/unicode: full file path to save data to.
:data: object: NBT data to be saved.
:savePolicy: int (-1, 0 or 1): special bit to handle different data types.
:magic: int/None: 'magic' number for PE worlds."""
... | 70,715 |
def dt_hms(d, n=3):
"""
Allow negative times
"""
try:
sign = '+' if d > 0. else '-'
x = abs(d)
h = int(x)
x = (x-h) * 60.
m = int(x)
s = (x-m) * 60.
w = n + 3
return f"{sign}{h:02d}h {m:02d}m {s:0{w}.{n}f}s"
except:
return None | 70,716 |
def fmt(y, t_min=0.5, n_fmt=None, kind='cubic', beta=0.5, over_sample=1, axis=-1):
"""The fast Mellin transform (FMT) [1]_ of a uniformly sampled signal y.
When the Mellin parameter (beta) is 1/2, it is also known as the scale transform [2]_.
The scale transform can be useful for audio analysis because its... | 70,717 |
def crawl_items(
spider_cls,
resource_cls,
settings,
spider_kwargs=None,
url_path="",
):
""" Use spider_cls to crawl resource_cls. URL of the resource is passed
to the spider as ``url`` argument.
Return ``(items, resource_url, crawler)`` tuple.
"""
spider_kwargs = {} if spider_kw... | 70,718 |
def get_file_contents(repo_path, file_path):
"""
Given an absolute file path, return the text contents of that file
as a string.
"""
binary = get_file_contents_binary(repo_path, file_path)
try:
return binary.decode('utf-8')
except UnicodeDecodeError:
return binary.decode('lat... | 70,719 |
def generate_param(n_dimensions: int):
"""Simulation of model's parameters"""
nnz = 20
idx = np.arange(n_dimensions)
W = torch.FloatTensor((-1) ** (idx + 1) * np.exp(-idx / 10.)).to(dtype=torch.float64)
W[nnz:] = 0.
return W | 70,720 |
def cleanDf(df, badaa=None):
"""Remove all invalid sequences (containing badaa) from
the alignment
badaa is '-*BX#Z' by default"""
return df.loc[[isvalidpeptide(s, badaa) for s in df.seq]] | 70,721 |
def check_ac_holder_match(holder_cert: x509.Certificate, holder: cms.Holder):
"""
Match a candidate holder certificate against the holder entry of an
attribute certificate.
:param holder_cert:
Candidate holder certificate.
:param holder:
Holder value to match against.
:return:
... | 70,722 |
def visualize_transistor(IV_examples,labels=None):
"""
Visualizes the transistor function
Parameters
----------
handle : function
Function handle of the transistor IV from the physics module.
Vgate : numpy array
Values of Vgate to be included in the plots.
Returns
-----... | 70,723 |
def validate_auto_scaling_group(self):
"""
Class: AutoScalingGroup
"""
if "UpdatePolicy" in self.resource:
update_policy = self.resource["UpdatePolicy"]
if (
not isinstance(update_policy, AWSHelperFn)
and "AutoScalingRollingUpdate" in update_policy.properties
... | 70,724 |
def minify_css(s):
"""
Minify CSS code.
@param s: css to minify
@type s: L{str}
@return: the minfied css
@rtype: L{str}
"""
if csscompressor is None:
raise NotImplementedError("Dependency 'csscompressor' required, but not found!")
return csscompressor.compress(
s... | 70,725 |
def cumsum(a, axis=None, dtype=None, out=None):
"""Returns the cumulative sum of an array along a given axis.
Args:
a (clpy.ndarray): Input array.
axis (int): Axis along which the cumulative sum is taken. If it is not
specified, the input is flattened.
dtype: Data type specifier... | 70,726 |
async def async_api_adjust_volume(hass, config, directive, context):
"""Process an adjust volume request."""
volume_delta = int(directive.payload["volume"])
entity = directive.entity
current_level = entity.attributes.get(media_player.const.ATTR_MEDIA_VOLUME_LEVEL)
# read current state
try:
... | 70,727 |
def random_database():
"""
Creates a random database in the testing Postgres instance and returns the
name of the database.
"""
# Setup connection with default credentials for testing.
with connect(dbname='holo', user='holocleanuser', password='abcd1234', host='localhost') as conn:
conn.... | 70,728 |
def fscore(target_mat, decision_mat, beta=1., event_wise=False):
"""
Args:
target_mat: n_hot matrix indicating ground truth events/labels
(num_frames times num_labels)
decision_mat: n_hot matrix indicating detected events/labels
(num_frames times num_labels)
even... | 70,729 |
def write_syx_file(filename, messages, plaintext=False):
"""Write sysex messages to a SYX file.
Messages other than sysex will be skipped.
By default this will write the binary format. Pass
``plaintext=True`` to write the plain text format (hex encoded
ASCII text).
"""
messages = [m for m... | 70,730 |
def update_docs_pull(record=False, pdf=False, man=False, force=False):
"""
A high-level interface that will update all of the projects.
This is mainly used from a cronjob or management command.
"""
for version in Version.objects.filter(built=True):
try:
update_docs(
... | 70,731 |
def append_suites(output_file_name):
""" Appends the standard suites """
in_file = file("benchmark_suites.py","r")
out_file = file(output_file_name,"a")
for line in in_file:
out_file.write(line)
out_file.write("\n")
in_file.close()
out_file.close() | 70,732 |
def joyplot(
df: pd.DataFrame,
grouping: str,
x_label: Optional['str'] = None,
y_label: Optional['str'] = None,
figsize: Optional[Tuple[float, float]] = (10,8),
title: Optional['str'] = None,
output_file: Optional['str'] = None,
dpi: Optional[float] = 300,
x_range: Optional[Tuple[f... | 70,733 |
def _EraseTombstone(device, tombstone_file):
"""Deletes a tombstone from the device.
Args:
device: An instance of DeviceUtils.
tombstone_file: the tombstone to delete.
"""
return device.RunShellCommand(
'rm /data/tombstones/' + tombstone_file, root=True) | 70,734 |
def write_xml(filename, xml_element):
"""Write a given xml element (with its children recursively) into a file with a given filename.
"""
with codecs.open(filename, mode='w', encoding='utf-8') as outfile:
outfile.write("<?xml version='1.0' encoding='UTF-8' standalone='yes'?>\n")
outfile.writ... | 70,735 |
def main(pconfig, pcfg, perrperc):
"""
Define paths to log, report. Find the newest file and parse it.
Prepare data for report and render it to html file
:param pconfig: default config (if not use --config)
:param pcfg: path if --config $PATH else None
:param perrperc: permissible number of erro... | 70,736 |
def graphite_electrolyte_reaction_rate_Kim2011(T, T_inf, E_r, R_g):
"""
Reaction rate for Butler-Volmer reactions between graphite and LiPF6 in EC:DMC
[1].
References
----------
.. [1] Kim, G. H., Smith, K., Lee, K. J., Santhanagopalan, S., & Pesaran, A.
(2011). Multi-domain modeling of lit... | 70,737 |
def test_strikethrough_491():
"""
Test case 491: Strikethrough text is any text wrapped in two tildes (~).
"""
# Arrange
source_markdown = """~~Hi~~ Hello, world!"""
expected_tokens = [
"[para(1,1):]",
"[text(1,1):~~Hi~~ Hello, world!:]",
"[end-para:::True]",
]
... | 70,738 |
def initialize_node_details(storage_gui_ip, user, key_file):
""" Initialize node details for cluster definition.
:args: storage_gui_ip (str), user (string), key_file (string)
"""
node_details, node = [], {}
node = {'ip_addr': storage_gui_ip, 'is_quorum': True, 'is_manager': True,
'is_gui... | 70,739 |
def massContour(ax, xArray, y4DArray, col, xlab, ylab=''):
"""
This function makes the "Lobster plot"
Parameters
----------
ax : axes object
matplotlib object where plot will be drawn.
xArray : array_like
This is the x-axis (energy in meV) array.
y4DArray : array_like
... | 70,740 |
def do_filter(parser, input_list):
"""
Filter flavor by applying parser on the flavor list
:param input_list: list of input data in JSON format
:param parser: jsonpath parser
:return: list of matched flavors in JSON
"""
return [match.value for match in parser.find(input_list)] | 70,741 |
def run(
args, _parser: argparse.ArgumentParser, _subparser: argparse.ArgumentParser
) -> typing.Optional[int]:
"""Run ``cubi-tk snappy pull-sheet``."""
res: typing.Optional[int] = check_args(args)
if res: # pragma: nocover
return res
logger.info("Starting to pull sheet...")
logger.inf... | 70,742 |
def module(script_in):
"""Decorate a python function or class as tvm script.
Alias for tvm.script.tir for now.
Returns
-------
output : Union[Function, Module]
The Function or Module in IR.
"""
return tir(script_in) | 70,743 |
def test_get_empty_folders(tmp_path, data_folder):
"""Detect empty folders in the working folder."""
dir_util.copy_tree(
str(data_folder.joinpath("working")), str(tmp_path), preserve_symlinks=True, update=True,
)
empty1 = tmp_path.joinpath("hardware/empty_folder")
empty1.mkdir()
empty2 ... | 70,744 |
def shorten_class(class_name: str) -> str:
"""Returns a shortened version of the fully qualilied class name."""
return class_name.replace('org.chromium.',
'.').replace('chrome.browser.', 'c.b.') | 70,745 |
def get_words(content: str) -> List[str]:
"""
文字列内に出現する名詞のリスト(重複含む)を取得する関数。
"""
words = [] # 出現した名詞を格納するリスト。
node = tagger.parseToNode(content)
while node:
# node.featureはカンマで区切られた文字列なので、split()で分割して
# 最初の2項目をposとpos_sub1に代入する。posはPart of Speech(品詞)の略。
pos, pos_sub1 = ... | 70,746 |
def get_hourly_avg(station_num):
"""Returns daily average data for REST API response providing JSON file with data for charts"""
# MySQL query to get average hourly availability for a given station
sql = """SELECT DAYNAME(update_time) AS day, ROUND(AVG(bikes_available)) AS available
FROM bikesdata.... | 70,747 |
def create_initial_parameters(instances, Ns):
"""
Create a list of initial parameters for spectra loaded from task instances.
:param instances:
A list of task instances where spectra were loaded. This should
be length `N` long.
:param Ns:
A list containing the number of spe... | 70,748 |
def load_snps_by_region(chrom, start, end):
"""Retrieve snp information by region"""
index = _get_index_from_chr(chrom)
search_snps = Search().using(es).doc_type('snps').index(index).filter("range", position={"lte": end, "gte":start})
return {snp.position: snp.to_dict() for snp in search_snps.scan() } | 70,749 |
def weight_function(run_params, displacement_norm):
"""Determine motion-dependent prediction weight of given supporter point.
This method determines the weight to apply to each supporter point when
using it for prediction of a target point based on the norm of its
displacement vector. The larger the di... | 70,750 |
def _read_cp1251_file(fname):
"""
Returns:
Возвращает список и ответ на вопрос - угадали ли мы кодировку?
"""
this_is_it = True
sets = iow.get_utf8_template()
sets['coding'] = 'cp1251'
sets['name'] = fname
# Если не та кодировка - возвращает пустой список
re... | 70,751 |
def clear_notebook_parameters(library_db):
"""empties the notebook parameter table"""
from src.praxxis.sqlite import connection
conn = connection.create_connection(library_db)
cur = conn.cursor()
clear_parameter = 'DELETE FROM "NotebookDefaultParam"'
cur.execute(clear_parameter)
conn.commi... | 70,752 |
def mixed_grad_color2gray(rgb_image):
"""EC: Convert an RGB image to gray image using mixed gradients."""
img = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2HSV)
s = img[:, :, 1].reshape((img.shape[0], img.shape[1], 1)) / 255.
v = img[:, :, 2].reshape((img.shape[0], img.shape[1], 1)) / 255.
mask = np.ones_... | 70,753 |
def PReadRec (inHis, recno, err):
"""
Read History record
returns string
* inHis = input Python History
* recno = desired record
* err = Python Obit Error/message stack
"""
################################################################
# Checks
if not PIsA(inHi... | 70,754 |
def remove_leading_garbage_lines_from_reference_section(ref_sectn):
"""Sometimes, the first lines of the extracted references are completely
blank or email addresses. These must be removed as they are not
references.
@param ref_sectn: (list) of strings - the reference section lines
@retu... | 70,755 |
def kernel_reset():
"""Reset kernel coverage.
Die on error.
"""
global options
info("Resetting kernel execution counters")
if (options.gcov_dir/"vmlinux").exists():
reset_file = options.gcov_dir/"vmlinux"
elif (options.gcov_dir/"reset").exists():
reset_file = options.gcov_d... | 70,756 |
def test_static_stability_analysis():
"""Test function 'staticStabilityAnalysis' """
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
cpacs_path = os.path.join(MODULE_DIR,'ToolInput','CPACSTestStability.xml')
cpacs_out_path = os.path.join(MODULE_DIR,'ToolInput', 'CPACSTestStability.xml')
csv... | 70,757 |
def ensure_csrf_cookie_cross_domain(func):
"""View decorator for sending a cross-domain CSRF cookie.
This works like Django's `@ensure_csrf_cookie`, but
will also set an additional CSRF cookie for use
cross-domain.
Arguments:
func (function): The view function to decorate.
"""
def... | 70,758 |
def _algorithm_kwargs(request):
"""Auto-parametrizes `_rl_algorithm_cls` for the `trainer` fixture."""
return dict(request.param) | 70,759 |
def create_directory_if_necessary(path):
"""Creates a directory for the given path if necessary.
Arguments:
path(str): A file path.
"""
directory = os.path.dirname(path)
# exist_ok is only available in python3. Without it, there could be a race condition
# between the workers to creat... | 70,760 |
def convert_tsv_entries_to_dataframe(tsv_dict: Dict, header: str) -> pd.DataFrame:
"""
Converts entries from TSV file to Pandas DataFrame for faster processing.
"""
header_fields = header.strip().split("\t")
data = {header: [] for header in header_fields}
for line in tsv_dict.values():
fields = line.st... | 70,761 |
def do_css():
""" Compresses the CSS files """
# -------------------------------------------------------------------------
# Parse theme's css.cfg and build list of CSS files to merge
#
theme_styles = settings.get_theme_styles()
info("Building theme %s" % theme_styles)
theme_config = sett... | 70,762 |
def count_dates_in_all_reports():
"""iterates over all reports"""
reports = [file for file in os.listdir(os.getcwd() + os.sep + "Raw IPCC Strings") if file[-4:] == ".csv" ]
for report in reports:
print("Starting with " + report)
count_dates(report) | 70,763 |
def decode_and_upload_base64_file(data, file_name):
""" Function to decode base64 files
Parameters
----------
date : str
string of user inputted graduation date.
Returns
-------
string
string of graduation date only with Month and Year.
"... | 70,764 |
def calc_sthovl_by_hkl_abc_cosines(
h: float, k: float, l: float, a: float, b: float, c: float,
cos_alpha: float, cos_beta: float, cos_gamma: float):
"""
Calculate sin(theta)/lambda for given reflections h, k, l
and unit cell parameters defined as a, b, c, cos(alpha), cos(beta), cos(gamma).
... | 70,765 |
def init_rulesengine(rulesengine_root, rulesengine_db):
"""handles initializing the ruleset db and directory"""
import os
from src.praxxis.display import display_rulesengine
from src.praxxis.sqlite import sqlite_init
os.mkdir(rulesengine_root)
display_rulesengine.display_init_rulesengine_root(... | 70,766 |
def pytest_collection_modifyitems(config, items):
"""
if -all not specified, the test functions makrd by slow is omitted
"""
if config.getoption("--all"):
return
skip_slow = pytest.mark.skip(reason="need --all option to run")
for item in items:
if "slow" in item.keywords:
... | 70,767 |
def test_resolve_framelike():
"""Test ``resolve_framelike``."""
# -----------------------
# default
frame = framelike.resolve_framelike(None)
assert frame.__class__.__name__.lower() == conf.default_frame
# -----------------------
# str
frame = framelike.resolve_framelike("galactic")
... | 70,768 |
def RE2Str(RE):
"""Helper for del_gnfa_states
---
Given an RE as a tree, return the string equivalent of the RE.
"""
if type(RE) == str:
if (RE == ""):
return '""' # was return '@', but now no more '@'
else:
return RE
elif type(RE) == tuple:
... | 70,769 |
def list_observations(model):
"""Return a JSON list of observations"""
obs = model.get_observations()
response.content_type = "application/json"
return json.dumps(obs) | 70,770 |
def getParagraphs(document):
""" Retourne un generateur pour tous les paragraphes du document.
La page d'entête n'étant pas incluse dans documents.paragraphs."""
body = document._body._body # pylint: disable=protected-access
ps = body.xpath('//w:p')
for p in ps:
yield Paragraph(p, docume... | 70,771 |
def add_api_config_to_queries(generated_query_strings, search_engines):
"""
Merges the two parameters and returns a list of dicts that include the
api config.
If only 1 API key is provided, it is assumed this is valid for many searches and is used for all queries
If more than 1 is p... | 70,772 |
def extract_feature(
vector_path, feature_id, projection_wkt, target_vector_path,
target_complete_token_path):
"""Make a local projection of a single feature in a vector.
Parameters:
vector_path (str): base vector in WGS84 coordinates.
feature_id (int): FID for the featur... | 70,773 |
def _get_first_model(structure: PdbStructure) -> PdbStructure:
"""Returns the first model in a Biopython structure."""
return next(structure.get_models()) | 70,774 |
def createDiffLineCV(video, cropx1, cropx2, cropy1, cropy2):
"""
Binarizes video and returns a frame to frame difference trace.
Inputs:
video - list of images
cropx1 - int, crop pixel starting for first dimension
cropx2 - int, crop pixel ending for first dimension
cropy1 - int, crop pixel st... | 70,775 |
def convert_entity_schema(entity_schema):
""" Convert entity schmea to record schema
"""
spots = list()
asocs = list()
spot_asoc_map = dict()
for entity in entity_schema:
spots += [entity]
spot_asoc_map[entity] = list()
return spots, asocs, spot_asoc_map | 70,776 |
def get_inchi_key(mol: Molecule) -> str:
"""Get an InChI key from a molecule."""
return inchi.generate(mol).getKey() | 70,777 |
def process_raw_input(input, source='html'):
"""
Parameters
----------
input
type
Returns
-------
processed text (str)
"""
if source == 'html':
return '\n'.join(input)
elif source == None:
return input | 70,778 |
def run():
"""Run this script."""
model_name_prefix = f'{PreTrainedKerasImageNetClassifier.__name__}-'
for keras_loader, preproc, img_dim_size, global_url, local_file_name in \
MODEL_SPECS:
try:
print(PreTrainedKerasImageNetClassifier.objects.update_or_create(
... | 70,779 |
def get_pheno_list(serotype_hits, session):
"""
Function to return phenotype list from list of serotype hits (deduplicated)
:param serotype_hits: list of serotype hits from stage 1 mash analysis
:param session: DB session
:return: list of deduplicated phenotypes or groups
"""
out_res = []
... | 70,780 |
def get_review_dates(app_reviews) -> pd.DataFrame:
"""Create a new dataframe, `reviewDates`, with the number of reviews for each app per year"""
review_dates = (
app_reviews.groupby(["appId", "reviewYear"])["appId"]
.count()
.unstack()
.reset_index()
)
app_total_reviews ... | 70,781 |
def print_train_usage():
""" Prints the usage for train program.
"""
str_usage = BLUE + "Usage:\n" + END
str_usage += " python logreg_train.py --dataset=... --graphic=... --method=...\n"
str_usage += BLUE + "Args:\n" + END
str_usage += YELLOW + " --graphic=[console/static]\n" + END
str_usage += " * console... | 70,782 |
def validate(config):
"""
Validate the beacon configuration
"""
# Configuration for memusage beacon should be a list of dicts
if not isinstance(config, list):
return False, "Configuration for memusage beacon must be a list."
else:
_config = {}
list(map(_config.update, con... | 70,783 |
def evaluate_conditionals_in_context (properties, context):
""" Removes all conditional properties which conditions are not met
For those with met conditions, removes the condition. Properies
in conditions are looked up in 'context'
"""
base = []
conditional = []
for p in pr... | 70,784 |
def visualize(**images):
"""PLot images in one row."""
n = len(images)
plt.figure(figsize=(16, 5))
for i, (name, image) in enumerate(images.items()):
plt.subplot(1, n, i + 1)
plt.xticks([])
plt.yticks([])
plt.title(" ".join(name.split("_")).title())
plt.imshow(ima... | 70,785 |
def mmd_t(
dist_xx, dist_xy, dist_yy, batch_size, alpha=1.0, beta=2.0, var_target=None, name='mmd',
do_summary=False, scope_prefix=''):
"""This function calculates the maximum mean discrepancy with t-distribution kernel
The code is inspired by the Github page of following paper:
Binkowski M... | 70,786 |
def _wsdl2dispatch(options, wsdl):
"""TOOD: Remove ServiceContainer stuff, and replace with WSGI.
"""
kw = dict()
# TODO: make all this handler arch
if options.address is True:
ss = ServiceDescriptionWSA()
else:
ss = ServiceDescription(**kw)
ss.fromWSDL(wsdl)
file_n... | 70,787 |
def reset_from_schedules(scheduler):
""""Reset all scheduler jobs, using information from the JSON object
:param scheduler: the TornadoScheduler instance to modify
:type scheduler: TornadoScheduler
:returns: True in case of success
:rtype: bool"""
ret = False
try:
scheduler.remove_a... | 70,788 |
def print_request_rendering_stats_never_rendered_requests(fuzzing_requests,
candidate_values_pool,
fuzzing_monitor):
""" Prints to file statistics for request renderings.
@param fuzzing_requests:... | 70,789 |
def player_move_level2():
"""
This a general function used in second and third stage of the game.
It takes input from the player using Input function and asks player which door they would like to go to.
"""
ask = "Which door you would like to go to?(1,2 or 3)\n"
dest = input(ask)
print('You ... | 70,790 |
def get_threshold_metrics(y_true, y_pred, drop_intermediate=False,
disease='all'):
"""
Retrieve true/false positive rates and auroc/aupr for class predictions
Arguments:
y_true - an array of gold standard mutation status
y_pred - an array of predicted mutation status
d... | 70,791 |
def pull_astronaut_list(url: str ='http://api.open-notify.org/astros.json') -> Dict[str, Any]:
"""
Pull a list of astronauts via API. Defaults to open-notify's API.
Args:
url: the URL to pull data from.
Returns:
A dict containing the astronaut count and names.
"""
data = reques... | 70,792 |
def get_widget_for_attr(traits_ui, attr_name):
""" Return the Qt widget in the UI which displays the attribute specified.
"""
x_editor = traits_ui.get_editors(attr_name)[0]
qt_widget = x_editor.control
return qt_widget | 70,793 |
def create_test_dirs():
"""
Create test directories
:return:
"""
script_dir = os.path.dirname(__file__)
test_dumbswitcher_dir = os.path.join(script_dir, "test_dumbswitcher_dir")
test_home = os.path.join(script_dir, "test_home")
if not os.path.exists(test_dumbswitcher_dir):
os.m... | 70,794 |
def fixMisplacedArom(gsdfile,gsdout,idMiss,idPartner,idNotMiss,idNotPartner
,molno,ats,ts):
"""
opens a gsd file, gets the trajectory, then writes out in place with
the incorrectly placed aromatic placed correctly
Parameters
----------
gsdfile: string
filename o... | 70,795 |
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload Bold config entry."""
if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
del hass.data[DOMAIN][entry.entry_id]
return unload_ok | 70,796 |
def download_preprocess_libsvm(dataset, replace=False, repreprocess=False):
"""Download and preprocess a given libsvm dataset."""
paths = [PATH, pjoin(PATH, 'regression'),
pjoin(PATH, 'binary'),
pjoin(PATH, 'preprocessed')]
for path in paths:
if not os.path.exists(path):
... | 70,797 |
def strip_url(url, origin_only=False):
"""
参考 https://www.w3.org/TR/referrer-policy/#strip-url
去除敏感信息如username
:param url:
:param origin_only:
:return:
"""
if not url:
return None
parsed_url = urlparse(url)
netloc = parsed_url.netloc
if origin_only and (parsed_url.use... | 70,798 |
def eval_single_file(simulation_output_dir):
"""
number of cells
number of cells detected
"""
sim_dat_dir = simulation_output_dir[0:simulation_output_dir.rindex('/')]
true_barcodes = get_barcodes_set(
'%s/true_barcodes.txt' % (sim_dat_dir))
pred_barcodes = get_barcodes_set(
'%s/threshold_paths.txt' % simul... | 70,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.