text string | label_name string | labels int64 |
|---|---|---|
#[test]
fn tokenize_simple_query() {
let tokens = collect_tokens(&mut Tokenizer::new(
"
SELECT *
FROM
(
SELECT count() AS `c`
FROM events
WHERE event_type = $0
GROUP BY name
)",
));
assert_tokens_ignore_whitespace(
&tokens,
&vec![
... | Rust | 0 |
path=args.log_dir,
file_name="engine_stdout.out",
)
override_args = {}
if args.host is not None:
override_args["host"] = args.host
if args.port is not None:
override_args["port"] = args.port
if args.engine_name is not None:
override_args["engine_name"] = args... | Python | 1 |
#!/usr/bin/env python
# Created by "Thieu" at 19:52, 19/03/2022 ----------%
# Email: nguyenthieu2102@gmail.com %
# Github: https://github.com/thieu1995 % ... | Python | 1 |
import unittest
from uniflow.node import Node
from uniflow.op.basic.copy_op import CopyOp
class TestCopyOp(unittest.TestCase):
def test_call(self):
# Test with one input node
input_node = Node(name="input_node", value_dict={"x": 1})
op = CopyOp("linear_op")
op([input_node])
... | Python | 1 |
();
let res = true;
assert_eq!(Solution::parse_bool_expr(expression), res);
let expression = "|(f,t)".to_string();
let res = true;
assert_eq!(Solution::parse_bool_expr(expression), res);
let expression = "&(t,f)".to_string();
let res = false;
assert_eq!(Solution::parse_bool_expr(expressi... | Rust | 0 |
max_gmap_len, max_gmap_len).to(torch.float32)
for i in range(batch_size):
gmap_pair_dists[i, :int(batch['gmap_lens'][i].item()), :int(batch['gmap_lens'][i].item())] = batch['gmap_pair_dists'][i]
batch['gmap_pair_dists'] = gmap_pair_dists
# vp batches: vp_angles
batch['vp_lens'] = torch.Tensor([... | Python | 1 |
dump()
return query_dict
else:
raise NotImplementedError("Unsupported `Query` object parsing method: not a subclass of BaseModel.")
def parse_prediction(self, response: Response) -> AbstractModelPrediction:
content = response.content
assert content is not None, "The ... | Python | 1 |
MAX_WAITING_TICKS
}
}
pub struct ReturningWorker;
struct WorkerAtlasResource {
atlas: Handle<TextureAtlas>,
}
fn random_pos(c: &Coordinate) -> (f32, f32) {
let mut rng = thread_rng();
let (x, y) = c.to_pixel(Spacing::FlatTop(SIZE));
let radius = SIZE / 2. * 3_f32.sqrt() - 15.;
let radius = r... | Rust | 0 |
[sync] module documentation.
//!
//! [sync]: crate::sync
use crate::i386::instructions::interrupts;
use spin::{Mutex as SpinLock, MutexGuard as SpinLockGuard};
use core::fmt;
use core::mem::ManuallyDrop;
use core::ops::{Deref, DerefMut};
use core::sync::atomic::Ordering;
use super::INTERRUPT_DISARM;
/// Permanently d... | Rust | 0 |
as usize;
assert_eq!(hu % CYCLE, key as usize);
assert_eq!(hu / CYCLE, highest as usize);
loop {
hu += 1;
if hu / CYCLE >= CYCLE {
hu = 0;
}
let mut key = u32_to_vec((hu % CYCLE) as u32);
key.reverse();
let value = u32_to_vec((hu / CYCLE) as u3... | Rust | 0 |
/// Policies to be added
scalars: Vec<(u8, Scalar)>,
},
/// Calculate aggregate. The length of the `input` vector must equal the
/// number of policies.
///
/// Accounts expected by this instruction:
///
/// 0. `[writable, signer]` The user account
/// 1. `[]` The p... | Rust | 0 |
en();
for x in 0..jl {
let mut m=0;
let mut xx=0;
if x+kl>jl {
break;
}
for i in x..x+kl {
if *j.get(i).unwrap()== *k.get(xx).unwrap() {
m=m+1;
}
xx=xx+1;
}
if m==kl{
let mut lb=b' ';... | Rust | 0 |
if TransQueries.joints3d in sample:
joint_children = visualizemeshes.joint_children(
sample[TransQueries.joints3d][0].numpy()
)
scene_children = scene_children + joint_children
if TransQueries.objpoints3d in sample:
obj_chi... | Python | 1 |
# ------------------------------------------------------------------
# Copyright (c) 2025 PyInstaller Development Team.
#
# This file is distributed under the terms of the GNU General Public
# License (version 2.0 or later).
#
# The full license is available in LICENSE, distributed with
# this software.
#
# SPDX-Licens... | Python | 1 |
import os
import numpy as np
import torch
from models.IFRNet import Model
from utils import read
from imageio import mimsave
model = Model().cuda().eval()
model.load_state_dict(torch.load('./checkpoints/IFRNet/IFRNet_GoPro.pth'))
img0_np = read('./figures/img0.png')
img8_np = read('./figures/img1.png')
img0 = (torc... | Python | 1 |
Y, YY = [np.array(x) for x in train_test_split(df.values, target.values, shuffle=S)]
# X = np.vstack((X, XX))
# Y = np.hstack((Y, YY))
scores = ['accuracy', 'f1', 'precision', 'recall', 'roc_auc']
# kernel: rbf, poly, linear, sigmoid
# Create a figure to plot the learning curve
# Create a figure to plot the learning ... | Python | 1 |
ar {
let letters_num = letters.len();
let mut rng = rand::thread_rng();
let size_range = Range::new(0, letters_num);
let index = size_range.ind_sample(&mut rng);
letters[index]
}
}
pub enum Branch {
One = 0,
Two,
Three,
Four,
Five,
Six,
}
// TODO: ac... | Rust | 0 |
erializer: D) -> Result<PickupDropOffType, D::Error>
where
D: Deserializer<'de>,
{
let s: String = String::deserialize(deserializer)?;
Ok(match s.as_str() {
"" | "0" => PickupDropOffType::Regular,
"1" => PickupDropOffType::NotAvailable,
"2" => PickupDr... | Rust | 0 |
let sw = Stopwatch::start_new();
request_count += 1;
match send_osm_request(&bbox).await {
Err(s) => {
failed = true;
error_message = s;
total_downloaded_data_size = usize::MAX;
break;
... | Rust | 0 |
hould be recorded, False otherwise.
"""
# If tracing is disabled, do not record any events.
if self.level == TraceLevel.NONE:
return False
# Define minimum trace level required for each event type
event_min_levels = {
TraceEventType.VARIABLE_WRITE: TraceL... | Python | 1 |
, 31, 110, 93, 77], OperandSize::Dword)
}
#[test]
fn pcmpistri_3() {
run_test(&Instruction { mnemonic: Mnemonic::PCMPISTRI, operand1: Some(Direct(XMM5)), operand2: Some(Direct(XMM2)), operand3: Some(Literal8(32)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast... | Rust | 0 |
of Life rules are based on
// current timestep. We will use this to maintain next state.
let mut next_state = HashMap::new();
for coord_str in self.cells.keys() {
let past_cell = self.cells.get(coord_str).unwrap();
let mut living_neighbors = 0;
let coords = ... | Rust | 0 |
tinue 'file_loop,
}
}
}
}
// The last vector could be empty or partially filled.
if !inner.is_empty() {
// Whatever is is, we will end this function's work right here anyway.
let _any_result = sender.send(inner);
}
... | Rust | 0 |
def after_delete(self):
events.append("after_delete")
@contextmanager
def around_delete(self):
events.append("around_delete_before")
yield
events.append("around_delete_after")
def test_delete_hooks():
obj = DeleteModel().save()
events.clear()
obj.delete()
... | Python | 1 |
::Quote => (),
Builtin::Let => {
let ast::Let(pairs, rest) = ast.bt_let()?;
let len = pairs.len();
for ast::LetBinding(name, ..) in pairs {
self.env.defvar(name);
}
self.find(rest)... | Rust | 0 |
import cv2
import glob
img_names = glob.glob('img/*.jpg')
img_names.sort()
n = len(img_names)
out = cv2.VideoWriter('output1.avi', cv2.VideoWriter_fourcc('X', 'V', 'I', 'D'), 10.0, (1640, 1232))
log = open('img/detected_result.txt')
font = cv2.FONT_HERSHEY_SIMPLEX
RED = (0, 0, 255)
ORANGE = (0, 128, 255)
YELLOW = (0,... | Python | 1 |
"""
wsproto
~~~~~~~
A WebSocket implementation.
"""
from typing import Generator, Optional, Union
from .connection import Connection, ConnectionState, ConnectionType
from .events import Event
from .handshake import H11Handshake
from .typing import Headers
__version__ = "1.2.0"
class WSConnection:
"""
Repre... | Python | 1 |
impl REGION32_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> REGION32_A {
match self.bits {
false => REGION32_A::DISABLED,
true => REGION32_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
... | Rust | 0 |
from this json
pub fn get_country_name(iso_code: &str) -> String {
//this is not too big. It adds only 10kb to the wasm, that is already 498kb
let json = r#"[
{"name": "Afghanistan ", "code": "AF"},
{"name": "Aland Islands", "code": "AX"},
{"name": "Albania", "code": "AL"},
{"name": "Algeria", "code": "DZ"},
{"... | Rust | 0 |
///
/// assert!(!state.has::<AnotherStruct>());
/// #
/// # });
/// # }
/// ```
pub fn has<T>(&self) -> bool
where
T: StateData,
{
let type_id = TypeId::of::<T>();
self.data.get(&type_id).is_some()
}
/// Tries to borrow a value from the `State` sto... | Rust | 0 |
request: Request<Arc<State>>) -> TideResult {
#[derive(Deserialize)]
struct Parameters {
comment: String,
private: Option<bool>,
}
debug!("Performing PATCH /m/:hash_id");
ensure_login!(request);
let state = request.state().clone();
let hash_id = request.param("hash_id").exp... | Rust | 0 |
oname>JensMetzner/frustum
use frustum::{Frustum, FrustumPath, Point3, Vec3, WorldSpace};
use palette::*;
use rayon::prelude::*;
pub struct Sphere {
origin: Point3<WorldSpace>,
radius: f64,
ambient: palette::Lab,
diffuse: palette::Lab,
specular: palette::Lab,
}
impl Sphere {
pub fn intersect(
... | Rust | 0 |
#!/usr/bin/python
import os
from distutils.core import setup
import progressbar
if os.stat('progressbar.py').st_mtime > os.stat('README').st_mtime:
file('README','w').write(progressbar.__doc__)
setup(
name = 'progressbar',
version = progressbar.__version__,
description = progressbar.__doc__.splitline... | Python | 1 |
from __future__ import print_function
import tensorflow as tf
import numpy as np
import pytest
import time
funcs = {
'add': 'a + b',
'sub': 'a - b',
'div': 'a / b',
'mul': 'a * b',
'minimum': 'np.minimum(a,b)',
'maximum': 'np.maximum(a,b)',
'pow': 'np.power(a,b)',
'squared_difference':... | Python | 1 |
limit - 1` checkpoints
if len(checkpoints) >= args.checkpoints_total_limit:
num_to_remove = len(checkpoints) - args.checkpoints_total_limit + 1
removing_checkpoints = checkpoints[0:num_to_remove]
... | Python | 1 |
_ if e == RCL_RET_SERVICE_INVALID => Error::RCL_RET_SERVICE_INVALID,
_ if e == RCL_RET_SERVICE_TAKE_FAILED => Error::RCL_RET_SERVICE_TAKE_FAILED,
_ if e == RCL_RET_TIMER_INVALID => Error::RCL_RET_TIMER_INVALID,
_ if e == RCL_RET_TIMER_CANCELED => Error::RCL_RET_TIMER_CANC... | Rust | 0 |
key,
pub amount: u64
}
impl_loadable!(MangoSrmAccount);
impl MangoSrmAccount {
pub fn load_mut_checked<'a>(
program_id: &Pubkey,
account: &'a AccountInfo,
mango_group_pk: &Pubkey
) -> MangoResult<RefMut<'a, Self>> {
check_eq_default!(account.owner, program_id)?;
chec... | Rust | 0 |
mantically_different_answers = True
deberta_prediction = 0
else:
semantic_set_ids[unique_generated_texts[j]] = semantic_set_ids[unique_generated_texts[i]]
deberta_predictions.append([unique_generated_texts[i], unique_generated_texts[j], deberta_p... | Python | 1 |
from django.contrib.sites.models import Site
from django.db import models
from django.urls import NoReverseMatch, get_script_prefix, reverse
from django.utils.encoding import iri_to_uri
from django.utils.translation import gettext_lazy as _
class FlatPage(models.Model):
url = models.CharField(_("URL"), max_length... | Python | 1 |
tooltip_js = """document.addEventListener("DOMContentLoaded", function () {
const tooltip = document.createElement("div");
tooltip.id = "glyphx-tooltip";
tooltip.style.position = "absolute";
tooltip.style.background = "white";
tooltip.style.border = "1px solid #ccc";
tooltip.style.padding = "4px 8px";
too... | Python | 1 |
};
} else if eof {
return Err(Error::ExpectedEqualsSign(None));
} // else ask more data
}
b'|' => {
if let Some(b) = data.get(1) {
return Ok(if *b == b'|' {
(Some((&data[... | Rust | 0 |
) = join(subscriber, publish).await;
s_err.unwrap();
p_err.unwrap();
assert_eq!(1, received.borrow().len());
}
#[tokio::test]
async fn connection_timeout() {
let (mut subscriber, _) = make_subscriber(9, "ignored".to_owned());
subscriber.initial_timeout = Duration::from_millis(100);
let start_ti... | Rust | 0 |
ES_LIMIT = 1406
RET_INVESTIGAITON_NOT_IN_PROGRESS = 1501
RET_INVESTIGAITON_UNCOMPLETE = 1502
RET_INVESTIGAITON_REWARD_TAKEN = 1503
RET_INVESTIGAITON_TARGET_STATE_ERROR = 1504
RET_PUSH_TIPS_NOT_FOUND = 1505
RET_TOWER_NOT_OPEN = 1521
RET_TOWER_HAVE_DAILY_RECORD = 1522
RET_TOWER_NOT_RECORD ... | Python | 1 |
signatures, later on).
#[derive(Clone, Eq, Hash, RustcEncodable, RustcDecodable)]
pub struct TokenStream {
ts: InternalTS,
}
// This indicates the maximum size for a leaf in the concatenation algorithm.
// If two leafs will be collectively smaller than this, they will be merged.
// If a leaf is larger than this, ... | Rust | 0 |
t = F.normalize(query_si_feat, dim=-1)
tar_img_feat = F.normalize(tar_img_feat, dim=-1)
loss = 0
if self.si_ti_weight > 0:
si_ti_loss, sim_matrix = self.loss(query_si_feat, tar_img_feat, self.temp)
# si_ti_loss, sim_matrix = self.loss(query_si_feat, tar_imig_feat, self.t... | Python | 1 |
,
datapoints: self
.datapoints
.into_iter()
.map(|dp| {
(
dp.0.to_f64().unwrap(),
dp.1.into_iter()
.map(|y_val| y_val.to_f64().unwrap())
... | Rust | 0 |
import os
import unittest
import numpy as np
import tensorflow as tf
import anago
from anago.models import load_model
from anago.preprocessing import IndexTransformer
DATA_ROOT = os.path.join(os.path.dirname(__file__), '../data/conll2003/en/ner')
SAVE_ROOT = os.path.join(os.path.dirname(__file__), 'models')
class ... | Python | 1 |
# Check numbers
records = geo_container.records_list
entries = geo_container.entries_list
assert len(records) == len(entries)
assert len(entries) == 4
if not geo_container.has_proxies():
geo_container.build_proxies()
assert geo_container.has_proxies()
assert len(geo_container.proxies_list) == le... | Python | 1 |
nge + wait_duration;
refresh = true;
}
}
if refresh {
refresh = false;
let rumble = nsinput::RumbleData::new_with_raw( low_channel_f, low_channel_a, high_channel_f, high_channel_a );
controller.set_rumble( rumble );
let color ... | Rust | 0 |
0, 1, 1];
let exits = Interpreter::exit_states(&l, &r);
assert_eq!(exits, vec![vec![0, 1, 1, 3, 4], vec![0, 1, 1, 3]]);
let exits = Interpreter::exit_states(&r, &l);
assert!(exits.is_empty());
}
#[test]
fn entry_states() {
let l = vec![0, 1, 1];
let r = vec![0, 1, 1, 3, 4];
let entries = In... | Rust | 0 |
def main(nums):
pd = [-1] * len(nums)
pd[0] = 0
for i, element in enumerate(nums):
for j in range(i + 1 , i + element + 1 ):
if j >= len(nums) or pd[j] != -1:
continue
pd[j] = pd[i]+1
return pd[-1]
# pd = None
# def min_numers_jumps(nums, i):
# glo... | Python | 1 |
unique
)
}
}
<gh_stars>0
//
// Copyright 2018 The Project Oak 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
//
// http://www.apache.org/licenses/LICENSE-2.0
//
/... | Rust | 0 |
# Lists
print([])
a = ["Baneen", "Esha", "Esha", "Urooj", "Urooj", "Urooj", "Urooj", "Hafsa", "Hamza", "Arshad", "Talha", "Junaid", "Saaria"]
print(a)
print(a[4])
a[4] = "Hamza Faisal"
print(a)
a.sort()
print(a)
a.reverse()
print(a)
a.append("Ali")
print(a)
a.insert(2, "Taha")
print(a)
a.pop(2)
print(a)
a.remov... | Python | 1 |
# Copyright 2017 Google LLC
#
# 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, s... | Python | 1 |
from blinker.base import ANY
from blinker.base import NamedSignal
from blinker.base import Namespace
from blinker.base import receiver_connected
from blinker.base import Signal
from blinker.base import signal
from blinker.base import WeakNamespace
__all__ = [
"ANY",
"NamedSignal",
"Namespace",
"Signal"... | Python | 1 |
}
"-f" => no_auth = true,
x if x.contains('=') => {
let mut k = x.split('=');
env.insert(k.next().unwrap().to_string(), k.next().unwrap().to_string());
}
x => uname = Some(x.to_string()),
}
}
if no_auth {
if unsaf... | Rust | 0 |
shape_prefix.clone(), c_prefix_strides))
} else {
None
};
wire = patch.wire_node(
format!("{}-matmatmul", &*node.name),
lir::MatMatMulUnaryFinite {
c_trans,
bc_c_shape: geo.bc_c_shape,
c_fact: TypedFact::dt_shape(TC::datum_type(), &*geo.final_c_sha... | Rust | 0 |
updating an existing record in the database.
///
/// # Example
///
/// ```rust
/// # sqlx_crud::doctest_setup! { |pool| {
/// use sqlx_crud::Schema;
///
/// assert_eq!(r#"UPDATE "users" SET "name" = ? WHERE "users"."user_id" = ? RETURNING "users"."user_id", "users"."name""#, User::updat... | Rust | 0 |
.and_then(|_| proxy::reload())
.unwrap_or_else(|e|
error!("failed to configure proxy for camera {}: {}", camera.id, e)
);
}
info!("created new camera {}", camera.id);
Ok(Json(camera))
}
/// Retrieves information about the specified camera
fn get_camera(
... | Rust | 0 |
"""
pygments.styles.gh_dark
~~~~~~~~~~~~~~~~~~~~~~~
Github's Dark-Colorscheme based theme for Pygments
Colors extracted from https://github.com/primer/primitives
:copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.style ... | Python | 1 |
# Install required libraries (uncomment if needed)
# !pip install tensorflow
# !pip install numpy
# Import required libraries
from numpy import loadtxt
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
# Load the dataset (adjust delimiter if needed, e.g., ',' or ' ')
dataset = l... | Python | 1 |
ized, width, color='g', edgecolor='black', hatch=patterns[1])
# google_lexicon = [14.8, 1.88]
# rects3 = ax.barh(ind+width*2, google_lexicon, width, color='b', edgecolor='black', hatch=patterns[9])
# ax.set_xlabel('Percentage')
# ax.set_yticks(ind+width)
# ax.set_yticklabels( ('WER %', 'PER %') )
# # ax.set_xlim(0,25)... | Python | 1 |
new(((self.bits >> 6) & 0x03) as u8)
}
}
<gh_stars>0
extern crate openssl;
use atcoder_problems_backend::lambda::TimeSubmissionsHandler;
use lambda_runtime;
use log;
use openssl_probe;
use simple_logger;
use std::env;
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
simple_logger::init_with_l... | Rust | 0 |
"""!sysinfo use psutil to get system information"""
from datetime import datetime
import psutil
from psutil._common import bytes2human
from pyrogram import Client, filters
self_or_contact_filter = filters.create(
lambda
_,
__,
message:
(message.from_user and message.from_user.is_contact) or message... | Python | 1 |
Buf) -> Result<Input> {
let name = format!("file '{}'", Colour::Yellow.paint(path.to_string_lossy()),);
let f = File::open(path)
.map_err(|e| Error::new(e.kind(), format!("failed to open {}: {}", name, e)))?;
let stream: InputStream = match path.extension().map(|x| x.to_str()) {
Some(Some(... | Rust | 0 |
r {
"vault"
}
fn var(&mut self, secretfile: &Secretfile, credential: &str) -> Result<String> {
let loc = secretfile.var(credential).cloned();
self.get_loc(credential, loc)
}
fn file(&mut self, secretfile: &Secretfile, path: &str) -> Result<String> {
let loc = secretfile... | Rust | 0 |
from os import getenv
import psycopg2
from dotenv import load_dotenv
def create_db():
load_dotenv()
conn = psycopg2.connect(
host=getenv("DB_HOST"),
dbname=getenv("DB_NAME"),
user=getenv("DB_USER"),
password=getenv("DB_PASSWORD"),
port=getenv("DB_PORT"),
)
curs... | Python | 1 |
el_dcp(system, cpu, out) {
{
let cache_types: Vec<CacheType> = vec![
CacheType::Code,
CacheType::Data,
CacheType::Unified,
CacheType::Trace,
];
walk_intel_legacy_cache(system, cpu, out, &cache_types);
}
... | Rust | 0 |
let result = tess2::FillTessellator::new().tessellate(
&path,
&options,
&mut NoOutput::new(),
);
if !cmd.ignore_errors {
result.unwrap();
}
}
... | Rust | 0 |
(),
kmer,
count,
out: vec![],
into: vec![]
}
}
}
/// Represents a de Bruijn graph
pub struct Graph {
/// List of nodes of the graph
nodes: Vec<Node>,
/// size of the k-mers
k: usize
}
impl Graph {
/// Builds an empty graph
fn new(k: usize) -> Graph {
Graph{
nodes: V... | Rust | 0 |
nt all the potential removes should be safe to
# remove.
for barrier in potential_removes:
if barrier is not final_barrier:
barrier.detach()
def apply(self, node: Routine, **kwargs) -> None:
'''
Applies the transformation, which eliminates unneccessary
... | Python | 1 |
'🭑', 'ꪝ', '𑘰', '𒅂', '𑶇', '𝄪', 'ᘱ', '🙥', '𒔊', 'ꔺ', '🜩',
'層', '⳪', '𖥵', '𝢒', '𔐥', 'ᬜ', '⮩', '𐐠', '𜾨', 'ꡉ', '𐴖', '⯋',
'ꕖ', '𝤂', '𐚊', '𛁬', '𝃈', 'Ⲣ', 'ꕅ', '⧑', '𘤇', '𑒘', '🟗', 'ꖶ',
'ᰗ', '𘢨', 'ꘔ', '🔽', '𐅌', 'ᐰ', '𐓠', '𐂝', 'ﺏ', '🚥', '𜾸',
'🟇', '𖦪', '𐊧', '怒', 'Ẽ', '﴾', '▙', '\u... | Rust | 0 |
b2_id = "box_2"
b2_size = layout_dict[b2_id]["size"]
b2_origin = layout_dict[b2_id]["origin"]
b2_prompt = layout_dict[b2_id]["prompt"]
b2_relation = layout_dict[b2_id]["relation"]
scene.add_box(id=b2_id, size=b2_size, origin=b2_origin, prompt=b2_prompt)
b2_mask, latent_ma... | Python | 1 |
import os
import logging
import warnings
from video_llama.common.registry import registry
from video_llama.datasets.builders.base_dataset_builder import BaseDatasetBuilder
from video_llama.datasets.datasets.laion_dataset import LaionDataset
from video_llama.datasets.datasets.llava_instruct_dataset import Instruct_Data... | Python | 1 |
ADPLL_LO_UNLOCK_INTRPT_CLEAR_SEL_W { w: self }
}
#[doc = "Bit 24"]
#[inline(always)]
pub fn adpll_sfreg_sel(&mut self) -> ADPLL_SFREG_SEL_W {
ADPLL_SFREG_SEL_W { w: self }
}
#[doc = "Bit 23"]
#[inline(always)]
pub fn adpll_lo_open(&mut self) -> ADPLL_LO_OPEN_W {
ADPLL_L... | Rust | 0 |
# Algoritmo con visualización animada (usado en la graficadora)
def comb_sort(arr, draw_func, delay):
estado = draw_func.estado
n = len(arr)
gap = n
shrink = 1.3
sorted_flag = False
def paso():
nonlocal gap, sorted_flag
if estado["valor"] == "detenido":
return
... | Python | 1 |
from selenium.webdriver.common.keys import Keys
from .utils import shift
INITIAL_CELLS = ['print("a")', 'print("b")', 'print("c")']
def test_insert_cell(prefill_notebook):
notebook = prefill_notebook(INITIAL_CELLS)
notebook.to_command_mode()
notebook.focus_cell(2)
notebook.convert_cell_type(2, "markd... | Python | 1 |
");
assert!(format!("{:#o}", !0u8) == "0o377");
}
#[test]
fn test_format_int_sign_padding() {
assert!(format!("{:+5}", 1) == " +1");
assert!(format!("{:+5}", -1) == " -1");
assert!(format!("{:05}", 1) == "00001");
assert!(format!("{:05}", -1) == "-0001");
assert!(format!("{:+05}", 1) == "+0... | Rust | 0 |
class Solution:
def checkStatus(self, a, b, flag):
# Case 1: exactly one is non-negative AND flag is False
if ((a >= 0 and b < 0) or (a < 0 and b >= 0)) and (flag == False):
return True
# Case 2: both are negative AND flag is True
elif (a < 0 and b < 0) and (flag == True)... | Python | 1 |
p_mask:
datapoint = self._device.datapoints.get_or_create(
self._mapping.dp_id,
TuyaBLEDataPointType.DT_BITMAP,
self._mapping.bitmap_mask,
)
bitmap_mask = self._mapping.bitmap_mask
bitmap_value = bytes(datapoint.value)
... | Python | 1 |
"uri" => self.uri = Some(Uri::from_str(&match nv.lit {
syn::Lit::Str(ref s) => s.value(),
_ => panic!("literal is not a string"),
}).expect("URI is not valid")),
k => panic!("unknown bagger key \"{}\"", k),
}
}
fn visi... | Rust | 0 |
LOSS = []
LOSS_ioc = []
LOSS_coc = []
LOSS_rec = []
while epoch < args.con_epochs:
if epoch == 0:
with torch.no_grad():
pos_dist_mean, neg_dist_mean, false_neg_dist_mean, true_neg_dist_mean, \
pos_cosine_mean, neg_cosine_mean, false_neg_cosine_mean... | Python | 1 |
ly active VS, VP and VM.
///
/// <!-- inputs/outputs -->
/// @return Returns bsl::errc_success on success, bsl::errc_failure
/// otherwise
///
pub fn bf_vs_op_advance_ip_and_run_current(&self) -> bsl::ErrcType {
let ret: u64;
unsafe {
ret = crate::bf_vs_op_adva... | Rust | 0 |
import numpy as np
from pytest import approx, raises
from tune.priors import create_priors, make_invgamma_prior, roundflat
def test_roundflat():
assert roundflat(0.3) == approx(0.0, abs=1e-6)
assert roundflat(0.0) == -np.inf
assert roundflat(-1.0) == -np.inf
def test_make_invgamma_prior():
prior = ... | Python | 1 |
= lambda s : s[0:-ord(s[-1])]
def encryptClientBytes(pin,message):
prf = lambda p, s: HMAC.new(p, s, SHA256).digest()
key = PBKDF2(pin,hashlib.sha256(pin).digest(),32,10000,prf)
cipher = AES.new(key,mode=blockalgo.MODE_ECB)
return cipher.encrypt(pad(message))
try:
f = open("keygen","rb")
excep... | Python | 1 |
import spacy
import nltk
from nltk.tokenize import word_tokenize
import string
import json
# Download the necessary data for NLTK
nltk.download('punkt')
# Load the Chinese language model
nlp_zh = spacy.load("zh_core_web_sm")
# Load texts from translations.json
with open('translations.json', 'r', encoding='utf-8') as... | Python | 1 |
Sender<MainThreadTask>,
pub(crate) task_receiver: Receiver<MainThreadTask>,
}
impl Default for Test {
fn default() -> Self {
let (sender, receiver) =
crossbeam_channel::bounded(DEFAULT_MAIN_THREAD_TASK_CHANNEL_CAPACITY);
Self {
main_rx: Default::default(),
t... | Rust | 0 |
cense, 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, software
// distributed under the License is distribute... | Rust | 0 |
sftp_filesystem_inner(credential: Credential) -> Result<FileSystem> {
let mut properties = HashMap::new();
properties.insert(
String::from("xenon.adaptors.filesystems.sftp.strictHostKeyChecking"),
String::from("false"),
);
let filesystem = FileSystem::create(
String::from("sftp"... | Rust | 0 |
const BLOCK_LEN_MASK: u64 = 0x3f;
/// Finalizes and returns the computed MD5 hash.
pub fn md5(&self) -> [u8; 16] {
// Finalize locally.
let mut block = [0; Md5::BLOCK_LEN];
let mut state = self.state;
// The block length is the amount of data buffered for the current block.... | Rust | 0 |
-2021'])
# Run
result = formatter.format_data(column)
# Assert
try:
# Pandas 1.4 has different behavior to newer versions
# This works with lower pandas versions and casts the second string as the first format
expected = pd.to_datetime(column).dt.str... | Python | 1 |
ChrSetPos(0x0059, 19640, 5950, -14500, 270)
ChrSetPos(0x005A, 14650, 4700, -15600, 270)
ChrSetPos(0x005B, 15730, 4950, -15600, 270)
ChrSetPos(0x005C, 16860, 5200, -15600, 270)
ChrSetPos(0x005D, 17850, 5450, -15600, 270)
ChrSetPos(0x005E, 18880, 5700, -15600, 270)
ChrSetPos(0x005F, 19640, 5950, -... | Python | 1 |
ne:
# FIX: Standardized to 'turbine_id'
turbine_data = df[df['turbine_id'] == selected_turbine]
if not turbine_data.empty:
current_rul = turbine_data['rul_hours'].iloc[-1]
avg_rul = turbine_data['rul_hours'].mean()
col1.metric("Current RUL (Selected Turbine)",... | Python | 1 |
|| $rev < Revision::Spurious)
&& !ResumeDataVariant::into_account_exists_status({
yield InterruptDataVariant::AccountExists(AccountExists { address: dst })
})
.unwrap()
.exists
{
cost += 25000;
}... | Rust | 0 |
from django.urls import path
from . import views
urlpatterns = [
path('', views.TranslationListView.as_view(), name='translation-list'),
path('<int:pk>/', views.TranslationDetailView.as_view(), name='translation-detail'),
path('translate/', views.translate_text, name='translate-text'),
path('<int:trans... | Python | 1 |
ow => "**",
OMul => OMul => "*",
ODiv => ODiv => "/",
ORem => ORem => "%",
OBitInv => OBitInv => "~",
OAssignIndex => OAssignIndex => "[]=",
OIndex => OIndex => "[]",
LNum(..) => LNum => "numeric literal",
LSingleStr(..) | LDoubleStr(..) | LQNeStr(..) | LQStr(..) => LStr => "string liter... | Rust | 0 |
import numpy as nd
listone = [10, 20, 30, 40, 50, 60], [1, 2, 3, 4, 5, 6], [2, 4, 6, 8, 10, 12]
arrayone = nd.array(listone) # Data Type=float,U32,
print(type(arrayone))
print(arrayone)
import numpy as nd
arrayone = nd.arange(1,13) .reshape(3,4)
print(arrayone)
import numpy as nd
arrayone = nd.zeros(6) .reshape(2,3)... | Python | 1 |
# utils/helpers.py
from typing import Any, Dict
from django.core.paginator import Paginator
def paginate_queryset(queryset, page: int, page_size: int) -> Dict[str, Any]:
paginator = Paginator(queryset, page_size)
page_obj = paginator.get_page(page)
return {
'items': page_obj.object_list,
... | Python | 1 |
t will error.
None,
/// Specify a command to execute on lair server start.
/// This command will be fed framed json signature requests on stdin,
/// and is expected to respond to those requests with framed
/// json responses on stdout.
#[serde(rename_all = "camelCase")]
Command {
//... | Rust | 0 |
ident_table: IdentifierTable::default(),
instance_var: FxHashMap::default(),
instance_method_table: FxHashMap::default(),
method_table: FxHashMap::default(),
class_var: FxHashMap::default(),
class_method_table: FxHashMap::default(),
su... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.