content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def getParserFile(theHelp, theEpilog=""):
"""
Get a commandline parser with the defaults of the commandline utils and a
list of source files.
"""
parser = _getParser(theHelp, theEpilog)
parser.add_argument("FILE", nargs='+', help="Input file")
return parser | 74,000 |
def main():
"""
Run the Application
"""
server = jsonrpclib.Server('http://localhost:1234')
result = server.register_user('adel', 'zalok', 'alice', 'alice@example.com', 'asdsad')
print result | 74,001 |
def from_pci_stats(pci_stats):
"""Create and return a PciDevicePoolList from the data stored in the db,
which can be either the serialized object, or, prior to the creation of the
device pool objects, a simple dict or a list of such dicts.
"""
pools = []
if isinstance(pci_stats, six.string_types... | 74,002 |
def _cloned_intersection(a, b):
"""return the intersection of sets a and b, counting
any overlap between 'cloned' predecessors.
The returned set is in terms of the entities present within 'a'.
"""
all_overlap = set(_expand_cloned(a)).intersection(_expand_cloned(b))
return set(elem for elem in ... | 74,003 |
def test_input_parameters_optional(data_regression, generate_input_parameters):
"""Test ``InputParameters`` can generate optional parameters."""
inputs = InputParameters(generate_input_parameters(full=False)).get_dict()
data_regression.check(inputs) | 74,004 |
def validate(number):
"""Checks to see if the number provided is a valid EIN. This checks
the length, groups and formatting if it is present."""
match = _ein_re.search(clean(number, '').strip())
if not match:
raise InvalidFormat()
get_campus(number) # raises exception for unknown campus
... | 74,005 |
def print_summary(results, show_stable=False, show_unstable=True):
"""Print summary similar to `print_summary2` except it doesn't print skipped tests."""
print_summary2(
results, show_stable=show_stable, show_unstable=show_unstable,
print_skipped=False) | 74,006 |
async def search(query_expr: str) -> str:
"""Search issues and PRs, the query_expr is an expression that GitHub search
supports such as 'org:some_org label:some_label'."""
response = await _search(query_expr)
items = [_map_search_item(item) for item in response.get("items")]
per_page = 100
rema... | 74,007 |
def post(request, size, page):
"""
Route: /api/v1/search
See config/api.yml for OpenAPI specification.
:param request: JSON body
:param size: int
:param page: int
:return:
"""
logger.info("Received search request: '{}'.".format(request))
# Check that paths are valid (to prevent ... | 74,008 |
def view_the_log() -> 'html':
"""Display the contents of the log file as a HTML table."""
contents = []
with open('vsearch.log') as log:
for line in log:
contents.append([])
for item in line.split('|'):
contents[-1].append(escape(item))
titles = ('Form Dat... | 74,009 |
def fdr_rvalue(p1, p2, m, c2=0.5, l00=0.8):
"""Function for computing FDR r-values using the method suggested by
Heller et al.
Input arguments:
================
p1, p2 : ndarray [n_tests, ]
The p-values that were selected for follow-up from the primary
study (p1) and the correspondi... | 74,010 |
def testORTTrainerOptionsInvalidMixedPrecisionEnabledSchema(input, error_msg):
"""Test an invalid input based on schema validation error message"""
with pytest.raises(ValueError) as e:
orttrainer_options.ORTTrainerOptions(input)
assert str(e.value) == error_msg | 74,011 |
def test_current_window_handle(browser):
"""Test current window handle property"""
assert browser.current_window_handle | 74,012 |
def list_experiments(api_client, fieldmask=None, read_time=None):
"""Yields all of the calling user's experiments.
Args:
api_client: A TensorBoardExporterService stub instance.
fieldmask: An optional `experiment_pb2.ExperimentMask` value.
read_time: A fixed timestamp from which to export data... | 74,013 |
def test_decode_token_raises_ex_with_bad_salt(user6, dev_app):
""" Not using the correct salt will raise exception. """
code = api.create_token(user6, dev_app.client_id)
with pytest.raises(jwt.exceptions.InvalidSignatureError):
jwt.decode(code, "bad_salt") | 74,014 |
def matches_filter(graph, props):
"""
Returns True if a given graph matches all the given props. Returns False
if not.
"""
for prop in props:
if prop != 'all' and not prop in graph['properties']:
return False
return True | 74,015 |
def goal_pred_loss(grasp_pred, goal_batch, huber=False):
"""
PM loss for grasp pose detection
"""
grasp_pcs = transform_control_points( grasp_pred, grasp_pred.shape[0], device="cuda", rotz=True )
grasp_pcs_gt = transform_control_points( goal_batch, goal_batch.shape[0], device="cuda", rotz=True )
... | 74,016 |
def generateIMSManifest(data):
""" parse data from config file 'toIMSconfig.json' and recreate imsmanifest.xml """
# create magic yattag triple
doc, tag, text = Doc().tagtext()
# open tag 'manifest' with default content:
doc.asis('<?xml version="1.0" encoding="UTF-8"?><manifest xmlns="http://www.ims... | 74,017 |
def build_l2s_loss(ordered_tiled, random_tiled, soft_perms_inf, n_numbers):
"""Builds loss tensor with soft permutations, for training."""
'''Am not using htis function explicitly in the training, decided to incorporate it inside the training code itself.
Keeping for reference'''
print("soft_perms_inf ... | 74,018 |
def describe_queries(logGroupName=None, status=None, maxResults=None, nextToken=None):
"""
Returns a list of CloudWatch Logs Insights queries that are scheduled, executing, or have been executed recently in this account. You can request all queries, or limit it to queries of a specific log group or queries with... | 74,019 |
def test_lifetime_connectivity_on_lifetime(diagram, element_factory):
"""Test lifeline's lifetime connectivity change on lifetime connection
"""
ll = diagram.create(LifelineItem, subject=element_factory.create(UML.Lifeline))
msg = diagram.create(MessageItem)
ll.lifetime.visible = True
# connec... | 74,020 |
def biweight_midvariance(a, c=15.0, M=None, axis=None, eps=1e-8, niter=1):
"""
Copyright (c) 2011-2016, Astropy Developers
Compute the biweight midvariance for an array.
Returns the biweight midvariance for the array elements.
The biweight midvariance is a robust statistic for determining
... | 74,021 |
def card_dealer(cards_dealt, players=1, deck="standard", decks_number=1):
"""
This function return randomly dealt cards for defined number of players.
Args:
* `cards_dealt` : number of cards for each player (int)
* `players` : number of players
Kwargs:
* `deck` : options are:
* `st... | 74,022 |
def tree(node, levels=[], max_depth=None):
"""
Displays the model tree.
This is a convenience function to visualize, in an interactive
Python session, the branch of the model tree underneath a given
`node`. It produces console output such as this:
```console
>>> mph.tree(model/'phys... | 74,023 |
def show_std_icons():
"""
Show all standard Icons
"""
app = qapplication()
dialog = ShowStdIcons(None)
dialog.show()
import sys
sys.exit(app.exec_()) | 74,024 |
def _debug_options(args) -> Optional[rdcp_command.RDCPCommand]:
"""[crashdump | dpctrace] [...]
If no arguments are given, retrieves the currently active debug options.
If at least one argument is given, enables that debug option and disables any options that are not given.
"""
enable_crashdump = N... | 74,025 |
async def test_insert_and_get_protocol(
protocol_file_directory: Path, subject: ProtocolStore
) -> None:
"""It should store a single protocol."""
protocol_resource = ProtocolResource(
protocol_id="protocol-id",
created_at=datetime(year=2021, month=1, day=1, tzinfo=timezone.utc),
sour... | 74,026 |
def vulndata(note, parsed_cpe, cve, namelen):
"""project vulndata object"""
data_id = md5(
f'{note.host.address}'
f'|{note.service.proto if note.service else None}'
f'|{note.service.port if note.service else None}'
f'|{cve["id"]}'.encode()
).hexdigest()
data = {
... | 74,027 |
def plane_face_intersection(a,b,c,d,face):
"""
Finds the intersection line of a plane with
the face of a solid. Returns the two points
that make up the line of intersection. a,b,c,d are
the coefficients of the plane ax+by+cz=d while face
is a sequence of points which form the plane.
args:... | 74,028 |
def url2table(url):
"""From an url given, extract only the 'rangkingTable' using beautifulsoup"""
logger.info('url2table')
response = requests.get(url)
page_html = response.text
soup = BeautifulSoup(page_html, 'html.parser')
rangkingtable = soup.find_all(attrs={"class": "rangkingTable"})[1]
... | 74,029 |
def test_get_card_points():
"""Test correct card points returned for players from fitted
(average) card points"""
df_cards = pd.Series({1: -1, 2: -2})
# >30 mins - return df value
assert get_card_points(1, 90, df_cards) == -1
assert get_card_points(2, 45, df_cards) == -2
# 360 mins - zero
... | 74,030 |
def max(msg, out):
"""Builtin reduce function that aggregates messages by max.
Parameters
----------
msg : str
The message field.
out : str
The output node feature field.
Examples
--------
>>> import dgl
>>> reduce_func = dgl.function.max(msg='m', out='h')
The ... | 74,031 |
def test_app_detail_view(client):
"""The bootcamp application detail view should return a successful response"""
application = BootcampApplicationFactory.create()
client.force_login(application.user)
url = reverse("applications_api-detail", kwargs={"pk": application.id})
resp = client.get(url)
a... | 74,032 |
def AddReferenceImageCreateFlags(parser):
"""Add Reference Image create command flags to parser."""
AddImagePathFlag(parser)
AddCatalogResourceArg(parser, verb='to add ReferenceImages to',
positional=False)
AddProductIdFlag(parser, verb='to associate this ReferenceImage to',
... | 74,033 |
def get_popularity(obj, region=None):
"""
Returns popularity value for the given obj to use in Elasticsearch.
If no region, uses global value.
If region and region is not mature, uses global value.
Otherwise uses regional popularity value.
"""
return _property_value_by_region(obj, region=r... | 74,034 |
def feature_importances_plot(model, labels, **kwargs):
"""
Calcola l'importanza normalizzata delle variabili di un modello
restituendo i dati e mostrando il plot.
-----------
Parametri:
model : modello di scikit-learn
labels : list | np.array
lista delle labels delle variabili
... | 74,035 |
def test_get_block_list(lines, expected):
"""Test captures multiline list."""
r = config_reader._get_list_block(lines)
assert r == expected | 74,036 |
def advise_boucmeas(input_df, output_df):
"""
Analyze two dataframes and add impact of boundary measurement into output_df
:param input_df: input data for inference
:param output_df: output data from inference
"""
thres_boucmeas_advice = input_df["configs"][2]["thres_boucmeas_advice"]
n_bouc... | 74,037 |
def human_sort_key(key: str) -> List[Any]:
"""
Function that can be used for natural sorting, where "PB2" comes before
"PB10" and after "PA3".
"""
def _convert(text: str) -> Union[int, str]:
return int(text) if text.isdigit() else text
return [_convert(x) for x in re.split(r'(\d+)', key... | 74,038 |
def clean_line_count_output(out):
"""Clean shell output into list based records"""
record = []
count_lines = out.split(b"\n")
#import ipdb;ipdb.set_trace()
for line in count_lines:
if line:
line = line.split()
log.debug(len(line))
if len(line) == 4:
... | 74,039 |
def un_rar(filepath):
"""un rar file"""
rar = rarfile.RarFile(filepath)
folder = filepath.replace(".rar", "")
if os.path.isdir(folder):
pass
else:
os.mkdir(folder)
os.chdir(folder)
rar.extractall()
rar.close() | 74,040 |
def remove_user(cursor, username):
""" remove the user and all groups without a user """
cursor.execute("DELETE FROM users WHERE username = ?", (username,))
cursor.execute("""
DELETE
FROM groups
WHERE NOT EXISTS(
SELECT
NULL
FROM
... | 74,041 |
def ParseColSpec(
col_spec, max_parts=framework_constants.MAX_SORT_PARTS,
ignore=None):
"""Split a string column spec into a list of column names.
We dedup col parts because an attacker could try to DoS us or guess
zero or one result by measuring the time to process a request that
has a very long colum... | 74,042 |
def get_class(class_string):
""" Returns class object specified by a string.
Arguments:
class_string -- The string representing a class.
Raises:
ValueError if module part of the class is not specified.
"""
module_name, _, class_name = class_string.rpartition('.')
... | 74,043 |
def crearVentana():
""" Crea la GUI junto con el establecimiento de sus propiedades """
ventana.geometry("850x600+300+60")
ventana.title("Prueba")
ventana.resizable(width=False, height=False) | 74,044 |
def call_after_ad(call: Callable[[], Any]) -> None:
"""Run a call after potentially showing an ad."""
# pylint: disable=too-many-statements
# pylint: disable=too-many-branches
# pylint: disable=too-many-locals
from ba._account import have_pro
from ba._enums import TimeType
import time
ap... | 74,045 |
def flip_bloom_filter(string: str, bf_len: int, num_hash_funct: int):
"""
Hash string and return indices of bits that have been flipped correspondingly.
:param string: string: to be hashed and to flip bloom filter
:param bf_len: int: length of bloom filter
:param num_hash_funct: int: number of hash... | 74,046 |
def multiclass_metrics(pred, gt):
"""
check precision and recall for predictions.
Output: overall = {precision, recall, f1}
"""
eps=1e-6
overall = {'precision': -1, 'recall': -1, 'f1': -1}
NP, NR, NC = 0, 0, 0 # num of pred, num of recall, num of correct
for ii in range(pred.shape[0]):
pred_ind = n... | 74,047 |
def positionLogicPlan(problem):
"""
Given an instance of a PositionPlanningProblem, return a list of actions that lead to the goal.
Available actions are game.Directions.{NORTH,SOUTH,EAST,WEST}
Note that STOP is not an available action.
"""
walls = problem.walls
width, height = problem.getWi... | 74,048 |
def dataset_from_csv(csv_path: str, **kwargs) -> Any:
"""
Load dataset from a CSV file using Pandas. kwargs if any are
forwarded to the `pandas.read_csv` function.
Parameters:
csv_path (str):
Path of the CSV file to load dataset from.
Returns:
Any:
Loaded da... | 74,049 |
def quick_sort(array, left: int = 0, right: int = None):
"""
Quick sort algorithm.
:param array: the array to be sorted.
:param left: the left index of sub array.
:param right: the right index of sub array.
:return: sorted array
>>> import random
>>> array = random.sample(range(-50, 50)... | 74,050 |
def calc_class_metrics(all_preds, all_labels, metric_type="group", span_type="exact"):
"""
Calculates a set of metrics for each class.
:param all_preds, all_labels: A list of list of groups. If metric_type ==
"joint", the groups should in joint form with an "entities" key
:param metric_type: A stri... | 74,051 |
def convert_to_text(web3, data):
"""
:param web3:
:param data:
:return:
"""
return web3.toText(data) | 74,052 |
def CallableParamRegistry(): # noqa: N802
"""Callable registry with a keyword parameter."""
class CallableParamRegistry:
registry = Registry('kwparam')
return CallableParamRegistry | 74,053 |
def __cli():
"""Command line interface.
Only used to run tests at the moment
"""
help = "Simple compound for MCTS. The CLI applies --rsmarts to --csmiles."
logging.warning("No CLI is available for chemical_compounds_state") | 74,054 |
def largest_product(product_list):
"""Find the largest product from a given list."""
largest = 1
for products in product_list:
if largest < max(products):
largest = max(products)
return largest | 74,055 |
def shapes_equal_trailing(*shapes):
"""Test if shapes are equal, starting from trailing end, except for leading ones."""
for lengths in zip_longest(*[shape[::-1] for shape in shapes], fillvalue=1):
if not all(length == lengths[0] for length in lengths):
return False
return True | 74,056 |
def is_executable(path):
"""Tests if the specified path corresponds to an executable file. This is,
it is a file and also has the appropriate executable bit set.
:param path: Path to the file to test.
:return: True if the file exists and is executable, False otherwise.
:rtype: bool
"""
if o... | 74,057 |
def generate_indices_filename(max_length, vocab_size, seed, inference, step3, set_type, multi_task, multi_task_lambda, disabled_properties):
"""
Generates a filename from baseline params (see baseline.py)
"""
name = f'{generate_unique_filename(max_length, vocab_size, seed, inference, step3, set_type, mu... | 74,058 |
def get_separable_problems(problem):
"""Return a list of separable problems whose sum is the original one.
Parameters
----------
problem : Problem
A problem that consists of separable (sub)problems.
Returns
-------
List
A list of problems which are separable whose sum is th... | 74,059 |
def provider_parser(subparser):
"""Configure provider parser for Infoblox"""
subparser.add_argument(
"--auth-user", help="specify the user to access the Infoblox WAPI"
)
subparser.add_argument(
"--auth-psw", help="specify the password to access the Infoblox WAPI"
)
subparser.add_... | 74,060 |
def grab_enumsets(base_url: str,
bearer: BearerToken,
dbsess: sqlalchemy.orm.session.Session,
enumset: int, delay: float) -> None:
"""This function gets invoked when running crawler enumset and it grabs the enumsets.
These are used to translate the type fiel... | 74,061 |
def _padded_size(size, padding_multipe=8):
""" Return the size of a field padded to be a multiple a give value. """
return int(ceil(size / padding_multipe) * padding_multipe) | 74,062 |
def add_api_component(logger, name, event_dict):
"""
Adds the component to the entry if the entry is not from structlog. This only applies to the API since it is
handled by external WSGI servers.
"""
event_dict["component"] = "API"
return event_dict | 74,063 |
def make_plans(*by_key, **plans):
"""
Given by_key which is a list of strings and plans which is a dictionary of key to
plan, return a dictionary of key to plans.
We will complain if:
* A key in by_key is not a registered plan
* A key in by_key is also in plans
"""
if not by_key and no... | 74,064 |
def split_list(l, split, density=None):
"""
Splits a list into part a of b
split should be a string of the form 'a/b'. For instance, '1/3' would give
the split one of three.
If the length of the list is not divisible by the number of splits, the
last split will have more items.
`density` ... | 74,065 |
def load_files(proof_fnames):
"""
From a list of XML filenames that contain a <proof> node,
it returns a list of lxml root nodes.
"""
roots = []
parser = etree.XMLParser(remove_blank_text=True)
for fname in proof_fnames:
docs = etree.parse(fname, parser)
roots.append(docs)
... | 74,066 |
def encoding(mctx, x):
"""File can be successfully decoded with the given character
encoding. May not be useful for encodings other than ASCII and
UTF-8.
"""
# i18n: "encoding" is a keyword
enc = getstring(x, _("encoding requires an encoding name"))
s = []
for f in mctx.existing():
... | 74,067 |
def shuffle_string(s: str) -> str:
"""
Mixes all the letters in the given string
Parameters:
s(str): the string to shuffle
Returns:
str: string with randomly reordered letters
Examples:
>>> shuffle_string('abc')
'cba'
>>> shuffle_string(... | 74,068 |
def get_data(input_text: str) -> list[Line]:
"""
returns list of Line objects
"""
lines = [Line.from_string(line_str) for line_str in input_text.splitlines()]
return lines | 74,069 |
def accuracy(output, target, topk=(1,), tok_groups=None, tok_group_labels=None, as_list=False):
"""Computes the accuracy over the k top predictions for the specified values of k"""
mask = target != -1
output = output[mask]
target = target[mask]
maxk = max(topk)
_, pred = output.topk(maxk, 1, ... | 74,070 |
def deprecated(func):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emmitted
when the function is used."""
def new_func(*args, **kwargs):
warnings.simplefilter('always', DeprecationWarning) # turn off filter
warnings.warn("C... | 74,071 |
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
env=None):
"""Call the given command(s)."""
assert isinstance(commands, list)
p = None
for c in commands:
try:
dispcmd = str([c] + args)
# remember shell=False, so use git.cmd on w... | 74,072 |
def timeout(seconds=10, error_message=os.strerror(errno.ETIME)):
"""
This decorator raise an TimeoutError exception if the function
takes more than 'seconds' seconds to terminate
From: https://stackoverflow.com/questions/2281850/
"""
def decorator(func):
def _handle_timeout(signum, fram... | 74,073 |
def glove2dict(src_filename):
"""
GloVe reader.
Parameters
----------
src_filename : str
Full path to the GloVe file to be processed.
Returns
-------
dict
Mapping words to their GloVe vectors as `np.array`.
"""
# This distribution has some words with spaces, so... | 74,074 |
def shear_matrix(angle, direction, point, normal):
"""Return matrix to shear by angle along direction vector on shear plane.
The shear plane is defined by a point and normal vector. The direction
vector must be orthogonal to the plane's normal vector.
A point P is transformed by the shear matrix into ... | 74,075 |
def laf_write(comm, fd_num, offset, write_mode, zdata):
"""Write size bytes at the given block offset."""
#_logger.debug("WRTE(0x%05x, #%d)", offset, len(data)); return
#write_cmd = lglaf.make_request(b'WRTE', args=[fd_num, offset], body=data)
#write_cmd = lglaf.make_request(b'WRTE', args=[fd_num, offse... | 74,076 |
def lpr_data(year=None):
"""
获取贷款基础利率(LPR)
Parameters
------
year:年份(int)
Return
------
date:日期
1Y:1年贷款基础利率
"""
pass | 74,077 |
def save_tiled_raster_images(tiled_img, filename):
"""
Save a a return value from `tile_raster_images` to `filename`.
Returns
-------
img : WRITEME
The PIL image that was saved
"""
if tiled_img.ndim==2:
ensure_Image()
img = Image.fromarray( tiled_img, 'L')
elif t... | 74,078 |
def two_points(
reviewed_assertions: typing.List[ReviewedAssertion],
) -> typing.Optional[ReviewedAssertion]:
"""Extract two point ReviewedAssertion of possible."""
if not any(map(ReviewedAssertion.from_multiple, reviewed_assertions)):
return None # is single => no two points
elif any(map(Revie... | 74,079 |
async def load(ctx, what: str):
"""Load a Module"""
msg = await ctx.send("Loading {}...".format(what))
try:
bot.load_extension(what)
await msg.edit(content="Loaded {}.".format(what))
except ImportError as e:
await msg.edit(content="Failed to load {}.".format(what))
finally:
... | 74,080 |
def limit_memory(memory=16):
"""
:param memory: 默认限制内存为 16G
:return:
"""
rsrc = resource.RLIMIT_AS
# res_mem=os.environ["RESOURCE_MEM"]
memlimit = memory * 1024 ** 3
resource.setrlimit(rsrc, (memlimit, memlimit))
# soft, hard = resource.getrlimit(rsrc)
print("memory limit as: %s ... | 74,081 |
def _sigma_clip(data, threshold=3, cen_func='median', dev_func='mad_std',
axis=None):
"""Create a mask of the sigma clipped pixels.
This function will not change the array, instead, just output a
mask for the masked elements.
Parameters
----------
data: array_like
Data ... | 74,082 |
def handler500(request, *args, **argv):
"""Error 500 configuration."""
return render(request, '{{cookiecutter.project_slug}}/404.html') | 74,083 |
def klucbGauss(x, level, sig2=1., lower=float("-inf"), upper=float("inf")):
"""returns u such that kl(x,u)=level for the Gaussian kl-divergence (can be done in closed form)."""
if (upper==x):
return x - np.sqrt(2*sig2*level)
elif (lower==x):
return x + np.sqrt(2*sig2*level)
else:
raise ValueError | 74,084 |
def base64_decode(data):
"""Decode a Base64 encodedstring"""
return b64decode(data.encode('utf-8')).decode('utf-8') | 74,085 |
def test_validate_expiration_year_basic_fail2():
"""
Basic test of validate_expiration_year() where the result is False, take 2
"""
assert not validate_expiration_year("200") | 74,086 |
def movie(request, movie_id):
"""显示电影对应的所有场次"""
one_movie = Movie.objects.get(movie_id=movie_id)
comments = Movie_comment.objects.filter(movie_id=movie_id)
score = False
if len(comments) > 0:
score = comments.aggregate(avg_score=Avg('score'))['avg_score']
cursor = connection.cursor()
... | 74,087 |
def stream_prices(pair, config_file, count=0):
"""Stream price data.
Parameters
----------
pair: str
The instrument pair in which to fetch prices.
config_file : str
Location of configuration file.
count: int
The number of price bars to get; infinite bars if count=0.
... | 74,088 |
def load_file_to_dict(path):
"""
Takes a file path and loads it into a nested json dict
following the format in json_form_schema.json
The file may be a xls file or json file.
If it is xls it is converted using xls2json.
"""
if path.endswith(".json"):
name = _section_name(path)
... | 74,089 |
def UpdatePerfDataFiles():
"""Updates the Chrome Endure graph data files with the latest test results.
For each known Chrome Endure slave, we scan its latest test results looking
for any new test data. Any new data that is found is then appended to the
data files used to display the Chrome Endure graphs.
R... | 74,090 |
def test_estimate_numax_basics():
"""Test if we can estimate a numax."""
f, p, true_numax, _ = generate_test_spectrum()
snr = SNRPeriodogram(f*u.microhertz, u.Quantity(p, None))
numax = snr.to_seismology().estimate_numax()
#Assert recovers numax within 10%
assert(np.isclose(true_numax, numax.va... | 74,091 |
def can_lead_to_object_uncertainty(gdatalog):
"""Figure out if a walked GDatalog[Δ] program can lead to object
uncertainty.
Object uncertainty happens when there is a rule in the program such that:
- there exist an atom in the antecedent of the rule such that the
predicate of this atom is... | 74,092 |
def averageRaDec(ra, dec):
"""Calculate average RA, Dec from input lists using spherical geometry.
Parameters
----------
ra : `list` [`float`]
RA in [radians]
dec : `list` [`float`]
Dec in [radians]
Returns
-------
float, float
meanRa, meanDec -- Tuple of average R... | 74,093 |
def _write_annot(fname, annot, ctab, names, table_name=_DEFAULT_TABLE_NAME):
"""Write a Freesurfer annotation to a .annot file."""
assert len(names) == len(ctab)
with open(fname, 'wb') as fid:
n_verts = len(annot)
np.array(n_verts, dtype='>i4').tofile(fid)
data = np.zeros((n_verts, ... | 74,094 |
def onnx2str(model_onnx, nrows=15):
"""
Displays the beginning of an ONNX graph.
See :ref:`onnxsklearnconsortiumrst`.
"""
lines = str(model_onnx).split('\n')
if len(lines) > nrows:
lines = lines[:nrows] + ['...']
return "\n".join(lines) | 74,095 |
def stats_to_s3(uri, stats, algo_namespace, recorded_cols=None,
folder='catalyst/stats', bytes_to_write=None):
"""
Uploads the performance stats to a S3 bucket.
Parameters
----------
uri: str
stats: list[Object]
algo_namespace: str
recorded_cols: list[str]
... | 74,096 |
def create_cmd_arguments(aux):
"""
Use the `argparse` module to make the optional and required command-line
arguments for the `wedap`.
Parameters
----------
Returns
-------
argparse.ArgumentParser:
An ArgumentParser that is used to retrieve command line arguments... | 74,097 |
def run_upload(
plugin: str,
port: str,
local: Path,
remote: str,
ftp_host: str,
ftp_user: str,
ftp_password: str,
ftp_remote: str,
ftp_mirror_options: str,
) -> None:
"""Load a plugin and start upload."""
plugin = import_module(f".{plugin}", "builder.upload")
# Run upl... | 74,098 |
def summary_table(dirname):
"""
Produce LaTeX table with one line for each GROUPS folder in
dirname, and a summary line below.
"""
print r' \begin{tabular}{|l|r|r|r|}'
print r' \hline'
print r' %-30s & Total & Correct & Success rate \\' % 'Image source'
print r' \hline'
for... | 74,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.