content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def plot_history(history):
"""Fonction qui permet de plotter les courbes de précision selon l'epoch et de perte
Args:
history: l'historique des métriques calculées par epoch
"""
plt.plot(history.history["loss"])
plt.plot(history.history["val_loss"])
plt.title("Perte du modèle pendant l'... | 5,304,200 |
def train(args):
"""Sets up connector to train two agents forever.
Args:
args: Command-line arguments.
Returns:
Game connector.
"""
weighted_heuristics = _get_weighted_heuristics(args)
transposition_table = _get_transposition_table(args)
searcher = _get_searcher(args)
... | 5,304,201 |
def test_recall_score_unsupported_average():
"""Test of `recall_score` with unsupported average parameter."""
y_pred = np.array([0, 1, 2])
y_true = np.array([0, 1, 2])
with pytest.raises(InvalidInput):
recall_score(y_pred, y_true, average="foobar") | 5,304,202 |
def get_text_width_px(window, text_str):
"""Using window settings, find width in pixels of a text str.
Args:
window (wx.Window): Window to contain string using default font
text_str (str): string to find the width of
Returns:
(int) width of text_str in pixels in the given window
... | 5,304,203 |
def post_jobs():
"""
Create a job to create preferences/predictions for a custom sequence using the specified model(model_name).
request['sequence_id'] str: uuid of the custom sequence to process
request['job_type'] str: see config.DataType properties for values
request['model_name'] str: name of th... | 5,304,204 |
def fjv_fev(m1, m2, m3, jv, ev, e_out, f_out):
"""Computes the expansion terms from Luo et al. (2016)
See there: eq.(31) and Appendix B1
"""
# Expressions from Appendix B1 in Luo et al. (2016)
Jf0 = (3/4) * np.array([
( -5*ev[1]*ev[2] +... | 5,304,205 |
def test_jsd_pmf2_1():
""" Test the JSD of a distribution with itself """
d1 = [0.5, 0.5]
jsd = jensen_shannon_divergence2(d1, d1)
assert jsd == pytest.approx(0) | 5,304,206 |
def set_placeholder_images(dataset):
""" sets all plots to a grey placeholder image
"""
filename = 'plot_placeholder.png'
placeholder_image_path = settings.STATIC_ROOT + 'images/' + filename
placeholder_media_path = settings.MEDIA_ROOT + '/' + filename
# copy from static to media
if not ... | 5,304,207 |
def join_lines(lines):
"""Joins `lines` with newlines and returns a single string.
You would think you could do that with
| join("\n")
but you can't — see https://github.com/debops/ansible-sshkeys/issues/4
"""
return ''.join("%s\n" % l for l in lines) | 5,304,208 |
def infotodict(seqinfo):
"""Heuristic evaluator for determining which runs belong where
allowed template fields - follow python string module:
item: index within category
subject: participant id
seqitem: run number during scanning
subindex: sub index within group
"""
info = {}
run... | 5,304,209 |
def stringlength_dat(x, m, tps, norm='default', isFreq=False, closed=True):
"""
Compute string length for data set.
Parameters
----------
x, m : arrays
x and y coordinates of data points.
tps : tuple or array
The trial periods (or frequencies): Either a three-tuple specifyin... | 5,304,210 |
def execute_test(command, path, name, variant, config, profile=None):
"""Executes a testcase given a whole command, path to the test file output,
name of the test and variant tested. Config is the global configuration"""
subprocess.Popen([command], stdout=None, stderr=subprocess.PIPE, shell=True).communicat... | 5,304,211 |
def create_attached_file(comment=None, name=None, data=None):
"""Creates a attached file instance."""
if name is None:
name = str(uuid.uuid4()) + '.txt'
if data is None:
data = uuid.uuid4().bytes
return AttachedFile(comment, name, data) | 5,304,212 |
def withprogressbar(func):
"""Decorates ``func`` to display a progress bar while running.
The decorated function can yield values from 0 to 100 to
display the progress.
"""
def _func_with_progress(*args, **kwargs):
max_width, _ = shutil.get_terminal_size()
gen = func(*args, **kwarg... | 5,304,213 |
def b_makeselects(bselected=None, sweep=None):
"""bselected - optional pre-selected bacctid
sweep - optional, shows investment election (ielectionid)
"""
dbcon = mysql.connector.connect(**moneywatchconfig.db_creds)
cursor = dbcon.cursor(dictionary=True)
markup = ''
# sweep
if sweep:
... | 5,304,214 |
def international_gravity(lat: float, epoch: str = '1980') -> float:
"""
International Gravity Formula
Estimate the normal gravity, :math:`g`, using the International Gravity
Formula [Lambert]_, adapted from Stokes' formula, and adopted by the
`International Association of Geodesy <https://www.iag-... | 5,304,215 |
def eclean_pkg(
destructive=False,
package_names=False,
time_limit=0,
exclude_file="/etc/eclean/packages.exclude",
):
"""
Clean obsolete binary packages
destructive
Only keep minimum for reinstallation
package_names
Protect all versions of installed packages. Only meani... | 5,304,216 |
def actions(board):
"""
Returns set of all possible actions (i, j) available on the board.
"""
action_list = list()
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] ==EMPTY:
action_list.append((i,j))
return action_list | 5,304,217 |
def health():
""" Serve React App """
return "Hello World!" | 5,304,218 |
def upgradeSystemOid(store):
"""
Upgrade the system tables to use explicit oid columns.
"""
store.transact(
_upgradeTableOid, store, 'axiom_types',
lambda: store.executeSchemaSQL(CREATE_TYPES))
store.transact(
_upgradeTableOid, store, 'axiom_objects',
lambda: store.ex... | 5,304,219 |
def down_it_tcp(_ctx: Context) -> None:
"""TCP flood method."""
bytes_to_send_len = _ctx.max_random_packet_len if _ctx.random_packet_len else 1024
while True:
try:
sock = _ctx.sock_manager.create_tcp_socket()
sock.connect((_ctx.host_ip, _ctx.port))
_ctx.Statistic... | 5,304,220 |
def validate_name(string, name_type):
"""
Validates the node & property names
"""
if type(string) != str and math.isnan(string):
return None
match = None
if name_type == 'node':
match = re.search('''[^a-zA-Z_]''', string)
elif name_type == 'property':
match = re.s... | 5,304,221 |
def compile_all(stages, num_micro_batches, default_as_option):
"""
Compile all input stages.
"""
num_cpus = int(
min(max(ray.available_resources()["CPU"] // 2, 1), len(stages)))
compile_workers = CompileWorkerPool(num_cpus)
for stage_id, (_, stage_config, auto_sharding_config,
... | 5,304,222 |
def reconcile(*arrays, order=0):
"""
Make sure 1D arrays are the same length. If not, stretch them to match
the longest.
Args:
arrays (ndarray): The input arrays.
order (int): The order of the interpolation, passed to
scipy.ndimage.zoom. Suggestion: 0 for integers and 1 for ... | 5,304,223 |
def create_supervised_tbptt_trainer(
model,
optimizer,
loss_fn,
tbtt_step,
dim=0,
device=None
):
"""Create a trainer for truncated backprop through time supervised models.
Training recurrent model on long sequences is computationally intensive as
it requires to process the whole seq... | 5,304,224 |
def get_X_feed(reverse=True, datapath=None, upsample=False, replicate=False):
"""
Generator for getting all the X vectors. Returns a tuple of (reversed, X) at each yield.
Each X is a numpy array that looks like this:
[N_words_Betrayer_season0, N_sentences_Betrayer_season0, N_requests_season0, politenes... | 5,304,225 |
def ImpulseNoise(p=0, name=None, deterministic=False, random_state=None):
"""
Creates an augmenter to apply impulse noise to an image.
This is identical to ``SaltAndPepper``, except that per_channel is always set to True.
dtype support::
See ``imgaug.augmenters.arithmetic.SaltAndPepper``.
... | 5,304,226 |
def is_indy_sdk_module_installed():
"""Check whether indy (indy-sdk) module is installed.
Returns:
bool: Whether indy (indy-sdk) is installed.
"""
try:
# Check if already imported
if "indy" in sys.modules:
return True
# Try to import
import indy # ... | 5,304,227 |
def generate_filenames(img, key, width=0):
"""
Generate a list of file names corresponding to the lines of image,
with each one containing the given key.
width will be calculated if not given or too small.
"""
needwidth = max(len(l) for l in img)
if width < needwidth + 2:
width = max(needwidth, 35) + 5
if ... | 5,304,228 |
def _tfNormalizerDecorator(cls):
""" A decorator to reuse the Normalizer classes by building a tensorflow
graph equivalence of OnlineNormalizer.normalize """
assert issubclass(cls, OnlineNormalizer)
class _tfNormalizerParams(tfObject):
""" a wrapper for maintaining the tf variables """
... | 5,304,229 |
def setup_package():
"""Setup the environment for the tests then start the server."""
global TEST_WORKSPACE
TEST_WORKSPACE = env.get_workspace('ssl')
os.environ['TEST_WORKSPACE'] = TEST_WORKSPACE
test_config = {}
# Setup environment variables for the test cases.
host_port_cfg = {'viewer_... | 5,304,230 |
def create_user(email, password, first_name, last_name):
"""
Creates a new user
:param email: string
:param password: string
:param first_name: string
:param last_name: string
:return object:
"""
user = User(email=email, first_name=first_name, last_name=last_name)
user.hash_pass... | 5,304,231 |
def doVar(*args):
"""
doVar(ea_t ea, bool isvar=True)
doVar(ea_t ea)
"""
return _idaapi.doVar(*args) | 5,304,232 |
def show_past_outfits():
"""Show user's past outfits on the calendar"""
#make fake data for history of outfits so that prior dates have shit
return render_template("past_outfits.html") | 5,304,233 |
def simplify_using_aff(kernel, expr):
"""
Simplifies *expr* on *kernel*'s domain.
:arg expr: An instance of :class:`pymbolic.primitives.Expression`.
"""
deps = get_dependencies(expr)
inames = deps & kernel.all_inames()
# FIXME: Ideally, we should find out what inames are usable and allow
... | 5,304,234 |
def addition(rct_zmas, prd_zmas, rct_tors=()):
""" z-matrix for an addition reaction
"""
ret = None
dist_name = 'rts'
dist_val = 3.
count1 = automol.zmatrix.count(rct_zmas[0])
if len(rct_zmas) == 2:
count2 = automol.zmatrix.count(rct_zmas[1])
if count1 == 1 or count1 < count... | 5,304,235 |
def check_mag_outliers(datafr, bands, systems):
"""Returns a list with all the types of outliers found for each photometric system.
Parameters
----------
datafr: Pandas DataFrame containing the magnitudes from different photometric systems
for the stars in a given carton
bands: total list o... | 5,304,236 |
def register_developer_game_info_model(group, model):
"""Register the model of the game for the challenge admin."""
register_admin_model(_developer_game_info_models, group, model) | 5,304,237 |
def temp_powlaw( V_a, T0, eos_d ):
"""
Return temperature for debye model
V_a: sample volume array
T0: temperature at V=V0
"""
# get parameter values
param_d = eos_d['param_d']
V0 = param_d['V0']
gamma0 = param_d['gamma0']
q = param_d['q']
gamma_a = gamma_powlaw( V_a, eos_d ... | 5,304,238 |
def hypergeometric_pmf(N, K, n, k, approx=False):
"""
Calculates the hypergeometric probability mass function.
See https://en.wikipedia.org/wiki/Hypergeometric_distribution
Parameters
----------
N : float
The population size.
K : float
The number of success states in the po... | 5,304,239 |
def to_tarball(alert_generator, **tarfile_kwargs):
"""
Write alert dicts to a tar archive
"""
uid = pwd.getpwuid(os.geteuid()).pw_name
gid = grp.getgrgid(os.getegid()).gr_name
euid = os.geteuid()
egid = os.getegid()
with tarfile.open(mode='w:gz', **tarfile_kwargs) as archive:
i =... | 5,304,240 |
def gen_tree(node_container, pair_score, node_scores, root, remain_index, mode):
"""
Step 1: Devide all nodes into left child container and right child container
Step 2: From left child container and right child container, select their respective sub roots
pair_scores: [obj_num, obj_num]
node_score... | 5,304,241 |
def register():
"""[ register using autoload ]"""
AutoLoader.register() | 5,304,242 |
async def test_query_presetposcam(ptz_control):
"""Verify PTZ control query presetposcams."""
route = respx.post(f"http://{HOST}:80/axis-cgi/com/ptz.cgi").respond(
text="""Preset Positions for camera 1
presetposno1=Home""",
headers={"Content-Type": "text/plain"},
)
response = await ptz_... | 5,304,243 |
def is_iterable(x: Any) -> bool:
"""Check if a value is iterable, which is not a scalar"""
return not is_scalar(x) | 5,304,244 |
def remove_empty_or_invalid_file(l_filename):
"""
Check if file is empty or if we captured an error in the command. If so, delete the file.
:param l_filename: Name of file to check
"""
# If file isn't empty (greater than 3 bytes)
# Some of these file only save one CRLF, and so we can't match o... | 5,304,245 |
def process(tile, image, scale, vmin, vmax, nbin, nodata, all_valid,
ignore_alpha):
""" Process one tile. """
# pylint: disable=too-many-arguments
tile = tile & image # clip tile to the image extent
if ignore_alpha:
tile = tile.set_z(tile.size.z - 1)
b_data = image.read(Block(ima... | 5,304,246 |
def _softmax(x: Tensor, dim: int) -> Tensor:
"""(F.softmax())
:param x: shape = (N, In)
:param dim: int. 一般dim设为-1
:return: shape = x.shape"""
return torch.exp(x) / torch.sum(torch.exp(x), dim, keepdim=True) | 5,304,247 |
def add_legend(ax=None,colors=[],labels=[],styles='solid',\
widths=0.7,anchor=(0,1), ncol=3,loc='lower left',fontsize='small',frameon=False,**kwargs):
"""
- Adds custom legeneds on a given axes,returns None.
- **Parameters**
- ax : Matplotlib axes.
- colors : List of ... | 5,304,248 |
def test_retrieve_and_encode_simple(test_client, test_collection_name):
"""Test retrieving documents and encoding them with vectors.
"""
VECTOR_LENGTH = 100
def fake_encode(x):
return test_client.generate_vector(VECTOR_LENGTH)
# with TempClientWithDocs(test_client, test_collection_name, 100)... | 5,304,249 |
def get_scale_name(model_path, scale=None):
""" try to get model scale from model name"""
rlt_scale = None
scale_name = str(osp.basename(model_path)[0:2]).lower()
if 'x' in scale_name:
try:
rlt_scale = int(scale_name.replace('x', ''))
except ValueError:
rlt_scale... | 5,304,250 |
def rbox_overlaps(anchors, gt_bboxes, use_cv2=False):
"""
Args:
anchors: [NA, 5] x1,y1,x2,y2,angle
gt_bboxes: [M, 5] x1,y1,x2,y2,angle
Returns:
"""
assert anchors.shape[1] == 5
assert gt_bboxes.shape[1] == 5
gt_bboxes_ploy = [rbox2poly_single(e) for e in gt_bboxes]
... | 5,304,251 |
def load_model_data(root_dir, model_name):
"""
Used for models split in several files.
Loads subscripts_dic, namespace and modules dictionaries
Parameters
----------
root_dir: str
Path to the model file.
model_name: str
Name of the model without file type extension (e.g. "... | 5,304,252 |
def add_user(
db_url: str,
jwt_secret: str,
username: str,
email: str,
password: str,
customer_id: int = 1
):
"""
Create a base user in the database.
Args:
db_url (str): The connection string to the database.
jwt_secret (str): The JWT secr... | 5,304,253 |
def split_and_check(
s: str, separator: str, n: Union[int, Tuple[int, ...]]
) -> Tuple[str, ...]:
"""Turn string into tuple, checking that there are exactly as many parts as expected.
:param s: String to parse
:param separator: Separator character
:param n: Expected number of parts, can be a single ... | 5,304,254 |
def make_random_gate_statement(
*, count=None, parameter_types=None, return_params=False
):
"""Make a gate statement with random arguments based on
a GateDefinition."""
definition, _, parameters = make_random_gate_definition(
parameter_count=count, parameter_types=parameter_types, return_params=... | 5,304,255 |
def run():
"""Run example"""
return 'running...' | 5,304,256 |
def send_reminders(app):
"""Send SMS reminders for next day appointments."""
app.logger.debug('<<< Starting job')
reminders = get_reminders(app=app, reminder_type='sms')
if reminders:
appointments = reminders.json()
notifications_endpoint = app.config.get('NOTIFICATIONS_ENDPOINT')
... | 5,304,257 |
def _get_kind(type_: Type[TData]) -> Optional[TypeKind]:
"""Extract kind information from type."""
if ABC in type_.__bases__:
return TypeKind.Abstract
elif Record not in type_.mro():
return TypeKind.Element
else:
return None | 5,304,258 |
def calculate_voting_power(error_rate):
"""Given a classifier's error rate (a number), returns the voting power
(aka alpha, or coefficient) for that classifier."""
if error_rate == 0:
return INF
elif error_rate == 1:
return -INF
else:
return make_fraction(1,2) * ln((1-error_r... | 5,304,259 |
def validate(args):
"""
Check that the CLI arguments are valid.
"""
if not args.source_path:
print("Error: You need to specify a source path.")
return False
else:
if not os.path.isdir(args.source_path):
print("Error: Source path is not a folder.you can run autosub... | 5,304,260 |
def delete_time_slot(time_slot_id: UUID) -> None:
"""Delete a time slot."""
db.session.execute(
delete(DbTimeSlot)
.where(DbTimeSlot.id == time_slot_id)
.execution_options(synchronize_session='fetch')
)
db.session.commit() | 5,304,261 |
def freq_correctionbis(cpt_matrice, beta) :
"""
Corrige les counts avec equiprobabilites
"""
for i in range(cpt_matrice.shape[0]) :
for j in range(cpt_matrice.shape[1]) :
cpt_matrice[i,j] = ((cpt_matrice[i,j] + (1/20) )/(1+beta))
return(cpt_matrice) | 5,304,262 |
def bit_to_long(bits: str) -> Decimal:
"""
Converts a bit string in the format '01' to a float, representing the NTP long format (64bit)
"""
ints = int(bits, 2)
result = Decimal(ints) / Decimal(_max_32bit)
return result | 5,304,263 |
def scale_from_internal(vec, scaling_factor, scaling_offset):
"""Scale a parameter vector from internal scale to external one.
Args:
vec (np.ndarray): Internal parameter vector with external scale.
scaling_factor (np.ndarray or None): If None, no scaling factor is used.
scaling_offset (... | 5,304,264 |
async def send_welcome(message: types.Message):
"""
This handler will be called when user sends `/start` or `/help` command
"""
await get_or_create_user(
telegram_id=message.from_user.id, first_name=message.from_user.first_name
)
buttons = buttons_constructor.init_inline(buttons=dialog.... | 5,304,265 |
def test_css_parsing():
"""Test the constructor for the CSS class."""
def check_css(css):
"""Check that a parsed stylsheet looks like resources/utf8-test.css"""
# Using 'encoding' adds a CSSCharsetRule
rule = css.stylesheet.rules[-1]
assert rule.selector.as_css() == 'h1::before'
... | 5,304,266 |
def apply_dhondt(
list_of_parties=['PRD','ARV','PSI','PNR'],
list_of_votes=[2015,1786,1540,1223],
num_of_chairs=12):
"""
list_of_parties: ['PRD','ARV','PSI','PNR']
list_of_votes: [2015,1786,1540,1223]
num_of_chairs: 12
output: (DataFrame)
PRD 4
ARV ... | 5,304,267 |
def test_19_connect_db():
"""Verify that we can get a connection based on the definition of the get_db_connection config function."""
pydbvolve.load_config(TEST_CONFIG_FILE)
config = pydbvolve.new_config()
config.update({'migration_action': 'info',
'version': pydbvolve.LATEST_VERSION... | 5,304,268 |
def get_temp() -> tuple:
"""
Retrieves the CPU temperature of the Raspberry Pi and turns the fan
on or off based on the read value.
:return: An empty tuple.
"""
cpu_temp = float(get_cpu_temperature())
if cpu_temp > maxTMP:
fan_on()
elif cpu_temp < stopTMP:
fan_off()
r... | 5,304,269 |
def parse_arguments(argv):
"""Parse command-line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument(
'--verbosity',
help='Set logging level.',
choices=['DEBUG', 'ERROR', 'FATAL', 'INFO', 'WARN'],
default='INFO',
)
parser.add_argument(
'--tra... | 5,304,270 |
def register_plugin(app, plugins):
""" Plugin register
:param app: flask app
:param plugins:
"""
app.config['fair_plugins'] = plugins or {} | 5,304,271 |
def level_image(image: Image.Image, adjustments: list[LevelsAdjustment]) -> Image.Image:
"""
Apply the specified levels adjustments to each band of an image.
:param image: The input image, with values in the range [0, 255].
:param adjustments: The levels adjustments to apply for each band.
:return:... | 5,304,272 |
def extract_network_information(shape, properties, fid, zoom):
"""
Take the triples of (route_type, network, ref) from `mz_networks` and
extract them into two arrays of network and shield_text information.
"""
mz_networks = properties.pop('mz_networks', None)
if mz_networks is not None:
... | 5,304,273 |
def test_create_photo_folder_name_no_year_keyword(date, month, expected):
"""Test src//photonomist//__main__ > photo_dir_name
"""
assert expected == photo_dir_name(date, month=month) | 5,304,274 |
def filter_pre_string(_string: str, lines_to_cut: int) -> str:
"""
Filter the xml out of html
:param str _string:
:param int lines_to_cut:
"""
filtered_array = _string.splitlines()[lines_to_cut:]
filtered_string = "".join(filtered_array)
filtered_string = filtered_string.strip()
re... | 5,304,275 |
async def test_websocket_proxy():
"""
用户websocket长连接测试:
主要测试功能有:
1. 服务端接收客户端websocket登录请求,并对之进行响应
2. 客户端向服务端发送一条游戏内部消息,观察服务端最后一层节点service是否正确响应,并且将结果返回给客户端;
测试时服务端配置:
登录请求:消息ID为1000, 登录消息暂时配置在route类型节点处理
游戏进入排位场: 消息ID 20000, 进入排位场消息暂时配置在service类型节点处理
客户端测试代码流程:
1. 先发送登录... | 5,304,276 |
def elasticsearch_award_index(db):
"""
Add this fixture to your test if you intend to use the Elasticsearch
award index. To use, create some mock database data then call
elasticsearch_award_index.update_index to populate Elasticsearch.
See test_award_index_elasticsearch_tests.py for sample usage.
... | 5,304,277 |
def extract_ontology_terms(spark_session: SparkSession, input_path) -> DataFrame:
"""
:param spark_session:
:param ontologies_path:
:return:
"""
ontology_terms = []
if ImpcConfig().deploy_mode in ["local", "client"]:
for ontology_desc in ONTOLOGIES:
print(f"Processing {o... | 5,304,278 |
def plot_input_flux(results_array, amp_array, mean_array, stddev_array):
"""
Plotting the integrated flux of the input mock emission lines against the absolute value of the input-output values coloured by whether they were 1 Gaussian, 2 Gaussian or insignificant fits; and split into panels of S/N < 5, 5-10, 10-15 and... | 5,304,279 |
def test_led_instantiation():
"""Test that we can instantiate an LED."""
LED(0, MockLEDBoard(), MockLEDDriver()) | 5,304,280 |
def get_one_example_from_examples_path(source, proto=None):
"""Get the first record from `source`.
Args:
source: str. A pattern or a comma-separated list of patterns that represent
file names.
proto: A proto class. proto.FromString() will be called on each serialized
record in path to parse it.... | 5,304,281 |
def test_relative_chem_pot(test_case_2):
"""verifying the relative chemical potential of the neutron and proton components"""
rel_chem_pot = test_case_2["eos"].relative_chem_pot(
test_case_2["n_b"], test_case_2["n_p"]
)
assert np.abs((rel_chem_pot - test_case_2["del_mu"]) / rel_chem_pot) < TOL | 5,304,282 |
def type_edit_text(control, text):
""" Enter the text into the given iTunes text box control """
control.click_input()
text = text_to_sendkeys_str(text)
type_string = "^A" + text
control.type_keys(type_string) | 5,304,283 |
def open_editor(notebook_filename, editor):
"""opens the notebook in specified shell editor"""
import sys, tempfile, os
from subprocess import call
from src.praxxis.display import display_error
from src.praxxis.util import error
EDITOR = os.environ.get('EDITOR', editor)
try:
call([E... | 5,304,284 |
def ssum(self, **kwargs):
"""Calculates and prints the sum of element table items.
APDL Command: SSUM
Notes
-----
Calculates and prints the tabular sum of each existing labeled result
item [ETABLE] for the selected elements. If absolute values are
requested [SABS,1], absolute values are u... | 5,304,285 |
def test_popping_from_a_WindowStack_returns_the_topmost_window():
"""When popping, a WindowStack returns the topmost window."""
mock_app = 'MockApp'
window_stack = WindowStack(mock_app)
window_stack.append(1)
window_stack.append(2)
window_stack.append(3)
assert window_stack.pop() == 3
... | 5,304,286 |
def get_nth_combination(
iterable,
*,
items: int,
index: int,
):
"""
Credit to:
https://docs.python.org/3/library/itertools.html#itertools-recipes
Examples:
>>> wallet = [1] * 5 + [5] * 2 + [10] * 5 + [20] * 3
>>> get_nth_combination(wallet, items=3, index=... | 5,304,287 |
def test_chunk_it_up():
"""Make sure all content is return from `chunk_it_up` generator"""
from optimade.server.middleware import AddWarnings
content = "Oh what a sad and tragic waste of a young attractive life!"
chunk_size = 16
assert len(content) % chunk_size != 0, "We want a rest bit, this isn't... | 5,304,288 |
def fft2(x, shape=None, axes=(-2, -1), overwrite_x=False):
"""Compute the two-dimensional FFT.
Args:
x (cupy.ndarray): Array to be transformed.
shape (None or tuple of ints): Shape of the transformed axes of the
output. If ``shape`` is not given, the lengths of the input along
... | 5,304,289 |
def equalize(pair, bias_axis, word_to_vec_map):
"""
Debias gender specific words by following the equalize method described in the figure above.
Arguments:
pair -- pair of strings of gender specific words to debias, e.g. ("actress", "actor")
bias_axis -- numpy-array of shape (50,), vector correspon... | 5,304,290 |
def test_text_angle_30(region, projection):
"""
Print text at 30 degrees counter-clockwise from horizontal
"""
fig = Figure()
fig.text(
region=region,
projection=projection,
x=1.2,
y=2.4,
text="text angle 30 degrees",
angle=30,
)
return fig | 5,304,291 |
def pow_church(m, n):
"""Return the Church numeral m ** n, for Church numerals m and n.
>>> church_to_int(pow_church(two, three))
8
>>> church_to_int(pow_church(three, two))
9
"""
"*** YOUR CODE HERE ***" | 5,304,292 |
def edit_cmd(args):
"""Builds and returns 'edit' command."""
cmd = commands.Edit(args.args, color=args.color)
return cmd | 5,304,293 |
def affichage() :
"""Affiche la grille de morpion actuelle dans la console """
print("-"*13)
for ligne in grille :
print("|", end="")
for case in ligne :
print(" " + case + " ", end='|')
print()
print("-"*13)
print() | 5,304,294 |
def get_image_band(filepath, modis_config=None):
"""Helper function to get bands for a particular modis scene
Args:
modis_config (dict): dictionary of configuration for a particular MODIS datasource
filepath (str): path to file to get image band for
"""
bands = list(modis_config["bands"... | 5,304,295 |
def create_mock_engine(bind, stream=None):
"""Create a mock SQLAlchemy engine from the passed engine or bind URL.
:param bind: A SQLAlchemy engine or bind URL to mock.
:param stream: Render all DDL operations to the stream.
"""
if not isinstance(bind, six.string_types):
bind_url = str(bind... | 5,304,296 |
def rst_table(header: Tuple[str, ...], rows: List[Tuple[str, ...]]) -> List[str]:
"""Create a ReST table from header and rows."""
blocks = [".. list-table::\n :header-rows: 1\n"]
num_columns = len(header)
for row in [header] + rows:
template = ("*" + " - {}\n " * num_columns).rstrip()
... | 5,304,297 |
def get_model(args):
""""Get model according to args.arch"""
print("==> Creating model '{}'".format(args.arch))
model = models.__dict__[args.arch](args)
return model | 5,304,298 |
def truncate_note_sequence_op(sequence_tensor, truncated_length_frames,
hparams):
"""Truncates a NoteSequence to the given length."""
def truncate(sequence_tensor, num_frames):
sequence = music_pb2.NoteSequence.FromString(sequence_tensor)
num_secs = num_frames / hparams_frames_... | 5,304,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.