content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def wrapper_configuration_get(): # noqa: E501
"""gets configuration details on the current wrapper configuration
# noqa: E501
:rtype: object
"""
return 'do some magic!' | 5,325,900 |
def controlMotorPID(controller, error, com):
"""send data to ESP32 with desired steps calculated by PID control."""
controller.updateData(error)
ctrl = controller.getControlParam()
sendData(ctrl,com) | 5,325,901 |
def update_qgs():
"""Generate QGIS project files."""
try:
# create ConfigGenerator
generator = config_generator()
qgs_writer_log = generator.write_qgs()
return {
'message': "Finished writing QGIS project files",
'log': qgs_writer_log
}
except ... | 5,325,902 |
def time_evolution_derivatives(
hamiltonian: pyquil.paulis.PauliSum,
time: float,
method: str = "Trotter",
trotter_order: int = 1,
) -> Tuple[List[circuits.Circuit], List[float]]:
"""Generates derivative circuits for the time evolution operator defined in
function time_evolution
Args:
... | 5,325,903 |
def had_cells_strength(strmfunc, min_plev=None, max_plev=None, lat_str=LAT_STR,
lev_str=LEV_STR):
"""Location and signed magnitude of both Hadley cell centers."""
lat = strmfunc[lat_str]
# Sometimes the winter Ferrel cell is stronger than the summer Hadley cell.
# So find the glo... | 5,325,904 |
def d_enter_waste_cooler(W_mass, rho_waste, w_drift):
"""
Calculates the tube's diameter of enter waste to waste cooler.
Parameters
----------
W_mass : float
The mass flow rate of waste, [kg/s]
rho_waste : float
The density of liquid at boilling temperature, [kg/m**3]
w_drift... | 5,325,905 |
def install_program():
"""
Installs user data on the system.
Creates the directory and asks for input for ground observer info.
"""
print """
Would you like to allow issTracker to install on your computer?
It will create on your computer:
- a file to save TLE info for your satellites
... | 5,325,906 |
def test_file__init__():
""" Test with __init__.py from fire project:
-------------------------------------------------------------------------------
Language files blank comment code
-------------------------------------------------------------------------------
Py... | 5,325,907 |
def error(msg):
"""Write a log message at the ERROR level."""
EXEKALL_LOGGER.error(msg) | 5,325,908 |
def test_bam_compare_arguments():
"""
Test minimal command line args for bamCoverage. The ratio
between the same file is taken, therefore, the expected value
is 1.0 for all bins.
"""
outfile = '/tmp/test_file.bg'
for fname in [BAMFILE_B, CRAMFILE_B]:
args = "--bamfile1 {} --bamfile2 ... | 5,325,909 |
async def finalize_round(request, persistence):
"""Finalize an owned round."""
game_id = request.match_info['game_id']
round_name = request.match_info['round_name']
user_session = await get_session(request)
if not client_owns_game(game_id, user_session, persistence):
return json_response({'... | 5,325,910 |
def update_cart_quantity(cart):
"""Update the total quantity in cart."""
total_lines = cart.lines.aggregate(
total_quantity=Sum('quantity'))['total_quantity']
if not total_lines:
total_lines = 0
cart.quantity = total_lines
cart.save(update_fields=['quantity']) | 5,325,911 |
def create_terms_key_terms_page(page, portal_topic):
"""
Parses the terms & definitions on a given key terms page,
and creates new glossary term snippets out of them.
"""
for block in page.specific.content:
if block.block_type != 'full_width_text':
continue
for child in b... | 5,325,912 |
def _arrs_to_ds(arrs, names=None):
"""Combine DataArrays into a single Dataset."""
if names is None:
names = [str(n) for n in range(len(arrs))]
return xr.Dataset(data_vars=dict(zip(names, arrs))) | 5,325,913 |
def formatTimeFromNow(secs=0):
""" Properly Format Time that is `x` seconds in the future
:param int secs: Seconds to go in the future (`x>0`) or the
past (`x<0`)
:return: Properly formated time for Graphene (`%Y-%m-%dT%H:%M:%S`)
:rtype: str
"""
return date... | 5,325,914 |
def exitFlow(x, n_classes):
""" Create the exit flow section
x : input to the exit flow section
n_classes : number of output classes
"""
def classifier(x, n_classes):
""" The output classifier
x : input to the classifier
n_classes : number of o... | 5,325,915 |
def get_files_for_variable(cmake_path, variables, variable):
""" Returns the path values associated with |variable| and relative to the
|cmake_path| directory. """
if not variable in variables:
raise Exception('Variable %s does not exist' % variable)
# Cmake file directory.
cmake_dirnam... | 5,325,916 |
def SingleChannelDDR4_2400(size: Optional[str] = "1024MB") -> SingleChannel:
"""
A single channel DDR3_2400.
:param size: The size of the memory system. Default value of 1024MB.
"""
return SingleChannel("DDR4_4Gb_x8_2400", size) | 5,325,917 |
def convert_Pa_to_dBSPL(pa):
""" Converts units of Pa to dB re 20e-6 Pa (dB SPL) """
return 20. * np.log10(pa / 20e-6) | 5,325,918 |
def isPalindromic(seq):
"""
is a sequence palindromic?
returns True or False
"""
if rc_expanded(seq.lower()) == seq.lower():
return(True)
return(False) | 5,325,919 |
def get_corpus(data_dir):
"""Get list of words in the text.
Args:
data_dir: data directory.
Returns:
list of str words.
"""
corpus = []
files = os.listdir(data_dir)
for filename in files:
data_path = os.path.join(data_dir, filename)
if not os.path.isfile(data... | 5,325,920 |
def randomPairsMatch(n_records_A: int, n_records_B: int, sample_size: int) -> IndicesIterator:
"""
Return random combinations of indices for record list A and B
"""
n: int = n_records_A * n_records_B
if not sample_size:
return iter([])
elif sample_size >= n:
random_pairs = numpy... | 5,325,921 |
def GetScaffoldLengths(genome_fna_fp):
""" This function gets the lengths of the scaffolds, returns a dict
Args:
genome_fna_fp: (str) Path to genome fna file (FASTA)
Returns:
Scaffold_To_Length: (dict)
scaffold_name: (str) -> length (int)
"""
Scaffold_To_Length = {}
... | 5,325,922 |
def define_properties(definitions, superprop=None):
"""
Define BRICK properties
"""
if len(definitions) == 0:
return
for prop, propdefn in definitions.items():
if isinstance(prop, str):
prop = BRICK[prop]
G.add((prop, A, OWL.ObjectProperty))
if superprop ... | 5,325,923 |
def insert_series(series):
"""insert series if missing"""
if not frappe.db.get_value('Series', series, 'name', order_by="name"):
frappe.db.sql("insert into tabSeries (name, current) values (%s, 0)", (series)) | 5,325,924 |
def log(message):
"""Convenience function to log a message to the database."""
db.session.add(LogEntry(message=message)) | 5,325,925 |
def approx_version_number():
"""
In the event that git is unavailable and the VERSION file is not present
this returns a "version number" in the following precedence:
- version number from path
downloads of viral-ngs from GitHub tagged releases
are likely ... | 5,325,926 |
def print_skew(
dat: str,
tsv_sam_sum: pd.Series) -> None:
"""
Parameters
----------
dat : str
Dataset name
tsv_sam_sum : pd.Series
Sum of reads per sample
"""
count, division = np.histogram(tsv_sam_sum)
skw = skew(count)
if abs(skw) > 1:
print... | 5,325,927 |
def plot(io, key, plottype=None, seedid=None, day=None, prep_kw={},
corrid=None, show=False,
**kwargs):
"""
Plot everything
:param io: |io|
:param key: key of objects to plot, or one of stations, data, prepdata
:param plottype: plot type to use
(non default values are ``'v... | 5,325,928 |
def flip_mesh(mesh):
"""
It flips the mesh of a shape.
----------------------------
Args:
mesh (obj: 'base.Trimesh'): The mesh of a shape
Returns:
mesh (obj: 'base.Trimesh'): The flipped mesh of the shape
"""
triangles = np.zeros((3, len(mesh.faces)))
for i, index in en... | 5,325,929 |
def leaky_twice_relu6(x, alpha_low=0.2, alpha_high=0.2, name="leaky_relu6"):
""":func:`leaky_twice_relu6` can be used through its shortcut: :func:`:func:`tl.act.ltrelu6`.
This activation function is a modified version :func:`leaky_relu` introduced by the following paper:
`Rectifier Nonlinearities Improve N... | 5,325,930 |
def fully_connected(inputs,
num_outputs,
scope,
use_xavier=True,
stddev=1e-3,
weight_decay=0.0,
activation_fn=tf.nn.relu,
bn=False,
bn_decay=None,
... | 5,325,931 |
def _x_orientation_rep_dict(x_orientation):
""""Helper function to create replacement dict based on x_orientation"""
if x_orientation.lower() == 'east' or x_orientation.lower() == 'e':
return {'x': 'e', 'y': 'n'}
elif x_orientation.lower() == 'north' or x_orientation.lower() == 'n':
return {... | 5,325,932 |
def write_interrupted_test_results_to(filepath, test_start_time):
"""Writes a test results JSON file* to filepath.
This JSON file is formatted to explain that something went wrong.
*src/docs/testing/json_test_results_format.md
Args:
filepath: A path to a file to write the output to.
test_start_time: ... | 5,325,933 |
def feature_evaluation(X: pd.DataFrame, y: pd.Series, output_path: str = ".") -> NoReturn:
"""
Create scatter plot between each feature and the response.
- Plot title specifies feature name
- Plot title specifies Pearson Correlation between feature and response
- Plot saved under given f... | 5,325,934 |
def move_at_objc_to_access_note(access_notes_file, arg, offset, access_note_name):
"""Write an @objc attribute into an access notes file, then return the
string that will replace the attribute and trailing comment."""
access_notes_file.write(u"""
- Name: '{}'
ObjC: true""".format(access_note_name))
... | 5,325,935 |
def test_idempotent_lambda_with_validator_util(
config_without_jmespath: IdempotencyConfig,
persistence_store: DynamoDBPersistenceLayer,
lambda_apigw_event,
timestamp_future,
serialized_lambda_response,
deserialized_lambda_response,
hashed_idempotency_key_with_envelope,
mock_function,
... | 5,325,936 |
def load_pdbbind_fragment_coordinates(frag1_num_atoms,
frag2_num_atoms,
complex_num_atoms,
max_num_neighbors,
neighbor_cutoff,
pdb... | 5,325,937 |
def cross_validation(dictionary):
"""
parses the data to enable cross validation.
This function takes as input the result of the load_data function
:param dictionary:
:return:
"""
result_dictionary = dict([('test data', np.array([])), ('training data', np.array([])), ('test subject', "")])
... | 5,325,938 |
def get_version_if_modified(gh_type, repo_name, typ, force=False):
"""
Return the latest version if the latest version is different
from the previously indexed version.
Return None if no change.
if force in True, always return the latest version
"""
latest_version = get_latest_version(gh_typ... | 5,325,939 |
def do_rest_request(**kwargs):
"""This function expects full_url or in absence of which, expects a combination of "url" and "query_params"""
if 'full_url' in kwargs:
query_url = kwargs['full_url']
elif 'rest_url' in kwargs and 'query_params' in kwargs:
query_url = kwargs['url'] + '?' + urlp... | 5,325,940 |
def variable(init_val, lb=None, ub=None):
"""
Initialize a scalar design variable.
:param init_val: Initial guess
:param lb: Optional lower bound
:param ub: Optional upper bound
:return: The created variable
"""
var = opti.variable()
opti.set_initial(var, init_val)
if lb is not N... | 5,325,941 |
def current_user() -> str:
"""
Retorna o usuário corrente.
"""
session_id = request.get_cookie(cookie_session_name())
c = get_cursor()
c.execute(
"""
select username
from sessions
where session_id = :session_id
""",
{"session_id": session_id},
)
... | 5,325,942 |
def compare_outputs(output1, output2, rtol=1e-5, atol=1e-7):
"""Compare outputs of two quantities."""
assert len(list(output1.keys())) == len(
list(output2.keys())
), "Different number of entries"
for key in output1.keys():
if isinstance(output1[key], dict):
compare_outputs(... | 5,325,943 |
def printer_worker(prefix, pause, exitRequest, pipelineIn, pipelineOut):
"""
This function is used for multiprocessing.
The controller of the process(es) will be referred to as the manager (just to make it easier).
Parameters
----------
prefix: Data for class constructor
pause: A mutex lock... | 5,325,944 |
def test_feeds(mock_feeds, user, feeds):
"""
Test for:
User.iter_feeds
User.feeds
"""
assert [*user.iter_feeds()] == feeds
assert user.feeds() == feeds
limit = len(feeds) - len(feeds) // 2
assert user.feeds(limit=limit) == feeds[:limit] | 5,325,945 |
async def async_setup(hass, hassconfig):
"""Setup Component."""
hass.data.setdefault(DOMAIN, {})
config = hassconfig.get(DOMAIN) or {}
hass.data[DOMAIN]['config'] = config
hass.data[DOMAIN].setdefault('entities', {})
hass.data[DOMAIN].setdefault('configs', {})
hass.data[DOMAIN].setdefault('... | 5,325,946 |
def mplplot(peaklist, w=1, y_min=-0.01, y_max=1, points=800, limits=None):
"""
A no-frills routine that plots spectral simulation data.
Arguments
---------
peaklist : [(float, float)...]
a list of (frequency, intensity) tuples.
w : float
peak width at half height
y_max : flo... | 5,325,947 |
def get_node_centroids(mesh):
"""
Calculate the node centroids of the given elements.
Parameters
----------
mesh : list of dicts or single dict
each dict containing
at least the following keywords
nodes : ndarray
Array with all node postions.
... | 5,325,948 |
def find_saas_replication_price(package, tier=None, iops=None):
"""Find the price in the given package for the desired replicant volume
:param package: The product package of the endurance storage type
:param tier: The tier of the primary storage volume
:param iops: The IOPS of the primary storage volu... | 5,325,949 |
def _get_option_of_highest_precedence(config, option_name):
"""looks in the config and returns the option of the highest precedence
This assumes that there are options and flags that are equivalent
Args:
config (_pytest.config.Config): The pytest config object
option_name (str): The name of... | 5,325,950 |
def get_industry_categories():
"""按编制部门输出{代码:名称}映射"""
expr = STOCK_DB.industries.drop_field('last_updated')
df = odo(expr, pd.DataFrame)
res = {}
for name, group in df.groupby('department'):
res[name] = group.set_index('industry_id').to_dict()['name']
return res | 5,325,951 |
def test_get_transaction_by_transaction_id_from_budget(ynab):
"""Tests that a transaction can be retrieved from a Budget object by ID"""
budget = ynab.budget("string")
transaction = budget.transaction("string")
assert isinstance(transaction, models.Transaction)
assert transaction.id == "string" | 5,325,952 |
def rate(t, y, dt, elph_tau, pol_tau, delay, start):
"""Rate equation function for two state model. y[0] is charge transfer state,
y[1] is polaron state, elph_tau is electron-phonon scattering constant, pol_tau is
polaron formation constant."""
dydt = [(pulse(t, dt, delay, start) - (y[0] - y[1])/e... | 5,325,953 |
def trace_module(no_print=True):
""" Trace my_module_original exceptions """
with putil.exdoc.ExDocCxt() as exdoc_obj:
try:
docs.support.my_module.func('John')
obj = docs.support.my_module.MyClass()
obj.value = 5
obj.value
except:
raise... | 5,325,954 |
def data_to_seq(X, Y,
t_lag=8,
t_future_shift=1,
t_future_steps=1,
t_sw_step=1,
X_pad_with=None):
"""Slice X and Y into sequences using a sliding window.
Arguments:
----------
X : np.ndarray with ndim == 2
Y : n... | 5,325,955 |
def masterbias(files,med=False,outfile=None,clobber=True,verbose=False):
"""
Load the bias images. Overscan correct and trim them. Then average them.
Parameters
----------
files : list
List of bias FITS files.
med : boolean, optional
Use the median of all the files. By defaul... | 5,325,956 |
def get_model_kind(model):
"""Returns the "kind" of the given model.
NOTE: A model's kind is usually, but not always, the same as a model's class
name. Specifically, the kind is different when a model overwrites the
_get_kind() class method. Although Oppia never does this, the Apache Beam
framework... | 5,325,957 |
def get_Zvalence_from_pseudo(pseudo):
"""
Extract the number of valence electrons from a pseudo
"""
with open(pseudo.get_file_abs_path(),'r') as f:
lines=f.readlines()
for line in lines:
if 'valence' in line:
try:
return int(float(... | 5,325,958 |
def detect_data_shifts(time_series,
filtering=True, use_default_models=True,
method=None, cost=None, penalty=40):
"""
Detect data shifts in the time series, and return list of dates where these
data shifts occur.
Parameters
----------
time_series : ... | 5,325,959 |
def add_to_instapaper(account, res, limit, interests):
"""Processes and calls post on array of hackernews post objects
:param account: user's Instapaper account information
:param res: array of hackernews post objects
:param interests: array of subdomain's user is interested in
"""
username, pa... | 5,325,960 |
def read_rds(filepath):
"""Read an RDS-format matrix into a Pandas dataframe.
Location can be data, scratch, or results.
Index is populated from first column"""
raw_df = pyreadr.read_r(filepath)[None]
if raw_df.isnull().values.any():
raise ValueError("NaN's were found in the data matrix.")
... | 5,325,961 |
def history():
"""Show history of transactions."""
# Read Transactions database for desired elements
transactions = db.execute("SELECT symbol, share, price, method, timestamp FROM Transactions WHERE id = :uid", uid = session["user_id"])
# Convert prices to 2 decimal places
for transaction in tr... | 5,325,962 |
def make_pdf(outfile, target=None, bypass_errors=False, remove_tmp=True,
only_page="", es_upload=NO_ES_UP):
"""Use prince to convert several HTML files into a PDF"""
logger.info("rendering PDF-able versions of pages...")
target = get_target(target)
temp_files_path = temp_dir()
render_pages(... | 5,325,963 |
def _load_expert_models(scenario_name, run_id, len_stream):
"""Load ExML experts.
If necessary, the model are automatically downloaded.
"""
# base_dir = f'/raid/carta/EXML_CLVISION_PRETRAINED_EXPERTS/{scenario_name}'
base_dir = default_dataset_location(
f"EXML_CLVISION22_PRETRAINED_EXPERTS/... | 5,325,964 |
def generate_args(job_name, common, cloud_provider, image, k8s_version,
test_suite, job):
"""Returns a list of args fetched from the given fields."""
args = []
args.extend(get_args(job_name, common))
args.extend(get_args(job_name, cloud_provider))
args.extend(get_args(job_name, ima... | 5,325,965 |
def isPrime(n):
"""
check is Prime,for positive integer.
使用试除法
"""
if n <= 1:
return False
if n == 2:
return True
i = 2
thres = math.ceil(math.sqrt(n))
while i <= thres:
if n % i == 0:
return False
i += 1
return True | 5,325,966 |
def plotCorrelation(X, Y, history=10000, name=None, group=None):
"""Plotting the correlation of two parameters X and Y over time.
(Using a buffer in the backend).
Args:
:X(Record): An event parameter, e.g. hit rate
:Y(Record): An event parameter, e.g. some motor position
Kwargs:
... | 5,325,967 |
def reconstruction_loss(loss_type: str,
in_dim: Tuple[int],
x: torch.Tensor,
x_reconstr: torch.Tensor,
logits: bool = True,
) -> torch.Tensor:
"""
Computes reconstruction loss (mse or cross-en... | 5,325,968 |
def NOR(*variables):
"""NOR.
Return the boolean expression for the OR of the variables. Equivalent to
``NOT(OR(*variables))``.
Parameters
----------
*variables : arguments.
``variables`` can be of arbitrary length. Each variable can be a
hashable object, which is the label of t... | 5,325,969 |
def post_index(new_index, old_index, alias, index_name, settings):
"""
Perform post-indexing tasks:
* Optimize (which also does a refresh and a flush by default).
* Update settings to reset number of replicas.
* Point the alias to this new index.
* Unflag the database.
* ... | 5,325,970 |
def timing_run(args, shell: bool = False, stdin=None, stdout=None, stderr=None,
environ=None, cwd=None, resources=None, identification=None, shuffle=False) -> RunResult:
"""
Create an timing process with stream
:param args: arguments for execution
:param shell: use shell to execute args
... | 5,325,971 |
def alterMethods(cls):
"""
Alter Monte methods on behalf of AutoHelp.
Return the signatures of the altered methods.
NOT_RPYTHON
"""
atoms = []
imports = set()
def nextName(nameIndex=[0]):
name = "_%d" % nameIndex[0]
nameIndex[0] += 1
return name
execNames... | 5,325,972 |
def make_multiclouds(docs: List[Union[dict, object, str, tuple]],
opts: dict = None,
ncols: int = 3,
title: str = None,
labels: List[str] = None,
show: bool = True,
figure_opts: dict = None,
... | 5,325,973 |
def action_prop(param, val=1):
"""A param that performs an action"""
def fdo(self):
self.setter(param, val)
return fdo | 5,325,974 |
def find_or_create(find, create):
"""Given a find and a create function, create a resource if it doesn't exist"""
result = find()
return result if result else create() | 5,325,975 |
def Gsigma(sigma):
"""Pickle a gaussian function G(x) for given sigma"""
def G(x):
return (math.e ** (-(x**2)/(2*sigma**2)))/(2 * math.pi* sigma**2)**0.5
return G | 5,325,976 |
def session_to_ical(session, detailed=False):
"""Serialize a session into an iCal.
:param session: The session to serialize
:param detailed: If True, iCal will include the session's contributions
"""
calendar = icalendar.Calendar()
calendar.add('version', '2.0')
calendar.add('prodid', '-//C... | 5,325,977 |
def add_selection_methods_to_method_holder():
"""
Adds the default methods to the SelectionMethodHolder.
"""
SelectionMethodHolder.add_selection_method(LineChart, SelectionTypes.HorizontalLine, get_selection_line_chart_horizontal_rect)
SelectionMethodHolder.add_selection_method(LineChart, SelectionT... | 5,325,978 |
def test_envelope_fails_on_message_empty_protocol_specification_id():
"""Check message.protocol_specification_id."""
class BadMessage(Message):
protocol_id = "some/some:0.1.0"
message = BadMessage()
with pytest.raises(ValueError):
Envelope(message=message, to="1", sender="1") | 5,325,979 |
def list_account_roles(nextToken=None, maxResults=None, accessToken=None, accountId=None):
"""
Lists all roles that are assigned to the user for a given AWS account.
See also: AWS API Documentation
Exceptions
:example: response = client.list_account_roles(
nextToken='string',
... | 5,325,980 |
def run_script(script_filepath, config_filepath, **kwargs):
"""Method to run experiment (defined by a script file)
Args:
script_filepath (str): input script filepath
config_filepath (str): input configuration filepath
"""
# Add config path and current working directory to sys.path to co... | 5,325,981 |
def _normalize_hosts(hosts):
"""
Helper function to transform hosts argument to
:class:`~elasticsearch.Elasticsearch` to a list of dicts.
"""
# if hosts are empty, just defer to defaults down the line
if hosts is None:
return [{}]
# passed in just one string
if isinstance(hosts,... | 5,325,982 |
def simple_aggregate(raw_dir: Path):
"""
A simple, sequential version of the aggregate functionality.
This combines uniref sequences with < 20% sequence identity into
a single fasta file of 200k sequences.
"""
seqrecs = []
count = 0
total = 0
dirs = list(raw_dir.iterdir())
np.ra... | 5,325,983 |
def data(self: Client) -> DataProxy:
"""Delegates to a
:py:class:`mcipc.rcon.je.commands.data.DataProxy`
"""
return DataProxy(self, 'data') | 5,325,984 |
def proximal_policy_optimization_loss(advantage, old_prediction, loss_clipping=0.2, entropy_loss=5e-3):
"""
https://github.com/LuEE-C/PPO-Keras/blob/master/Main.py
# Only implemented clipping for the surrogate loss, paper said it was best
:param advantage:
:param old_prediction:
:param loss_clip... | 5,325,985 |
def tokenize_string(string):
"""Split a string up into analyzable characters.
Returns a list of individual characters that can
then be matched with the regex patterns.
Note that all accent characters can be found with
the range: \u0300-\u036F. Thus, strings are split
by [any_character]... | 5,325,986 |
def test_azure_firewall_network_rule_create_command_for_firewall(requests_mock):
"""
Scenario: Create network rule in firewall rule collection.
Given:
- User has provided valid credentials.
When:
- azure-firewall-network-rule-create called.
Then:
- Ensure outputs prefix is correct.
... | 5,325,987 |
def onSuccessfulTorrentAdd(mediaInfoRecord, mode):
"""
onSuccessfulTorrentAdd groups operations that should be run upon successfully initiating a download, including updating the mediaIndex.json file and sending an email
:testedWith: TestNewTorrentController:test_onSuccessfulTorrentAdd
:return: None
"""
# notify ... | 5,325,988 |
def compute_final_metrics(source_waveforms, separated_waveforms, mixture_waveform):
"""Permutation-invariant SI-SNR, powers, and under/equal/over-separation."""
perm_inv_loss = wrap(lambda tar, est: -signal_to_noise_ratio_gain_invariant(est, tar))
_, separated_waveforms = perm_inv_loss(source_waveforms,sepa... | 5,325,989 |
def main():
"""
Entry point to the script. Prints answers to the three questions to the
console.
"""
# Change this parameter to query other organizations
repos = all_repos_filtered(api_repo_url('customerio'))
issues_count = 0
watchers_max = {'name': '', 'watchers': 0}
# No need to... | 5,325,990 |
def test_get_config_and_set_config():
"""Does get_config and set_config work properly"""
app = create_ctfd()
with app.app_context():
assert get_config('setup') == True
config = set_config('TEST_CONFIG_ENTRY', 'test_config_entry')
assert config.value == 'test_config_entry'
ass... | 5,325,991 |
def gen_sdc_pandas_series_rolling_impl(pop, put, get_result=result_or_nan,
init_result=numpy.nan):
"""Generate series rolling methods implementations based on pop/put funcs"""
def impl(self):
win = self._window
minp = self._min_periods
input_series... | 5,325,992 |
def drop_ships_by_key_value(key_to_check, value_to_check, db):
"""
Steady method for dropping db entries using a key:value requirement
:param key_to_check:
:param value_to_check:
:param db:
:return: alters the db in place
"""
ships = db.keys()
for ship in ships:
ship_db = db[... | 5,325,993 |
def lprint(*args: Iterable):
""" Synchronized print """
if not hasattr(lprint, 'lock'):
lprint.lock = threading.Lock()
with lprint.lock:
print(*args) | 5,325,994 |
def gen_random_colors(num_groups, colors=None):
"""
Generates random colors.
Parameters
----------
num_groups : int
The number of groups for which colors should be generated.
colors : list : optional (contains strs)
Hex based colors that should be appended if no... | 5,325,995 |
def get_file_creation_date(path):
"""
Get the file creation date.
"""
assert_file(path)
creation_timestamp = os.path.getctime(path)
creation_date = dt.datetime.fromtimestamp(creation_timestamp)
return creation_date | 5,325,996 |
def eval_moses_bleu(ref, hyp):
"""
Given a file of hypothesis and reference files,
evaluate the BLEU score using Moses scripts.
"""
assert os.path.isfile(hyp)
assert os.path.isfile(ref) or os.path.isfile(ref + "0")
assert os.path.isfile(BLEU_SCRIPT_PATH)
command = BLEU_SCRIPT_PATH + " %s... | 5,325,997 |
def lint_mypy(session):
"""Check types with mypy."""
files = session.posargs or [PACKAGE_DIR, TESTS_DIR]
session.install(".[tests,lint]")
session.run(
"python",
"-m",
"mypy",
*files,
) | 5,325,998 |
def build_graph(sorted_sequence):
"""
Each node points to a list of the nodes that are reacheable from it.
"""
elements = set(sorted_sequence)
graph = defaultdict(lambda : [])
for element in sorted_sequence:
for i in [1, 2, 3]:
if element + i in elements:
grap... | 5,325,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.