text string | label_name string | labels int64 |
|---|---|---|
&Grid<char>,
config: &Config,
rng: &mut R,
) -> Grid<Cell> {
Grid::new_grid_map_ref(char_grid, |&ch| {
char_to_cell(ch, config, rng).expect(&format!("unrecognised char: {}", ch))
})
}
fn char_grid_to_terrain_description<R: Rng>(
grid: &Grid<char>,
rng: &mut R,
) -> TerrainDescription {... | Rust | 0 |
weight = 0]
pub fn burn(origin, token: (<T as orml_nft::Trait>::ClassId, <T as orml_nft::Trait>::TokenId)) {
let who = ensure_signed(origin)?;
orml_nft::Module::<T>::burn(&who, token)?;
Self::deposit_event(RawEvent::BurnedToken(who,token.0,token.1));
}
}
}
//!... | Rust | 0 |
) -> std::fmt::Result
where
F: Write,
{
write!(f, "#version {}", pv.version)?;
if let Some(ref profile) = pv.profile {
match **profile {
ast::PreprocessorVersionProfileData::Core => {
f.write_str(" core")?;
}
ast::PreprocessorVersionProfileData::C... | Rust | 0 |
get = Point;
#[inline]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl std::ops::DerefMut for PrimalFeasiblePoint {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
#[derive(Debug)]
pub struct PrimalPhase1 {
pub std_form: StandardForm,
pub p... | Rust | 0 |
2c_struct)
}
}
}
/*
This will reset the state, to false, of the button that has been released upon release
*/
I2CEvent::ResetState(device) => {
let mut dev = {
match device {
Device::D0 => &mut i2c_struc... | Rust | 0 |
# Copyright 2021 The TensorFlow 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 applica... | Python | 1 |
import galois
import math
import struct
def inputStuff(s):
arr = []
sizeStuff = (1 << ((int(math.log2(len(s)))+1) & 0x3f))
sl = [s[i] if i < len(s) else 0 for i in range(sizeStuff)]
for i in range(sizeStuff//2):
arr.append((sl[i*2] << 8) | (sl[i*2+1]))
return arr
def outputStuff(arr):
... | Python | 1 |
garan=int(input("Nhập số gà rán"))
hamburger=int(input("Nhập số Hamburger"))
cocacola=int(input("Nhập số cocacola"))
print("Chào mừng các bạn đến với nhà hàng thức ăn nhanh !")
print("Mời bạn nhập số lượng từng món ăn:")
print("Gà rán: ",garan)
print("Hamburger: ",hamburger)
print("Cocacola: "... | Python | 1 |
ut contents).unwrap();
strings.push(contents);
}
});
// to verify that we're actually doing work in all the threads
//let mut active_threads = AtomicUsize::new(0);
strings.into_par_iter().for_each(|source| {
//let thread_count = active_threads.fetch_add(1,Ordering::Relaxed);
... | Rust | 0 |
"""GitGuard Applications Package"""
# Import guard-codex modules and make them available as guard_codex
# This allows imports like 'from apps.guard_codex import activities'
# even though the directory is named 'guard-codex'
try:
from . import guard_codex
except ImportError:
# If direct import fails, try impor... | Python | 1 |
super().__init__()
self.data = data
def _create_nsview(self) -> NSView:
view = NSView.alloc().init()
# Custom implementation
return view
```
### Form Handling
```python
from hibiki.ui import Form, FormField, RequiredValidator, EmailValidator
form = Form([
FormF... | Python | 1 |
, target: Target) -> ast::Namespace {
let mut cache = FileCache::new();
cache.set_file_contents("test.sol", src.to_string());
solang::parse_and_resolve("test.sol", &mut cache, target)
}
pub fn first_error(errors: Vec<ast::Diagnostic>) -> String {
match errors.iter().find(|m| m.level == ast::Level::Er... | Rust | 0 |
= []
for c in range(n_clusters):
ck_idx = [i+start for i in range(len(lbls)) if lbls[i] == c]
threads.append(executor.submit(summarize, ck_idx, lock))
wait(threads, return_when=ALL_COMPLETED)
print([t.result() for t in threads])
... | Python | 1 |
_project_path
.to_str()
.chain_err(|| ErrorKind::InternalError("project path is not valid unicode".to_string()))?;
println!("{}", path);
Ok(())
}
pub fn inspect(name: &str, maybe_config: Result<config::Config>, json: bool, logger: &Logger) -> Result<()> {
let config = maybe_config?;
let project = confi... | Rust | 0 |
D
};
let refi = &mut self.pinter.refi[pidx];
refi[REFP_0] = t0;
refi[REFP_1] = t1;
let mvd = &mut self.pinter.mvd[pidx][lidx];
let mvp = &self.pinter.mvp_scale[lidx][refi_cur];
mvd[MV_X] = mv[MV_X] - mvp[mvp_idx[lidx] as usize][MV_X];... | Rust | 0 |
ed with honey syrup."
}
]
}
]
async def main():
restaurant_agent = Agent(
name="Restaurant_Assistant",
instructions=
f"""
You are a restaurant booking assistant.
You will help users find their desired dishes based on their preferences.
... | Python | 1 |
fferRequest,
session: String,
}
fn create_exchange_offer(
body: web::Json<CreateExchangeOfferRequest>,
plasma_client: web::Data<PlasmaClientShell>,
) -> Result<HttpResponse> {
let session = decode_session(body.session.clone()).unwrap();
let account = plasma_client.get_my_address(&session).unwrap();... | Rust | 0 |
_rule = True
return Ok()
else:
sleep(5)
return Err(
Constants.ANDROID_EMULATOR_PREPARE_ERR,
f"Restart Simulator with root role {self.device} failed!",
)
def get_real_devices(self):
return self.get_devices_list(True)
de... | Python | 1 |
RopeOrStr::Rope(or) => ms == or,
RopeOrStr::Str(os) => ms == os,
},
}
}
}
impl<'a> fmt::Display for RopeOrStr<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
RopeOrStr::Rope(r) => write!(f, "{}", r),
RopeO... | Rust | 0 |
octree
.shared_child(1).unwrap().shared_data() {
TreeNodeType::Footnote { .. } => (),
_ => panic!(),
}
match doctree
.shared_child(1).unwrap()
.shared_child(0).unwrap().shared_data() {
TreeNodeType::Paragraph { .. } => (),
_ => panic!(),
}
}
#[test]
... | Rust | 0 |
ize) -> bool {
let _ = address;
true
}
fn read_byte(self: &Self, address: usize) -> Result<u8, std::io::Error> {
Ok(self.bytes[&address])
}
fn read_word(self: &Self, address: usize) -> Result<u16, std::io::Error> {
Ok(self.words[&address])... | Rust | 0 |
"""
平台工厂模式实现。
提供平台提供者的自动注册和创建功能。
"""
import logging
from typing import Dict, Type
from .base import PlatformProvider
logger = logging.getLogger(__name__)
class PlatformFactory:
"""平台工厂类
负责管理和创建不同平台的提供者实例。
支持自动注册和动态创建平台提供者。
"""
_providers: Dict[str, Type[PlatformProvider]] = {}
_instances... | Python | 1 |
import os
import argparse
import numpy as np
from scripts.hybrik_loc2rot import HybrIKJointsToRotmat
from scripts.pyrender import SMPLRender
import cv2
from scipy.spatial.transform import Rotation as RRR
parser = argparse.ArgumentParser(
description='Render a SMPL video by a j3ds npy file.')
parser.add_argument('-... | Python | 1 |
# C2_W1 Utilities
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# Plot multi-class training points
def plot_mc_data(X, y, class_labels=None, legend=False,size=40):
classes = np.unique(y)
for i in classes:
lab... | Python | 1 |
(bit_width as usize) {
if self.get_bit(i + bit_offset) {
let index = if cfg!(target_endian = "big") {
bit_width as usize - 1 - i
} else {
i
};
val |= 1 << index;
}
}
val
}
... | Rust | 0 |
from ortools.sat.python import cp_model
import math
class OrtoolOptimizer:
def __init__(self):
self.name = "Items Stack Assembler"
self.model = cp_model.CpModel()
def optimizeNumberOfVehicles(self, myDataSetStats, df_vehicles):
"""CP SAT solver to optimize number of vehicles selected."""
model =... | Python | 1 |
wysize = int( wysize * (float(ds.RasterYSize - ry) / rysize) )
rysize = ds.RasterYSize - ry
return (rx, ry, rxsize, rysize), (wx, wy, wxsize, wysize)
# -------------------------------------------------------------------------
def scale_query_to_tile(self, dsquery, dstile):
... | Python | 1 |
ize(
"shape,alignment_bytes,enable_pad",
[
((512, 1), 32, False),
((512, 1), 32, True),
((32, 30), 64, False),
((32, 30), 64, True),
((512, 100, 1), 32, False),
((512, 100, 1), 32, True),
((32, 50, 30), 64, False),
... | Python | 1 |
| jdkr d S | jrd S | jd \}}}}d}| j}t|ts#J |d dkr4|dv r4|| _|df}|rt| jd |d | jd |d }dD ]} || krS qTqK|d usZJ |d |d |d |d | d | |d |d |d | d | |d f}| jd | d | | jd | d | f| _| }t
||||g... | Python | 1 |
G_ECDSA_WITH_SHA384).unwrap(),
ai384
);
assert_eq!(
get_hash_alg_from_sig_alg(&PKIXALG_SHA384_WITH_RSA_ENCRYPTION).unwrap(),
ai384
);
assert_eq!(
get_hash_alg_from_sig_alg(&PKIXALG_ECDSA_WITH_SHA512).unwrap(),
ai512
);
assert_eq!(
get_hash_alg_from... | Rust | 0 |
ol_idx = get_column_letter(j + 1)
cell = ws[f'{col_idx}{row_number}']
# bold headers
if (row_number == 1) and dataset.headers:
cell.font = bold
if freeze_panes:
# Export Freeze only after first Line
... | Python | 1 |
{
CfdCreateAddress, CfdFreeAddressesMultisigHandle, CfdGetAddressFromLockingScript,
CfdGetAddressFromMultisigKey, CfdGetAddressInfo, CfdGetAddressesFromMultisig, CfdGetPeginAddress,
CfdGetPegoutAddress,
};
/// Hash type of locking script.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum HashType {
/// p2p... | Rust | 0 |
})
.flatten();
let shape_style = ShapeStyle {
color: line.color.to_rgba(),
stroke_width: line.stroke_width,
filled: true,
};
chart
.draw_series(LineSeries::new(connection_points, shape_style.clone()))?
.label(line.label.clone())
.legend(move |(x, y)| {
plotters::element::Circle::new((x... | Rust | 0 |
of a transfer
Transfer(Transfer),
/// A record of a deploy
DeployInfo(DeployInfo),
/// Auction metadata
EraInfo(EraInfo),
/// A bid
Bid(Box<Bid>),
}
impl TryFrom<&ExecutionEngineStoredValue> for StoredValue {
type Error = bytesrepr::Error;
fn try_from(ee_stored_value: &ExecutionEn... | Rust | 0 |
d = (
# # not self.trading_mode.filter_settings.use_ema_filter
# # and not self.trading_mode.filter_settings.use_sma_filter
# # and not self.trading_mode.kernel_settings.use_kernel_smoothing
# # )
# # end_long_trade = self.trading_mode.general_settings.use_dynamic_exi... | Python | 1 |
import pymysql
import time
import os
import datetime
from db_driver import mysql_driver
class add_monitor(mysql_driver):
def __init__(self,db_config,request):
super().__init__(**db_config)
self.request = request
def get_privilege(self):
mysql_ip = self.request.form['mysql_... | Python | 1 |
from typing import List
def solve(grid: List[List[int]]) -> List[List[int]]:
h = len(grid)
w = len(grid[0]) if h > 0 else 0
new = [row.copy() for row in grid]
pts = [(r, c) for r in range(h) for c in range(w) if grid[r][c] == 1]
if len(pts) >= 2:
pts.sort()
dr = pts[1][0] - pts[0][0]... | Python | 1 |
in table_data:
if all(record.get(col) == val for col, val in conditions.items()):
return record.get(cfg.idMapping[fk], None)
return None
def mapFact(df, result, dimension):
for table, table_cfg in cfg.tables.items():
records = pd.DataFrame(index=df.index)
for col_name, rules... | Python | 1 |
e')
title = note.get('title')
content = note.get('content')
status = note.get('status')
created_date = note.get('created_date')
issue_date = note.get('issue_date')
print ('_' * 8)
if not num_note is None:
print(f'Заметка №{num_note}')
print(f'Имя пользователя: {username}')
... | Python | 1 |
# -*- mode:python -*-
# Copyright (c) 2016 RISC-V Foundation
# Copyright (c) 2016 The University of Virginia
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must ... | Python | 1 |
rustc-link-search=native={}",
dst.join("lib").display()
);
println!("cargo:rustc-link-lib=static=gc");
for dir in &[LIB_ATOMIC_OPS_DIR, LIB_GC_DIR] {
std::process::Command::new("sh")
.arg("-c")
.arg(format!("cd {} && git clean -dfx", dir))
.output()
... | Rust | 0 |
# Keep ONLY the Duplicates
# The intersection_update() method will keep only the items that are present in both sets.
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z=x.intersection(y)
a=y&z
print(a)
print(z)
x.intersection_update(y)
print(x) | Python | 1 |
so we can properly execute mint and burn
mint: Some(MinterData {
minter: env.contract.address,
cap: None,
}),
};
TOKEN_INFO.save(deps.storage, &data)?;
let denom = deps.querier.query_bonded_denom()?;
let invest = InvestmentInfo {
owner: info.sender,
... | Rust | 0 |
("create_ts");
let u: DateTime<chrono::offset::Utc> = row.get("update_ts");
let e = Ent {
id: row.get("id"),
ino: row.get("ino"),
name: row.get("name"),
is_dir: row.get("is_dir"),
size: ro... | Rust | 0 |
e_rows_json_to_nu_stream(ctrl_c, r.rows()),
Err(e) => Err(ShellError::untagged_runtime_error(format!("{}", e))),
}
}
#[derive(Debug, Deserialize)]
struct AdviseResult {
query: String,
advice: Advice,
}
#[derive(Debug, Deserialize)]
struct Advice {
adviseinfo: Vec<serde_json::Value>,
}
use anyh... | Rust | 0 |
from clive.lib import load_json_data
class TestLoadJsonFiles:
def test_bad_paths(self):
assert load_json_data(None) == []
assert load_json_data('') == []
assert load_json_data('/nonexistent/file') == []
def test_non_json_file(self, tmpdir):
path = tmpdir.join('foo.txt')
... | Python | 1 |
de_json::Value = io::read_yaml(&file)?;
let response = args
.client()?
.post(&["v0", "leaders"])
.json(&input)
.execute()?
.text()?;
println!("{}", response);
Ok(())
}
fn delete(args: RestArgs, id: u32) -> Result<(), Error> {
args.client()?
.delete(&["v0"... | Rust | 0 |
-= learn_rate * d_L_d_ypred * d_ypred_d_h2 * d_h2_d_b2
# Нейрон o1
self.w5 -= learn_rate * d_L_d_ypred * d_ypred_d_w5
self.w6 -= learn_rate * d_L_d_ypred * d_ypred_d_w6
self.b3 -= learn_rate * d_L_d_ypred * d_ypred_d_b3
# --- Считаем полн... | Python | 1 |
ESSION_WINDOW])
.unwrap();
assert!(!session_fc.borrow().frame_needed());
s.read(&mut buf).unwrap();
assert!(session_fc.borrow().frame_needed());
}
#[test]
fn session_flow_control_reset() {
let (mut s, session_fc) = create_stream_session_flow_control();
s... | Rust | 0 |
tils;
mod int_utils;
mod ser_der_utils;
<reponame>openacid/celeritasdb<filename>components/epaxos/src/replication/broadcast.rs
use tonic::Response;
use crate::qpaxos::QPaxosClient;
use crate::qpaxos::ReplicaId;
use crate::qpaxos::ReplicateReply;
use crate::qpaxos::ReplicateRequest;
use crate::replica::ReplicaPeer;
pu... | Rust | 0 |
nt = [0]
def count_sync(op):
if isinstance(op, tvm.tir.Call) and op.op.same_as(tvm.ir.Op.get("tir.tvm_storage_sync")):
count[0] += 1
tvm.tir.stmt_functor.post_order_visit(f.body, count_sync)
assert count[0] == 4
@tvm.script.tir
def tir_func(a: ty.handle, b: ty.handle) -> None:
A ... | Python | 1 |
"""Unit tests for `yapapi.engine` module."""
from unittest.mock import Mock
import pytest
import yapapi.engine
import yapapi.rest
from tests.factories.golem import GolemFactory
from yapapi.engine import Job
@pytest.mark.parametrize(
"default_subnet, subnet_arg, expected_subnet",
[
(None, None, None... | Python | 1 |
# file: runme.py
# Test various properties of classes defined in separate modules
import sys
print("Testing the %import directive with templates")
import base
import foo
import bar
import spam
def write_flush(s):
# Python 2/3 compatible write and flush
sys.stdout.write(s)
sys.stdout.flush()
# Create som... | Python | 1 |
# -*- coding: utf-8 -*-
#
# This file is part of Bika LIMS
#
# Copyright 2011-2017 by it's authors.
# Some rights reserved. See LICENSE.txt, AUTHORS.txt.
from bika.lims import api
from bika.lims import logger
"""Catalog Dexterity Objects that appear in more than one catalog
"""
def reindexMovedObject(obj, event):
... | Python | 1 |
, the caller should always use a certain amount of
/// modesty when reporting these values to the user. For example,
/// it's probably better to say "Arti says it's stuck because it
/// can't make connections to the internet" rather than "You are
/// not on the internet."
pub fn blocked(&self) -> Op... | Rust | 0 |
le, // use negative angles for a clockwise arc.
0.0,
);
// Calling `PathBuilder::build` will return a `Path` ready to be used to create
// Bevy entities.
let path = builder.build();
let paddle_material = materials.add(Color::rgb(0.1, 0.4, 0.5).into());
let circle_material = materials.add... | Rust | 0 |
INITIALIZEEXOPTION_USECOMPLETIONPORT: u32 = 3u32;
#[doc = "*Required features: 'Win32_Devices_Tapi'*"]
pub const LINEINITIALIZEEXOPTION_USEEVENT: u32 = 2u32;
#[doc = "*Required features: 'Win32_Devices_Tapi'*"]
pub const LINEINITIALIZEEXOPTION_USEHIDDENWINDOW: u32 = 1u32;
#[repr(C, packed(1))]
#[doc = "*Required featur... | Rust | 0 |
[i,j] = mpf(val)
# perform A -> QR decomposition
Q, R = qr(A, mode, edps = exdps)
#print('\n\n A = \n', nstr(A, 4))
#print('\n Q = \n', nstr(Q, 4))
#print('\n R = \n', nstr(R, 4))
#print('\n Q*R = \n', nstr(Q*R, 4))
maxnorm = mpf('1.0E-11')
n1 = norm(A ... | Python | 1 |
alizeOwned,
{
self.requests_enqueued.fetch_add(1, Ordering::SeqCst);
let params =
serde_json::to_value(params).map_err(|err| RetryClientError::SerdeJson(err))?;
let mut retry_number: u32 = 0;
loop {
let err;
// hack to not hold `R` across an aw... | Rust | 0 |
VulkanResult::new(_return, surface_capabilities)
}
#[inline]
#[track_caller]
#[doc = "[Vulkan Manual Page](https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/vkGetPhysicalDeviceSurfaceFormats2KHR.html) · Function"]
#[doc(alias = "vkGetPhysicalDeviceSurfaceFormats2KHR")]
pub un... | Rust | 0 |
]: https://www.gnu.org/software/bash/manual/html_node/Shell-Builtin-Commands.html
//! [`enable -f`]: https://www.gnu.org/software/bash/manual/html_node/Bash-Builtins.html#index-enable
//!
//! # Usage
//!
//! ## Crate Configuration
//!
//! The crate where the builtin is implemented has to include `cdylib` in its
//! [`c... | Rust | 0 |
/// ```
/// sea_query::sea_query_driver_postgres!()
/// ```
///
/// Specify a path to the `sqlx` crate instance
/// ```
/// sea_query::sea_query_driver_postgres!(sqlx = "...")
/// ```
///
/// Specify a path to the `sea-query` crate instance
/// ```
/// sea_query::sea_query_driver_postgres!(sea_query = "...")
/// ```
//... | Rust | 0 |
lientDeleteProhibited:注册商禁止删除
serverRenewProhibited: 注册局禁止续费
clientRenewProhibited: 注册商禁止续费
:rtype: list of str
"""
return self._DomainStatus
@DomainStatus.setter
def DomainStatus(self, DomainStatus):
self._DomainStatus = DomainStatus
@property
def BuyStatus(self):
... | Python | 1 |
atic str = ".cargo_at_ssh_control";
if fs::metadata(CONTROL_FILE).is_ok() {
// Control file already exists, remove it
try!(fs::remove_file(CONTROL_FILE));
}
// Remove the control file after we're done, so we don't clutter the directory.
// FIXME: This will probably fail on Windows (but... | Rust | 0 |
#
# Copyright (C) 2009-2020 the sqlparse authors and contributors
# <see AUTHORS file>
#
# This module is part of python-sqlparse and is released under
# the BSD License: https://opensource.org/licenses/BSD-3-Clause
"""filter"""
from sqlparse import lexer
from sqlparse.engine import grouping
from sqlparse.engine.stat... | Python | 1 |
*self == GPIO6INTDR::INTBOTH
}
}
#[doc = "Possible values of the field `GPIO6OUTCFG`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GPIO6OUTCFGR {
#[doc = "FNCSEL = 0x3 - Output disabled value."]
DIS,
#[doc = "FNCSEL = 0x3 - Output is push-pull value."]
PUSHPULL,
#[doc = "FNCSEL = ... | Rust | 0 |
fn rsort_msb_u32_17(bencher: &mut Bencher) { radix_sort_msb::<u32,_,_>(bencher, 1 << 17, &|&x| x); }
fn rsort_msb_u32_18(bencher: &mut Bencher) { radix_sort_msb::<u32,_,_>(bencher, 1 << 18, &|&x| x); }
fn rsort_msb_u32_19(bencher: &mut Bencher) { radix_sort_msb::<u32,_,_>(bencher, 1 << 19, &|&x| x); }
fn rsort_msb_u32_... | Rust | 0 |
ke:
//!
//! ```rust
//! # extern crate strum;
//! # #[macro_use] extern crate strum_macros;
//! // You need to bring the type into scope to use it!!!
//! use strum::EnumMessage;
//!
//! #[derive(EnumMessage,Debug)]
//! enum Color {
//! #[strum(message="Red",detailed_message... | Rust | 0 |
from gym.envs.registration import register
#import logging
#LOGGER = logging.getLogger(__name__)
_REGISTERED = False
def register_envs():
from rlutil.envs.gridcraft.mazes import MAZE1, MAZE_LAVA
from rlutil.envs.gridcraft.grid_spec import REWARD, LAVA
from rlutil.envs.env_utils import CustomGymEnv
fr... | Python | 1 |
.reset_index() \
.pivot(index='utt_piece_ids', columns='lang', values='count') \
.fillna(0)
piece_counts_sums = {}
for c in piece_counts_matrix.columns:
piece_counts_sums[c] = piece_counts_matrix[c].sum()
for c in piece_counts_matrix.columns:
piece_counts_matr... | Python | 1 |
/// [RemoteViews](https://developer.android.com/reference/android/widget/RemoteViews.html#RemoteViews(java.lang.String,%20int))
///
/// Required features: "java-lang-String"
#[cfg(any(feature = "all", all(feature = "java-lang-String")))]
pub fn new_String_int<'env>(__jni_env: &'e... | Rust | 0 |
break 'outer;
}
}
nchunk_pending = nchunk_pending.saturating_sub(1);
}
if let Err(e) = self.free_ids.push_slice(&to_send) {
elog!("GC: Fail to send free ids {:?}", e);
self.pending.extend_from_slice(&to_send);
Ok... | Rust | 0 |
() {
use crate::ser::to_bytes;
use core::convert::TryInto;
let test: b064k::B064K = (&[1, 2, 9][..])
.try_into()
.expect("vector smaller than 64K should not fail");
let expected = vec![3, 0, 1, 2, 9];
assert_eq!(to_bytes(&test).unwrap(), expected);
}
#[test]
fn test_b0_64k_2() {
... | Rust | 0 |
from django.template import RequestContext
from django.test.client import RequestFactory
from wagtailmenus.models.menus import ContextualVals, OptionVals
SUB_MENU_TEMPLATE_LIST = (
'menus/sub_menu_level_2.html',
'menus/sub_menu_level_3.html',
)
SINGLE_ITEM_SUB_MENU_TEMPLATE_LIST = ('menus/sub_menu_level_2.htm... | Python | 1 |
spin::Mutex;
lazy_static! {
static ref MAILBOX: Mutex<Mailbox> = Mutex::new(Mailbox::new());
}
#[derive(Debug)]
pub struct PropertyMailboxError(u32);
pub type PropertyMailboxResult<T> = Result<T, PropertyMailboxError>;
impl From<PropertyMailboxError> for String {
fn from(error: PropertyMailboxError) -> Self... | Rust | 0 |
self.node_stack.pop();
let new_path = match self.current_path.rfind("\\"){
Some(index) => {
self.current_path[0..index].to_string()
},
None => "".to_string()
};
... | Rust | 0 |
# cook your dish here
t = int(input())
for i in range(t):
a, b, x, y = map(int,input().split())
if((a/x)>(b/y)):
print("Chefina")
elif((b/y)>(a/x)):
print("Chef")
else:
print("Both")
| Python | 1 |
"""Copyright 2024 wangxin.jeffry@gmail.com
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 applicable law or agreed to in writing, so... | Python | 1 |
6,t=2,p=1$c29tZXNhbHQ\
$C4TWUs9rDEvq7w3+J4umqA32aWKB1+DSiRuBfYxFj94",
);
}
#[cfg(not(debug_assertions))]
#[test]
fn test_argon2id_version13_9() {
hash_test(
Variant::Argon2id,
Version::Version13,
2,
65536,
1,
b"password",
b"diffsalt",
... | Rust | 0 |
t(f" Improved throughput: {roi_data['improved_throughput']:.1f} features/month")
print()
print(f" Incremental value: ${roi_data['incremental_monthly_value']:,.0f}/month")
print(f" Incremental cost: ${roi_data['incremental_cost']:,.0f}/month")
print()
print(f" Monthly ROI: {ro... | Python | 1 |
#!/usr/bin/env python
#
# Scripts download oui.txt from web and load data to PostgreSQL database.
#
# Dariusz Pawlak <pawlakdp@gmail.com>
# 2014.05.16
#
#
import re
import urllib
#
import psycopg2
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
from psycopg2 import errorcodes
#
# PgSQl connection
#
DBHOST=""... | Python | 1 |
tring())),
}
}
//skip to the jth position
fn seek(self, offset: u64, vm: &VirtualMachine) -> PyResult {
match self.buffer.borrow_mut().seek(offset) {
Some(value) => Ok(vm.ctx.new_int(value)),
None => Err(vm.new_value_error("Error Performing Operation".to_string())),
... | Rust | 0 |
_image: &mut RgbaImage,
sheets: &Sheets,
biome: &Biome,
config: &Spelunkicon,
rng: &mut StdRng,
grid: &PlacedTileGrid,
) {
let sheet_image = sheets.sheet_floor_from_biome(biome).unwrap();
let right_deco = vec![
sheet_image.view(5 * TILE_WIDTH, 5 *... | Rust | 0 |
)
.into(),
normal: (
mesh.normals[3 * i],
mesh.normals[3 * i + 1],
mesh.normals[3 * i + 2],
)
.into(),
});
}
// Vertex array
let mut _vbo = ArrayBuffe... | Rust | 0 |
terfaceDevice\"`*"]
pub const DIK_WEBFAVORITES: u32 = 230u32;
#[doc = "*Required features: `\"Win32_Devices_HumanInterfaceDevice\"`*"]
pub const DIK_WEBFORWARD: u32 = 233u32;
#[doc = "*Required features: `\"Win32_Devices_HumanInterfaceDevice\"`*"]
pub const DIK_WEBHOME: u32 = 178u32;
#[doc = "*Required features: `\"Win... | Rust | 0 |
import streamlit as st
import re
import json
import hashlib
import datetime
from typing import Dict, List, Optional, Tuple
import uuid
import requests
# import tts # Removed because the 'tts' module could not be resolved
import TextToSpeech as ttss
# Page configuration
st.set_page_config(
page_title="SecureBank Ch... | Python | 1 |
import re
txt = "vhvcnwlcicjfvmabbbbbbfmivmwcl"
print(re.search("a{1}b*",txt))
| Python | 1 |
(unet)
## 0.108M | 0.428G| 9.466M (time: 4/15 depth=4)
## 0.131M | 0.514G | 9.467M (多尺度池化)
## 0.131M | 0.529G | 13.398M (inceptionFormer restormer_swin_light)
## 0.103| 0.414G| 9.957M (inception + CAB)
x = torch.randn(1, 3, 64, 64)
model = myNet(embed_dim=48)
# model = unetSR()
print(mo... | Python | 1 |
is_equal:
correct_num += 1
else:
badcase_list.append({'query':label[0]['query'], 'gt_label':gt_label, 'pred_ans':final_ans})
print('badcase length=', len(badcase_list))
print('labels length=', len(labels))
print(f'correct_num={correct_num}')
with o... | Python | 1 |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 21 14:43:14 2017
@author: Sayali Sonawane
"""
#Import packages
import plotly
import pandas as pd
from plotly.graph_objs import Scattermapbox,Data,Layout
# Read Data
# Dataset: Starbucks Locations in USA
# Data Source: https://gist.github.com/dankoh... | Python | 1 |
}
}
struct ChicagoPizzaStore;
impl PizzaStore for ChicagoPizzaStore {
fn create_pizza(&self, pizza_type: &str) -> Box<dyn Pizza> {
match pizza_type {
"cheese" => Box::new(ChicagoStyleCheesePizza::new()),
_ => panic!(
"Don't know how to create Chicago style {} p... | Rust | 0 |
e(bytes);
self.append_terminator();
}
}
impl GeneralHasher for WorldsWorstHasher {
type Digest = Vec<u8>;
fn digest(&self) -> Self::Digest {
self.digest.clone()
}
fn reset(&mut self) -> &mut Self {
self.digest.clear();
self.append_terminator();
self
}
}... | Rust | 0 |
def fix_mirex_chord_name(chord_name):
def is_valid_scale(scale_name):
if(1<=len(scale_name)<=2):
if('A'<=scale_name[0]<='G'):
if(len(scale_name)==1 or scale_name[1]=='#' or scale_name[1]=='b'):
return True
return False
if(chord_name=='N' or chord... | Python | 1 |
cond.desugar(env),
if_true.desugar(env),
if_false.desugar(env),
))
},
concrete::Term::Case(span, ref head, ref clauses) => {
raw::RcTerm::from(raw::Term::Case(
span,
head.desugar... | Rust | 0 |
est = 3
differentTest: Test.Test
differentTest =
w
",
&vec!["test", "differentTest"],
);
helper(
"
type Test = Igore
withNestedValues: Test.Test
withNestedValues =
let
shouldIgnore = Test.test
in
()
",
&vec!["withNestedValues"],
);
... | Rust | 0 |
# pr dari kelas terbuka
# operasi logika & komparasi
# -----0+++++5------8++++11-----
#quest 1
print("--- Quest 1 ---")
ans1 = float (input("masukkan angka \ndiatas 0 \ndan \ndibawah 5 \n= "))
ans2 = float (input("masukkan angka \natas 8 \ndan \ndibawah 11 \n = "))
the1 = ans1 > 0
the2 = ans1 < 5
king1 = the1 and ... | Python | 1 |
}
impl Decodable for OrderType {}
impl Default for OrderType {
fn default() -> Self {
OrderType::Market
}
}
#[derive(Debug,Clone)]
pub enum TriggerMethod {
Default,
DoubleBidAsk,
Last,
DoubleLast,
BidAsk,
LastOrBidAsk,
MidPoint,
}
impl Encodable for TriggerMethod {
fn... | Rust | 0 |
eshold:
root_cause = RootCause.get(FEATURES_CAUSE_MAPPER.get('C_VIEW'))
query_context.slow_sql_instance.add_cause(root_cause)
return
query_context.slow_sql_instance.tables_name = exist_tables
feature_generator = QueryFeature(query_context)
feature_generator.in... | Python | 1 |
move {
loop {
match receiver.receive().await {
Err(e) => {
log::error!("UNEXPECTED ERROR: {:?}", e);
return;
... | Rust | 0 |
, fx.layout_of(out_ty));
let param_types = vec![
AbiParam::special(pointer_ty(fx.tcx), ArgumentPurpose::StructReturn),
AbiParam::new(types::I128),
AbiParam::new(types::I128),
];
let args = [
out_place.to_ptr().get_addr(f... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.