text string | label_name string | labels int64 |
|---|---|---|
.params
.iter()
.zip(args.iter_mut().map(|v| mem::take(*v)))
.map(|(name, value)| {
let var_name = unsafe_cast_var_name_to_lifetime(name.as_str(), state);
(var_name, ScopeEntryType::Normal, value)
}),
... | Rust | 0 |
_bits > halfway;
let is_halfway = truncated_bits == halfway;
// Bit shift so the leading bit is in the hidden bit.
// This optimixes pretty well:
// ```text
// mov ecx, esi
// shr rdi, cl
// xor eax, eax
// cmp esi, 64
// cmovne rax, rdi
// ret
... | Rust | 0 |
]
service_logging = OCILog()
pipeline_run._set_service_logging_resource(service_logging)
consolidated_log_expression = pipeline_run._build_filter_expression()
assert (
consolidated_log_expression
== f"(source = '*{PIPELINE_RUN_OCID}' AND (subject = '{cu... | Python | 1 |
DEPTH_STENCIL_STATE_CREATE_RASTERIZATION_ORDER_ATTACHMENT_STENCIL_ACCESS_BIT_ARM = 0x00000002,
VK_PIPELINE_DEPTH_STENCIL_STATE_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF,
});
bitflag_struct!(VkRenderingFlags: VkRenderingBitFlags);
bitflag_enum!(VkRenderingBitFlags {
VK_RENDERING_CONTENTS_SECONDARY_COMMAND_BUFFERS_... | Rust | 0 |
m(res[:2]**2)
errors = jax.vmap(single_error)(eps_samples, l_a_samples)
best_idx = jnp.nanargmin(errors)
guess = stack(eps_samples[best_idx], l_a_samples[best_idx])
opt = jaxopt.LevenbergMarquardt(objective_solve_for_eps_l_a, maxiter=100, tol=1e-4)
solution, info = opt.run(guess,... | Python | 1 |
from fastapi.routing import APIRouter
{%- if cookiecutter.add_users == 'True' %}
from {{cookiecutter.project_name}}.web.api import users
from {{cookiecutter.project_name}}.db.models.users import api_users
{%- endif %}
{%- if cookiecutter.enable_routers == "True" %}
{%- if cookiecutter.api_type == 'rest' %}
from {{cook... | Python | 1 |
from multiprocessing import Manager, Pool
from app import NextApp
from backend import BlinkWinkApp
def run_next_app(shared_dict, lock):
NextApp(shared_dict, lock).run()
def run_blink_wink_app(shared_dict, lock):
bwa = BlinkWinkApp(shared_dict, lock)
bwa.blink_wink_detection()
if __name__ == "__main__":
... | Python | 1 |
get_child() {
if let Some(string) = child.get_name() {
if string == name {
return Some(child);
}
}
if let Some(widget) = find_widget_by_name(&child, name) {
return Some(widget);
}
}
}
None... | Rust | 0 |
);
},
}
}
}
fn parse(input: String, interpreter: &mut risp::Interpreter, parser: &mut risp::Parser) {
match parser.parse(input.as_bytes()) {
Ok(exps) => for (i, exp) in exps.iter().enumerate() {
println!("${} exp: {:?}", i, exp);
},
Err(err) => println!... | Rust | 0 |
for binary_heap::IntoIter<A>
where
B: Ord,
{
type Output = binary_heap::IntoIter<B>;
fn func_map<F>(self, f: F) -> Self::Output
where
F: FnMut(A) -> B,
{
self.map(f).collect::<BinaryHeap<_>>().into_iter()
}
}
impl<A, B> TryFuncMap... | Rust | 0 |
reset_block,
rhs_block,
),
link,
);
self.start_block(rhs_block);
self.drop_value(&built_lhs, lhs.span);
let built_rhs = self.build_expr(rhs);
self.emit_instruction(
cfg::Instruction::Assign(result, Spanned::new(b... | Rust | 0 |
def binary_search(arr, tn):
low = 0
high = len(arr) - 1
while low <= high:
m = int((high - low) / 2) + low
if arr[m] == tn:
return m
else:
if arr[m] < tn:
low = m + 1
else:
high = m - 1
if low > high:
r... | Python | 1 |
atoo {
fn handle_vibrate_cmd(
&self,
device: Arc<DeviceImpl>,
message: messages::VibrateCmd,
) -> ButtplugDeviceResultFuture {
// Store off result before the match, so we drop the lock ASAP.
let manager = self.manager.clone();
Box::pin(async move {
let result = manager.lock().await.upd... | Rust | 0 |
A_sp_hat : nomarlized adjacency spatial matrix
A_se_hat : nomarlized adjacency semantic matrix
"""
super(ODEGCN, self).__init__()
# spatial graph
self.sp_blocks = nn.ModuleList(
[nn.Sequential(
STGCNBlock(in_channels=num_features, o... | Python | 1 |
# -*- coding: utf-8 -*-
import datetime
import time
from odoo import api, fields, models
from odoo import tools
from odoo.addons.bus.models.bus import TIMEOUT
from odoo.tools.misc import DEFAULT_SERVER_DATETIME_FORMAT
DISCONNECTION_TIMER = TIMEOUT + 5
AWAY_TIMER = 1800 # 30 minutes
class BusPresence(models.Model):... | Python | 1 |
{
let ref mut gen = StdGen::new(thread_rng(), 50);
let _: TypeQualifierC = Arbitrary::arbitrary(gen);
}
#[test]
fn test_pointer_level_c_does_not_panic() {
let ref mut gen = StdGen::new(thread_rng(), 50);
let _: PointerLevelC = Arbitrary::arbitrary(gen);
}
#[test]
fn test_array_dimension_c_does_not_pa... | Rust | 0 |
.unwrap();
// GAME_THREAD_PROFILER.with(|p| if let Some(p) = p.borrow_mut().take() {
// if let Ok(data) = p.get_data() {
// let mut buf = format!("Captured {} frames. Game thread overhead: {:.3} msec:\n",
// data.lap_count,
// ... | Rust | 0 |
nfig = Config::parse(&config_path)?;
assert_eq!("0.0.1.1", config.server.address);
Ok(())
}
}
<reponame>bookmoons/wasmer<filename>lib/runtime-core/src/sys/windows/mod.rs
mod memory;
pub use self::memory::{Memory, Protect};
extern crate minigrep;
use std::env;
use std::process;
fn main() {
let... | Rust | 0 |
if pretrained:
state_dict = hf_checkpoint_load("swin_rope_mixed_small_patch4_window7_224")
model.load_state_dict(state_dict, strict=False)
return model
def swin_rope_mixed_base_patch4_window7_224(pretrained=False, img_size=224):
window_size = img_size // 32
model = RoPESwinTransformer(
... | Python | 1 |
"""This module contains common functions"""
import time
import os
import getpass
from os.path import expanduser
from symautomata.dfa import DFA
import imp
import re
def accept_bool(user_input):
"""
Transforms a string into bool
Args:
user_input (str): The string parameter
Retun... | Python | 1 |
let hygeia_home = home.join(".hygeia");
let cwd = home.join("current_dir");
let _ = fs::create_dir_all(&cwd);
let mut cmd = Command::cargo_bin(env!("CARGO_PKG_NAME")).unwrap();
let output = cmd
.arg("list")
.env(project_home_env_variable(), &hygeia_home)
.env("PATH", hygeia_h... | Rust | 0 |
from texas_hold_em_utils import Card
from texas_hold_em_utils.sklansky import sklansky_playable_position, sklansky_rank
def main():
while True:
print("Enter the value of the first card: ")
value1 = str(input())
if value1 not in ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", ... | Python | 1 |
region_start_coordinates: Option<&'a [TiledResourceCoordinate]>,
resource_region_sizes: Option<&'b [TileRegionSize]>,
heap: Option<&Heap>,
range_flags: &'c [TileRangeFlags],
heap_range_start_offsets: Option<&'d [u32]>,
range_tile_counts: Option<&'e [u32]>,
flags: Option<T... | Rust | 0 |
es", level=4, path=summoning
)[0].add_source("Tome of Rituals", 16)
LinearMagicRitual.objects.get_or_create(
name="Protection Against Mages", level=4, path=summoning
)[0].add_source("Tome of Rituals", 16)
LinearMagicRitual.objects.get_or_create(
name="Protection Against Changelings", level=4, path=summoning
)[0... | Python | 1 |
) <NAME> <<EMAIL>>
// *
// * For the full copyright and license information, please view the LICENSE
// * file that was distributed with this source code.
// spell-checker:ignore (ToDO) tstr sigstr cmdname setpgid sigchld
mod status;
#[macro_use]
extern crate uucore;
extern crate clap;
use crate::status::ExitSta... | Rust | 0 |
eckout> {
let checkout = try!(GitCheckout::clone_into(dest, self.clone(),
GitReference::for_str(reference.as_slice())));
try!(checkout.fetch());
try!(checkout.update_submodules());
Ok(checkout)
}
pub fn rev_for<S: Str>(&self, reference: S) -> ... | Rust | 0 |
from odoo import models, fields
class ResConfigSettings(models.TransientModel):
_inherit = 'res.config.settings'
jklp_export_path = fields.Char(
string="Export-Verzeichnis",
config_parameter="jklp_invoice_fs_export.path",
default="/mnt/paperless_consume",
help="Ordner, in den R... | Python | 1 |
))
.finalize()
}
}
impl<'a, T> From<&'a urdf_rs::Robot> for Chain<T>
where
T: na::Real,
{
fn from(robot: &urdf_rs::Robot) -> Self {
let mut ref_nodes = Vec::new();
let mut child_link_name_to_node = HashMap::new();
let mut joint_name_to_node = HashMap::new();
let ... | Rust | 0 |
should be called before any other methods provided
/// by ZboxFS.
/// This method can be called more than one time.
pub fn init_env() {
INIT.call_once(|| {
env_logger::try_init().ok();
crypto::Crypto::init().expect("Initialise crypto failed");
... | Rust | 0 |
#!/usr/bin/python3
import sys
def getNOps(n, inst_ptr, modes, program):
ops = list()
for i in range(0, n):
rem = modes % 10
modes = int(modes / 10)
if rem == 0:
ops.append(program[program[inst_ptr + i + 1]])
else:
ops.append(program[inst_ptr + i + 1])
... | Python | 1 |
value").is_err());
}
}
}
<filename>sim/chapter07/src/lib.rs<gh_stars>0
mod Computer;
mod SimpleAdd;
mod StackTest;
mod BasicTest;
mod PointerTest;
mod StaticTest;
mod modules;use bevy::math::Vec2;
pub fn project_ortho(pos: Vec2, tile_width: f32, tile_height: f32) -> Vec2 {
let x = tile_width * pos.x;
... | Rust | 0 |
offset.in_start = index;
}
OffsetMode::Out => {
node_offset.out_start = index;
}
}
}
last_id = cur_id;
}
for node_offset in &mut node_offsets[... | Rust | 0 |
:
if not src_shape.is_ragged(axis) and dst_shape.is_ragged(axis):
dst_size = dst_shape.dimension_size(axis)
rt_input = _ragged_tile_axis(rt_input, axis, dst_size)
return rt_input
def _ragged_tile_axis(rt_input, axis, repeats):
"""Tile a dimension of a RaggedTensor to match a ragged shape."""
as... | Python | 1 |
# Copyright 2020 The TensorFlow Authors
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | Python | 1 |
tions generated by the state machine.
///
/// An action could either be a generic action as defined in `GmpAction` Or any
/// other protocol-specific action that is associated with `ProtocolSpecific`.
#[derive(Debug, PartialEq, Eq)]
enum Action<P: ProtocolSpecific> {
Generic(GmpAction<P>),
Specific(P::Action),
... | Rust | 0 |
str> {
if rom.len() < 0x150 {
return Err("Rom is too small to contain a rom header (rom is smaller than 0x150 bytes)");
}
let mbc_type: MBCType = try!(CartInfo::get_type(rom[0x0147]));
let rom_size: usize = try!(CartInfo::get_rom_size(rom[0x0148]));
let ram_size: usize = try!(CartInfo::get_ram_size(rom[0x... | Rust | 0 |
())),
ErrorName::from_str(valid_string)
);
}
}
/// There is a maximum name length of 255 which applies to bus names, interfaces, and members.
pub const MAX_NAME_LENGHT: usize = 255;
lazy_static! {
/// The special message bus name org.freedesktop.DBus responds to a number of additional mess... | Rust | 0 |
Analysis failed or timed out")
# Example 2: List all tasks
print("\n📋 Example 2: List All Tasks")
tasks = client.list_tasks()
if tasks:
print(f"Found {len(tasks.get('tasks', []))} tasks:")
for task in tasks.get("tasks", []):
print(
f" - {task['task_id']}: ... | Python | 1 |
de(alias = "vBucketMap")]
vbucket_map: Vec<Vec<i32>>,
}
pub enum KeyValueRequest {
Get {
key: String,
},
Set {
key: String,
value: Vec<u8>,
expiry: u32,
},
Insert {
key: String,
value: Vec<u8>,
expiry: u32,
},
Replace {
key... | Rust | 0 |
import os
import sys
# 获取项目根目录并添加到模块搜索路径中
script_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.dirname(script_dir)
sys.path.insert(0, project_root)
from config.config import (
get_default_download_dir,
DEFAULT_MODEL_NAME,
MODEL_TRUST_REMOTE_CODE,
MODEL_USE_FAST_TOKENIZER,
... | Python | 1 |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
from frappe.tests.utils import FrappeTestCase
# test_records = frappe.get_test_records('Interest')
class TestInterest(FrappeTestCase):
pass
| Python | 1 |
!("Parsing took: {}ms", now.elapsed().unwrap().as_millis());
part1(passports.clone());
part2(passports.clone());
}
mod ext;
mod manifest;
mod tla;
mod trace;
pub use ext::*;
pub use manifest::*;
pub use tla::*;
pub use trace::*;
use clap::Clap;
use jrsonnet_evaluator::{error::Result, EvaluationState, FileImp... | Rust | 0 |
terest::READ, cx.waker().clone());
TaskPoll::Pending
}
}
}
/// A future that resolves once the associated object becomes ready for writing
pub struct Writable<'s, 'l, F: AsRawFd> {
io: &'s mut Async<'l, F>,
}
impl<'s, 'l, F: AsRawFd> std::future::Future for Writable<'s, 'l, F> {
type O... | Rust | 0 |
class ModifyAccountDescriptionResponse(AbstractModel):
"""ModifyAccountDescription返回参数结构体
"""
def __init__(self):
r"""
:param _RequestId: 唯一请求 ID,由服务端生成,每次请求都会返回(若请求因其他原因未能抵达服务端,则该次请求不会获得 RequestId)。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self._... | Python | 1 |
();
assert_eq!(w2.into_writer().as_slice(), &final_data);
/*writing unary 1 values*/
let mut w: BitRecorder<u32, LittleEndian> = BitRecorder::new();
w.write_unary1(0).unwrap();
w.write_unary1(3).unwrap();
w.write_unary1(0).unwrap();
w.write_unary1(1).unwrap();
w.write_unary1(0).unwrap()... | Rust | 0 |
string())
.collect::<Vec<String>>()
.join(", ")
)
}
}
// ------------------------------------------------------------------------------------------------
impl ToAbbrString for FunctionCall {}
// ------------------------------------------------------------------------------... | Rust | 0 |
import importlib
import pkgutil
from batchgenerators.utilities.file_and_folder_operations import *
def recursive_find_python_class(folder: str, class_name: str, current_module: str):
tr = None
for importer, modname, ispkg in pkgutil.iter_modules([folder]):
# print(modname, ispkg)
if not ispkg... | Python | 1 |
DC/test")
# parser.add_argument("--z_spacing", default=10)
# parser.add_argument("--num_classes", default=4)
# parser.add_argument('--test_save_dir', default='./predictions', help='saving prediction as nii!')
# parser.add_argument('--deterministic', type=int, default=1,
# help='whet... | Python | 1 |
_ffi {
($($t:ident)*) => {$(
#[stable(feature = "raw_os", since = "1.1.0")]
#[doc = include_str!(concat!("../../../../core/src/ffi/", stringify!($t), ".md"))]
// Make this type alias appear cfg-dependent so that Clippy does not suggest
// replacing expressions like `0 as c_char` with... | Rust | 0 |
n_stats_df['mode'] == mode) & (sing_dyn_stats_df['wave_type'] == max_wave_type) & (sing_dyn_stats_df['measure'] == 'mean_duration')]['p_bh'].values[0])
bf = write_scientific(sing_dyn_stats_df[(sing_dyn_stats_df['mode'] == mode) & (sing_dyn_stats_df['wave_type'] == max_wave_type) & (sing_dyn_stats_df['measure'] == '... | Python | 1 |
self.init = true;
let x = self.rng.gen_range(0.0, self.width as f32);
let y = self.rng.gen_range(0.0, self.height as f32);
return Some(self.insert_point(Vec2::new(x, y)));
}
while !self.active_points.is_empty() {
let index = self.rng.gen::<f32>() * (self.... | Rust | 0 |
()
.encoding(ContentEncoding::Identity)
.header("content-type", "image/png")
.body(b)
})
.map_err(Into::into)
}
pub fn scale_app() -> impl HttpServiceFactory {
web::scope("/scale")
.wrap(
Cors::new()
.allowed_methods... | Rust | 0 |
n typ(&self) -> &ObjectType {
&self.typ
}
pub fn high(&self) -> i32 {
self.high
}
pub fn low(&self) -> i32 {
self.low
}
pub fn width(&self) -> u32 {
(1 + self.high - self.low).try_into().unwrap()
}
pub fn is_bitvector(&self) -> bool {
... | Rust | 0 |
"""
Radix sort complexity analysis
Radix sort simply applies counting sort k-times, once for each digit of the
input. The range of numbers for each counting sort is just b, where b is the base
of the digits. E.g. counting sort in base 10, would have a range of 10,
aka. u = b = 10
Time complexity
Each counting so... | Python | 1 |
k_consumers = task.get_consumers();
assert_eq!(task_consumers.len(), consumers.len());
for consumer in consumers {
assert!(task_consumers.contains(&consumer.id));
}
}
#[test]
fn test_task_deps() {
let mut core = Core::default();
//create_test_workers(&mut core, &[1, 1, 1]);
submit_exam... | Rust | 0 |
FUNCTION: &'static str = "reset_members";
}
#[derive(:: subxt :: codec :: Encode, :: subxt :: codec :: Decode)]
pub struct ChangeKey {
pub new: ::subxt::sp_core::crypto::AccountId32,
}
impl ::subxt::Call for ChangeKey {
const PALLET: &'static str = "CouncilMembership";
const FUNCTION: &'stat... | Rust | 0 |
[test]
fn send_packets() {
use SenderAction::*;
let start = TimeStamp::MIN;
let mut buffer = SendBuffer::new(&new_settings());
for n in 0..=16u32 {
let _ = buffer.push_data(test_data_packet(n, false));
}
for n in 0..=16 {
let actions = buffer.... | Rust | 0 |
import _plotly_utils.basevalidators
class ShowexponentValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(
self,
plotly_name="showexponent",
parent_name="scatter3d.line.colorbar",
**kwargs,
):
super(ShowexponentValidator, self).__init__(
... | Python | 1 |
wrapped_features.append(NominalEncoding(f))
return wrapped_features
def _get_ndim(featurizer: Featurizer, feature_type: str):
dummy_mol = Chem.MolFromSmiles('CC')
if feature_type == 'atom':
return len(featurizer(dummy_mol.GetAtomWithIdx(0)))
return len(featurizer(dummy_mol.GetBondWithIdx(0)))
... | Python | 1 |
ACK: Rgb<u8> = Rgb([0, 0, 0]);
const DARK_GRAY: Rgb<u8> = Rgb([76, 76, 76]);
const GRAY: Rgb<u8> = Rgb([127, 127, 127]);
const LIGHT_GRAY: Rgb<u8> = Rgb([178, 178, 178]);
const RED: Rgb<u8> = Rgb([255, 0, 0]);
const ORANGE: Rgb<u8> = Rgb([255, 127, 0]);
const YELLOW: Rgb<u8> = Rgb([255, 255, 0]);
const GREEN: Rgb<u8>... | Rust | 0 |
}?{}",
host, "/api/v0/dag/put", "format=cbor&pin=true&input-enc=cbor&hash=blake2b-256"
);
let cbor = DagCborCodec.encode(&dag).unwrap().into_inner();
let client = reqwest::Client::new();
let form = multipart::Form::new().part("file", multipart::Part::bytes(cbor));
let response: serde_json::Value = client.... | Rust | 0 |
};
}
// build-related status codes
declare_code!(
TOOLCHAIN_SEARCH_ERROR,
BUILT,
COMPILATION_TIMED_OUT,
COMPILER_FAILED
);
// per-test status codes
declare_code!(
TIME_LIMIT_EXCEEDED,
RUNTIME_ERROR,
TEST_PASSED,
JUDGE_FAU... | Rust | 0 |
ildren.len());
for i in 0..children.len() {
values.push(children[i].decode(&value_partition[i])?);
}
Ok(values)
}
pub(crate) fn find_bool_lr(types: &[AbiType], index: usize, delta: i32) -> Result<usize, AbiError> {
let mut until: usize = 0;
loop {
let current_index: usize = (index ... | Rust | 0 |
"""
算法对比工具
提供并排算法对比、结果可视化和性能分析展示功能
"""
import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.gridspec import GridSpec
import seaborn as sns
from typing import Dict, List, Tuple, Any, Optional, Callable
import pandas as pd
from pathlib import Path
import time... | Python | 1 |
import jax
import numpy as np
import lag.data as data
from lag.models import RenewalCoalescentModel
def test_lnl_runs():
samps = np.arange(5, 10) + 0.5
coals = samps[1:] + 0.25
rate_grid = np.arange(19)
intervals = data.CoalescentData(coals, samps, rate_grid)
_ = RenewalCoalescentModel.piecewise_... | Python | 1 |
a.partial_cmp(b).unwrap());
unimplemented!("no median yet")
}
/// L2 norm (Euclidean norm) of input values. The L2
/// norm of an empty list is 0.0.
///
/// # Examples:
///
/// ```
/// # use stats::*;
/// assert_eq!(Some(0.0), l2(&[]));
/// ```
/// ```
/// # use stats::*;
/// assert_eq!(Some(5.0), l2(&[-3.0, 4.0... | Rust | 0 |
"""
160. Intersection of Two Linked Lists
Optimal:
-> Using fast/slow pointer approach
-> fast will be n steps ahead of slow where n is the difference between lengths of ll
-> Now both fast and slow will start moving together.
-> The point where they collide is the answer
"""
# Definition for singly-li... | Python | 1 |
"""保存练习结果到知识管理系统"""
saved_record_ids = []
for result in analyzed_results:
if result["knowledge_point_id"]:
try:
record_id = self.km_system.save_practice_results([{
"subject_name": result["subject_name"],
... | Python | 1 |
iven a string representation of `Self`, parse it into a `PgVarlena<Self>`.
///
/// It is expected that malformed input will raise an `error!()` or `panic!()`
fn input(input: &crate::cstr_core::CStr) -> PgVarlena<Self>
where
Self: Copy + Sized;
/// Convert `Self` into text by writing to the ... | Rust | 0 |
M_UPPER - 1) as *const _, 0)
}
}
#[derive(Debug)]
pub struct FillBuf {
pub buf: GrantW<'static, bbconsts::U32768>,
pub used: usize,
}
impl FillBuf {
pub fn content_len(&self) -> usize {
self.used
}
}
impl rlercobs::Write for FillBuf {
type Error = ();
#[inline(always)]
fn wri... | Rust | 0 |
PARAMS_SOURCE = "keyvault" # keyvault|config
# ----------------------------------------------------------------------------------------
# --- LOCUST PARAMETERS ------------------------------------------------------------------
# ----------------------------------------------------------------------------------------... | Python | 1 |
>(filename: T) -> Box<Future<Item = Option<(PixbufFormat, i32, i32)>, Error=Error>> {
use gio::GioFuture;
GioFuture::new(&(), move |_obj, send| {
use send_cell::SendCell;
let cancellable = gio::Cancellable::new();
let send = SendCell::new(send);
Self::ge... | Rust | 0 |
location: _,
unwind: Some(unwind),
} => {
self.propagate_bits_into_entry_set_for(in_out, target, dirty_list);
if !self.dead_unwinds.contains(bb) {
self.propagate_bits_into_entry_set_for(in_out, unwind, dirty_list);
... | Rust | 0 |
gories: None,
},
})
}
use failure::Error;
use regex::Regex;
use std::{
fs::File,
io::{Read, Write},
path::{Path, PathBuf},
};
fn out_dir() -> PathBuf {
std::env::var("OUT_DIR").expect("OUT_DIR environment var not set.").into()
}
#[cfg(not(feature = "bundled"))]
mod webrtc {
use super::... | Rust | 0 |
mbda self: object(),lambda self,v: None,lambda self: None)
"""Gets a value that determines the scaling of child controls.
"""
ShowFocusCues=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a value indicating whether the control should display focus rectangles.
"""
ShowKeyboardCu... | Python | 1 |
import discord
from grief.core import commands
from grief.core.i18n import Translator
from grief.core.utils import AsyncIter
_ = Translator("AdminConverters", __file__)
class SelfRole(commands.Converter):
async def convert(self, ctx: commands.Context, arg: str) -> discord.Role:
admin = ctx.command.cog
... | Python | 1 |
from pymongo import MongoClient
from app.constants.mongo_constants import MongoDBContractLabelCollections
from app.utils.logger_utils import get_logger
from config import MongoDBContractLabelConfig
logger = get_logger('MongoDB Contract Label')
class MongoDBContractLabel:
def __init__(self, connection_url=None, ... | Python | 1 |
s_err() {
println!("{}", r.err().unwrap().to_string());
}
});
}
#[test]
pub fn test_save_batch() {
async_std::task::block_on(async {
let activity = BizActivity {
id: Some("12312".to_string()),
name: None,
... | Rust | 0 |
raction(first.clone(), second.clone(), td);
leak.is_empty()
});
if all_are_covered {
return Space::new_empty();
}
// いずれかの引数のスペースが直交していたら何もしない。
// (いずれかの引数のスペースが空だったら、コンストラクタパターンも空。)
// (それ以外のケースに関して... | Rust | 0 |
ne, cursor_start.column, cursor_end.line, cursor_end.column
))
.unwrap();
}
fn remove_syntax_group(nvim: &mut Neovim) {
nvim.command("syntax clear ScorchedEarth").unwrap();
}
fn get_valid_parent_highlight_group(
nvim: &mut Neovim,
group_set: &HashSet<HighlightGroup>,
) -> Option<HighlightGroup> {
... | Rust | 0 |
s_bin in self.data_set.iter() {
raw_data += &process_bin.plotable_data();
raw_data += "\n";
}
raw_data
}
fn save_with_id<U: Display>(&self, id: U) -> Result<&Self, PreexplorerError> {
for (counter, process_bin) in self.data_set.iter().enumerate() {
le... | Rust | 0 |
rt corresponds to Alg 3 (IncreaseSamples)
if eps_1.is_finite() {
let dt = dt_max.min(1f64.max(((1.0 / eps) * (eps_1 / eps).powi(2).ln()).ceil()));
dt_prev = Some(dt);
t += dt;
} else if let Some(dt) = dt_prev {
t += dt;
} else {
t += dt... | Rust | 0 |
5, |i| {
/// state += i + 1;
/// state
/// });
/// assert_eq!(&*arr, &[1, 3, 6, 10, 15]);
/// ```
#[inline]
pub fn init_boxed_slice<T, F>(n: usize, f: F) -> Box<[T]>
where
F: FnMut(usize) -> T,
{
unsafe {
let layout = Layout::array::<T>(n).expect("Layout overflow");
// SAFETY: `Box::fro... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import json
import re
import xml.etree.ElementTree as ET
from pathlib import Path
import base64
import colorsys
import numpy as np
def hex_to_rgba(hex_color, alpha=1.0):
"""Convert hex color to RGBA tuple."""
hex_color = hex_color.lstrip('#')
... | Python | 1 |
def xywh2xyxy(x):
"""
Convert bounding box coordinates from (x, y, width, height) format to (x1, y1, x2, y2) format where (x1, y1) is the
top-left corner and (x2, y2) is the bottom-right corner.
Args:
x (np.ndarray | torch.Tensor): The input bounding box coordinates in (x, y, width, height) for... | Python | 1 |
nvs
if __name__ == "__main__":
print("start launching tensorflow job")
if "TF_WORKSPACE" not in os.environ:
print("TF_WORKSPACE env should be set.")
exit(1)
workspace = os.environ.get("TF_WORKSPACE", "")
if "TF_SCRIPT" not in os.environ:
print("TF_SCRIPT env should be set.")
exit(1)
tf_scri... | Python | 1 |
sol = C1 + C2*exp(-x*y)
eq = Derivative(y*f(x), x) + f(x).diff(x, 2)
assert checkodesol(eq, sol, f(x)) == (True, 0)
def test_issue_16146():
raises(ValueError, lambda: dsolve([f(x).diff(x), g(x).diff(x)], [f(x), g(x), h(x)]))
raises(ValueError, lambda: dsolve([f(x).diff(x), g(x).diff(x)], [f(x)]))
... | Python | 1 |
///
/// SSLCreate takes three required parameters, app_id, certificate_chain, private_key. Returns the created [`SSL`][response].
/// ```rust
/// use heroku_rs::prelude::*;
///# let api_client = HttpApiClient::create("API_KEY").unwrap();
///
/// let certificate_chain = "chain_here";
/// let private_key = "key_here"... | Rust | 0 |
use approx::assert_abs_diff_eq;
use ndarray::array;
use super::*;
#[test]
fn cancel_y() {
let (rot, r) = GivensRotation::cancel_y(1.0f64, 2.0).unwrap();
assert_abs_diff_eq!(r, 5.0_f64.sqrt());
assert_abs_diff_eq!(rot.c, 0.4472136, epsilon = 1e-5);
assert_abs_diff_e... | Rust | 0 |
context.read_gs(&uref.into()) {
Ok(Some(StoredValue::CLValue(cl_value))) => {
Ok(Some(cl_value.into_t().map_err(|_| Error::CLValue)?))
}
Ok(Some(_)) => Err(Error::Storage),
Ok(None) => Ok(None),
Err(execution::Error::BytesRepr(_)) => Err(Error:... | Rust | 0 |
itertools.product(*before_left),
itertools.product(*before_right)):
left = ''.join(before_l)
right = ''.join(before_r)
list_before_r = list(before_r)
left_right = ... | Python | 1 |
{'services.open_lite6_gripper': True},
{'services.close_lite6_gripper': True},
{'services.stop_lite6_gripper': True},
{'services.set_mode': True},
{'services.set_state': True},
],
condition=UnlessCondition(use_sim)
)
image_compression_nodes =... | Python | 1 |
st.st_mode | stat.S_IEXEC)
if BINARY_URL in CHECKSUMS:
sha = hashlib.sha256()
with open(BINARY_PATH, "rb") as f:
for chunk in iter(lambda: f.read(CHUNK_SIZE * sha.block_size), b""):
sha.update(chunk)
calculated_hash... | Python | 1 |
import requests
import pandas as pd
from datetime import datetime
from dotenv import load_dotenv
import os
# GitHub Personal Access Token
load_dotenv()
token = os.getenv('GITHUB_TOKEN')
# リポジトリ情報
owner = 'ktakita1011'
repo = 'from_scratch_5'
headers = {
'Authorization': f'token {token}',
'Accept': 'applicati... | Python | 1 |
_911_983_139_663_491_615_228_241_121_378_191,
42_535_295_865_117_307_932_921_825_928_971_026_423,
42_535_295_865_117_307_932_921_825_928_971_026_047,
42_535_295_865_117_307_932_921_825_928_971_026_027,
170_141_183_460_469_231_731_687_303_715_884_105_727,
170_1... | Rust | 0 |
.fold(0, |acc, b| acc + b.count_ones())
});
b.bytes = cap as u64 / 8;
}
#[doc = "Register `PSELRXD` reader"]
pub struct R(crate::R<PSELRXD_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<PSELRXD_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
... | Rust | 0 |
[`HashMap::get`] for more info.
#[inline]
pub fn get<Q: ?Sized + Hash + Eq>(&self, key: &Q) -> CacheOut<&V>
where
K: Borrow<Q>,
{
self.get_with_lifetime(key).map(|v| &v.0)
}
/// Gets the [`CacheItem`] at `key` from the cache.
/// Consider using [`Self::get`] for most operati... | Rust | 0 |
"""
# Copyright Xiang Wang, Inc. 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
Author: Xiang Wang, xiangking1995@163.com
S... | Python | 1 |
tc = int(input())
for _ in range(tc):
n = int(input())
ootd = {}
for _ in range(n):
_, b = input().split()
ootd[b] = ootd.get(b, 0) + 1
result = 1
for i in ootd.values():
result *= i + 1
print(result - 1) | Python | 1 |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
"""
This module contains APIs to manipulate ops.
"""
from dataclasses import dataclass
from typi... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.