text string | label_name string | labels int64 |
|---|---|---|
modifier(
action: BinaryModifierAction,
labels: Vec<String>,
group: BinaryModifierGroup,
) -> BinaryModifier {
BinaryModifier {
action,
labels,
group: Some(group),
}
}
pub fn binary_modifier_group_right(labels: Vec<String>) -> BinaryModifierGroup {
BinaryModifierGroup {
... | Rust | 0 |
c @ s d Z d d l Z e j Z d d Z d e j f d YZ d e j f d YZ d e j f d
YZ d e j f d YZ d
Z
d S( s
Python 'utf-32-le' Codec
iNt strictc C s t j | | t S( N( t codecst utf_32_le_decodet True( t ... | Python | 1 |
if device is None:
device = torch_xla.device()
tensors = xu.as_list(tensors)
cpu_tensors = [
t.clone().detach().requires_grad_(t.requires_grad) for t in tensors
]
xla_tensors = [
x.to(device).detach().requires_grad_(x.requires_grad) for x in tensors
]
cpu_results = xu.... | Python | 1 |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
def update_potential(potential, axes, cmap):
# pc_pad = np.pad(potential, pad_width=1, mode='reflect')
pc_pad = np.pad(potential, pad_width=1, mode='edge')
# pc_pad = np.pad(potential, pad_width=1, mode='constan... | Python | 1 |
: {:?}", rsp);
let rsp = client
.publish()
.topic_arn(&topic_arn)
.message("hello sns!")
.send()
.await?;
println!("published a message: {:?}", rsp);
// If you set this to your email address, you should get an email from SNS
Ok(())
}
// Copyright 2018 The Grin D... | Rust | 0 |
Type,
derived_key_size: u32,
hash_type: HashType,
tag_size: u32,
ciphertext_segment_size: u32,
) -> tink_proto::AesCtrHmacStreamingKeyFormat {
tink_proto::AesCtrHmacStreamingKeyFormat {
version: AES_CTR_HMAC_AEAD_KEY_VERSION,
key_size,
params: Some(tink_proto::AesCtrHmacStrea... | Rust | 0 |
{
CascadingFilter {
filter_1: BiquadFilter::new(params),
filter_2: BiquadFilter::new(params),
}
}
fn set_params(&mut self, params: &Self::Params) {
self.filter_1.set_params(params);
self.filter_2.set_params(params);
}
}
impl AudioFilter for Cascading... | Rust | 0 |
s.path.normpath(sys.executable)
# finalize_options ()
def run (self):
# Run all relevant sub-commands. This will be some subset of:
# - build_py - pure Python modules
# - build_clib - standalone C libraries
# - build_ext - Python extensions
# - build_s... | Python | 1 |
-> RafxResult<()> {
self.0.flush(descriptor_set_allocator)
}
}
pub mod detect;
mod has_debug_syms;
pub mod parse;
pub use has_debug_syms::has_debug_syms;
pub use parse::parse;
mod memory;
mod sleddb;
pub use memory::MemTable;
pub use sleddb::SledDb;
use crate::{KvError, Kvpair, Value};
pub trait Storage... | Rust | 0 |
iner').appendChild(activitySection);
""")
await page.wait_for_timeout(2000)
# Capture the demo results
await page.screenshot(path='screenshots/demo-complete-results.png', full_page=True)
print("📸 Captured complete demo results!")
... | Python | 1 |
import torch.nn.parallel
import torch.optim
from options.config import Config
from options.args import *
from libs.prepare import *
from libs.preprocess import *
def run(cfg, dict_DB):
preprocess = Preprocessing(cfg, dict_DB)
preprocess.run()
def main():
# option
cfg = Config()
cfg = parse_args(c... | Python | 1 |
e.clone())
}))
}
});
let addr = http_bind
.parse()
.context(format!("{} is not a valid ip config", http_bind))?;
let server = Server::bind(&addr)
.serve(make_svc)
.with_graceful_shutdown(utils::sigint(String::from("mock service")));
info!("Http serve... | Rust | 0 |
"""Model for UNLModify pseudo-transaction type."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Dict
from typing_extensions import Self
from xrpl.models.required import REQUIRED
from xrpl.models.transactions.pseudo_transactions.pseudo_transaction import (
Pseudo... | Python | 1 |
struct to receive
/// deferred calls from a `DynamicDeferredCall`.
pub trait DynamicDeferredCallClient {
fn call(&self, handle: DeferredCallHandle);
}
/// Unique identifier for a deferred call registered with a
/// [DynamicDeferredCall](crate::common::dynamic_deferred_call::DynamicDeferredCall)
#[derive(Copy, Clo... | Rust | 0 |
mRow == row {
kp1 = true;
}
if plant.mPlantCol == col + 1 && plant.base.mRow == row {
kp2 = true;
}
if kp1 && kp2 {
break;
}
}
}
if kp1 && kp2 && !(*boa... | Rust | 0 |
action_id,
accepted: accepted,
})
}
/// Get the window ID
pub fn get_window_id(&self) -> &u8 {
&self.window_id
} /// Get the action ID (nonce)
pub fn get_action_id(&self) -> &i16 {
&self.action_id
} /// get the accepted field (UNDOCUMENTED)
pub fn g... | Rust | 0 |
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 13 21:08:30 2020
@author: NNK
"""
import pyspark
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName('SparkByExamples.com').getOrCreate()
data = [("James","Smith","USA","CA"),
("Michael","Rose","USA","NY"),
("Robert","Williams","USA","CA")... | Python | 1 |
on its own line.
inline: bool,
// True if there is a trailing comma before the closing brace.
trailing_comma: bool,
}
fn find_closing_brace<T: Iterator<Item = TokenInfo>>(tokens: &mut T) -> Block {
for info in tokens.by_ref() {
if info.token.kind == TokenKind::OpenBrace {
break;
... | Rust | 0 |
Opts),
/// delete a node from chain
#[clap(name = "delete-node")]
DeleteNode(DeleteNodeOpts),
/// init node
#[clap(name = "init-node")]
InitNode(InitNodeOpts),
/// update node
#[clap(name = "update-node")]
UpdateNode(UpdateNodeOpts),
/// delete a chain
#[clap(name = "delete-c... | Rust | 0 |
overlap, valid_sequence)
scores['AUC'] = auc
scores['OP50'] = auc_curve[:, threshold_set_overlap == 0.50]
scores['OP75'] = auc_curve[:, threshold_set_overlap == 0.75]
# ******************************** Precision Plot **************************************
... | Python | 1 |
ER { bits }
}
#[doc = "Bit 16 - Output compare 1 mode bit 3"]
#[inline]
pub fn oc1m_3(&self) -> OC1M_3R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 16;
((self.bits >> OFFSET) & MASK as u32) != 0
};
OC1M_3R { bits }
}
#[do... | Rust | 0 |
number of ground state occurences
for dct in results1:
if dct["ground"]:
ground1 += 1
eng1.append(dct["energy"])
dictlist.append(
{
"pos": [list(p) for p in dct["pos"]],
"energy": dct["energy"],
"pg_init": dct["pg_init"... | Python | 1 |
len(img.shape)
if (dim == 2):
strt = ndimage.generate_binary_structure(2, 1)
else:
strt = ndimage.generate_binary_structure(3, 1) # 三维结构元素,与中心点相距1个像素点的都是邻域
ero = ndimage.morphology.binary_erosion(img, strt)
edge = np.asarray(img, np.uint8) - np.asarray(ero, np.uint8)
return edge
de... | Python | 1 |
# here the internal data ie private data of bot is bei
baseurl="https://api.telegram.org/"
TOKEN="bot7452688807:AAFewUJKZOniA8ldH9EACAh784l8KYSJE6g/"
store="-4566364009"
monitor="-1002186023307"
cloud="-1002344593355"
public="unicloudgndu"
mid="-1002474677568"
# mid area {'update_id': 771734112, 'message': {'message_i... | Python | 1 |
import trimesh
import os
from multiprocessing import Pool, current_process
import multiprocessing as mp
from tqdm import tqdm
import sys
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.dirname(current_dir))
from utils.render_utils import generate_image_for_fid
os.environ['EGL_DEVICE_I... | Python | 1 |
} => 49,
Card {
rank: Rank::Three,
suit: Suit::Diamonds,
} => 50,
Card {
rank: Rank::Two,
suit: Suit::Diamonds,
} => 51,
}
}
}
fn get_rgba8img(filename: &str) -> ImageResult<RgbaImage... | Rust | 0 |
class Solution:
def countDays(self, days: int, meetings: list[list[int]]) -> int:
today = 0
for i, j in sorted(meetings, key=lambda x: x[0]):
if j <= today:
continue
elif i > today:
days -= j - i + 1
else:
d... | Python | 1 |
e': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('dja... | Python | 1 |
null() {
let csi1 = CMap_get_CIDSysInfo(cmap);
let csi2 = CMap_get_CIDSysInfo((*cmap).useCMap);
if strcmp((*csi1).registry, (*csi2).registry) != 0
|| strcmp((*csi1).ordering, (*csi2).ordering) != 0
{
warn!(
"CIDSystemInfo mismatched {} <--> {}",
... | Rust | 0 |
self.routing_fn = nn.Linear(in_chs, self.num_experts)
def forward(self, x):
shortcut = x
pooled_inputs = F.adaptive_avg_pool2d(x, 1).flatten(1) # CondConv routing
routing_weights = torch.sigmoid(self.routing_fn(pooled_inputs))
x = self.conv_pw(x, routing_weights)
... | Python | 1 |
{
rust_ffs(i)
};
assert_eq!(ffs_ret, rust_ffs_ret);
let ffsl_ret = unsafe {
ffsl(i as i64)
};
let rust_ffsl_ret = unsafe {
rust_ffsl(i as i64)
};
assert_eq!(ffsl_ret, rust_ffsl_ret);
let ffsll_ret = unsafe {
... | Rust | 0 |
: {}", ev.etype)),
}
}
}
pub fn tb_put_string(
max_x: i32, max_y: i32,
col: i32, row: i32,
str: &str,
fg: u32, bg: u32,
wrap: bool
) -> (i32, i32) {
let mut ccol = col;
let mut crow = row;
for c in str.chars() {
unsafe {
tb_put_cell(ccol, crow, &RawCell {... | Rust | 0 |
smi_canon = Chem.MolToSmiles(
Chem.MolFromSmiles(item, sanitize=True),
isomericSmiles=False,
canonical=True,
)
if smi_canon != "":
mutated_smiles_canon.append(smi_canon)
except:
continue
mutated_sm... | Python | 1 |
"""
Implement the following operations of a stack using queues.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
empty() -- Return whether the stack is empty.
Example:
MyStack stack = new MyStack();
stack.push(1);
stack.push(2);
stack.top(); //... | Python | 1 |
#!/usr/bin/python3
"""
Integer validator
Write a class BaseGeometry (based on 6-base_geometry.py)
"""
class BaseGeometry:
"""
Docstyle for BaseGeometry
"""
def area(self):
"""
raises an Exception with the message area() is not implemented
"""
raise Exception('area() is ... | Python | 1 |
ns)} collections...")
results = await resetter.reset_collections(selected_collections)
# Display results
print("\n📋 Reset Results:")
print("=" * 40)
successful = 0
failed = 0
total_deleted = 0
for collection, result in results.items():
if r... | Python | 1 |
"The value is incorrect"
);
}
}
<reponame>wcampbell0x2a/wireshark_dissector_rs
// Copyright 2021-2021, <NAME> and the wireshark_dissector_rs contributors
// SPDX-License-Identifier: GPL-2.0-or-later
use crate::epan;
use crate::plugin;
extern crate libc;
use core::fmt::Debug;
/// The trait the dissector... | Rust | 0 |
Mx,My,Mz)
### false if it's 2D (Fx,Fy,Mz).
meanCFs= limitState.check(setCalc= None, crossSections= reinfConcreteSectionDistribution, listFile='N', calcMeanCF='Y', controller= controller)
feProblem.errFileName= "cerr" # From now on display errors if any.
feProblem.logFileName= "clog" # From now on display war... | Python | 1 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, api
class ResConfigSettings(models.TransientModel):
_inherit = 'res.config.settings'
# pos.config fields
pos_discount_pc = fields.Float(related='pos_config_id.discount_pc',... | Python | 1 |
}
Unit::FrameV2(head, FrameBody::TALB(frame)) => {
assert_eq!("<NAME>èièková a Lubomír Nohavica s klavírem",
frame.text);
let meta_writer = MetadataWriter::new("").unwrap();
let frame_bytes = meta_writer.frame((head, FrameBody::TALB... | Rust | 0 |
, ctx: &Context) -> Result<()> {
ctx.administrator()?;
let db = ctx.db.deref();
let enc = ctx.crypto.deref();
SettingDao::set::<String, Self, Crypto>(db, enc, &Self::KEY.to_string(), self, false)?;
Ok(())
}
}
impl send_email::Config {
pub fn get(ctx: &Context) -> Result<... | Rust | 0 |
verlap]
@property
def accept_json(self) -> bool:
"""True if this object accepts JSON."""
return "application/json" in self # type: ignore[comparison-overlap]
_locale_delim_re = re.compile(r"[_-]")
def _normalize_lang(value: str) -> list[str]:
"""Process a language tag for matching."""
... | Python | 1 |
import os
import json
from concurrent.futures import ThreadPoolExecutor
from tqdm import tqdm
import requests
from collections import defaultdict
PATH_TO_MAPS = "./maps"
def iterate_jsons(path_to_walk:str="."):
for dirpath, dirnames, filenames in os.walk(path_to_walk):
for filename in filenames:
... | Python | 1 |
_PtrOfStereoSGBM_get_inner_ptr, cv_PtrOfStereoSGBM_get_inner_ptr_mut
}
impl PtrOfStereoSGBM {
#[inline] pub fn as_raw_PtrOfStereoSGBM(&self) -> *const c_void { self.as_raw() }
#[inline] pub fn as_raw_mut_PtrOfStereoSGBM(&mut self) -> *mut c_void { self.as_raw_mut() }
}
impl crate::calib3d::StereoSGBMConst f... | Rust | 0 |
// DERIVES
// ------------------------------------------------------------------------------------------------
#[proc_macro_derive(Layer)]
pub fn derive_layer(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
// Check input is an enum
let variants = match input.dat... | Rust | 0 |
import sys
import evaluate
from evaluate.utils import launch_gradio_widget
sys.path = [p for p in sys.path if p != "/home/user/app"]
module = evaluate.load("coval")
sys.path = ["/home/user/app"] + sys.path
launch_gradio_widget(module)
| Python | 1 |
o_export]
macro_rules! impl_get_author {
($($t:ty),+ $(,)?) => ($(
impl<T: Config> HasAuthor<T> for $t {
fn get_author(&self) -> &T::AccountId {
&self.author
}
}
)+)
}
impl_get_author!(Comment<T::AccountId>, Ad<T::A... | Rust | 0 |
# -*- coding: utf-8 -*-
# -- stdlib --
import random
# -- third party --
# -- own --
from thb import characters
from thb.meta.common import ui_meta, N
# -- code --
@ui_meta(characters.reisen.Reisen)
class Reisen:
# Character
name = '铃仙'
title = '永琳的首席药品品尝官'
illustrator = '镜_Area@幻想梦斗符'... | Python | 1 |
(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct APIReferenceKey<K> {
id: K,
}
impl<T: APIDocument> APIReference<T> {
// CONSTRUCTORS -----------------------------------------------------------
pub fn new_key(id: T::Id) -> Self {
Self::Key(APIReferenceKey { id })
}
// GET... | Rust | 0 |
# Koko Eating Bananas
# Problem Statement: A monkey is given ‘n’ piles of bananas, whereas the ‘ith’ pile has ‘a[i]’ bananas. An integer ‘h’ is also given, which denotes the time (in hours) for all the bananas to be eaten.
# Each hour, the monkey chooses a non-empty pile of bananas and eats ‘k’ bananas. If the pile con... | Python | 1 |
};
if res == sys::SSH_OK as i32 {
Ok(bound_port as u16)
} else if let Some(err) = sess.last_error() {
Err(err)
} else {
Err(Error::fatal("error in ssh_channel_listen_forward"))
}
}
/// Accept a remote forwarded connection.
/// You ... | Rust | 0 |
, Spinner, Textbox, VectorEdit, VectorEditEvent,
};
static THEME: &'static str = include_str!("themes/panel_animated_theme.css");
#[derive(Debug, Clone, PartialEq)]
pub enum ColorEditEvent {
ColorChanged(u8, u8, u8, u8),
}
pub struct ColorEdit {
vector_edit: Entity,
rval: u8,
gval: u8,
bval: u8,... | Rust | 0 |
"""
Sets:
Sets são coleções não ordenadas de itens únicos.
"""
gamesSet = {"Fifa23", "Red Dead 2", "Star Wars", "The Legend of Zelda", "Red Dead 2"}
print(gamesSet)
print(len(gamesSet))
# 1 - True e 1 são considerados o mesmo valor
exampleSet = {"Fifa23", True, 1, 90.50}
print(exampleSet)
# 2 - Adicionando item no ... | Python | 1 |
uter_lsum = 3.0
toy_lsize = 3
toy_outer_rsum = 3.0
toy_rsize = 3
toy_five_number = np.full(5, 5.0)
stripe.set_biodescriptors(
toy_inner_mean,
toy_inner_std,
toy_outer_lsum,
toy_lsize,
toy_outer_rsum,
toy_rsiz... | Python | 1 |
result = self.nodes[0].z_mergetoaddress(["*"], myzaddr, 0, 10, 2)
assert_equal(result["mergingUTXOs"], Decimal('10'))
assert_equal(result["remainingUTXOs"], Decimal('6'))
assert_equal(result["mergingNotes"], Decimal('2'))
assert_equal(result["remainingNotes"], Decimal('0'))
... | Python | 1 |
EitherOrBoth::Right(_frame) => break,
};
unsafe {
self.page_table
.map_to(page, frame, flags, self.allocator)
.expect("failed to map page")
.flush();
... | Rust | 0 |
### Variables ###
my_string_variable = "My String variable"
print(my_string_variable)
my_int_variable = 5
print(my_int_variable)
my_int_to_str_variable = str(my_int_variable)
print(my_int_to_str_variable)
print(type(my_int_to_str_variable))
my_bool_variable = False
print(my_bool_variable)
# Concatenación de varia... | Python | 1 |
-> Vec<String> {
// data.retain(|c| !c.is_whitespace());
// let mut result : Vec<String> = Vec::new();
// for character in data.chars() {
// if (&result).len() == 0 {
// (&mut result).push(character.to_string());
// continue;
// }
// let result_length = (&... | Rust | 0 |
: &Span<'_>) {
if let Err(ref mut e) = res {
let Error::Message { location, .. } = e;
if location.is_none() {
let (line, column) = span.start_pos().line_col();
*location = Some(Location { line, column });
}
}
}
use crate::interpreter::environment::EnvironmentId;
u... | Rust | 0 |
ch common_locs {
None => { common_locs = Some(current_locs); }
Some(common) => { common_locs = Some(&common & ¤t_locs); }
}
debug!("Restricting common_locs:\n\tcommon_locs={:?}", common_locs);
continue;
}
// Don't fan out into _every_ keydoor available;
// only fan... | Rust | 0 |
_var_long(buffer: &[u8], cursor: &mut usize) -> Option<i64> {
// adapted from https://wiki.vg/Protocol#VarInt_and_VarLong
let mut value = 0i64;
let mut len = 0isize;
let mut byte: i64;
let mut cur = *cursor;
loop {
byte = buffer[cur].into();
cur += 1;
value |= (byte & 0x7... | Rust | 0 |
#!/usr/bin/env python
import argparse
import yaml
import docker
import os
from pathlib import Path
import fileinput
import sys, os, subprocess, shutil
import time
from configparser import ConfigParser
# create docker container based on Dockerfile_unique(Dockerfile_test)
#from testbuild_docker import call
# create d... | Python | 1 |
# SPDX-FileCopyrightText: Copyright (C) 2010-2011 Anders Logg
# SPDX-License-Identifier: LGPL-3.0-or-later
"""This demo program solves the incompressible Navier-Stokes equations
on an L-shaped domain using Chorin's splitting method."""
# Created by Anders Logg
# Modified by Mikael Mortensen 2011
#
# First added: 201... | Python | 1 |
om torch import distributions as d
from torchrl.objectives import ClipPPOLoss, KLPENPPOLoss, PPOLoss
set_composite_lp_aggregate(False).set()
GROUPED_ACTIONS = False
make_params = Mod(
lambda: (
torch.ones(4),
torch.ones(4),
torch.ones(4, 2),
torch.ones(4, 2),
torch.ones(4,... | Python | 1 |
down(&self) {
self.0.shutdown()
}
}
const BATCH1: &str = r#"{"serverId":s1,"batchId":1,"batch":[test1]}"#;
const BATCH2: &str = r#"{"serverId":s1,"batchId":2,"batch":[test2]}"#;
static INIT: Once = Once::new();
fn init() {
INIT.call_once(|| {
Builder::from_... | Rust | 0 |
ructor.consistency));
}
if !consts.is_empty() {
s.field("consts", consts);
}
if !type_consts.is_empty() {
s.field("type_consts", type_consts);
}
if !xhp_enum_values.is_empty() {
s.field("xhp_enum_values", xhp_enum_values);
}
... | Rust | 0 |
(ffi::g_get_user_data_dir()) }
}
#[doc(alias = "g_get_user_runtime_dir")]
#[doc(alias = "get_user_runtime_dir")]
pub fn user_runtime_dir() -> std::path::PathBuf {
unsafe { from_glib_none(ffi::g_get_user_runtime_dir()) }
}
#[doc(alias = "g_get_user_special_dir")]
#[doc(alias = "get_user_special_dir")]
pub fn user_... | Rust | 0 |
(5, 1, 9),
(5, 2, 1),
(5, 5, 3),
(6, 4, 6),
(6, 6, 9),
(7, 2, 5),
(7, 3, 7),
(8, 0, 8),
(8, 1, 2),
];
pub const VALID_SOLUTION: [(usize, usize, u8); 81] = [
(0, 0, 1),
(0, 1, 2),
(0, 2, 3),
(0, 3, 4),
(0, 4, 5),
(0, 5, 6),
(0, 6, 7),
(0, 7, 8),
(0,... | Rust | 0 |
m += 1;
}
}
output.set_value(row, col, z_val);
}
if verbose {
progress = (100.0_f64 * row as f64 / (rows - 1) as f64) as usize;
if progress != old_progress {
println!("Progress: {}%", progress... | Rust | 0 |
import asyncio
import time
from modules.app_logger import app_logger
from .base import AbstractSensorGPS
_SENSOR_GPS_ADAFRUIT_UART = False
try:
import serial
import adafruit_gps
_uart = serial.Serial("/dev/ttyS0", baudrate=9600, timeout=10)
_sensor_adafruit_gps = adafruit_gps.GPS(_uart, debug=False)
... | Python | 1 |
/// 012
///
///The image you received is 25 pixels wide and 6 pixels tall.
///
///To make sure the image wasn't corrupted during transmission, the Elves would like you to find the layer that contains the fewest 0 digits. On that layer, what is the number of 1 digits multiplied by the number of 2 digits?
///
///... | Rust | 0 |
"""
Script to generate and display a logical block diagram of the U-Net
architecture.
Loads the CNN U-Net model from config and uses the visualize_architecture
method to create a diagram (PNG) of the model structure.
"""
import os
import sys
from typing import cast
import hydra
from hydra.core.global_hydra import Gl... | Python | 1 |
FULL = 0
return
# 模拟解冻
print("sunshine.exe is running--------------"+KEY2)
time.sleep(TIMESLEEP1)
try:
keyboard.press_and_release(KEY2)
except:
... | Python | 1 |
text = text.strip()
return text
def sentence_to_dict(self, text):
text = self.remove_punctuations(text)
text = text.lower()
word_counts = {}
for word in text.split():
if word in word_counts:
word_counts[word] += 1
else:
... | Python | 1 |
h.overflow.i16" fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
ifn!("llvm.umul.with.overflow.i32" fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
ifn!("llvm.umul.with.overflow.i64" fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
ifn!("llvm.expect.i1" fn(i1, i1) -> i1);
// Some intrinsics were introduced in later... | Rust | 0 |
nge (2024); Boekestijn (2025).
"""
N = lambda_r.shape[0]
alpha = alpha.flatten()
observation = observation.flatten()
f = alpha[:K]
h = alpha[K:]
exp_h = jnp.exp(h)
r = observation - lambda_r @ f # Residuals
# Ensure sigma2 is 1D for diagonal matrix operations
sigma2_1d = sig... | Python | 1 |
Step to schedule mutations in order. The fuzzing engine only ever
uses `ordered_mutate` directly, but the former is sometimes necessary to
compose mutators together.
If you don't want to bother with ordered mutations, that is fine. In that
case, only implement `random_mutate` and call it from the `ordered_mutate`
... | Rust | 0 |
))
}
/// Concatenate packed 32-bit integers in b and a producing an intermediate 64-bit result. Shift the result right by imm8 bits, and store the lower 32-bits in dst.
///
/// [Intel's documentation](https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm512_shrdi_epi32&expand=5105)
#[inline]
#[target_... | Rust | 0 |
ligned_start);
let size = round_page_up(program_header.p_memsz.wrapping_add(padding_start));
let slice_start = program_header.p_offset;
let slice_end = program_header
.p_offset
.wrapping_add(program_header.p_filesz);
... | Rust | 0 |
# JSON 파일 삭제
json_path = f"episodes/{series_id}/{episode['episode_number']}/text_data.json"
supabase.storage.from_("webtoon-data").remove([json_path])
except Exception as e:
storage_errors.append(f"에피소드 {episode['id']} 파일 삭제 실패: {format_erro... | Python | 1 |
_any_hash(&self) -> &dyn AnyHash;
fn downcast_ref(this: &dyn PlatformTargetDesc) -> Option<&Self>
where Self: Sized,
{
use std::any::TypeId;
use std::mem::transmute;
use std::raw::TraitObject;
let this_tyid = Any::type_id(this);
let self_tyid = TypeId::of::<Self>();
if this_tyid != sel... | Rust | 0 |
(func) = self.cache_line.pop() {
self.stack.push_front(func);
}
} else {
logging::weird_stack_line(line);
}
}
fn after_event(&mut self, occurrences: &mut Occurrences) {
// end of stack, so emit stack entry
if !self.skip_stack {
... | Rust | 0 |
s needed for installing a piece of software,
/// or for the software to find its data and configuration files on the system.
/// The default values are
/// ```ignore
/// XDG_DATA_HOME=\$HOME/.local/share
/// XDG_CONFIG_HOME=\$HOME/.config
/// XDG_DATA_DIRS=/usr/local/share/:/usr/share/
/// XDG_CONFIG_DIRS=/etc/xdg
///... | Rust | 0 |
from fastapi import HTTPException, Depends
from app.domain.schemas.coupon_schema import CouponCreateSchema, CouponResponseSchema
from app.domain.models.website_model import Coupon
from app.services.coupon_service import CouponService
from uuid import UUID
from app.services.website_service import WebsiteService
from ty... | Python | 1 |
prime = lambda num: num > 1 and all(num % i != 0 for i in range(2, int(num ** 0.5) + 1))
numb = list(range(1, 50))
prime_num = list(filter(prime, numb))
print(prime_num)
| Python | 1 |
from .models import Category, Exam, Lesson, Course, Contact
from modeltranslation.translator import TranslationOptions,register
@register(Category)
class ProductTranslationOptions(TranslationOptions):
fields = ('category_name',)
@register(Exam)
class ProductTranslationOptions(TranslationOptions):
fields = ('... | Python | 1 |
adds filter based on finding name."""
util.ValidateMutexOnFindingAndSourceAndOrganization(args)
finding_name = util.GetFullFindingName(args, version)
req.parent = util.GetSourceParentFromFindingName(finding_name, version)
req.filter = f"name : \"{util.GetFindingIdFromName(finding_name)}\""
return req
def _... | Python | 1 |
os::raw::c_char;
}
extern "C" {
pub fn uloc_toUnicodeLocaleType_63(
keyword: *const ::std::os::raw::c_char,
value: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
extern "C" {
pub fn uloc_toLegacyKey_63(
keyword: *const ::std::os::raw::c_char,
) -> *const ::s... | Rust | 0 |
import torch
'''
Sample rays from views (and images) with/without masks
--------------------------
INPUT Tensors
Ks: intrinsics of cameras (M,3,3)
Ts: extrinsic of cameras (M,4,4)
image_size: the size of image [H,W]
images: (M,C,H,W)
mask_threshold: a float threshold to mask rays
masks:(M,H,W)
-------------------
O... | Python | 1 |
rvations = {}
step_delta = None
if self._target_freq:
rate = rospy.Rate(self._target_freq)
rospy.loginfo(f"starting to spin")
try:
while not rospy.is_shutdown():
obs = self._check_reset()
if not self._scenario_path:
... | Python | 1 |
pub fn new() -> Self {
TracingConsole {}
}
}
impl Console for TracingConsole {
fn add(&mut self, message: ConsoleMessage) -> bool {
match message.level {
ConsoleLevel::Debug => {
tracing::event!(tracing::Level::DEBUG, "{}", message... | Rust | 0 |
address of the
/// shell variable is still valid.
pub unsafe fn get(&self) -> Variable {
unsafe fn cstr(addr: *const c_char) -> CString {
CStr::from_ptr(addr).to_owned()
}
if self.is_assoc() {
let items = self
.assoc_items()
.map(... | Rust | 0 |
one
best_matched_pose_id = None
best_matched_iou = 0
for id, previous_pose in enumerate(previous_poses):
if not mask[id]:
continue
iou = get_similarity(current_pose, previous_pose)
if iou > best_matched_iou:
best_matched_iou = i... | Python | 1 |
else:
# self.add_hook()
self._init_visdom(None, 1)
# for save boxes from all queries
self.save_all_boxes = params.save_all_boxes
self.z_dict1 = {}
self.z_list = []
self.thor_wrapper = THOR_Wrapper(net=self.network, st_capacity=params.cfg.TEST.... | Python | 1 |
/// Get filysystem path for the block at height.
///
/// # Errors
/// - Filesystem access failure (HW or permissions)
///
pub async fn get_block_path(&self, block_height: NonZeroU64) -> Result<PathBuf> {
let filename = self.get_block_filename(block_height).await?;
Ok(self.path.join(... | Rust | 0 |
import RPi.GPIO as GPIO
import time
def move_motor(step_pin, dir_pin, steps, direction):
GPIO.output(dir_pin, direction)
for _ in range(steps):
GPIO.output(step_pin, GPIO.HIGH)
time.sleep(0.0002) # 1ms 대기
GPIO.output(step_pin, GPIO.LOW)
time.sleep(0.0002)
def move_Z_motor(step... | Python | 1 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests import HttpCase, tagged
@tagged('post_install', '-at_install')
class TestSnippets(HttpCase):
def test_snippet_newsletter_popup(self):
self.start_tour("/", "snippet_newsletter_popup_edition"... | Python | 1 |
lect the last item in seq_len dim
logits = logits[:, -1, :] # (batch_size, vocab_size), this will reduce the dim
probs = F.softmax(logits, dim=-1) # (batch_size, vocab_size), the sum of the value in the last dim is 1
next_words = torch.multinomial(probs, num_samples=1) # (batch_size,... | Python | 1 |
rams = parameters_for_codecs(codecs);
info!("Accepting SCO connection for {}: {:?}.", peer_id, ¶ms);
let proxy = self.proxy.clone();
Self::setup_sco_connection(proxy, peer_id, ScoInitiatorRole::Accept, params)
}
}
///
/// Blitz Money
///
/// Frontend/Ui of module for manange rules of pa... | Rust | 0 |
gtt.meta()
if os.path.exists(os.path.join(tgt_folder, 'meta.json')):
with open(os.path.join(tgt_folder, 'meta.json'), 'r', encoding="utf-8") as fp:
meta_info = json.load(fp)
meta_info['extent']['total'] = len(total_gt_list)
with open(os.path.join(tgt_folder, 'meta.json'), 'w', enc... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.