text string | label_name string | labels int64 |
|---|---|---|
kasakaID
"""
)
datas = open(args.data).read().splitlines()
datas = [i for i in datas if len(i) > 0]
print(f"total account : {len(datas)}")
while True:
tasks = [
Tethertod(
q,
click_min,
click_max,
interval... | Python | 1 |
'ylen'][i] + 1, dtype=np.int32)
p = self.df['trigger_points'][i]
trigger_points[:len(p)] = p - 1 # 0-indexed
# speacial treatment for the last token
trigger_points[len(p) - 1] = min(trigger_points[len(p) - 1], xlen - 1)
# NOTE: <eos> is not treated here
... | Python | 1 |
Sym.setCategory("C32")
defSym.setKey("extra-include-directories")
defSym.setValue( '{0}'.format(targetPath))
defSym.setAppend(True, ';')
defSym.setDependencies(CALSecFileUpdate, ["CAL_NON_SECURE"])
AddFilesDir(tngComponent, configName, 'app/tng')
# List of Certificates that will be included b... | Python | 1 |
. An example would be a request id
pub fn set_property(
&mut self,
name: impl Into<String>,
value: impl Into<Value>,
) {
self.context.set_property(name, value);
}
/// Adds a dimension.
/// This is generally a low cardinality key-value pair that is part of the metric ... | Rust | 0 |
#
# synctool.parallel.py WJ114
#
# synctool Copyright 2024 Walter de Jong <walter@heiho.net>
#
# synctool COMES WITH NO WARRANTY. synctool IS FREE SOFTWARE.
# synctool is distributed under terms described in the GNU General Public
# License.
#
'''do things in parallel. This module is very UNIX-only, sorry... | Python | 1 |
Instruction types
#[cfg(target_arch = "bpf")]
use solana_sdk::program::invoke_signed;
use solana_sdk::{
instruction::{AccountMeta, Instruction},
program_error::ProgramError,
pubkey::Pubkey,
};
use std::mem::size_of;
/// fee rate as a ratio
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub ... | Rust | 0 |
'リィンのSTRが#3C100#2C上がった!',
TxtCtl.ShowAll,
TxtCtl.Enter,
),
)
WaitForMsg()
OP_25(0x00)
Jump('loc_29830')
def _loc_29746(): pass
label('loc_29746')
OP_48(0x00, 0x0000, 0x0066, 0x0064)
OP_23(0x05, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0x00)
Talk(
... | Python | 1 |
ource = """
namespace Foo {
namespace Bar { class Forward; }
namespace Baz {
class Test {
public:
virtual void Foo();
};
} // namespace Baz
} // namespace Foo
"""
expected = """\
namespace Foo {
namespace Baz {
class MockTest : public Test {
public:
MOCK_METHOD0(Foo,
void());
};
} // namespace Baz
} // n... | Python | 1 |
S r SSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSK J
r
Jr SSKr
SSKr SSKrSSKJr SSKJr Sr\R, " \5 \R. " \5 : a Sr/ SQrSr\R6 " S 5 =( d S
... | Python | 1 |
::en));
eprintln!("max-size {}", max_size.to_formatted_string(&Locale::en));
eprintln!("RustCrypto {}", newhash);
eprintln!("rootdir {}", dir);
}
let mut filesizes = BTreeMap::<u64, Vec::<String>>::new();
let tree = WalkDir::new(dir).into_iter();
for e in tree.filter_map(|e| e.... | Rust | 0 |
dogenous and exogenous variables
model.swap(var1=m,var2=shock_names)
else:
model.mapSwap = None
# Simulate the alternative scenario
y,dates = run(model=model)
rows,columns = y.shape
results = {}
for j in rang... | Python | 1 |
ap => 7,
ExdQualifiers::AverageLap => 8,
ExdQualifiers::ToDestination => 9,
ExdQualifiers::ToGo => 10,
ExdQualifiers::ToNext => 11,
ExdQualifiers::NextCoursePoint => 12,
ExdQualifiers::Total => 13,
ExdQualifiers::ThreeSecondAverage => 1... | Rust | 0 |
-11-09T11:48:46.000Z",
"id": "1458038855005782017",
"lang": "ja",
"text": "next stream→【KIARAOKE ENDURANCE】\n\nThe next milestone is close!\n1.25 million, can we do it?!\nI will try to sing as long as possible to reach it!!!!\n125万人が近い...いけるのかな!?耐久... | Rust | 0 |
;
pub const WINPTY_ERROR_AGENT_CREATION_FAILED: u32 = 8;
pub const WINPTY_FLAG_CONERR: u64 = 1;
pub const WINPTY_FLAG_PLAIN_OUTPUT: u64 = 2;
pub const WINPTY_FLAG_COLOR_ESCAPES: u64 = 4;
pub const WINPTY_FLAG_ALLOW_CURPROC_DESKTOP_CREATION: u64 = 8;
pub const WINPTY_MOUSE_MODE_NONE: u32 = 0;
pub const WINPTY_MOUSE_MODE... | Rust | 0 |
import ctypes # 파이썬 extension을 사용하기 위한 모듈
import platform
import time
path = 'C:\\Users\\PMKJun\\source\\repos\\logLoader\\x64\\Debug\\logLoader.dll'
c_module = ctypes.windll.LoadLibrary(path)
print(c_module)
filesizeLoad = c_module.filesizeLoad
filesizeLoad.argtypes = [ctypes.c_char_p]... | Python | 1 |
mut self) -> Option<&mut EsAggregation> {
self.aggs.as_mut()
}
fn aggs(&self) -> Option<&EsAggregation> {
self.aggs.as_ref()
}
fn aggs_clear(&mut self) {
self.aggs = None;
}
fn aggs_init(&mut self) {
self.aggs = Some(HashMap::new());
}
fn set_aggs(&mut... | Rust | 0 |
= 1;
if takes_input {
ncurses::refresh();
}
}
if takes_input {
ncurses::endwin();
}
Ok(output)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hello_world() {
let program = String::from("++++++++[>++++[... | Rust | 0 |
94563
"""
d_rl_losses = []
d_fk_losses = []
d_losses = []
g_adv_losses = []
g_mse_losses = []
g_l2_losses = []
g_losses = []
key_word = ["d_rl_loss", "d_fk_loss", "d_loss",
"g_adv_loss", "g_mse_loss", "g_l2_loss", "g_loss"]
losses = {key_word[0]: d_rl_losses,
... | Python | 1 |
data.animal.base.rotation[0],
pitch: data.animal.base.rotation[1],
})
.unwrap_or_default(),
EntityInit::Player,
);
client.set_network_id(*builder.get::<NetworkId>().unwrap());
if player_data.is_err() {
debug!("{} is a new player", client.username())
... | Rust | 0 |
es_to_list_of_steps_to_create(step_names=step_names, channel=channel)
if len(step_names) > 0:
# Create folder for new version and add a step file for each dataset.
create_steps(channel=channel, step_names=step_names)
# Generate dictionary of new step dependencies.
dag_steps = creat... | Python | 1 |
ess/weak.pdf
pub struct FirstMoveAI {
}
impl FirstMoveAI {
pub fn new() -> FirstMoveAI {
FirstMoveAI {
}
}
}
impl PlayerController for FirstMoveAI {
fn name(&self) -> String {
"FirstMove".to_string()
}
fn play(&self, color: Color, board: &Board) -> Option<Move> {
... | Rust | 0 |
c
def docs_iter(self):
# Otherwise, only build it if needed
return LazyDocsIter(lambda: iter(self.docs_store()), self._iter())
@lru_cache()
def docs_count(self):
counts = [mapping.docs.docs_count() for mapping in self._docs_mapping]
if any(count is None for count in counts)... | Python | 1 |
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QColor
from PyQt5.QtWidgets import QHBoxLayout
from PyQt5.QtWidgets import QVBoxLayout
from qfluentwidgets import CardWidget
from qfluentwidgets import Slider
from qfluentwidgets import CaptionLabel
from qfluentwidgets import StrongBodyLabel
class SliderCard(CardWid... | Python | 1 |
ith_key)
assert pem_objects[0]['type'] == 'CERTIFICATE'
assert pem_objects[1]['key_type'] == 'rsa'
assert not pem_objects[1]['key_enc']
@pytest.mark.parametrize(
"var_str",
[
'{"a": "b"}',
'---\na: b\nc: d',
'',
'""',
],
)
def test_valid_vars(var_str):
vars_... | Python | 1 |
}
}
false
}
pub fn parse_target_names(bam_file: &String) -> Result<Vec<String>> {
let bam = bam::Reader::from_path(bam_file).chain_err(|| ErrorKind::BamOpenError)?;
let header_view = bam.header();
let target_names_dec: Vec<&[u8]> = header_view.target_names();
let mut target_names: Vec<... | Rust | 0 |
x0008_0000_0000_0000;
const DRUNK_WORLD = 0x0010_0000_0000_0000;
const DOWNED_EMPRESS_OF_LIGHT = 0x0020_0000_0000_0000;
const DOWNED_QUEEN_SLIME = 0x0040_0000_0000_0000;
const GET_GOOD_WORLD = 0x0080_0000_0000_0000;
const TENTH_ANNIVERSARY_WORLD = 0x0100_0000_0000_0000;
}
}
... | Rust | 0 |
if !update_ds.exists() {
return Err(BuildError::MissingFile(update_ds));
}
let update_prgs =
prebuilt_dir.join(&self.update_prgs_path().file_name().unwrap());
if !update_prgs.exists() {
return Err(BuildError::MissingFile(update_prgs));
}
let ... | Rust | 0 |
# vim: set expandtab shiftwidth=4 softtabstop=4:
# === UCSF ChimeraX Copyright ===
# Copyright 2022 Regents of the University of California. All rights reserved.
# The ChimeraX application is provided pursuant to the ChimeraX license
# agreement, which covers academic and commercial uses. For more details, see
# <http... | Python | 1 |
* const PCapHandle, buf: * const u8, size: c_int) -> c_int,
pcap_geterr: unsafe extern "C" fn (handle: * const PCapHandle) -> * const c_char,
pcap_next: unsafe extern "C" fn (handle: * const PCapHandle, header: * mut PCapPacketHeader) -> * const u8,
}use std::mem;
use winapi::{
ctypes::c_int,
um::winuser::... | Rust | 0 |
import re
def safe_format(fmt, **kwargs):
"""
Function that safely formats strings with arbitrary potentially user-supplied format strings
Looks for interpolation placeholders like {target} or {{ target }}
"""
return re.sub(
r"\{?\{([^{}]*)\}\}?", lambda m: kwargs.get(m.group(1).strip(), m... | Python | 1 |
sert!(course_2_instance_1.is_ok());
let course_1_instance_2 = insert(
tx.as_mut(),
NewCourseInstance {
id: Uuid::new_v4(),
course_id: course_1_id,
name: None,
description: None,
variant_status: None,
... | Rust | 0 |
# Copyright (c) 2020 kitsune.ONE team.
# This program 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 Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed i... | Python | 1 |
EdwardsPoint;
fn mul(self, scalar: &'b Scalar) -> EdwardsPoint {
scalar_mul::variable_base::mul(self, scalar)
}
}
impl<'a, 'b> Mul<&'b EdwardsPoint> for &'a Scalar {
type Output = EdwardsPoint;
fn mul(self, point: &'b EdwardsPoint) -> EdwardsPoint {
point * self
}
}
#[cfg(feature ... | Rust | 0 |
logging.warning('[X] Loop detected, skipping JUMP 0x%x' % jump_addr)
logging.warning('[X] push_instr.ssa %s' % push_instr.ssa.format())
halt = True
halt = True
elif op in ['PC', 'MSIZE', 'GAS']:
# SSA STACK
instr.ssa = SSA(new_assignement=s... | Python | 1 |
# Databricks notebook source
# MAGIC %md
# MAGIC # Model Adaptation Demo
# MAGIC ## Fine-tuning a European Financial Regulation Assistant model
# MAGIC
# MAGIC In this demo we will generate synthetic question/answer data about Capital Requirements Regulation and after that will use this data to dine tune the Llama 3.0 ... | Python | 1 |
,
vocab_layer_norm,
vocab_projector,
}
}
/// Forward pass through the model
///
/// # Arguments
///
/// * `input_ids` - Optional input tensor of shape (*batch size*, *sequence_length*). If None, pre-computed embeddings must be provided (see `input_embeds`)
//... | Rust | 0 |
)> = Vec::new();
for (k, v) in map.iter() {
out.push((*k, *v));
}
out.sort_by(|x, y| x.1.cmp(&y.1));
out
}
pub fn count_pairs(input: &Vec<char>) -> HashMap<(char, char), usize> {
let mut map: HashMap<(char, char), usize> = HashMap::new();
for c in input.windows(2) {
map.entry((... | Rust | 0 |
from os import listdir, rmdir
from os.path import isfile, join
from pathlib import Path
from PIL import Image
import json
import urllib.request
import shutil
import zipfile
current_icons_path = '../CoinTicker/Assets.xcassets/Icons'
remote_icons_path = 'https://github.com/spothq/cryptocurrency-icons/archive/master.zip'... | Python | 1 |
ime/5)
>>> x = carrier + noise
Compute and plot the STFT's magnitude.
>>> f, t, Zxx = signal.stft(x, fs, nperseg=1000)
>>> plt.pcolormesh(t, f, np.abs(Zxx), vmin=0, vmax=amp, shading='gouraud')
>>> plt.title('STFT Magnitude')
>>> plt.ylabel('Frequency [Hz]')
>>> plt.xlabel('Time [sec]')
>>> plt.show()
Compare the en... | Python | 1 |
ILearningModelBindingPreview}
impl RtActivatable<ILearningModelBindingPreviewFactory> for LearningModelBindingPreview {}
impl LearningModelBindingPreview {
#[inline] pub fn create_from_model(model: &LearningModelPreview) -> Result<LearningModelBindingPreview> {
<Self as RtActivatable<ILearningModelBindingPr... | Rust | 0 |
nt: u32 = 0;
while get_cycle_count().wrapping_sub(start) < cycles {
loop_count += 1;
}
print_info(x, loop_count, &mut prev_ccount);
// comment out next line to check watchdog behavior
watchdog.feed();
... | Rust | 0 |
(
user_id,
h["symbol"],
h["company_name"],
h["shares"],
h["avg_price"],
h.get("sector"),
)
for h in portfolio_data
],
)
conn.commi... | Python | 1 |
region.height() as i32,
format as u32,
data_type as u32,
data.as_ptr() as *const _,
);
}
}
}
pub fn retrieve(&self, data: &mut [u8]) {
if self.size.area() * 4 > data.len() {
return;
... | Rust | 0 |
/// # extern crate rustc_hash;
/// use rustc_hash::FxHasher;
/// use coca::{arena::Arena, collections::ArenaDirectMappedCache};
/// use core::{hash::BuildHasherDefault, mem::MaybeUninit};
///
/// # fn test() -> Option<()> {
/// let mut backing_region = [MaybeUninit::uninit(); 1024];
/// let mut arena = Arena::from(&m... | Rust | 0 |
are. However, the information kiosk designers at Easter Bunny HQ were not expecting to deal with a master cryptographer like yourself.
To decrypt a room name, rotate each letter forward through the alphabet a number of times equal to the room's sector ID. A becomes B, B becomes C, Z becomes A, and so on. Dashes become... | Rust | 0 |
def step(self, optimizer, scheduler, update=True):
"""
Performs one step of the optimizer.
:param loss: value of loss function
:param optimizer: optimizer
:param update: if True executes weight update
"""
if update:
if self.grad_clip != float('inf'):
... | Python | 1 |
for vaddr in vaddrs]
return sections
else:
raise ValueError
return None
def vaddr_to_file_offset(self, vaddrs):
"""
Transform virtual address to file offset
:param vaddrs: addr string or int or list
:returns file offset or list
"""
... | Python | 1 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import List
from uuid import uuid4
import aiounittest
from botframework.streaming import PayloadStream, StreamingRequest
from botframework.streaming.payloads import SendOperations
from botframework.streaming.pay... | Python | 1 |
alid or |buffer| is NULL. If |length| is"]
#[doc = " less than the returned length, or |buffer| is NULL, |buffer| will"]
#[doc = " not be modified."]
pub fn FPDF_VIEWERREF_GetName(
document: FPDF_DOCUMENT,
key: FPDF_BYTESTRING,
buffer: *mut ::std::os::raw::c_char,
... | Rust | 0 |
buffer.next_syllable(0);
while start < buffer.len() {
reorder_syllable(plan, start, end, buffer);
start = end;
end = buffer.next_syllable(start);
}
}
#[no_mangle]
pub extern "C" fn rb_complex_khmer_setup_masks(
_: *const ffi::hb_shape_plan_t,
buffer: *mut ffi::rb_buffer_t,
... | Rust | 0 |
)
} else {
NaiveDate::from_str(&s)
.map(|d| Some(d))
.map_err(serde::de::Error::custom)
}
// let s = String::deserialize(deserializer)?;
// if s.is_empty() {
// Ok(None)
// } else {
// NaiveDate::from_str(&s)
// .map(|d| Some(d))
// ... | Rust | 0 |
"""
@fileoverview This module defines essential data structures for the research workflow.
It includes classes for handling Tavily search inputs, document clustering, and report evaluation.
"""
from pydantic import BaseModel, Field
from typing import List, Optional
class TavilyQuery(BaseModel):
"""
Represents... | Python | 1 |
'''
f=open('sample_file.txt','r')
if f:
print('file successfully opened..')
f=open('sample_file.txt',mode='w')
if f:
print('file successfully opened...')
'''
# Other Arguments for opening
# f=open('sample_file.txt', 'r', 10, 'utf-8')
f = open('sample_file.txt', mode='r', buffering=10, encoding='utf-8')
if... | Python | 1 |
received"]
#[doc = " VLAN packets tagged with a given VLAN Tag Identifier."]
#[doc = ""]
#[doc = " @param port_id"]
#[doc = " The port identifier of the Ethernet device."]
#[doc = " @param vlan_id"]
#[doc = " The VLAN Tag Identifier whose filtering must be enabled or disabled."]
#[doc =... | Rust | 0 |
memmem_search(ten_words, full_text, true);
aho_corasick_seach(ten_words, full_text, true);
}
<reponame>teratide/narrow
/// Subtrait for primitive types.
///
/// This exists to use as trait bound where one or more of the supertraits of
/// this trait are required, and to restrict certain implementations to Arrow
///... | Rust | 0 |
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.mail import send_mail
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
import stripe
from .models import StripeWebhookResponse
User = get_user_model()
stripe.api_key = settings.S... | Python | 1 |
, is_static)),
a if a == hash(9) => Some(Blake2F::execute(input, target_gas, context, is_static)),
// nor Ethereum precompiles :
a if a == hash(1024) => {
Some(Sha3FIPS256::execute(input, target_gas, context, is_static))
}
a if a == hash(1025) => Some(Dispatch::<R>::execute(
... | Rust | 0 |
ListRequest {
usergroup: "S0604QSJC".to_string(),
team_id: Some("T1234567890".to_string()),
include_disabled: Some(true),
};
let mut mock = MockSlackWebAPIClient::new();
mock.expect_post_json().returning(|_, _, _| {
Ok(r##"{
"ok": true,
"users... | Rust | 0 |
.emulate_frame();
out += &t.debug_port().take_text();
}
// Release all sequential
for k in &keys {
t.emulator().send_kempston_key(*k, false);
t.sync_target();
t.emulate_frame();
out += &t.debug_port().take_text();
}
expect![[r#"00,01,03,07,0F,1F,3F,7F,FF,FE,... | Rust | 0 |
# Copyright (c) 2010-2011 Joshua Harlan Lifton.
# See LICENSE.txt for details.
"""Plover: Open Source Stenography Software"""
if __name__ == "plover":
from plover.i18n import Translator
_ = Translator(__package__)
else:
# exec from `setup.py`, package data
# may not be available, and we don't
# w... | Python | 1 |
solve_part1() {
assert_eq!(solve_part1(), 8111);
}
#[test]
fn test_solve_part2() {
assert_eq!(solve_part2(), 22088);
}
}
fn main() {
println!("{}", solve_part1());
println!("{}", solve_part2());
}
<filename>src/main.rs
//! ``ppcasm`` - A PowerPC disassembler.
// Integer Instru... | Rust | 0 |
by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
//! # Kinematics (... | Rust | 0 |
# Numeros cercanos codigo compacto
"""
Escribe un programa en el que dados 5 números enteros solicitado al usuario, determine cuál de los 4
números enteros Está más cerca del primero.
"""
number_1 = int(input("Primer numero: "))
numbers = [int(input(f"Numero {i + 2}: ")) for i in range(4)]
subtractions = [number_... | Python | 1 |
import requests
import re
import socket
def verify_login(url, valid_lock, valid_template_lock, verbose = False):
found = False
res = requests.post(url + "/login", verify=False, data={"username":"admin@xormon.com", "password":"xorux4you"})
hostname = None
try:
pattern = r'https?://(.*):'
... | Python | 1 |
tor)
self.client.force_login(org1_manager)
with self.subTest("test user list"):
path = reverse("users:user_list")
with self.assertNumQueries(9):
r = self.client.get(path)
self.assertEqual(r.status_code, 200)
self.assertNotIn("is_superuser"... | Python | 1 |
self, descriptor_sets: I)
where
I: Iterator<Item = DescriptorSet>,
{
let sets_iter = descriptor_sets.map(|d| d.raw);
inplace_or_alloc_from_iter(sets_iter, |sets| {
self.device.raw.free_descriptor_sets(self.raw, sets);
})
}
unsafe fn reset(&mut self) {
... | Rust | 0 |
me", path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
class FunctionResult(TypedDict):
keep: bool
execution_result: str
def execute_from_response(
function: Callable, call_answer: Union[Dict[str, Any], None]
) -> FunctionResult:
"""Execut... | Python | 1 |
mes::mod1::Struct2>>
// gdb-command:whatis generic_ref_trait
// gdb-check:type = struct &Trait2<type_names::Struct1, type_names::Struct1>
// gdb-command:whatis generic_mut_ref_trait
// gdb-check:type = struct &mut Trait2<type_names::mod1::mod2::Struct3, type_names::GenericStruct<usize, isize>>
// BARE FUNCTIONS
// ... | Rust | 0 |
mm_movemask_epi8(tmp_v3) as u64;
*structurals = !(structural_res_0
| (structural_res_1 << 16)
| (structural_res_2 << 32)
| (structural_res_3 << 48));
let tmp_ws_v0: __m128i = _mm_cmpeq_epi8(
_mm_and_si128(v_v0, whitespace_shufti_m... | Rust | 0 |
/ 2 # xy center to top-left corner
for p, b in zip(pred.tolist(), box.tolist()):
jdict.append({'image_id': image_id,
'category_id': coco91class[int(p[5])] if is_coco else int(p[5]),
'bbox': [round(x, 3) for x in b]... | Python | 1 |
("나이", type="number", placeholder="나이를 입력하세요")
if age:
st.info(f"입력된 나이: {age}")
with col2:
linear_input("비활성화된 입력", disabled=True, placeholder="비활성화됨")
linear_divider()
# 5. 알림 컴포넌트 데모
st.markdown("## 🔔 알림 (Alert)")
st.markdown("사용자에게 중요한 정보나 상태를 알리는 알림 컴... | Python | 1 |
import json
import logging
from fastapi import HTTPException
import httpx
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("ollama_service")
async def get_generated_text(prompt: str, text: str, model: str):
url = "http://localhost:11434/api/generate"
final_prompt = f"""
{prompt}
<te... | Python | 1 |
_ref().map_or(0, |m| 1 + sizeof_len((m).get_size()))
+ self.labels.as_ref().map_or(0, |m| 1 + sizeof_len((m).get_size()))
+ self.container_status.as_ref().map_or(0, |m| 1 + sizeof_len((m).get_size()))
+ self.unreachable_time.as_ref().map_or(0, |m| 1 + sizeof_len((m).get_size()))
+ self.l... | Rust | 0 |
(Tensor): (bs, c, h, w)
weight (Tensor): (bs, num_query, 1, n_points*group)
n_points (int): 32
Return:
out (Tensor): (bs, n_queries, n_groups, n_points, c//n_groups)
'''
B1, n_queries, _t, n_groups_points, _ = sample_points.shape
assert _t == 1
B2, C_feat, H_feat, W_feat = v... | Python | 1 |
&[|r: Bindings| {
assert_eq!(r.get(&sym!("x")).unwrap(), &term!(1));
assert_partial_expression!(r, "y", "1 > _this");
Ok(())
}],
)
}
#[test]
fn test_grounding_not_2() -> TestResult {
test_grounding(
r#"
f(x)... | Rust | 0 |
es = Some(CacheValues::new(utc_time, is_leap_second));
self.stored_key = cache_key;
}
TimeDate::new(
self.cache_values.as_mut().unwrap(),
reduced_nanosecond,
millisecond,
)
}
}
macro_rules! impl_cache_fields_getter {
( $($field:ident: $ty... | Rust | 0 |
from mmdet.models import BatchFixedSizePad, DetDataPreprocessor, MSELoss
from mmengine.config import read_base
from seg.models.detectors import BackboneDistillation
from seg.models.backbones import OpenCLIPBackbone, SAMBackbone
from seg.models.necks import LastLayerNeck
from seg.models.necks.transformer_neck import Mu... | Python | 1 |
ile at `src` into `dest`
pub fn decompress_file(src: &Path, dest: &Path, opts: DecompressOptions) -> Result<()> {
let mut reader = BufReader::new(File::open(src)?);
if opts.no_emit {
let mut writer = sink();
decompress::decompress(&mut reader, &mut writer, &opts)?;
} else {
let mut ... | Rust | 0 |
from cs_flickrgallery.testing import ACCEPTANCE_TESTING
from cs_flickrgallery.testing import FUNCTIONAL_TESTING
from cs_flickrgallery.testing import INTEGRATION_TESTING
from pytest_plone import fixtures_factory
pytest_plugins = ["pytest_plone"]
globals().update(
fixtures_factory((
(ACCEPTANCE_TESTING, "... | Python | 1 |
"""Tokenize radiology report impressions and save as a list."""
from tqdm import tqdm
def get_impressions_from_pandas(df):
"""Get the report impressions from a pandas DataFrame and clean them."""
imp = df["Report Impression"]
imp = imp.str.strip()
imp = imp.replace(r"\n", " ", regex=True)
imp = i... | Python | 1 |
] = '(?P<commit>[0-9a-f]{7,40})'
str_fields['commit_number'] = '(?P<commit_number>[0-9]{1,7})'
str_fields['tag_number'] = '(?P<tag_number>[0-9]{1,5})'
# escape parenthesis in fields in order to not messa up the regexp
fixed_fields = dict([(k, v.replace('(', r'\(').replace(')', r'\)')) for k, v in kwargs... | Python | 1 |
depth = x.W.shape[1]
filter_shape = (x.W.shape[-2], x.W.shape[-1])
strides = attributes["strides"][-1]
# check for squre strides for now.
assert(strides == attributes["strides"][-2])
padding =attributes["autoPadding"]
... | Python | 1 |
() -> NameMap<T> {
NameMap{values: Vec::new()}
}
/// Lowers the map into a `NameMapSlice`, which may not receive new
/// key-value pairs, but can overwrite existing values.
pub fn into_slice(self) -> NameMapSlice<T> {
NameMapSlice::new(self.values.into_boxed_slice())
}
/// Remo... | Rust | 0 |
go.Figure()
colors = ["blue", "red", "green", "orange", "purple"]
for i, (metric_name, metric_data) in enumerate(risk_metrics.items()):
color = colors[i % len(colors)]
fig.add_trace(
go.Scatter(
x=dates,
y=metric_data,
mode="lines+m... | Python | 1 |
pub lcdm18w: LCDM18W,
#[doc = "0x34 - LCD Memory 20/21"]
pub lcdm20w: LCDM20W,
#[doc = "0x36 - LCD Memory 22/23"]
pub lcdm22w: LCDM22W,
#[doc = "0x38 - LCD Memory 24/25"]
pub lcdm24w: LCDM24W,
#[doc = "0x3a - LCD Memory 26/27"]
pub lcdm26w: LCDM26W,
#[doc = "0x3c - LCD Memory 28/2... | Rust | 0 |
writer,
"{} {} {}",
cast_pixel(color.x()),
cast_pixel(color.y()),
cast_pixel(color.z()),
)?;
Ok(())
}
#[derive(Debug, Clone)]
pub struct Ray {
pub origin: Vector,
pub direction: Vector,
}
impl Ray {
pub fn new(origin: Vector, direction: Vector) -> Ray {
... | Rust | 0 |
questions: 1,
answers: 0,
nameservers: 0,
additional: 0,
});
assert_eq!(packet.questions.len(), 1);
assert_eq!(packet.questions[0].qtype, QT::A);
assert_eq!(packet.questions[0].qclass, QC::IN);
assert_eq!(&packet.questions[0].qname.... | Rust | 0 |
izes on the wire. All
/// sizes are enforced during serialization. Attempting to write past the end of a delimited region
/// or leaving a delimited region less than fully written raises an error.
///
/// ### Struct prefixes
///
/// Structs may have an embedded size prefix on the wire. The struct must implement
... | Rust | 0 |
they've been
//! defined. And finally, an RHS operation's operands must be defined before
//! the RHS operation itself. In general, definitions must come before uses!
//!
//! * Shorter increment chains are better! This means fewer tests when matching
//! left-hand sides, and a more-compact, more-cache-friendly a... | Rust | 0 |
E, 0xFE1E,
0x6Ea3,
0xFE1E,
];
assert_asm_bitpatterns(&asm, &expected);
// No remainder here
let asm2 = "LD I, 0x11FD".to_string();
let expected2: Vec<u16> = vec![
0xAFFF,
0x6EFF,
0xFE1E, 0xFE1E,
];
asse... | Rust | 0 |
# 3.Acceder y modificar elementos: Utiliza índices para acceder a elementos específicos en listas, tuplas o diccionarios. También puedes modificar los valores de los elementos si es necesario.
# Persona
perfil_persona = { "nombre": "Juan", "edad": 30, "ciudad": "Madrid", "profesion": "Ingeniero"}
# Acceder a un valo... | Python | 1 |
(SELECT * FROM event WHERE event.room_id = $1 AND deleted_at IS NULL)
AS event
FULL OUTER JOIN
(SELECT * FROM change WHERE change.edition_id = $3)
AS change
ON change.event_id = event.id
WHERE
((e... | Rust | 0 |
model_rows.append(res)
if model_rows:
mod_csv = os.path.join(args.outdir, 'diab_genotype_models.csv')
pd.DataFrame(model_rows).to_csv(mod_csv, index=False)
print(f"Saved diabetes×genotype model index: {mod_csv}")
# Predictor histograms
for pred in PREDICTORS:
if pred... | Python | 1 |
...
11 |> }
|> - immutable borrow ends here
"#[1..]);
}
#[test]
fn overlapping() {
let file_text = r#"
fn foo() {
vec.push(vec.pop().unwrap());
}
"#;
let cm = Rc::new(CodeMap::new());
let foo = cm.new_filemap_and_lines("foo.rs", file_text);
let span0 = cm.span_substr(&foo, file_text, "vec.pus... | Rust | 0 |
t_full_shape(output_channels);
let k = kernel.len() / output_channels;
let m = output_channels;
let n = patch.output_spatial_shape.iter().product();
let kernel = kernel.to_shared();
let kernel: Array2<D> = if kernel_is_hwio {
let mut permutation: Vec<usize> = vec![k... | Rust | 0 |
let mut out = Vec::new();
patch(&mut Cursor::new(DATA), &mut Cursor::new(dlt), &mut out).unwrap();
// check that patched version is the same as DATA2
let out_str = from_utf8(&out).unwrap();
assert_eq!(out_str, DATA2);
}
}
<filename>src/common/models/mod.rs
pub mod addresses;
pub mo... | Rust | 0 |
, consumer: C) -> C::Result
where
C: Consumer<Self::Item>,
{
bridge(self, consumer)
}
fn len(&self) -> usize {
self.slice.len() / self.chunk_size
}
fn with_producer<CB>(self, callback: CB) -> CB::Output
where
CB: ProducerCallback<Self::Item>,
{
c... | Rust | 0 |
local_max = 0;
}
}
}
max
}
#[test]
fn example_1() {
let nums1 = vec![1, 2, 3, 2, 1];
let nums2 = vec![3, 2, 1, 4, 7];
assert_eq!(find_length(nums1, nums2), 3)
}
#[test]
fn example_2() {
let nums1 = vec![0, 0, 0, 0, 0];
let nums2 = vec![0, 0, 0, 0, 0];
... | Rust | 0 |
t.route('/api/posts/add', methods=['POST'])
def create_post():
json_data = request.get_json()
r = requests.request('GET', 'http://localhost/api/posts/get')
manager = PostManager()
# title, caption = json_data.get('title'), json_data.get('caption')
# post_data = {'title':title,'caption':caption}
# post = Post(titl... | Python | 1 |
::error::Error>> {
let out_dir = std::env::var("OUT_DIR")?;
let out_dir_path = std::path::Path::new(&out_dir);
println!("OUT_DIR={}, is_dir={}", out_dir, out_dir_path.is_dir());
tonic_build::compile_protos("proto/helloworld.proto")?;
Ok(())
}
<filename>src/metadata.rs
use std::fs::read_to_string;
us... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.