text string | label_name string | labels int64 |
|---|---|---|
me(&[
ItemConfig {
name: "recharge_demand",
title: ItemConfig::DEFAULT_RECHARGE_TITLE,
config: ItemConfigType::Float { min: 1.0, max: 3.0, default: 1.8 }
},
ItemConfig {
name: "melt_rate",
title: "融化频率",
config: ItemConfigTy... | Rust | 0 |
request(self, request: Request):
# Prepare headers
headers = request.headers
headers.setdefault(
'User-Agent',
bytes_to_str(request.user_agent or DEFAULT_USER_AGENT)
)
headers.setdefault(
'Accept-Encoding',
'gzip,deflate' if request... | Python | 1 |
ros must be defined
///
/// * `mask_bodies_callback($callback:path)`
/// select between `mask_bodies`
///
macro_rules! mask_bodies_escaping_ptr {
($fa:expr, 128, ) => {
mask_bodies_callback!($crate::bodies_exact_one_ptr);
};
($la:expr, $ra:expr, $fb:expr, $fc:expr, 128, ) => {
mask_bodie... | Rust | 0 |
import chess
def score_material(board):
piece_values = {
chess.PAWN: 1,
chess.KNIGHT: 3,
chess.BISHOP: 3,
chess.ROOK: 5,
chess.QUEEN: 9,
chess.KING: 0 # King is invaluable, but we set it to 0 for scoring purposes
}
score = 0
for p, v in piece_values... | Python | 1 |
(buf):
converted = MyArray(buf.shape, buf.dtype, buf)
return np.asarray(converted)
buf = np.arange(4)
got = foo(buf)
# the following fails because our np.asarray is returning the source
# array type
self.assertIs(type(got), np.ndarray)
def test_myarr... | Python | 1 |
Array::zeros(bbox.shape_ndarray_shape().as_slice());
n.read_ndarray_into::<i32>("test/array/group", &array_meta, &bbox, a_c.view_mut())
.unwrap();
assert_eq!(array, a);
assert_eq!(array, a_c);
assert_eq!(a, a_c);
}
<gh_stars>0
use std::marker::PhantomData;
use std::path::Path;
use image::{Dyn... | Rust | 0 |
not opts:
print(
usage
% (
os.path.basename(
sys.argv[0],
)
)
)
return
for opt, val in opts:
if opt == "-s":
bCallback = 1
if opt == "-l":
ShowConnections()
... | Python | 1 |
from setuptools import setup, find_packages
try:
packages = find_packages()
except ImportError:
import os
packages = [x.strip('./').replace('/','.') for x in os.popen('find -name "__init__.py" | xargs -n1 dirname').read().strip().split('\n')]
with open("README.md", "r") as fh:
long_description = fh.re... | Python | 1 |
y_close_base_stream_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
}
impl<O: IsA<FilterInputStream> + IsA<glib::object::Object>> FilterInputStreamExt for O {
fn get_base_stream(&self) -> Option<InputStream> {
unsafe {
from_glib_none(ffi::g_filter_input_stream_get_base_stream(se... | Rust | 0 |
::RefCell;
use v8::ValueDeserializerHelper;
use v8::ValueSerializerHelper;
pub(crate) fn init_builtins_v8() -> Vec<OpDecl> {
vec![
op_ref_op::decl(),
op_unref_op::decl(),
op_set_macrotask_callback::decl(),
op_set_next_tick_callback::decl(),
op_set_promise_reject_callback::decl(),
op_set_uncau... | Rust | 0 |
behavior = Behavior::MovingTo(flee_loc);
game.replace_behavior(&attacker_loc, behavior);
true
} else {
debug!("{attacker} is hurt and wanted to flee but was unable to");
false
}
}
fn switched_to_attacking(game: &mut Game, oid: Oid, units: Time) -> Option<Acted> {
let loc = g... | Rust | 0 |
a
d/ @ s d Z ddlZG dd dejZG dd dejZG dd dejZG d d
d
eejZG dd deejZd
d ZdZe eZ
dS )zj Python Character Mapping Codec cp424 generated from 'MAPPINGS/VENDORS/MISC/CP424.TXT' with gencodec.py.
Nc @ s e Zd Zddd... | Python | 1 |
,
initializer: Option<&'a Node<'a>>,
optional: bool,
computed: bool,
readonly: bool,
is_static: bool,
export: bool,
},
TSMethodSignature {
key: &'a Node<'a>,
params: No... | Rust | 0 |
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | Python | 1 |
"Sing", "Glare"]
buckets["Support"] += 1
elif given_pokemon_class_data.moves[move] == 5:
buckets["Support"] += 1
elif given_pokemon_class_data.moves[move] == 9:
trick_room_user = "Trick Room"
if move_index == 22:
move_index = 19
else:
move_index += 1
write_file.write(f"Attack Type Bucket {atta... | Python | 1 |
"""Compute backends for opt_einsum."""
# Backends
from opt_einsum.backends.cupy import to_cupy
from opt_einsum.backends.dispatch import (
build_expression,
evaluate_constants,
get_func,
has_backend,
has_einsum,
has_tensordot,
)
from opt_einsum.backends.tensorflow import to_tensorflow
from opt_e... | Python | 1 |
s("l"), // 15
])),
LINE, // 16
s("mnopq"), // 17..21
]));
// If fit.
// assert_eq!(print(80, &doc), "abcdef ghi jk l mnopq");
// If not fit.
assert_eq!(print(13, &doc), "abcdef\nghi\njk\nl\nmnopq");
}
#[test]
... | Rust | 0 |
.par_map(None, move |(image_file, records)| {
let classes = classes.clone();
let class_whitelist = class_whitelist.clone();
move || -> Result<_> {
let size = {
let imagesize::ImageSize {
... | Rust | 0 |
xpected)
# __xor__ syntax
with tm.assert_produces_warning(FutureWarning):
expected = index1 ^ index2
assert tm.equalContents(result, expected)
assert result.name is None
class TestSetOpsSort:
@pytest.mark.parametrize("slice_", [slice(None), slice(0)])
def test_unio... | Python | 1 |
min_dist.append(infos[0]['info'].min_dist)
episode_rew += rew[0]
eval_masks = torch.tensor(
[[0.0] if done_ else [1.0] for done_ in done],
dtype=torch.float32,
device=device)
for info in infos:
if 'episode' in info.... | Python | 1 |
from sqlalchemy import (
Column,
UUID,
String,
Text,
Integer,
Boolean,
DateTime,
PrimaryKeyConstraint,
text,
func,
Index
)
from sqlalchemy.dialects.postgresql import JSONB
from internal.extension.database_extension import db
from .app import AppDatasetJoin
from .upload_file ... | Python | 1 |
import logging
import os
from sys import platform
import yaml
import igibson
from igibson.envs.igibson_env import iGibsonEnv
from igibson.render.profiler import Profiler
from igibson.utils.assets_utils import download_assets, download_demo_data
def main(selection="user", headless=False, short_exec=False):
"""
... | Python | 1 |
rain_water() {
let test_cases = vec![
(vec![
vec![1,4,3,1,3,2],
vec![3,2,1,3,2,4],
vec![2,3,3,2,3,1],
], 4),
];
for (map, expect) in test_cases {
assert_eq!(Solution::trap_rain_water(map.clone()), expect, "map: {... | Rust | 0 |
_crops containing batches of images.
batch_idx (int): index of the batch.
Returns:
torch.Tensor: total loss composed of DINO loss and classification loss.
"""
out = super().training_step(batch, batch_idx)
class_loss = out["loss"]
feats1, feats2 = out["fe... | Python | 1 |
# function for doing a morph between two sounds using the hpsModel
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import get_window
from smstools.models import hpsModel as HPS
from smstools.transformations import hpsTransformations as HPST
from smstools.models import utilFunctions as UF
inputFil... | Python | 1 |
up::stripe::Customer::async_list(auth).await?;
/// ```
pub async fn async_list(creds: Auth) -> Result<Vec<Self>, reqwest::Error>{
let mut objects: Vec<Self> = Vec::new();
let mut has_more = true;
let mut starting_after: Option<String> = None;
while has_more{
let json... | Rust | 0 |
# -*- coding: utf-8 -*-
# Part of Fothz. See LICENSE file for full copyright and licensing details.
{
'name': 'Test Full Crm Flow',
'version': '1.0',
'category': 'Hidden/Tests',
'description': """
This module is intended to test the main crm flows of Fothz, both frontend and
backend. It notably include... | Python | 1 |
kBackupQuota
@DiskBackupQuota.setter
def DiskBackupQuota(self, DiskBackupQuota):
self._DiskBackupQuota = DiskBackupQuota
@property
def AutoVoucher(self):
return self._AutoVoucher
@AutoVoucher.setter
def AutoVoucher(self, AutoVoucher):
self._AutoVoucher = AutoVoucher
... | Python | 1 |
╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝
Hiroaki Fujiwara, 2024
==== CALCULATION CONDITIONS
RADIUS = {self.R} [m]
RPM = {self.RPM}
V = {self.V} [m/s]
J = {self.J}
==== BASIC RESULTS
Thrust = {self.T} [N]
Torque = {self.Q} [Nm]
Ct = {self.Ct} [UIUC definition]
Cq = {self.Cq} [UIUC definition]
Cp = {self.Cp} [UIUC defi... | Python | 1 |
pub app_id: ApplicationId,
pub unk_1: u32,
pub unk_flags: u32,
pub unk_2: [u8; 0x10],
pub unk_3: u32,
pub unk_4: u16,
pub unk_reserved: [u8; 0x2],
pub unk_6: [u8; 0x8],
pub unk_7: [u8; 0x10],
pub unk_8: u32,
pub unk_9: u8,
pub unk_reserved_2: [u8; 0xB]
}
#[derive(Copy, ... | Rust | 0 |
extract previous loop start
match loop_checker.pop() {
Some((chr, matching_loop)) => {
assert!(chr == '[', "No matching `]` for ]!");
// jump to loop start intruction
program.push(OpCode:... | Rust | 0 |
from_pretrained(
self.config["clip_model"]
)
return self._clip_processor
def load_task(self, task_name_or_config: str | DictConfig):
if isinstance(task_name_or_config, str):
task_config = self.get_task_config(task_name_or_config)
else:
tas... | Python | 1 |
(IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1)), 1234);
let exp_result = TransportType::IpConnection(exp_socket);
let act_result = parse_ip_connection(&IP_ADDR).unwrap();
assert_eq!(act_result, exp_result);
}
#[test]
fn parse_ip_connection_invalid() {
let result = parse_ip_connection... | Rust | 0 |
_char(f: fn(*const char)) {
let a = ['c'; 1];
let b = ['d'; 3];
let c = ['e'; 15];
f(&a as *const _);
f(&b as *const _);
f(&c as *const _);
// Any type of local array variable leads to stack protection with the
// "strong" heuristic. The 'basic' heuristic only adds stack protection to
... | Rust | 0 |
chain;
// Specify the errors we will produce and foreign links
error_chain! {
types {
Error, ErrorKind, ResultExt, Result;
}
foreign_links {
Io(std::io::Error);
Url(url::ParseError);
Provider(flowcore::errors::Error);
Glob(glob::PatternError);
}
}
use crate::env... | Rust | 0 |
r while getting root window's geometry, XGetGeometry returned non Success status -> {}",
status
);
}
let width = unsafe { width.assume_init() };
let height = unsafe { height.assume_init() };
let depth = unsafe { depth.assume_init() };
... | Rust | 0 |
from fastapi import BackgroundTasks, FastAPI, Depends
app = FastAPI()
def write_notification(email: str, message=""):
with open("log.txt", mode="w") as email_file:
content = f"notification for {email}: {message}"
email_file.write(content)
@app.post("/send-notification/{email}")
async def send_n... | Python | 1 |
import pytest
from unittest.mock import patch
import requests
import json
import os
from pinecone_text.dense import JinaEncoder
@pytest.mark.parametrize(
"encoding_function",
[
("encode_documents"),
("encode_queries"),
],
)
def test_encode_single_text(encoding_function):
encoder = Jin... | Python | 1 |
#这个py文件对应的合约是contracts/TestStruct.sol
#注意:TestStruct.sol 的编译器版本是solc6以上
from client.contractnote import ContractNote
from client.bcosclient import (
BcosClient,
BcosError
)
import os
from eth_utils import to_checksum_address
from client.datatype_parser import DatatypeParser
from console_utils.console_common imp... | Python | 1 |
res.push('=');
}
}
// safe unwrap: if we had non standard chars, it would have errored before
Ok(STD.decode(&res).unwrap())
}
#[cfg(test)]
mod tests {
use super::{decode, encode};
#[test]
fn can_decode_bcrypt_base64() {
let hash = "YETqZE6eb07wZEO";
assert_eq!(
"hello world",
... | Rust | 0 |
igsize=(12, 4))
# Biểu đồ Loss
ax1.plot(history.history['loss'],
label='Train Loss', color='blue')
ax1.plot(history.history['val_loss'],
label='Val Loss', color='orange')
ax1.set_title('Loss')
... | Python | 1 |
: !applyref:sorted
_args:
- [3, 4, 1, 2]
_kwargs:
reverse: False
d: !ref <c>-<c>
# 2. Only pass the keyword arguments
e: !applyref:random.randint
a: 1
b: 3
f: !ref <e><e>
# 3. Only pass the positional arguments
g: !applyref:random.randint... | Python | 1 |
e.numpy()
assert np.isfinite(np_values * np_values + np_values).any()
check_remote(rpc.Server("127.0.0.1"))
for dtype in [
"bool",
"int4",
"int8",
"uint8",
"int16",
"uint16",
"int32",
"int32",
"int64",
"uint64",
... | Python | 1 |
seg=32, ring=16):
verts = []; faces = []
for i in range(ring):
u = 2*math.pi*i/ring; cu, su = math.cos(u), math.sin(u)
for j in range(seg):
v = 2*math.pi*j/seg; cv, sv = math.cos(v), math.sin(v)
x = (R + r*cv) * cu
y = r * sv
... | Python | 1 |
class Solution:
def minInsertions(self, s: str) -> int:
return len(s) - self._longestPalindromeSubseq(s)
# Same as 516. Longest Palindromic Subsequence
def _longestPalindromeSubseq(self, s: str) -> int:
n = len(s)
# dp[i][j] := LPS's length in s[i..j]
dp = [[0] * n for _ in range(n)]
for i i... | Python | 1 |
.and(0);
assert_eq!(a, Some(1));
assert_eq!(b, None);
}
#[test]
fn test_and_then() {
let a = true.and_then(|| 1);
let b = false.and_then(|| 0);
assert_eq!(a, Some(1));
assert_eq!(b, None);
}
#[test]
fn test_or() {
let a = true.or(1);
... | Rust | 0 |
1_PU_A::ENABLED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the fie... | Rust | 0 |
j = locals()[lib]
for key, val in _baks[lib].items():
setattr(obj, key, val)
def unsafe_execute(program: str, exec_globals: dict):
try:
gc_bak = gc.isenabled()
gc.disable()
with reliability_guard():
exec(program, exec_globals)
fina... | Python | 1 |
"--chunk-max",
10,
]
call = list(map(str, call))
logging.info("CALL: " + " ".join(call))
procs.append(subprocess.Popen(call))
for p in procs:
p.wait()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parse... | Python | 1 |
# 設定ファイル(config.py)###############
version = 'v2' # プログラムバージョン
channel = 27 # 周波数チャンネル !!!ch24-38は簡易無線局要申請!!!
pwr = 22 #20mw->13
######################################
# 周波数リスト(チャンネル:周波数)
# https://www.tele.soumu.go.jp/j/adm/system/ml/920mhz/index.htm (最終確認20231016)
# ch24-38は簡易無線局である為要申請
frequency_list = {
# 簡易無... | Python | 1 |
# stop words as whitespace-separated list.
# Source: https://raw.githubusercontent.com/dohliam/more-stoplists/master/yo/yo.txt
STOP_WORDS = set(
"a an b bá bí bẹ̀rẹ̀ d e f fún fẹ́ g gbogbo i inú j jù jẹ jẹ́ k kan kì kí kò "
"l láti lè lọ m mi mo máa mọ̀ n ni náà ní nígbà nítorí nǹkan o p padà pé "
"púpọ̀ p... | Python | 1 |
"lengths",
"lucky",
"luxury",
"lymph",
"marquis",
"matrix",
"megahertz",
"microwave",
"mnemonic",
"mystify",
"naphtha",
"nightclub",
"nowadays",
"numbskull",
"nymph",
"onyx",
"ovary",
"oxidize",
"oxygen",
"pajama",
"peekaboo",
"phlegm",... | Rust | 0 |
d('ul', {'class': 'sf-menu'}).contents
# links = []
# for li in lis:
# anchor_tags = li.find('ul')
# if anchor_tags:
# for a in anchor_tags.find_all('a'):
# href = a.get('href')
# links.append(href)
# response = requests.get("https://redstarexhaustusa.com/nsx")
# soup = Beautif... | Python | 1 |
#[error(transparent)]
Io(#[from] IoError),
/// An error occurred in the Matrix client library.
#[error(transparent)]
MatrixError(#[from] MatrixError),
/// An error occurred in the crypto store.
#[cfg(feature = "encryption")]
#[error(transparent)]
CryptoStoreError(#[from] CryptoSto... | Rust | 0 |
mem: MemArg::RegScaled(xreg(20), xreg(20), I16),
srcloc: None,
},
"9C7AB478",
"ldrsh x28, [x20, x20, LSL #1]",
));
insns.push((
Inst::ULoad32 {
rd: writable_xreg(1),
mem: MemArg::Unscaled(xreg(2), SImm9::zero()),
srcloc: ... | Rust | 0 |
= ['-created']
verbose_name = _('Closing Entry Model')
constraints = [
models.UniqueConstraint(
fields=[
'closing_entry_model',
'account_model',
'unit_model',
'activity'
],
... | Python | 1 |
Z\xec \xe0E\xe4\xf3u\xd5\
\x88\x8a\x89}\x13\xc7\xd1j}\xc4\xb5:\xa8\xf1\xf3\x5c\
\x1c\x05</u\x10mp\x08\xb0\x92I\xc3\xcb\x9b}\
s%I*+\xdb:I\xea\x94f[\xa7\xed\x98\x9c\
H\xcd\xd7}I\x92\xd2\xab\x11\x1b\x8d\xc7\x91\xd7\xc60\
\xc4F\xfe\xf1\xc4\xd7\x98\xc3\xba\xa3\x078\x19\xd8/q\
\x1c\xad\xb6\x08x\x06p,\x936\xbcK\xae\x17x\x16\
... | Python | 1 |
splay the HD of
the character, either 1 or 1+1 for Fighters.
"""
def get_hp(self):
# we set HP to None, which lets the template know we will display HD
# instead.
return None
@property
def hd(self):
return "1" if self.character_class != characterclass.FIGHTER else "... | Python | 1 |
count < 0 {
return Err(Error::UncompressError);
}
offset += count as isize;
unsafe { CStr::from_ptr(buffer.as_ptr() as *const i8)
.to_string_lossy().into_owned() }
};
soa.serial = unsafe {
let slice: &[u8] = slice::fr... | Rust | 0 |
from maskrcnn_benchmark.data.datasets.coco import COCODataset
from collections import OrderedDict
import json
def dele(split):
with open('./datasets/coco/annotations/instances_' + split + '2014.json', 'r') as f:
o_annos = json.load(f)
sets = [i['id'] for i in o_annos['images']]
dic = {i['id']: {'im... | Python | 1 |
::std::fmt::Result {
f.debug_struct(&format!(
"GstAudioSinkClassExtension @ {:?}",
self as *const _
))
.field("clear_all", &self.clear_all)
.finish()
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct GstAudioSrcClass {
pub parent_class: GstAudioBaseSrcCla... | Rust | 0 |
_os_error()));
}
if unsafe { chroot(cpath(&path).as_ptr()) } != 0 {
return Err(format!("Error chroot to {:?}: {}",
path, IoError::last_os_error()));
}
let res = fun();
if unsafe { chroot(CString::new(".").unwrap().as_ptr()) } != 0 {
return Err(format!("Erro... | Rust | 0 |
import sys
import re
html = sys.stdin.readlines()
html = "".join(html)
html = re.sub(r'\n', " ", html)
hrContent = "--------------------------------------------------------------------------------"
html = html.split("\n")
res = []
for temp in html:
tempRes = []
tempCount = 0
splited = temp.split(sep=" ")
... | Python | 1 |
# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose with or without fee is hereby granted,
# provided that the above copyright notice and ... | Python | 1 |
ool::<u32>::new_allocator(&mut stack_u32_buffer, bzero);
let stack_hc_allocator = MemPool::<HuffmanCode>::new_allocator(&mut stack_hc_buffer, bzero);
let mut available_in: usize = input.len();
let mut input_offset: usize = 0;
let mut output_offset: usize = 0;
let mut written: usize = 0;
let mut brotli_state... | Rust | 0 |
adresult = fs::read_to_string("adventinputs/year19day13.txt");
if let Ok(input) = readresult {
let term = Term::stdout();
let mut program = intcode::read_tokens(&input);
program[0] = 2;
let mut ctx = intcode::build_program_context(program, vec![]);
let... | Rust | 0 |
,
Const3,
Const4,
LoadLocal,
LoadLocal2,
LoadLocal3,
LoadLocal4,
LoadLocalAndConst,
LoadLocalCaptured,
LoadModule,
StoreLocal,
StoreLocalCaptured,
StoreModule,
StoreModuleAndExport,
Unpack,
ArrayIndex,
ArrayIndexNoPop,
SetArrayIndex,
ArrayIndexSet,... | Rust | 0 |
"""
Write a function to flatten a list and sum all of its elements.
assert recursive_list_sum(([1, 2, [3,4],[5,6]]))==21
"""
def recursive_list_sum(lst):
total = 0
for i in lst:
if isinstance(i, list):
total += recursive_list_sum(i)
else:
total += i
return total
asse... | Python | 1 |
Logger
{
pub fn new() -> Logger
{
Logger
{
print_all_on: false,
file_path: String::new(),
print_asap: false,
// print_info: false,
// save_info: false,
// print_error: false,
// save_error: false,
// print_verbose: false,
// save_verbose: false,
messages: Vec::with_capacity(DE... | Rust | 0 |
_site:
parts.extend(
[
user_option_part,
" or ",
permissions_part.lower(),
]
)
else:
parts.append(permissions_part)
parts.append(".\n")
# Suggest the user to enable Long P... | Python | 1 |
n.standardize(x_, axis=axis, mean=mean, epsilon=epsilon)
param_bcast_axes = list(range(x.ndim))
del param_bcast_axes[axis]
if scale is not None:
y *= jnp.expand_dims(scale + scale_offset, param_bcast_axes)
if offset is not None:
y += jnp.expand_dims(offset, param_bcast_axes)
... | Python | 1 |
from typingtest.user import User
class Session:
def __init__(self):
self.user = None
self.state = "HOME" # stores the current state, for example, home/idle, test, settings, etc.
self.universe = None
self.test_performed = 0
def set_current_state(self, state: str) -> None:
... | Python | 1 |
679, im: 1.1656663448809618e-16 },
Complex { re: -1.0603511152022404e-15, im: 0.008333333333332324 },
Complex { re: -0.0013888888888827402, im: 5.789264486508273e-15 },
Complex { re: -2.491995923872859e-14, im: -0.00019841269843586228 },
Complex { re: 2.4801587374768556e-5, im: 6.704175576866034e-14 },
... | Rust | 0 |
score = (gain << 20) | horizon
if score > best_score:
best_score, best_gain, best_cands = score, gain, [cand]
elif score == best_score:
best_cands.append(cand)
if best_gain == 0:
break
cand = rng.choice(b... | Python | 1 |
from random import randint
# ..mais pourquoi certains ont des parenthèses ? Comme print ? Ou input ? Ceux sont... des fonctions !
def helloWorld():
print("Hello World!")
# Affiche hello world dans la console
helloWorld()
# Pourquoi les parenthèses ? Pour apporter des informations aux fonctions si nécessaire
# Pa... | Python | 1 |
e(next_state) => Self::load_out_queue_info(engine, next_state, &last_mc_state, &mut mc_shard_states).await?,
None => prev_out_queue_info.clone()
};
} else {
Self::add_trivial_neighbor(&mut neighbors, &shard, &prev_out_queue_info, None,
... | Rust | 0 |
# Random RGB Sticklet by @PhycoNinja13b
# modified by @UniBorg
# ported to userbot by @heyworld & thanks to @Xcruzhd2 for Fonts
import io
import os
import random
import textwrap
from PIL import Image, ImageDraw, ImageFont
from telethon.tl.types import InputMessagesFilterDocument
from userbot.events import register
f... | Python | 1 |
/// # futures::executor::block_on(async {
/// let listener = UnixListener::bind("/tmp/socket")?;
/// let mut incoming = listener.incoming();
///
/// while let Some(stream) = incoming.next().await {
/// let mut stream = stream?;
/// stream.write_all(b"hello").await?;
/// }
/// # s... | Rust | 0 |
# Prog03: Create a program that ask user to input 2 numbers.
# Print the difference of the two numbers.
# ------------------------------------------------------------------
# Phase 1: Planning
# - Objective: I will create a program to calculate the difference of two user-input numbers.
# - Scope: Simple subtraction... | Python | 1 |
,
program::{invoke, invoke_signed},
serialize_utils::{read_pubkey, read_u16},
system_instruction, sysvar,
sysvar::{instructions::get_instruction_relative, SysvarId},
};
use crate::{
constants::{
A_TOKEN, BLOCK_HASHES, BOT_FEE, COLLECTIONS_FEATURE_INDEX, CONFIG_ARRAY_START,
CONFIG_LI... | Rust | 0 |
/// * `msg` - the template message
///
/// Use `from_msg` to create a reply from a received message.
#[deprecated(
since = "0.2.0",
note = "Please use the from instead"
)]
pub fn from_msg(msg: &types::Message) -> Self {
Self::from(msg)
}
/// Add attachment to an existing m... | Rust | 0 |
ard_fault_handler);
default_handler!(memory_fault_handler);
default_handler!(bus_fault_handler);
default_handler!(usage_fault_handler);
default_handler!(svcall_handler);
default_handler!(debug_monitor_handler);
default_handler!(pendsv_handler);
default_handler!(systick_handler);
#[used]
#[link_section = ".exception_ve... | Rust | 0 |
Virtual, "signal-red".to_owned()),
SignalID::new(SignalType::Virtual, "signal-unknown".to_owned()),
SignalID::new(SignalType::Virtual, "signal-white".to_owned()),
SignalID::new(SignalType::Virtual, "signal-yellow".to_owned()),
];
}<filename>gstreamer-player/src/player_video_overlay_video_ren... | Rust | 0 |
pub fn apb_ctrl_backup_mem_start_addr(&self) -> APB_CTRL_BACKUP_MEM_START_ADDR_R {
APB_CTRL_BACKUP_MEM_START_ADDR_R::new((self.bits & 0xffff_ffff) as u32)
}
}
impl W {
#[doc = "Bits 0:31"]
#[inline(always)]
pub fn apb_ctrl_backup_mem_start_addr(&mut self) -> APB_CTRL_BACKUP_MEM_START_ADDR_W ... | Rust | 0 |
-----------------------------------------------
# Layer visibility controls
with st.expander("🧭 Layer Visibility Controls"):
show_heatmap = st.checkbox("Show Heatmap", value=True)
show_customer_markers = st.checkbox("Show Customer Markers", value=True)
show_existing_hubs = st.checkbox(... | Python | 1 |
EventFilter::QUERY_CACHE_HITS,
TimestampKind::Instant,
);
}
/// Start profiling a query being blocked on a concurrent execution.
/// Profiling continues until the TimingGuard returned from this call is
/// dropped.
#[inline(always)]
pub fn query_blocked(&self, q... | Rust | 0 |
tring())
.font(FontFamily::SYSTEM_UI, 14.0)
.default_attribute(TextAttribute::Weight(FontWeight::BOLD))
.text_color(
data.config
.get_color_unchecked(LapceTheme::EDITOR_FOREGROUND)
.clone(),
... | Rust | 0 |
ed` except it can be called by anyone
/// and the target `stash` must have no funds left.
///
/// This can be called from any origin.
///
/// - `stash`: The stash account to reap. Its balance must be zero.
///
/// # <weight>
/// Complexity: O(S) where S is... | Rust | 0 |
left
flip_x: true,
// And don't flip it upside-down ( the default )
flip_y: false,
..default()
},
..default()
});
}
<reponame>alanthinker/Pleco<filename>pleco/src/tools/prng.rs
//! Contains the Pseudo-random number generator. Used for generating rando... | Rust | 0 |
pub type c_ulong = u32;
pub type c_longlong = i64;
pub type c_ulonglong = u64;
}
#[allow(clippy::all)]
#[allow(non_upper_case_globals)]
#[allow(non_camel_case_types)]
#[allow(non_snake_case)]
mod bindings {
use super::c_types;
include!(env!("EMBUILD_GENERATED_BINDINGS_FILE"));
}
<reponame>weirdbandkid... | Rust | 0 |
VERSION_TUPLE = (0, 9, 4)
__version__ = ".".join(map(str, VERSION_TUPLE))
| Python | 1 |
import cdsapi
from typing import Union, List
class PressureLevelDownloader:
"""Descarga datos ERA5 para niveles de presión. Versión simple y autónoma."""
def __init__(self):
self.client = cdsapi.Client()
def download(
self,
variables: List[str],
year: Union[int, str, List],
... | Python | 1 |
# Print progress indicator
print(".", end="", flush=True)
# Close the WAV file if opened
if wav_fh:
wav_fh.close()
print(f"\nSaved to '{output_filename}'")
# Wait for playback to finish if playing
if play_audio... | Python | 1 |
generic as $trait>::$trait_type };
);
};
// Unnamed type can't be parsed
(@format_generic
$(#[$attr:meta])*;
$event_generic_param:ident;
$($instance:ident $( = $event_default_instance:path)? )?;
{ $generic_type:ty, $($rest:tt)* };
{ $($parsed:tt)* };
) => {
$crate::__decl_generic_event!(@cannot_parse ... | Rust | 0 |
from django.urls import path
from .views import SubjectViewSet
urlpatterns = [
path('subjects/', SubjectViewSet.as_view({'get': 'get_all'}), name='subjects'),
path('choose_subjects/<int:pk>/', SubjectViewSet.as_view({'get': 'choose_subjects'}), name='choose_subjects'),
path('start/<int:pk>/', SubjectViewSe... | Python | 1 |
",
"version": "matching(semver, '0.0.0')"
},
"response": {
"catalogue": {
"pact:match" : "eachValue(matching($'CatalogueEntry'))",
"CatalogueEntry": {
"type": "matching(regex, 'CONTENT_MATCHER|CONTENT_GENERATOR', 'CONTENT_MATCHER')"... | Rust | 0 |
sert_eq!("#f7c9c9", do_evaluate(&[], b"hsl(0, 75%, 88%);"))
}
#[test]
fn test_hsl_yellow() {
assert_eq!("#ffff42", do_evaluate(&[], b"hsl(60, 100%, 63%);"))
}
#[test]
fn test_hsl_blue_magenta() {
assert_eq!("#6118aa", do_evaluate(&[], b"hsl(270, 75%, 38%);"))
}
#[cfg(test)]
use super::super::super::variablesco... | Rust | 0 |
, amount liquid at genesis
build(|config: &GenesisConfig<T, I>| {
for (_, balance) in &config.balances {
assert!(
*balance >= <T as Trait<I>>::ExistentialDeposit::get(),
"the balance of any account should always be more than existential deposit.",
)
}
});
}
}
decl_module! {
pub struct Mod... | Rust | 0 |
return sample_clash.intersection(&sample_clash2).count() > 0;
}
#[cfg(test)]
mod test {
use super::*;
use maplit::{hashmap, hashset};
use std::fs;
#[test]
fn singleton_set() {
let index = b"ACTGCGAA".to_vec();
let index_set = hashset! { index.clone() };
assert_eq!(ind... | Rust | 0 |
cess(f"Welcome back, {user_data['name']}!")
st.rerun()
else:
st.error("Invalid email or password")
else:
st.error("Please enter both email and password")
with col2:
st.subheader("📝 Sign ... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.