text string | label_name string | labels int64 |
|---|---|---|
: rail_y - handle_height / 2.0,
width: handle_width,
height: handle_height,
},
border_radius: handle_border_radius,
border_width: style.handle.border_width,
border_color: style.handle.border_color,
},
style.handle.color,
... | Rust | 0 |
= mc::NamedField(variant_arg_name);
add_fragment_sibling_local(field_name, Some(variant_info.id));
}
}
mc::PositionalField(tuple_idx) => {
let variant_arg_types = &variant_info.args;
for (i, _variant_arg... | Rust | 0 |
timizer, scheduler, path, args):
if args.hybrid in [7,8]:
from batch_engine_KD import valid_trainer, batch_trainer
else :
from batch_engine import valid_trainer, batch_trainer
maximum1, maximum2, maximum3 = float(-np.inf), float(-np.inf),float(-np.inf)
best_epoch1, best_epoch2, best_epo... | Python | 1 |
SET,
#[doc = "0x2c - PORTDINV register"]
pub portdinv: PORTDINV,
#[doc = "0x30 - LATD register"]
pub latd: LATD,
#[doc = "0x34 - LATDCLR register"]
pub latdclr: LATDCLR,
#[doc = "0x38 - LATDSET register"]
pub latdset: LATDSET,
#[doc = "0x3c - LATDINV register"]
pub latdinv: LATDI... | Rust | 0 |
reserved3(&self) -> RESERVED3_R {
RESERVED3_R::new(((self.bits >> 3) & 0x1fff_ffff) as u32)
}
#[doc = "Bits 0:2 - 2:0\\]
Select a peripheral signal that connects to AUXIO\\[8i+1\\]
when IOPOE bit 1 is set."]
#[inline(always)]
pub fn src(&self) -> SRC_R {
SRC_R::new((self.bits & 0x07) as ... | Rust | 0 |
from marie.parsers.helper import add_arg_group
def mixin_head_parser(parser):
"""Mixing in arguments required by head pods and runtimes into the given parser.
:param parser: the parser instance to which we add arguments
"""
gp = add_arg_group(parser, title='Head')
gp.add_argument(
'--com... | Python | 1 |
sert_eq!(client.last(1), "1/7 points: 2<br/>0/7 points: 1 (Yourself)");
assert_eq!(client.last(2), "1/7 points: 2 (Yourself)<br/>0/7 points: 1");
}
// Bug: THRUSTER could still THRUST after THRUSTEE already decides
#[test]
fn cant_thrust_after_decide() {
let mut client = common::setup();
client.send(1, ".n... | Rust | 0 |
er (`#`) is ignored. Comments
//! can be put in front of the line, making the whole line a comment or after non
//! comment text:
//!
//! ```conf
//! ## Complete comment
//! key=value # Comment
//! [Section] # Comment
//! ```
//!
//! To include a literal hash character into a value or key it has to be escaped
//! by ... | Rust | 0 |
fore.iter() {
field[i.coord.y as usize][i.coord.x as usize].Type = i.cell;
}
}
fn print_menu() {
clear();
let mut height : i32 = 0;
let mut width : i32 = 0;
getmaxyx(stdscr, &mut height, &mut width);
mv(height/2-8, width/2-23);
printw("______ _ _ _ _ _ ... | Rust | 0 |
o_glib_none().0, &mut error);
if error.is_null() { Ok(from_glib_full(ret)) } else { Err(from_glib_full(error)) }
}
}
pub fn new_from_ppd(ppd_name: &str, ppd_display_name: &str, width: f64, height: f64) -> PaperSize {
assert_initialized_main_thread!();
unsafe {
fr... | Rust | 0 |
}
/// Erase all characters from the screen.
pub fn erase(&mut self) {
self.buf.fill(Cell::default());
}
pub fn erase_line(&mut self, line: usize) {
self.buf.row_mut(line).fill(Cell::default());
}
/// Push the contents of the internal buffer to the screen.
pub fn refresh... | Rust | 0 |
self) -> WKUPIS11_R {
WKUPIS11_R::new(((self.bits >> 27) & 0x01) != 0)
}
#[doc = "Bit 28 - WKUP Input Status 12"]
#[inline(always)]
pub fn wkupis12(&self) -> WKUPIS12_R {
WKUPIS12_R::new(((self.bits >> 28) & 0x01) != 0)
}
#[doc = "Bit 29 - WKUP Input Status 13"]
#[inline(alwa... | Rust | 0 |
/ pure_inf_time
print(
f'Overall fps: {fps:.1f} img / s, '
f'times per image: {1000 / fps:.1f} ms / img',
flush=True)
break
return fps
def repeat_measure_inference_speed(cfg,
checkpoint,
... | Python | 1 |
str, database_type: DatabaseType, right: &str) {
test_expression(database_type, left, right);
}
#[theory]
#[test]
#[case("sqrt(6.855)", NSQL, "sqrt(6.855)")]
fn test_sqrt(left: &str, database_type: DatabaseType, right: &str) {
test_expression(database_type, left, right);
}
#[theory]
#[test]
#[case("tan(6.855)... | Rust | 0 |
.result()
.unwrap();
easy.perform().unwrap();
}
<gh_stars>10-100
use std::result::Result;
use clap::ArgMatches;
use crate::command::{Command, MultiProcessor};
use crate::db::storage;
use crate::model::Task;
use crate::view::single;
pub struct Done<'a> {
args: &'a ArgMatches<'a>,
}
impl<'a> ... | Rust | 0 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | Python | 1 |
er.info(f"[{self.service_name}] Started notification service")
# Set up queue consumers with QoS settings
channel = await self.rabbit.get_channel()
# Set prefetch to prevent overwhelming the service
await channel.set_qos(prefetch_count=10)
immediate_queue = await channel.get_q... | Python | 1 |
force: If True, reload all MCP servers even if they are not changed.
"""
logger.debug("Reloading MCP servers, force: %s", force)
if not force:
to_shutdown = set(self._configs.keys()) - set(new_configs.keys())
to_launch = set(new_configs.keys()) - set(self._confi... | Python | 1 |
#! /usr/bin/python
# -*- python -*-
# -*- coding: utf-8 -*-
# twatch - Experimental use of the perf python interface
# Copyright (C) 2011 Arnaldo Carvalho de Melo <acme@redhat.com>
#
# This application is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License... | Python | 1 |
e="function")
def library_secondary(arctic_secondary, library_name):
arctic_secondary.initialize_library(library_name, m.VERSION_STORE, segment='month')
return arctic_secondary.get_library(library_name)
@pytest.fixture(scope="function")
def user_library(arctic, user_library_name):
arctic.initialize_librar... | Python | 1 |
Style, DrawingErrorKind};
use crate::drawing::DrawingBackend;
use crate::style::Color;
pub fn draw_rect<B: DrawingBackend, S: BackendStyle>(
b: &mut B,
upper_left: BackendCoord,
bottom_right: BackendCoord,
style: &S,
fill: bool,
) -> Result<(), DrawingErrorKind<B::ErrorType>> {
if style.as_col... | Rust | 0 |
_dl = DummyDataloader(10)
trainer = StepTrackingTrainer(
train_dl_mock=train_dl, model=Mock(), optimizer=Mock(), loss_func=Mock()
)
# With 10 batches per epoch and grad_accumulation=1, we get 10 update steps per epoch
# So 2 epochs would normally give us 20 steps
# But we set max_steps=7, ... | Python | 1 |
mut queues) = Device::new(
physical_device,
&Features::none(),
&required_device_extensions(),
queue_families,
)
.expect("Unable to create logical device!");
let graphics_queue = queues.next().unwrap();
let present_queue = queues.next().unwrap_or(graphics_queue.clone());
(d... | Rust | 0 |
, [1279], [13163], [14610], [14804], [15913], [16471], [16791], [18189], [1875],
[19841], [22039], [22330], [23785], [23984], [24293], [24618], [25970], [26700], [27], [28401], [28725],
[29], [29342], [29847], [31175], [32406], [32756], [33409], [33490], [33717], [33994], [34516], [3556],
[36475... | Python | 1 |
bundle_mask[next_item] = True
bundle = np.nonzero(bundle_mask)[0]
price = private_values[bundle].sum() + len(bundle) ** (1 + self.additivity)
return bundle, price
################# PySCIPOpt modeling #################
def solve(self, instance):
bids = instance['bids']
... | Python | 1 |
#!/usr/bin/env python3
# Copyright (C) 2019 Checkmk GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.
# mypy: disable-error-code="no-untyped-def"
from ... | Python | 1 |
# coding: utf-8
"""
Coinbase Developer Platform APIs
The Coinbase Developer Platform APIs - leading the world's transition onchain.
The version of the OpenAPI document: 2.0.0
Contact: cdp@coinbase.com
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manua... | Python | 1 |
licable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
use std::sync::Arc;
use std::thread::{self, ThreadId};
use futures::executor::{self, Notify, Spawn... | Rust | 0 |
):
with pymongo.timeout(1):
if self.om.runtime.celeryapp.conf.get('CELERY_ALWAYS_EAGER'):
# local runtime in principle always works
# -- however broker may still fail
# -- hence we check the broker instead
self.om.runtime.celeryapp.cont... | Python | 1 |
urn Err(s!(OUT_OF_RANGE_MSG))
}
}
fn get_i16(&self, byte_offset: u32, bit_offset: u32, length: u32) -> Result<i16> {
if length == 0 { return Err(s!(LEN_ZERO)); };
if length <= 16 {
if self.len() as u32 * 8 >= byte_offset * 8 + bit_offset + length { // Ensure that we stay within the vector
// i... | Rust | 0 |
# --- THIS FILE IS AUTO-GENERATED ---
# Modifications will be overwitten the next time code generation run.
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Textfont(_BaseTraceHierarchyType):
_parent_path_str = "scattergeo.selected"
... | Python | 1 |
nt()),
})
}
}
impl TryFrom<dom::IntegerNode> for Value {
type Error = Error;
fn try_from(node: dom::IntegerNode) -> Result<Self, Self::Error> {
let node_str = node.syntax().to_string().replace("_", "");
Ok(match node.repr() {
dom::IntegerRepr::Dec => match node_str.pars... | Rust | 0 |
#[test]
fn run_no_args() {
test::run_script_and_validate(
vec![create(""), Box::new(ArrayCommand {})],
r#"
test_var = test_array 1 2 3
out = dump_state
"#,
CommandValidation::Contains("out".to_string(), "3".to_string()),
);
}
<gh_stars>1-10
use std::{fmt, marker... | Rust | 0 |
one,Default)]
pub struct MsgExecResponse {
// message fields
pub results: ::protobuf::RepeatedField<::std::vec::Vec<u8>>,
// special fields
pub unknown_fields: ::protobuf::UnknownFields,
pub cached_size: ::protobuf::CachedSize,
}
impl<'a> ::std::default::Default for &'a MsgExecResponse {
fn def... | Rust | 0 |
types)]
use libc::{c_char, c_int, c_void};
use std::ffi::{CStr, CString};
pub const FLB_ERROR: u32 = 0;
pub const FLB_OK: u32 = 1;
pub const FLB_RETRY: u32 = 2;
pub const FLB_PROXY_OUTPUT_PLUGIN: u32 = 2;
pub const FLB_PROXY_GOLANG: u32 = 11;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct flb_plugin_proxy_def {
... | Rust | 0 |
"""
Las tuplas en Python o tuples son muy similares a las listas, pero con dos diferencias. Son inmutables, lo que significa que no pueden ser modificadas una vez declaradas, y en vez de inicializarse con corchetes se hace con (). Dependiendo de lo que queramos hacer, las tuplas pueden ser más rápidas.
"""
#Son una sec... | Python | 1 |
t`] or `tuple`.
Returns:
prev_sample (TODO): updated sample in the diffusion chain. derivative (TODO): TODO
"""
pred_original_sample = sample_prev + sigma_prev * model_output
derivative_corr = (sample_prev - pred_original_sample) / sigma_prev
sample_prev = sample_ha... | Python | 1 |
.each(|bi| {
quote!{ moniker::BoundPattern::<String>::visit_mut_vars(#bi, __on_var); }
});
s.bind_with(|_| BindStyle::Ref);
let visit_binders_body = s.each(|bi| {
quote!{ moniker::BoundPattern::<String>::visit_binders(#bi, __on_binder); }
});
s.bind_with(|_| BindStyle::RefMut);
... | Rust | 0 |
2 => LevelInfo{
start: StrandInfo{nodeCount: 4, edges: vec![(0,1), (0,2), (2,3)], mutables: vec![(3, Doubler)]},
target: StrandInfo{nodeCount: 6, edges: vec![(0,1), (1,2), (2,3), (1,4), (4,5)], mutables: vec![]},
maxSplices: 1},
3 => LevelInfo{
start: St... | Rust | 0 |
era),
// Primal
"BEHEMOTH" => Ok(Server::Behemoth),
"BRYNHILDR" => Ok(Server::Brynhildr),
"DIABOLOS" => Ok(Server::Diabolos),
"EXCALIBUR" => Ok(Server::Excalibur),
"EXODUS" => Ok(Server::Exodus),
"FAMFRIT" => Ok(Server::Famfrit),
... | Rust | 0 |
t getattr(projectile, 'is_boss_bullet', False): # ボスの弾でない場合のみ相殺可能
for attack in player.active_attacks:
if projectile_hit:
break
# 武器と弾丸の正方形衝突判定(最高速化)
... | Python | 1 |
oader. Does inplace replacement.
fn loader_spinner(receiver: Receiver<bool>) {
let time_between = 50;
std::thread::spawn(move || loop {
print_char_with_stop!('|', time_between, true, receiver);
print_char_with_stop!('/', time_between * 2, true, receiver);
print_c... | Rust | 0 |
import time
from counterpartycore.lib.api import wsgi
def test_lazy_logger(caplog, test_helpers):
lazy_logger = wsgi.LazyLogger()
assert lazy_logger.last_message is None
assert lazy_logger.last_print == 0
assert lazy_logger.message_delay == 10
with test_helpers.capture_log(caplog, "Coucou"):
... | Python | 1 |
}
KeepAlive::Yes
}
fn poll(
&mut self,
cx: &mut Context<'_>,
) -> Poll<
ConnectionHandlerEvent<
Self::OutboundProtocol,
Self::OutboundOpenInfo,
Self::OutEvent,
Self::Error,
>,
> {
if let Some(open_info) = s... | Rust | 0 |
rules! ovec {
() => {
vec![]
};
($elem:expr; $n:expr) => {
vec![crate::obj!($elem), $n]
};
($($x:expr),+ $(,)?) => {
vec![$(crate::obj!($x)),+]
};
}
/// Create a new type object.
#[macro_export]
macro_rules! typeobject {
(pub $name:ident $body:tt) => {
$crate... | Rust | 0 |
import cv2
import numpy as np
import datetime
from utilities.gelsightmini import GelSightMini
FULLWIDTH = 3280
FULLHEIGHT= 2464
# Image size and crop
imgw = FULLWIDTH
imgh = FULLHEIGHT
brd_frac = 0
imgw = 640 # FULLWIDTH
imgh = 480 # FULLHEIGHT
brd_frac = 0.15
def show_image():
counter = 0
cam = GelSightMi... | Python | 1 |
headers, HEADER_CURRENT_WRITE_QUORUM)
}
pub(crate) fn current_write_quorum_from_headers_optional(
headers: &HeaderMap,
) -> Result<Option<u64>, Error> {
get_option_from_headers(headers, HEADER_CURRENT_WRITE_QUORUM)
}
pub(crate) fn collection_partition_index_from_headers(headers: &HeaderMap) -> Result<u64, Err... | Rust | 0 |
ource;
use rafx::base::slab::RawSlabKey;
pub struct SpriteExtractJob {}
impl SpriteExtractJob {
pub fn new() -> Self {
Self {}
}
}
impl ExtractJob for SpriteExtractJob {
fn extract(
self: Box<Self>,
extract_context: &RenderJobExtractContext,
frame_packet: &FramePacket,
... | Rust | 0 |
TypedIR {
FuncDef(String, Vec<UnTypedIR>),
ConstInt(i32),
ConstString(String),
Var(String),
Unary(String, Box<UnTypedIR>),
Binary(String, Box<UnTypedIR>, Box<UnTypedIR>),
Call(String, Vec<UnTypedIR>),
Assign(Box<UnTypedIR>, Box<UnTypedIR>),
Return(Box<UnTypedIR>),
If(Box<UnTypedI... | Rust | 0 |
unsafe { ::ffi::libusb_exit(context) };
}
<reponame>xd009642/llvm-profparser<filename>src/instrumentation_profile/stats.rs
use crate::instrumentation_profile::types::*;
use std::fmt;
#[derive(Clone, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct ValueSiteStats {
total_num_value_sites: usize,
... | Rust | 0 |
props,
}
}
}
impl Component for Fragment {
#[cfg(not(tarpaulin_include))]
fn render(&self, _frame: &mut Canvas, _area: Rect) {}
fn update(&mut self, props: Props) -> Msg {
self.props = props;
Msg::None
}
fn ge... | Rust | 0 |
// This dispatch does not work because the incorrect enum is used
node.dispatch(SomeTest::INCREMENT);
let babel = babel!(
MyAction2,
parse_MyAction2,
MyAction,
parse_MyAction,
SomeTest,
parse_SomeTest
);
let testo2 = Testo { counter: 10 };
let te... | Rust | 0 |
timeout_t = time.time() + 5.
t1 = TestTask(task1)
t1.start()
while not t1.done and time.time() < timeout_t:
time.sleep(0.5)
self.assertTrue(t1.success)
self.assertTrue('hello' in t1.value.data)
# test wait for message with timeout
def task2():
... | Python | 1 |
row_indexes=slice(1,2)
)
def _test_double_pred(self):
# Test a double precision float predicate
self.verify_pred_type_scans(
preds=[
self.type_table['double_val'] < 200.11
],
row_indexes=slice(1,2)
)
def _test_float... | Python | 1 |
assert_eq!(Fixed8::ONE.to_string(), "1");
assert_eq!(Fixed8::from(5).to_string(), "5");
assert_eq!(Fixed8::from_f64(-3.5).to_string(), "-3.5");
assert_eq!(Fixed8::from_f64(127.99609375).to_string(), "127.99609375");
}
#[test]
fn neg() {
assert_eq!(-Fixed8::from(0), ... | Rust | 0 |
debug_struct(&format!("GeeTreeMultiMapClass @ {:?}", self as *const _))
.finish()
}
}
#[repr(C)]
pub struct _GeeTreeMultiMapPrivate(c_void);
pub type GeeTreeMultiMapPrivate = *mut _GeeTreeMultiMapPrivate;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct GeeTreeMultiSetClass {
pub parent_class: GeeAbstra... | Rust | 0 |
"name": ORGANIZATION_NAME,
"information": "info",
"slug": ORGANIZATION_SLUG,
"verified_at": null,
"verified": true,
"disabled": false,
"disabled_reason": null,
"created_at": "2015-08-03T17:06:45.307+03:00",
"updated_at": "2017-12... | Rust | 0 |
import tensorflow as tf
from core.features import FeatureMetas, Features
from core.blocks import DNN, CrossNetwork
def DCN(
feature_metas,
cross_kernel_initializer='glorot_uniform',
cross_kernel_regularizer=tf.keras.regularizers.l2(1e-5),
cross_bias_initializer='zeros',
cross_... | Python | 1 |
import matplotlib.pyplot as plt
from wbml.plot import tweak
from stheno import Measure, GP, EQ, RQ, Linear, Delta, Exp, B
B.epsilon = 1e-10
# Define points to predict at.
x = B.linspace(0, 10, 200)
x_obs = B.linspace(0, 7, 50)
with Measure() as prior:
# Construct a latent function consisting of four different ... | Python | 1 |
import os
from swarm import Agent
from dotenv import load_dotenv
# Import other agents
from .weather_agent import weather_agent
from .stockprice_agent import stockprice_agent
from .arxiv_agent import arxiv_agent
from .duckduckgo_agent import duckduckgo_agent
from .python_repl_agent import python_repl_agent
# Load env... | Python | 1 |
plans': 0}
def seed_meal_food_items_correct(session: Session) -> Dict[str, int]:
return {'meal_food_items': 0}
def seed_physical_education_meals_correct(session: Session) -> Dict[str, int]:
return {'physical_education_meals': 0}
def seed_physical_education_meal_foods_correct(session: Session) -> Dict[str, in... | Python | 1 |
,
output_scale_factor=output_scale_factor,
pre_norm=resnet_pre_norm,
)
)
temp_convs.append(
TemporalConvLayer(
out_channels,
out_channels,
dropout=0.1,
... | Python | 1 |
tasksFile = benchUtil.getArg("-tasks", None, True)
if sourceData.tasksFile is None:
raise RuntimeError("No tasks file defined: -tasks [file]")
comp = competition.Competition(randomSeed=0)
index = comp.newIndex(
constants.TRUNK_CHECKOUT,
sourceData,
postingsFormat="Lucene104",
idFieldPostings... | Python | 1 |
.) because this is a glifparser image, relative to the glif's points.
// So, we need points::calc::calc_(x|y). Remember also, the glif y is positive, while Skia's
// negative.
canvas.draw_image(&image.img, (0., 0.), None);
canvas.restore();
}
... | Rust | 0 |
_str__(self):
return f"Invoice Template - {self.name} ({self.school})"
class FeeReminder(models.Model):
"""Tracks fee reminders sent to parents"""
fee_record = models.ForeignKey(
FeeRecord, on_delete=models.CASCADE, related_name="reminders"
)
sent_via = models.CharField(
max_l... | Python | 1 |
ON CONFLICT DO NOTHING
""", paragraph_id, match_id, run_id)
except Exception as e:
logging.error(f"Error inserting paragraph match: {str(e)}")
def split_into_paragraphs(text: str) -> List[str]:
"""Split text ... | Python | 1 |
e colors using priority.
let color = match (background_color, sprite_color) {
(None, None) => backdrop_color,
(Some(color), None) => color,
(
Some(color),
Some(SpriteColor {
priority: BelowBg, ..
... | Rust | 0 |
textwrap::indent(&doc, " * ").replace("\n\n", "\n *\n");
format!("/**\n{} */\n", text)
}
fn quote_type_arguments(ty_args: &[TypeArgumentABI]) -> String {
ty_args
.iter()
.map(|ty_arg| ty_arg.name().to_string())
.collect::<Vec<_>>()
.join(", ")
... | Rust | 0 |
@classmethod
def _read_pcd(cls, file_path):
pc = open3d.io.read_point_cloud(file_path)
ptcloud = np.array(pc.points)
return ptcloud
| Python | 1 |
lumns);
return self.values[i * self.num_columns + j];
}
pub fn set_interned(&'b mut self, i: usize, j: usize, v: TableValueR<'b>) {
assert!(i < self.len());
assert!(j < self.num_columns);
InsertedRow::assign_interned(&mut self.values[i * self.num_columns + j], v, self.arena);
... | Rust | 0 |
atched video info, should be removed
video_infos_b["P07_001"] = VideoInfo(
video_id="P07_001", resolution="720x1280", duration=17.001, fps=30
)
# Unmatched video frame entry, should be removed
video_frames_b["P07_002"]: VideoFrameInfo(
min_frame_number=1, max_fra... | Python | 1 |
}
fn make_test_payload() -> Payload {
Payload::Storm(StormWrapper::default())
}
fn make_fake_incoming(packet_num: u64, ack: u64, acked_in_bits: &[u64]) -> GameMessage {
let mut message: GameMessage = GameMessage::default();
message.packet_num = packet_num;
message.ack = ack... | Rust | 0 |
Dict[str, str]) -> Dict[str, str]:
"""
Validate and clean tags according to AWS requirements
Args:
tags: Dictionary of tags to validate
Returns:
Validated and cleaned tags dictionary
"""
validated_tags = {}
for key, value in tags.items():
# AWS tag... | Python | 1 |
fn deduplicate_files_with_source <
AsPath1: AsRef <Path>,
AsPath2: AsRef <Path>,
> (
source_filename: AsPath1,
dest_filenames: & [AsPath2],
) -> Result <(), String> {
let source_filename = source_filename.as_ref();
// nothing to do unless there is are no dest filenames
if dest_filenames.is_empty () {
retur... | Rust | 0 |
f re.search(pattern, filename, re.IGNORECASE):
self._reject(
"rejected_content",
f"Suspicious filename pattern detected: {filename}",
)
# 2. Check for embedded executables or scripts in content
dangerous_signatures = [
... | Python | 1 |
_length: usize) -> usize {
if input_length % 128 <= 111 {
128 - input_length % 128
} else {
256 - input_length % 128
}
}
const fn new() -> Self {
Self {
h: [
0x6a09_e667_f3bc_c908,
0xbb67_ae85_84ca_a73b,
... | Rust | 0 |
hash_map::DefaultHasher,
};
use rayon::prelude::*;
#[derive(Default, Debug)]
struct Bag {
hash: u64,
contents: Vec<u64>,
weight: usize,
}
fn main() {
let mut aoc = Aoc::new()
.year(Some(2020))
.day(Some(7))
.init()
.unwrap();
let input = aoc.get_input(false);
... | Rust | 0 |
doc = "APORT2Y Channel 14"]
#[inline(always)]
pub fn aport2ych14(self) -> &'a mut W {
self.variant(VASEL_A::APORT2YCH14)
}
#[doc = "APORT2Y Channel 16"]
#[inline(always)]
pub fn aport2ych16(self) -> &'a mut W {
self.variant(VASEL_A::APORT2YCH16)
}
#[doc = "APORT2Y Channel... | Rust | 0 |
#!/usr/bin/python3
import os
import shutil
import subprocess
import sys
import setuptools.command.build_py
from setuptools import setup
podir = "./po"
pext = ".po"
langs = sorted([x[:-3] for x in os.listdir(podir) if x[-3:] == pext])
def modir(lang):
return os.path.join("build/mo", lang)
def mkmo(lang):
... | Python | 1 |
e std::{
collections::BTreeSet,
self,
};
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct Coord<T> {
row: Pixels,
col: Pixels,
_phantom: std::marker::PhantomData<T>,
}
impl <T> Coord<T> {
pub fn new(row: Pixels, col: Pixels) -> Coord<T> {
Coord {
row,
... | Rust | 0 |
import grpc
import json
import vm
import logging
cc_pb2, cc_pb2_grpc = grpc.protos_and_services("cheesycheatsAPI.proto")
class Api(cc_pb2_grpc.DatabaseServicer):
def __init__(self, db) -> None:
self.db = db
super().__init__()
def Redeem(self, request, _, user):
cheat_id = request.id
... | Python | 1 |
ef test_vote(base_model, test_dataloader, epoch, val_writer, args, config, logger = None, times = 10):
base_model.eval() # set model to eval mode
test_pred = []
test_label = []
npoints = config.npoints
with torch.no_grad():
for idx, (taxonomy_ids, model_ids, data) in enumerate(test_datal... | Python | 1 |
8usize , concat ! (
"Alignment of " , stringify ! (
spdk_nvme_reservation_acquire_data ) ));
assert_eq! (unsafe {
& ( * ( 0 as * const spdk_nvme_reservation_acquire_data ) ) .
crkey as * const _ as usize } , 0usize , concat ! (
"Al... | Rust | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
import mindspore
def multiscale_structural_similarity_index_measure(preds, target, gaussian_kernel=True, sigma=1.5, kernel_size=11,
reduction='ele... | Python | 1 |
serde_json::from_slice(&input).expect("invalid json report")
{
// drop experiment field as it contains non deterministic values
map.remove("ex");
Value::Object(map)
} else {
panic!("invalid json report");
... | Rust | 0 |
if icon is None:
# Use default icons if no custom one is specified.
# If it has children show a full folder, otherwise
# show an open folder
has_children = self.rowCount(index) > 0
icon = "folder" if has_... | Python | 1 |
u128::to_be_bytes(key_int);
assert!(reader.get(&search_key)? == all_data.get(&key_int).cloned());
}
// Test boundary cases
assert!(reader.get(&u128::to_be_bytes(u128::MIN))? == all_data.get(&u128::MIN).cloned());
assert!(reader.get(&u128::to_be_bytes(u128::MAX))? == all_data... | Rust | 0 |
&Config, agent: String) -> Result<String, Box<dyn Error + Sync + Send>> {
let mut hbs = Handlebars::new();
if let Some(file) = config.index.file.as_ref() {
hbs.register_template_file("index", file)?;
} else {
let index = include_str!("index.hbs");
hbs.register_template_string("index"... | Rust | 0 |
!("Error reading directory")).ok();
}
return pro;
}
<filename>runtime/src/lib.rs
// Copyright 2019-2021 Thales Inc.
// This file is part of Thales.
// Thales is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foun... | Rust | 0 |
capital_coordinates = {
'Andhra Pradesh': (16.573000, 80.358200),
'Arunachal Pradesh': (27.082500, 93.611300),
'Assam': (26.143300, 91.789800),
'Bihar': (25.594100, 85.137600),
'Chhattisgarh': (21.251400, 81.629600),
'Goa': (15.490900, 73.827800),
'Gujarat': (23.215600, 72.636900),
'Hary... | Python | 1 |
fn get_highest_seen(&mut self, Key) -> Ballot;
fn get_accepted_ballot(&mut self, Key) -> Ballot;
fn get_accepted_value(&mut self, Key) -> Option<Value>;
fn set_highest_seen(&mut self, Key, Ballot);
fn set_accepted_ballot(&mut self, Key, Ballot);
fn set_accepted_value(&mut self, Key, Option<Value... | Rust | 0 |
EOR>")
}
}
#[derive(Hash, PartialEq, Eq)]
struct QsoKey(Call, Grid, Grid, Band, Band);
fn main() -> std::io::Result<()> {
let call_op = Ascii::new(env::args().nth(1).expect("Missing operator call sign"));
let stdin = io::stdin();
let mut cycle = 0u64;
// Look back queues
let mut rx = VecDeque::<Spot>::new();
... | Rust | 0 |
e_abbastanza_scura_e_capelli_bianchi:',
'fa': ':مرد_پوست_گندمی_موسفید:',
'id': ':pria_warna_kulit_gelap-sedang_rambut_putih:',
'zh': ':男人_中等深肤色白发:',
'ru': ':мужчина_темный_тон_кожи_седые_волосы:'
},
'\U0001F468\U0001F3FC': { # 👨🏼
'en': ':man_medium-light_skin_tone:',
... | Python | 1 |
"""
Drop a table (`employees`.`departments`).
Example SQL:
DROP TABLE `employees`.`departments`;
We would expect the table and it's children to be removed.
"""
from app.revisioner.tests.e2e import inspected
from app.revisioner.tests.test_e2e import mutate_inspected
preload_fixtures = ['datastore']
inspected_tab... | Python | 1 |
[i]))
time.sleep(PickTime)
uart.write(str('1'))#放置在1位置
time.sleep(PutTime)
break
#将识别颜色与位置表相连
def GetColorPosition():
print("Get Color Position\n")
#请先确保ColorCode1和ColorCode2已被赋值,且获取过Blobs状态。
global ColorPosition,BlobState,XTH01,XTH12
for ... | Python | 1 |
(L2, C, H, W), ...]
# for example [[2, 256, 50, 176], [1, 256, 50, 176], ...]
split_x = self.regroup(x, record_len)
# (B,L,L,2,3)
pairwise_t_matrix = pairwise_t_matrix[:,:,:,[0, 1],:][:,:,:,:,[0, 1, 3]] # [B, L, L, 2, 3]
pairwise_t_matrix[...,0,1] = pairwise_t_matrix[...,0,1] * ... | Python | 1 |
et expected = 1.057604e7;
assert_relative_eq!(energy, expected, max_relative = 1e-4);
let energy = ewald.k_space_energy(&system) / K_BOLTZMANN;
let expected = 7.58785e3;
assert_relative_eq!(energy, expected, max_relative = 2e-3);
let ener... | Rust | 0 |
from enum import Enum
import os
import pdb
import subprocess
import json
class Position(Enum):
UTG = 2
HJ = 3
CO = 4
BTN = 5
SB = 0
BB = 1
class GAME_CODES(Enum):
ALIVE = 0
TOO_MANY_POSTFLOP = 1
FINISHED = 2
PREFLOP_STRATEGY_PATH = "ranges/processed_preflop.json"
PREFLOP_RANGES_PA... | Python | 1 |
/// Offset (10 bits)
pub const offset: u32 = 10;
/// Mask (13 bits: 0x1fff << 10)
pub const mask: u32 = 0x1fff << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW ... | Rust | 0 |
import numpy as np
import pandas as pd
import pytest
from causal_falsify.utils.simulate_data import (
create_polynomial_representation,
simulate_data,
)
# --------------------------
# Tests for create_polynomial_representation
# --------------------------
def test_create_polynomial_correct_shape():
X =... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.