text string | label_name string | labels int64 |
|---|---|---|
+ 1
def _count_vocab_from_corpus(self):
"""
count the frequency of tokens in the specified corpus
"""
for corpus in self.corpus_files.keys():
mode = 'ALL'
with open(self.corpus_files[corpus], 'r') as f_in:
logger.info('Loading ' + corpus + ' ... | Python | 1 |
u128::from(self.s(i)) * u128::from(self.U(i - 1)) / u128::from(self.C(i - 1)),
)
.unwrap();
self.cache_S.lock().insert(i, S);
S
}
#[allow(non_snake_case)]
pub fn U(&self, i: BlockNumber) -> u64 {
{
if let Some(U) = self.cache_U.lock... | Rust | 0 |
pop() == Some(-1));
let mut i = InputStream::from("0 -1 OR");
interpret(&mut s, &mut i).unwrap();
assert!(s.stack.pop() == Some(-1));
let mut i = InputStream::from("0 0 OR");
interpret(&mut s, &mut i).unwrap();
assert!(s.stack.pop() == Some(0));
let mut i = Inp... | Rust | 0 |
import _plotly_utils.basevalidators
class GrouptitlefontValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(
self, plotly_name="grouptitlefont", parent_name="layout.legend", **kwargs
):
super(GrouptitlefontValidator, self).__init__(
plotly_name=plotly_name,
... | Python | 1 |
orthook:
reporthook(blocknum, blocksize, size)
finally:
sfp.close()
# check that we got the whole file, if we can
if size >= 0 and read < size:
raise DistlibException(
'retrieval incomplete: got only %d out of %d bytes'
... | Python | 1 |
from django.core.management.base import BaseCommand
from django.core.mail import send_mail
from django.utils import timezone
from rentals.models import Rental
class Command(BaseCommand):
help = 'Send monthly rental billing reminder'
def handle(self, *args, **kwargs):
today = timezone.now().date()
... | Python | 1 |
let index = fibonacci_search(&"a", &vec!["a", "b", "c", "d", "google", "zoo"]);
assert_eq!(index, Some(0));
}
#[test]
fn search_ints() {
let index = fibonacci_search(&4, &vec![1, 2, 3, 4]);
assert_eq!(index, Some(3));
let index = fibonacci_search(&3, &vec![1, 2, 3,... | Rust | 0 |
Fluence FaaS instance: {}", e));
let interface = faas.get_interface();
let arguments = vec![fluence_faas::IFunctionArg {
name: String::from("name"),
ty: fluence_faas::IType::String,
}];
let output_types = vec![fluence_faas::IType::String];
let greeting_sign = fluence_faas::FaaSFu... | Rust | 0 |
from ssr.config.ssr_config import SSRConfig
from ssr.input_adapters.image_extraction_pipeline import ImageExtractionPipeline
from ssr.path_manager import PathManager
from ssr.utility.logging_extension import logger
from ssr.utility.os_extension import assert_dirs_equal
from ssr.gdal_utility.pan_sharpening import perfor... | Python | 1 |
# Question 1: We've seen that n = 42 is legal. What about 42 = n?
# In Python, variable assignment follows the pattern variable = value.
# Assigning a value to a literal like 42 = n is not allowed and will result in a SyntaxError.
n = 42 # This assigns the value 42 to the variable n
# 42 = n # Uncommenting this line... | Python | 1 |
as_os_str()) // where to write generated .rs
.status()
.expect("failed to execute process")
} else {
Command::new("sh")
.current_dir(generator_path.as_os_str())
.arg("generator.py")
.arg(generator_path.as_os_str())
... | Rust | 0 |
ckConfig {
pub fn uncompressed(mut self) -> Self {
self.compression = None;
self
}
pub fn with_compression_level(mut self, level: u8) -> Self {
self.compression = Some(level);
self
}
}
impl Default for PackConfig {
fn default() -> PackConfig {
PackConfig {
... | Rust | 0 |
];
for (input, expected) in tests {
assert_eq!(parse_secs(&input).unwrap(), *expected, "input: {}", input);
}
let tests = &[
("1s 1m", Error::OutOfOrder),
("1s 1s", Error::AlreadySeen),
("0s", Error::InvalidData),
("06s", Erro... | Rust | 0 |
cies();
}
if let Some(transform_component) = self.try_cast::<TransformComponent>() {
return transform_component.build_dependencies();
}
}
pub fn on_dirty(&self, dirt: FlagSet<ComponentDirt>) {
if let Some(path) = self.try_cast::<Path>() {
return path.on_... | Rust | 0 |
path: &Path) -> Result<String, Error> {
let output = Command::new("bpftool")
.args(&["btf", "dump", "file"])
.arg(path)
.args(&["format", "c"])
.output()
.map_err(Error::BpfTool)?;
if !output.status.success() {
return Err(Error::BpfToolExit {
code: ou... | Rust | 0 |
from tkinter import *
import pandas
import random
BACKGROUND_COLOR = "#B1DDC6"
current_card = {}
to_learn = {}
try:
data = pandas.read_csv("data/words_to_learn.csv")
except FileNotFoundError:
original_data = pandas.read_csv("data/french_words.csv")
print(original_data)
to_learn = original_data.to_dict... | Python | 1 |
h) = pix.dimension();
for mut star in &mut self.stars {
star.x = star.x - (star.z * dt * 10.0);
if star.x < 0.0 {
star.x = w - 1.0;
star.y = pix.random(1.0, h) - 1.0;
star.z = pix.random(1.0, self.colors.len() as f32);
}
let color = *self.colors.get(star.z as usize).... | Rust | 0 |
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import csv
from odoo.tools import file_open
from . import models
from . import wizard
def _edit_tax_types(env, template_data):
"""
Applies all existing tax l10n_es_edi_facturae_tax_type field to their proper value if any link between t... | Python | 1 |
from unittest.mock import MagicMock, patch
from tabdpt import estimator
@patch("tabdpt.estimator.hf_hub_download", return_value="my/hf/path")
@patch("tabdpt.estimator.safe_open")
@patch("tabdpt.estimator.torch.cuda.is_available", return_value=False)
@patch("tabdpt.estimator.json.loads", return_value={"env": {}})
@pa... | Python | 1 |
#!/usr/bin/env python#*****************************************************************************
# Compilation: javac Whitelist.java
# Execution: java Whitelist whitelist.txt < data.txt
# Dependencies: StaticSetOfInts.java In.java StdOut.java
#
# Data files: http://algs4.cs.princeton.edu/11model/tinyW... | Python | 1 |
import torch
import torch.nn.functional as F
def compute_similarity_matrix(input_tensor, block_size=1024):
# 将32*32*768张量展平为1024*768
flattened_tensor = input_tensor.view(-1, input_tensor.size(-1))
num_vectors = flattened_tensor.size(0)
# 初始化相似度矩阵
similarity_matrix = torch.zeros(num_vectors, num_ve... | Python | 1 |
itgraph::interface::{DynamicGraph, ImmutableGraphContainer};
use genome_graph::types::{PetBCalm2EdgeGraph, PetBCalm2NodeGraph};
use std::io::Write;
use omnitigs::macrotigs::macronodes::strongly_connected_macronode_algorithm::StronglyConnectedMacronodes;
use omnitigs::macrotigs::microtigs::strongly_connected_hydrostruct... | Rust | 0 |
I]: https://eleuther.ai
pub struct GptJ6B {
_priv: (),
}
impl KnownEngineDefinition for GptJ6B {
const ID: &'static str = "gptj_6B";
const MAX_TOKENS: usize = 2048;
}
impl private::Sealed for GptJ6B {}
/// [Boris] is a fine tuned version of GPT-J for the French language. Use this model is you want the
//... | Rust | 0 |
inner()
})
.collect::<Vec<_>>();
impls.sort();
w.write_str(&impls.join(""));
}
fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>, cx: &Context<'_>) -> String {
use crate::formats::item_type::ItemType::*;
let name = it.name.as_ref().unwrap();
let ty = match it.type_() {
... | Rust | 0 |
sited, so prevent them from being reselected
(batch, city_t)
"""
u1 = self.W_q2(query).unsqueeze(-1).repeat(1,1,ref.size(1))# u1: (batch, 128, city_t)
u2 = self.W_ref2(ref.permute(0,2,1))# u2: (batch, 128, city_t)
V = self.Vec2.unsqueeze(0).unsqueeze(0).repeat(ref.size(0), 1, 1)
u = torch.bmm(V, self.clip_... | Python | 1 |
} else {
self.set_r(reg, value);
}
address += 4;
}
if !params.registers.contains(¶ms.rn) {
self.add_r(params.rn, regs_size);
}
let cc = 1 + params.registers.len() as u32;
... | Rust | 0 |
, Clone, Debug)]
struct Lenet5 {
#[autograph(layer)]
conv1: Conv,
#[autograph(layer)]
relu1: Relu,
#[autograph(layer)]
pool1: MaxPool,
#[autograph(layer)]
conv2: Conv,
#[autograph(layer)]
relu2: Relu,
#[autograph(layer)]
pool2: MaxPool,
#[autograph(layer)]
dense1:... | Rust | 0 |
return false;
}
let payload_position = writer.get_position();
if !util::WriteEbmlElementArgF32(
writer,
MkvId::MkvSamplingFrequency,
self.sample_rate_ as f32,
) {
return false;
}
if !util::WriteEbmlElementArgU6... | Rust | 0 |
(): map T::AccountId => bool; // whitelist of allowed affiliate accountIds, initialized at genesis in chain_spec.rs
}
}
// The module's dispatchable functions.
decl_module! {
/// The module declaration.
pub struct Module<T: Trait> for enum Call where origin: T::Origin {
fn deposit_event() = default;
pub fn... | Rust | 0 |
R_FLAG_DEPTH);
pub const Stencil: Self = Self(D3D12_CLEAR_FLAG_STENCIL);
}
impl_bitflag_operators!(ClearFlags);
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct ColorWriteEnable(u32);
#[allow(non_upper_case_globals)]
impl ColorWriteEnable {
pub const Red: Self = Self(D3D12_COLOR_WRITE_ENABLE_RED);
p... | Rust | 0 |
e. When you attach a
/// managed policy to a role, the managed policy becomes part of the role's permission
/// (access) policy.</p>
/// <note>
/// <p>You cannot use a managed policy as the role's trust policy. The role's trust
/// policy is created at the same time as the role, using <a>CreateRole</a>.
/// You can upd... | Rust | 0 |
NetworkMixin.__init__(policy, config)
SACTFPolicy = build_tf_policy(
name="SACTFPolicy",
get_default_config=lambda: ray.rllib.agents.sac.sac.DEFAULT_CONFIG,
make_model=build_sac_model,
postprocess_fn=postprocess_trajectory,
action_distribution_fn=get_distribution_inputs_and_class,
loss_fn=sac_... | Python | 1 |
SEventStreamInvalidate": (b"v^{__FSEventStream=}",),
"FSEventStreamStop": (b"v^{__FSEventStream=}",),
"FSEventsPurgeEventsForDeviceUpToEventId": (b"ZiQ",),
"FSEventStreamGetDeviceBeingWatched": (b"i^{__FSEventStream=}",),
"FSEventStreamCopyDescription": (
b"^{__CFString=}^{__FSEventStream=}",
... | Python | 1 |
ls, out_channels, groups, bias=False)
self.init_eps = eps
if train_eps:
self.eps = Parameter(Tensor([eps]))
else:
self.register_buffer('eps', Tensor([eps]))
self.reset_parameters()
def reset_parameters(self):
self.mlp... | Python | 1 |
ependencies().collect::<Vec<_>>(), vec![]);
let dep1 = Uuid::new_v4();
let dep2 = Uuid::new_v4();
task.add_dependency(dep1).unwrap();
assert_eq!(task.get_dependencies().collect::<Vec<_>>(), vec![dep1]);
task.add_dependency(dep1).unwrap(); // add twice is ok
... | Rust | 0 |
_signal_token_name(self):
TOP_SIGNAL_NAME = '/workflow/__SIGNAL__/some_signal'
name = Name.from_signal_token_name(TOP_SIGNAL_NAME)
self.assertEqual('some_signal', name.signal)
self.assertIsNone(name.workflow)
self.assertEqual(TOP_SIGNAL_NAME, name.get_signal_token_name())
... | Python | 1 |
dtype=np.float32)
render_image = image.copy()
dic = {}
if os.path.exists(json_path):
with open(json_path, 'r') as f:
dic = json.load(f)
for track_id, result in track_dict.items():
bbox = result['bbox']
brand, subbrand, year, color = result['brand']
kpts2d... | Python | 1 |
],
spirv::Decoration::XfbStride => vec![mr::Operand::LiteralInt32(try_decode!(self.decoder.int32()))],
spirv::Decoration::FuncParamAttr => vec![mr::Operand::FunctionParameterAttribute(try_decode!(self.decoder.function_parameter_attribute()))],
spirv::Decoration::FPRoundingMode => vec... | Rust | 0 |
import logging
from tornado import gen
@gen.coroutine
def ensure_indexes(db, drop=False):
if drop:
logging.info('Dropping indexes...')
yield db.posts.drop_indexes()
yield db.categories.drop_indexes()
yield db.events.drop_indexes()
logging.info('Ensuring indexes...')
yiel... | Python | 1 |
struct BucketLists {
// /// The approved buckets list contains bucket sessions the user can join.
// pub approved_buckets: Loadable<Vec<ApprovedBucket>>,
// /// The public buckets are buckets that bucket owners have made public.
// /// Users must ask to join these buckets, and they will be approved by the ... | Rust | 0 |
import sys
import json
import gzip
import yaml
ISO_CODE_TAGS = ['ISO3166-1', 'ISO3166-2']
def extract_zones_by_iso_code():
zones = {}
for line in gzip.open(sys.stdin.buffer):
zone = json.loads(line)
iso_codes = []
for tag in ISO_CODE_TAGS:
value = zone["tags"].get(tag)
... | Python | 1 |
0_DUTY_RES_R::new((self.bits & 0x1f) as u8)
}
#[doc = "Bits 5:22 - This register is used to configure parameter for divider in high speed timer0 the least significant eight bits represent the decimal part."]
#[inline(always)]
pub fn div_num_hstimer0(&self) -> DIV_NUM_HSTIMER0_R {
DIV_NUM_HSTIMER... | Rust | 0 |
orage]
pub type StoreFiles<T: Config> =
StorageMap<_, Twox64Concat, FileId, StoreFile<BalanceOf<T>, BlockNumberFor<T>>>;
/// Information for file orders
#[pallet::storage]
pub type FileOrders<T: Config> = StorageMap<
_,
Twox64Concat,
FileId,
FileOrder<T::AccountId, BalanceOf<T>, BlockNumberFor<T>>,
>;
... | Rust | 0 |
to the next nybble.
DecimalAdjust,
/// Sets the carry flag.
SetCarryFlag,
/// Inverts the Accumulator.
Compliment,
/// Inverts the carry flag.
ComplimentCarryFlag,
}
impl AluUnaryOp {
/// Get the ALU unary operation type for the given opcode. Panics if the code is greater than 7.
p... | Rust | 0 |
(), 32f32));
},
&EntityAction::Update(d_time) => {
},
_ => { },
}
actions
}
}
<reponame>bernep/Telescope<filename>src/models/password_requirements.rs
use std::collections::HashSet;
/// Commonly used passwords to protect against.
pub const COMMON_PASSW... | Rust | 0 |
none(), ALICE, proof));
System::set_block_number(VESTING_STEP);
assert_ok!(CrowdloanRewards::claim(Origin::signed(ALICE)));
System::set_block_number(DEFAULT_VESTING_PERIOD);
assert_ok!(CrowdloanRewards::claim(Origin::signed(ALICE)));
assert_eq!(CrowdloanRewards::claimed_rewards(), CrowdloanRewards::total_rewa... | Rust | 0 |
import asyncio
import logging
import os
from dotenv import load_dotenv
from aiogram import Bot, Dispatcher, types
from aiogram.types import Message
# Загружаем переменные окружения из файла .env
load_dotenv()
# Получаем токен из переменной окружения
TOKEN = os.getenv("TOKEN") # Вставь свой токен в файл .env
if not T... | Python | 1 |
#!/usr/bin/env python3
# --------------------------------------------------------------------
# SPDX-License-Identifier: AGPL-3.0-or-later
# © Copyright 2008-2024 José Manuel Rodríguez de la Rosa and contributors.
# See the file CONTRIBUTORS.md for copyright details.
# See https://www.gnu.org/licenses/agpl-3.0.html fo... | Python | 1 |
# ----------------------------------------------------------------------------
# - Open3D: www.open3d.org -
# ----------------------------------------------------------------------------
# Copyright (c) 2018-2024 www.open3d.org
# SPDX-License-Identifier: MIT
# ---------... | Python | 1 |
Iso3::TUN => Iso2::TN,
Iso3::TUR => Iso2::TR,
Iso3::TUV => Iso2::TV,
Iso3::TWN => Iso2::TW,
Iso3::TZA => Iso2::TZ,
Iso3::UGA => Iso2::UG,
Iso3::UKR => Iso2::UA,
Iso3::UMI => Iso2::UM,
Iso3::URY => Iso2::UY,
Iso... | Rust | 0 |
torBar", u"⥘"),
("\\NotLeftTriangleBar", u"⧏̸"),
("\\nRightarrow", u"⇏"),
("\\1/", u"⅟"),
("\\bfrakm", u"𝖒"),
("\\bigslopedvee", u"⩗"),
("\\blocklowhalf", u"▄"),
("\\veedoublebar", u"⩣"),
("\\forks", u"⫝̸"),
("\\Alpha", u"Α"),
("\\backepsilon", u"϶"),
("\\nsucccurlyeq", u"⋡"),
("\\scrc", u"𝒸"),... | Python | 1 |
from .. import Provider as SsnProvider
class Provider(SsnProvider):
def ssn(self) -> str:
"""
Returns an Israeli identity number, known as Teudat Zehut ("tz").
https://en.wikipedia.org/wiki/Israeli_identity_card
"""
newID = str(self.generator.random.randrange(111111, 9999... | Python | 1 |
info!("https-proxy has started. Listening for new connections on {:?}.", &server_config.addr);
Ok(
(client, listener, tls_acceptor, mirrors)
)
}
fn create_logger() -> Result<(), SetLoggerError> {
let colors = ColoredLevelConfig::new()
.trace(Color::White)
.info(Color::Green)
... | Rust | 0 |
system_data::CreatedByType>,
#[serde(rename = "createdAt", default, skip_serializing_if = "Option::is_none")]
pub created_at: Option<String>,
#[serde(rename = "lastModifiedBy", default, skip_serializing_if = "Option::is_none")]
pub last_modified_by: Option<String>,
#[serde(rename = "lastModifiedByTy... | Rust | 0 |
234',
'--filter', 'trasher',
'--filter-out', 'erasure-code',
'--throttle', '3',
]
archive_upload = 'user@archive:/tmp'
argv = (self.options +
['--teuthology-git-url', 'TEUTHOLOGY_URL',
'--teuthology-branch', 'TEUTHOLOGY_BRANCH'... | Python | 1 |
save_path_2=f"{self.external_data_path}\\camera{img_name_2}.jpg",
cfg_params=cfg_params, aruco_flag=m_global.aruco_flag)
if stitch_mode & self.stitch_mode_right:
img_name_1, img_name_2 = "R_R", "MR_R"
img_ex_1 = cv2.imrea... | Python | 1 |
proof_to_json(access.proof.as_ref().unwrap()),
address: access.address.clone(),
access: access.log2_size.clone(),
};
out["accesses"]
.push(access_json)
.expect("Unexpected error while building AccessLog JSON");
}
out.dump()
}
pub fn steps() -> S... | Rust | 0 |
or<'a, T: UserAuthClient> {
client: &'a T,
buffer: VecDeque<files::Metadata>,
cursor: Option<String>,
}
impl<'a, T: UserAuthClient> Iterator for DirectoryIterator<'a, T> {
type Item = StoreResult<files::Metadata>;
fn next(&mut self) -> Option<Self::Item> {
if let Some(entry) = self.buffer.pop_front() {
... | Rust | 0 |
from PyObjCTools.TestSupport import TestCase, min_os_level
import ShazamKit
class TestSHMediaItem(TestCase):
def test_typed_enum(self):
self.assertIsTypedEnum(ShazamKit.SHMediaItemProperty, str)
def test_constants(self):
self.assertIsInstance(ShazamKit.SHMediaItemShazamID, str)
self.a... | Python | 1 |
b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w)
);
impl_trait!(
(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X),
(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x)
);
impl_trait!(
(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U... | Rust | 0 |
Some(6)),
(2, "bytes 3-5/6", None),
(2, "bytes 1-5/6", None),
(2, "bytes 2-4/6", None),
(2, "bytes 2-6/6", None),
];
for (start, header, result) in expected {
assert_eq!(total_for_content_range(header, start).ok(), result);
}
}
}
<r... | Rust | 0 |
pw: PointerWidth) -> u32 {
let bw = match ty {
SimpleTy::Int(w, _) => w,
SimpleTy::Size(_) | SimpleTy::Pointer => pw.0,
SimpleTy::Float32 => 32,
SimpleTy::Float64 => 64,
SimpleTy::Other => unreachable!(), // FIXME
};
bw as u32
}
fn cast_bv<'bv>(bv: BV<'bv>, from_ty: ... | Rust | 0 |
others are
# used as slaves. Names other than 'main' are arbitrary.
devices=devices,
)
else:
updater = training.updater.StandardUpdater(train_iter, optimizer, device=device)
# Write output files to output_data_dir.
# These are zipped and uploaded to S3 output path as... | Python | 1 |
.request.install_opener(opener)
return 1
else:
if log:
logging.debug("Found a previous proxy but it didn't work")
# try finding/using a proxy.pac file
pacURLs = getPacFiles()
if log:
logging.debug("Found proxy PAC files: %s" % pacURLs)
proxies = p... | Python | 1 |
_trunc}
targets = {'orig_joint_img': crowdpose_joint_img, 'fit_joint_img': smpl_joint_img, 'orig_joint_cam': crowdpose_joint_cam, 'fit_joint_cam': smpl_joint_cam, 'pose_param': smpl_pose, 'shape_param': smpl_shape}
meta_info = {'orig_joint_valid': crowdpose_joint_valid, 'orig_joint_trunc': crowd... | Python | 1 |
= nxt_unit_sptr_u;
#[derive(Copy, Clone)]
#[repr(C)]
pub union nxt_unit_sptr_u {
pub base: [uint8_t; 1],
pub offset: uint32_t,
}
pub type nxt_unit_request_info_t = nxt_unit_request_info_s;
#[derive(Copy, Clone)]
#[repr(C)]
pub struct nxt_unit_callbacks_s {
pub request_handler: Option<unsafe extern "C" fn(_... | Rust | 0 |
apt this for transaction / mempool
// // Check if the block is already in the state.
// // BUG: check if the hash is in any chain (#862).
// // Depth only checks the main chain.
// match state.oneshot(zs::Request::Depth(hash)).await {
// Ok(zs::Response::D... | Rust | 0 |
((pitch_mse + roll_mse) / 2)
avg_pearson.append(np.array(avg_prs))
print(f"[{dataset}] Avg max: {np.argmax(avg_pearson)}, pitch max: {np.argmax(pitch_list)}, roll max: {np.argmax(roll_list)}")
avg_pearson_list.append(avg_pearson)
avg_mse_list.append(avg_mse)
fig = plt.figure(figsize=[3,3])
for ... | Python | 1 |
# Generated by Django 5.0.6 on 2024-09-10 04:37
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('Inventory', '0012_raga_posted_date_raga_posted_week'),
]
operations = [
migrations.RenameField(
model_name='raga',
old_name=... | Python | 1 |
Self::new_rgba_comp(r, g, b, a)
}
pub fn new_rgb(rgb: u32) -> Self {
let mut rem = rgb;
let b = (rem % 256) as u8;
rem = rem / 256;
let g = (rem % 256) as u8;
rem = rem / 256;
let r = (rem % 256) as u8;
Self::new_rgba_comp(r, g, b, 0xFF)
}
... | Rust | 0 |
ar,
(*resp).devices_len as usize,
);
let devices: Vec<String> = strings
.iter_mut()
.map(|s| {
std::ffi::CStr::from_ptr(*s)
.to_str()
.unwrap_or("Unknown")
... | Rust | 0 |
diffusion_graph.potentials[0][1][0][1] = 80.;
diffusion_graph.potentials[0][1][3][1] = -1E9 as f64;
assert_eq!(-999999999.0, diffusion_graph.energy());
assert_eq!(0., diffusion_graph.potentials[0][0][1][0]);
assert_eq!(0., diffusion_graph.potentials[0][0][1][1]);
assert_eq!(0... | Rust | 0 |
PointerKernelGetFromScriptVariable(uchar4 * v_out, uint32_t x, uint32_t y) {}
void blurPointerKernelGetFromScriptVariablePointer(uchar4 * v_out, uint32_t x, uint32_t y) {}
#endif
// Square set values
// Following functions set a predefined count of values in the output allocation,
// using the input as element t... | Rust | 0 |
# =============================================================================
# Imports
# =============================================================================
import numpy as np
import matplotlib.pyplot as plt
from multiprocessing import Pool
from multiprocessing import cpu_count
from utils import monte_ca... | Python | 1 |
f64::NEG_INFINITY, f64::NEG_INFINITY);
// assert_abs_diff_ne!(f64::NEG_INFINITY, f64::INFINITY);
// assert_abs_diff_eq!(f64::INFINITY, f64::MAX);
// assert_abs_diff_eq!(f64::NEG_INFINITY, -f64::MAX);
// }
#[test]
fn test_nan() {
assert_abs_diff_ne!(f64::NAN, f64::NAN);
... | Rust | 0 |
te_assertr /V//TV5T5TTr c D U S S:w d e[ R " U SSS9$ )r r sTr r r )r s r\ sympy_index_symbolr ) 7c>> <<d==r c SS jn[ R " U 5... | Python | 1 |
expected.value,
)
.unwrap();
let actual = key_agreement(&PrivateKey::from(scalar), &PublicKey::from(point)).unwrap();
assert_eq!(actual, expected);
}
#[test]
/// Ref: https://www.ietf.org/rfc/rfc7748.html#section-5.2
fn test_rfc_section_5_iter() {
let mut k = B... | Rust | 0 |
# Licensed under an MIT open source license - see LICENSE
import numpy as np
from astropy.modeling.models import Gaussian2D, Const2D, Gaussian1D, Const1D
from astropy.utils import NumpyRNGContext
# Define ways to make 1D and 2D profiles (typically Gaussian for ease)
def twoD_gaussian(shape=(201, 201), x_std=10., y_s... | Python | 1 |
f create_post(args):
session = bsky_login_session(args.pds_url, args.handle, args.password)
# trailing "Z" is preferred over "+00:00"
now = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
# these are the required fields which every post must include
post = {
"$type": "app.bsk... | Python | 1 |
"""
ip:-
take input of the string
abfgresagtyuiofde
op:-
print longest sub string without repeating character
12 resagtyuiofd
"""
s=input()
d=dict()
d[s[0]]=0
mx=-1
j=0
n=len(s)
i=1
while i<n:
if s[i] not in d:
d[s[i]]=i
else:
if mx<i-j:
mx=i-j
if d[s[i]]>j:
... | Python | 1 |
se {
break;
}
}
// Calculate how much of the input was consumed.
if input_i > input.len() {
input_i = input.len();
} else {
while !input.is_char_boundary(input_i) {
input_i += 1;
}
}
Ok((&out_buffer[..output_i], input_i))
}
pub fn decode... | Rust | 0 |
entory's management.
extern crate termion;
use termion::{color, cursor};
use player::*;
use util::palettes::*;
// ---------------------------------------------------------- //
/// Initializes the inventory for the player to use.
pub fn init() -> [usize; 15] {
let mut inv: [usize; 15] = [0; 15];
inv
}
/// Lists ... | Rust | 0 |
import json
import scrapy
import fake_useragent
from snopes.items import SnopesItem
class LeadstoriesionSpider(scrapy.Spider):
name = "leadstories"
allowed_domains = ["leadstories.com"]
start_urls = ["https://leadstories.com/cgi-bin/mt/mt-search.fcgi?search=&IncludeBlogs=1&blog_id=1&archive_type=Index&l... | Python | 1 |
, ValueIterator, ValueList, ValueMap,
},
std::ops::DerefMut,
};
pub fn make_module() -> ValueMap {
use Value::*;
let mut result = ValueMap::new();
result.add_fn("clear", |vm, args| match vm.get_args(args) {
[List(l)] => {
l.data_mut().clear();
Ok(Empty)
}
... | Rust | 0 |
# coding: utf-8
from adhocracy.lib.session.converter import SignedValueConverter
from adhocracy.tests import TestController
class SessionTest(TestController):
def test_basic(self):
c = SignedValueConverter(b'shh!')
encoded = c.encode({'x': [1]})
decoded = c.decode(encoded)
self.as... | Python | 1 |
import os
from dotenv import load_dotenv
from atomic_sdk import AtomicClient, AtomicAPIError
# --- Configuration ---
load_dotenv()
API_KEY = os.environ.get("ATOMIC_API_KEY")
CLIENT_ID = os.environ.get("ATOMIC_CLIENT_ID")
# This is a test webhook.site URL, feel free to change it to your own.
WEBHOOK_URL = "https://web... | Python | 1 |
import matplotlib.pyplot as plt
import pandas as pd
import pypsa
import sys
import os
import argparse
import yaml
import copy
import numpy as np
import time # 添加时间模块
# 添加scripts目录到Python路径
sys.path.append(os.path.join(os.path.dirname(__file__)))
from config import CONFIG # 导入配置
from analyze_startups import analyze_... | Python | 1 |
os.makedirs(self._tmpdir, exist_ok=True)
yield
# Clean up test files after each test
for file in Path(self._tmpdir).glob("*"):
file.unlink()
def pytest_generate_tests(metafunc):
"""Generate test cases for each markdown file."""
if "doc_path" in metafunc.fixturenames:
... | Python | 1 |
8_AVX512 = 5569,
XED_IFORM_VPUNPCKHBW_ZMMu8_MASKmskw_ZMMu8_ZMMu8_AVX512 = 5570,
XED_IFORM_VPUNPCKHDQ_XMMdq_XMMdq_MEMdq = 5571,
XED_IFORM_VPUNPCKHDQ_XMMdq_XMMdq_XMMdq = 5572,
XED_IFORM_VPUNPCKHDQ_XMMu32_MASKmskw_XMMu32_MEMu32_AVX512 = 5573,
XED_IFORM_VPUNPCKHDQ_XMMu32_MASKmskw_XMMu32_XMMu32_AVX512 = ... | Rust | 0 |
x10;
out1[10] = x11;
out1[11] = (x12 as u64);
out1[12] = x13;
out1[13] = x14;
out1[14] = (x15 as u64);
out1[15] = x16;
out1[16] = (x17 as u64);
}
/*
* The function fiat_p521_sub subtracts two field elements.
* Postconditions:
* eval out1 mod m = (eval arg1 - eval arg2) mod m
*
* Input Bounds:
* ... | Rust | 0 |
from typing import List
from collections import Counter
class Solution:
def isPossibleToSplit(self, nums: List[int]) -> bool:
counter = Counter(nums) # Count occurrences of each number
# Check if any number appears more than twice
for freq in counter.values():
if fre... | Python | 1 |
self.kgraph.get_max_nbng();
let mut edge_list = Vec::<(u32,u32, F)>::with_capacity(max_nbng * nbnodes);
for i in 0..nbnodes {
for edge in &neighboourhood_info[i] {
edge_list.push((i as u32, edge.node as u32, edge.weight));
}
}
let mst_edge_iter = ... | Rust | 0 |
.timezone)
yahooFeed.addBarsFromCSV("orcl", common.get_data_file_path("orcl-2001-yahoofinance.csv"), marketsession.USEquities.timezone)
# Fill the database using the bars from the Yahoo! feed.
sqliteFeed = tmpFeed.getFeed()
sqliteFeed.getDatabase().addBarsFromFeed(yahooF... | Python | 1 |
city, citiesCode = getCity()
for i, j in citiesCode.items():
print(i, j)
while True:
inputCode1 = int(input("Nhập đỉnh bắt đầu: "))
inputCode2 = int(input("Nhập đỉnh kết thúc: "))
if inputCode1 == 0 or inputCode2 == 0:
break
startCity = citiesCode[inputCo... | Python | 1 |
(benches, parse_line_benchmark, parse_date_benchmark);
criterion_main!(benches);
<filename>src/compiler/desugar.rs
use std::{
convert::TryFrom,
collections::HashSet,
};
use crate::common::span::{Span, Spanned};
use crate::compiler::{
rule::Rule,
ast::{AST, ASTPattern, ArgPattern},
cst::{CST, CSTPa... | Rust | 0 |
urvature failures
}
# --------------------------
# Point Distribution Metrics
# --------------------------
# Earth Mover’s Distance (mean ℓ₂, normalized by diag)
# References:
# • Fan et al., “A point set generation network for 3D object reconstruction from a single image,” CVPR 2017
# • Zhang et al., “DeepEMD: Few... | Python | 1 |
len: *mut libc::socklen_t) -> io::Result<Socket> {;
let fd = cvt_r(|| unsafe {
libc::accept4(self.0.raw(), storage, len, libc::SOCK_CLOEXEC)
})?;
let fd = FileDesc::new(fd);
Ok(Socket(fd))
}
pub fn listen(&self, backlog: libc::c_int) -> io::Result<()> {
cvt... | Rust | 0 |
ures=module.in_features,
out_features=module.out_features,
bias=module.bias is not None,
dtype=module.weight.dtype,
device=module.weight.device,
)
new_module.weight = module.weight
new_module.bias = module.bias
total_count += 1
retu... | Python | 1 |
common_divisor = ::num::integer::gcd(dx, dy);
let dx = dx / greatest_common_divisor;
let dy = dy / greatest_common_divisor;
let mut x = station.x + dx * x_direction;
let mut y = station.y + dy * y_direction;
// println!("\tFor station {:?} to asteroid {:?}, dx: {}, xdir: {}, dy:... | Rust | 0 |
SizeUser for Sha256VarCore {
type OutputSize = U32;
}
impl VariableOutputCore for Sha256VarCore {
const TRUNC_SIDE: TruncSide = TruncSide::Left;
#[inline]
fn new(output_size: usize) -> Result<Self, InvalidOutputSize> {
let state = match output_size {
28 => consts::H256_224,
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.