text string | label_name string | labels int64 |
|---|---|---|
oisoned=True)
# 4. 后门防御
print("\nRunning backdoor defense...")
defense = BackdoorDefense(model, tokenizer)
suspicious_words = defense.detect_triggers(poisoned_test_data)
print("Top suspicious words:")
for word, lfr, count in suspicious_words:
print(f"Word: '{word}', LFR: {lfr:.4f}, ... | Python | 1 |
import tkinter
from tkinter import *
from chatapp import ChatApp as cA # Importing ChatApp class from chatapp module
import os # Importing the os module for path operations
from keras.models import load_model # A function from Keras to load a pre-trained neural network model.
import nltk
import utils as u
import jso... | Python | 1 |
# -*- coding: utf-8 -*-
# 版权所有 2019 深圳米筐科技有限公司(下称“米筐科技”)
#
# 除非遵守当前许可,否则不得使用本软件。
#
# * 非商业用途(非商业用途指个人出于非商业目的使用本软件,或者高校、研究所等非营利机构出于教育、科研等目的使用本软件):
# 遵守 Apache License 2.0(下称“Apache 2.0 许可”),您可以在以下位置获得 Apache 2.0 许可的副本:http://www.apache.org/licenses/LICENSE-2.0。
# 除非法律有要求或以书面形式达成协议,否则本软件分发时需保持当前许可“原样”... | Python | 1 |
hp?comic=%s'
url = stripUrl % '-1'
firstStripUrl = stripUrl % '1'
imageSearch = '//div[@id="comic"]//img[contains(@src, "/comics/")]'
prevSearch = '//a[@alt="go back"]'
endOfLife = True
help = 'Index format: n'
class WildeLife(ComicControlScraper):
url = 'http://www.wildelifecomic.com/'
... | Python | 1 |
868500000, 867100000, 867300000, 867500000, 867700000,
867900000,
],
lora_std: LoRaStdChannel {
frequency: 868300000,
bandwidth: 250000,
spreading_factor: 7,
..Default::default()
... | Rust | 0 |
None, None), name),
format!("{} {}", ERROR_INVALID_FLOW, name),
)])
}
pub fn to_json(&self) -> serde_json::Value {
let mut map: serde_json::Map<String, serde_json::Value> = serde_json::Map::new();
map.insert("id".to_owned(), serde_json::json!(self.id));
map.insert(... | Rust | 0 |
from __future__ import annotations
from decimal import Decimal
from typing import Any
from django.apps import apps
from salesman.conf import app_settings
def format_price(value: Decimal, context: dict[str, Any] = {}) -> str:
"""
Default price format function. Can be overriden by providing a
dotted path... | Python | 1 |
import unittest
import numpy as np
from numpy.testing import assert_almost_equal
from dymos.utils.hermite import hermite_matrices
class TestHermiteMatrices(unittest.TestCase):
def test_quadratic(self):
# Interpolate with values and rates provided at [-1, 1] in tau space
tau_given = [-1.0, 1.0]... | Python | 1 |
nceProhibitedError(self.type(), exc.msg)
def _link_cached_relations(self, manifest):
schemas: Set[str] = set()
relations_schemas = self._get_cache_schemas(manifest)
for relation in relations_schemas:
self.verify_database(relation.database)
schemas.add(relation.schema... | Python | 1 |
def somar(n1, n2):
return n1 + n2
def multiplicar(n1, n2):
return n1 * n2
def maior(n1, n2):
return max(n1, n2)
def menu():
print(
"""
[ 1 ] - SOMAR
[ 2 ] - MULTIPLICAR
[ 3 ] - MAIOR
[ 4 ] - NOVOS NÚMEROS
[ 5 ] - SAIR DO PROGRAMA
"""
)
... | Python | 1 |
es(&["pending"])
.set(m.finality_proofs.pending_requests.into());
metrics.finality_proofs.with_label_values(&["active"])
.set(m.finality_proofs.active_requests.into());
metrics.finality_proofs.with_label_values(&["failed"])
.set(m.finality_proofs.failed_requests.into());
metrics.finality_proofs.wit... | Rust | 0 |
ffset + 6)]);
Ok(move_stats)
}
/// Set move stats by move ID
///
/// # Example
///
/// ```
/// use pkmnapi_db::patch::*;
/// use pkmnapi_db::*;
/// use std::fs;
/// # use std::env;
/// # let rom_path = env::var("PKMN_ROM").expect("Set the PKMN_ROM environment variab... | Rust | 0 |
e {
pub const COMMANDS: &str = "commands";
pub const PUG_CHANNELS: &str = "pug_channel";
pub const GAME_MODES: &str = "game_modes";
pub const GAME_MODE_JOINS: &str = "game_mode_joins";
pub const PLAYER_ROSTER: &str = "player_roster";
pub const PICKING_SESSIONS: &str = "picking_sessions";
pub... | Rust | 0 |
;
<filename>src/strymon_executor/src/lib.rs<gh_stars>0
// Copyright 2017 ETH Zurich. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. T... | Rust | 0 |
from typing import TypeVar, Iterable, Union
from assimilator.core.database import UnitOfWork, SpecificationList
from assimilator.core.services.base import Service
from assimilator.core.patterns import LazyCommand
ModelT = TypeVar("ModelT")
class CRUDService(Service):
def __init__(self, uow: UnitOfWork):
... | Python | 1 |
#!/usr/bin/python
import re # Asegúrate de tener esta importación al inicio del script
import gi
gi.require_version("GdkPixbuf", "2.0")
gi.require_version("Gtk", "3.0")
import dbus
import dbus.service
from dbus.mainloop.glib import DBusGMainLoop
from gi.repository import GLib
import datetime
import os
import typing
... | Python | 1 |
#
# Solved Problems in Geostatistics
#
# ------------------------------------------------
# Script for lesson 5.2
# "Variogram Calculation"
# ------------------------------------------------
import sys
sys.path.append(r'../shared')
from numpy import *
from geo import *
from matplotlib import *
from pylab import *
fro... | Python | 1 |
static ref LFO_TABLE: Box<[i16; 65]> = Box::new([
0, 24, 49, 74, 97, 120, 141, 161, 180, 197, 212, 224, 235, 244, 250, 253,
255, 253, 250, 244, 235, 224, 212, 197, 180, 161, 141, 120, 97, 74, 49, 24,
0, -24, -49, -74, -97, -120, -141, -161, ... | Rust | 0 |
:*;
use syntax::names::*;
use syntax::trees;
use super::symbols::*;
use super::graph::*;
use super::earley::*;
use driver;
use driver::*;
use driver::bundle::*;
use std::collections::VecDeque;
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::BTreeMap;
use rpds::HashTrieSet;
use std... | Rust | 0 |
"windows")]
command.creation_flags(winapi::um::winbase::CREATE_NO_WINDOW);
command.spawn().map_err(|e| match e.kind() {
//shell failed to execute the command. Separate out FileNotFound from all other errors
//as by far the most likely cause is ffmpeg is not installed.
std::io::ErrorKin... | Rust | 0 |
ssert_eq!(res_c.status(), Status::Ok);
assert_eq!(res_c.body_string(), Some("deleted".into()));
let mut res_d = client.delete("/body-data/streaming/upload.txt").dispatch();
assert_eq!(res_d.status(), Status::Ok);
assert_eq!(
res_d.body_string(),
Some("No such file or directory (os erro... | Rust | 0 |
> {
self.access.find_object(self.inner)
}
/// Try to find the [`ObjectRef`] associated with this object id, and return `None` if it's not available locally.
///
/// # Note
///
/// There can only be one `ObjectRef` per `Easy`. To increase that limit, clone the `Easy`.
pub fn try_obje... | Rust | 0 |
any case, you've extracted just the numbers in such a way that the first number is always the same specific field, the second number is always a different specific field, and so on - you just don't know what each position actually means!
//!
//! Start by determining which tickets are completely invalid; these are ticke... | Rust | 0 |
from django.shortcuts import render, redirect
from django.contrib.auth import login
from django.urls import reverse_lazy
from django.views.generic import CreateView
from django.contrib.auth.views import LoginView, LogoutView
from django.contrib.auth.models import Group
from .models import CustomUser
from .forms import ... | Python | 1 |
# import os
# import sys
# path = os.path.dirname(os.path.abspath(__file__))
# sys.stdin = open(path + "/input1.txt", "r")
def solve(n: int) -> None:
"""Для заданного N посчитайте количество различных строк длины N,
которые содержат только буквы 'X' и 'Y' и не содержат 'YY' как подстроку.
Решение:
... | Python | 1 |
from res.general_text import BACK_BUTTON_TEXT
INFO_BALANCE_BUTTON_TEXT = "Информация о балансе"
EDIT_BALANCE_BUTTON_TEXT = "Редактировать баланс"
BALANCE_HELLO_TEXT = f"""💰 Баланс
Выберите действие, которое вы хотите выполнить с балансом при помощи кнопок 🧾 <b>{INFO_BALANCE_BUTTON_TEXT}</b>
и ✏️ <b>{EDIT_BALA... | Python | 1 |
_xmm_k1z_xmmm128b64", Code::EVEX_Vcvttpd2udq_xmm_k1z_xmmm128b64);
h.insert("EVEX_Vcvttpd2udq_xmm_k1z_ymmm256b64", Code::EVEX_Vcvttpd2udq_xmm_k1z_ymmm256b64);
h.insert("EVEX_Vcvttpd2udq_ymm_k1z_zmmm512b64_sae", Code::EVEX_Vcvttpd2udq_ymm_k1z_zmmm512b64_sae);
h.insert("Extrq_xmm_imm8_imm8", Code::Extrq_xmm_imm8_imm... | Rust | 0 |
--------------------
// THE TRAIT
// The following trait define a measurability
// characterist: an object is measurable if it
// is possible to compute the area and the perimeter
pub trait Measurable {
fn area(&self) -> f64;
fn perimeter(&self) -> f64;
}
// -----------------------------------------------------... | Rust | 0 |
: super::Registry::HKEY, schemeguid: *const ::windows_sys::core::GUID, subgroupofpowersettingsguid: *const ::windows_sys::core::GUID, powersettingguid: *const ::windows_sys::core::GUID, acvalueindex: u32) -> u32;
#[doc = "*Required features: `\"Win32_System_Power\"`, `\"Win32_System_Registry\"`*"]
#[cfg(feature... | Rust | 0 |
= self.index + 1;
return ret;
}
for choice in 1..num_items {
let mut new_exec = self.pre_chosen.to_vec().to_owned();
new_exec.append(&mut self.new_choices.to_owned());
new_exec.push(choice);
self.executions.push(new_exec);
}
se... | Rust | 0 |
import matplotlib.pyplot as plt
from matplotlib import rcParams
rcParams['font.family'] = 'Times New Roman'
# 数据
epochs = [2000, 4000, 6000, 8000, 10000, 12000, 14000, 16000, 18000]
ious = [0.8898, 0.8732, 0.8900, 0.8357, 0.8546, 0.8487, 0.8303, 0.8349, 0.8379]
dscs = [0.8949, 0.8864, 0.8950, 0.8668, 0.8768, 0.8737, ... | Python | 1 |
"""
Test the plugin in integration-tests/plugins/simplest that makes use of all tljh
recognized plugin hooks that are defined in tljh/hooks.py.
"""
import os
import subprocess
from ruamel.yaml import YAML
from tljh import user
from tljh.config import CONFIG_FILE, HUB_ENV_PREFIX, USER_ENV_PREFIX
GIT_REPO_PATH = os.p... | Python | 1 |
;
fn try_from(value: i32) -> ::std::result::Result<Self, Self::Error> {
Ok(match value {
0 => WireType::Variant,
1 => WireType::Bits64,
2 => WireType::LengthDelimited,
3 => WireType::StartGroup,
4 => WireType::EndGroup,
5 => WireType::... | Rust | 0 |
fn verify_product_owner(merchant: T::AccountId, product_id: ProductId) -> DispatchResult {
let owner = Self::product_owner(product_id)?;
match owner == merchant {
true => {
// check if the merchants org owns the product
let org_products = OrganisationProduct::<T>::get(&merchant);
ensure!(!org... | Rust | 0 |
import pyclesperanto_prototype as cle
import numpy as np
def test_copy_horizontal_slice_from_3d():
test1 = cle.push(np.asarray([
[
[1, 4],
[0, 4]
],
[
[1, 3],
[1, 2]
]
]))
test2 = cle.create((2, 2))
cle.copy_horizontal_sl... | Python | 1 |
part_B,part_flag_B = annot_B
# get mutual keypoints
if keypoint_A.shape!=(0,0) and keypoint_B.shape!=(0,0):
mutual_kp_idx = np.nonzero(keypoint_flag_A * keypoint_flag_B)[1]
keypoint_A = keypoint_A[:,mutual_kp_idx]
keypoint_B = keypoint_B[:,mutual_kp_idx]
else:... | Python | 1 |
-> (StableRowIndex, Vec<Line>);
/// Returns render related dimensions
fn get_dimensions(&self) -> RenderableDimensions;
}
impl_downcast!(Renderable);
impl Renderable for Terminal {
fn get_cursor_position(&self) -> StableCursorPosition {
let pos = self.cursor_pos();
StableCursorPosition {... | Rust | 0 |
dule.get_triangular_moving_average(growth=True, lag=[1, 2, 3])
)
def test_get_true_range(recorder):
recorder.capture(technical_module.get_true_range())
recorder.capture(technical_module.get_true_range(growth=True))
recorder.capture(technical_module.get_true_range(growth=True, lag=[1, 2, 3]))
def tes... | Python | 1 |
from player2024s.info_types import PredictionRole, PredictionRoleList
from player2024s.stance import Stance
from player2024s.langchain import OpenAIAgent
from player2024s.info_types import PredictionRole, DivineResult
from typing import Dict, List
openai_agent = OpenAIAgent(temperature=1)
def get_prediction_role(
... | Python | 1 |
from metaproc.bilibili_api.core import BilibiliAPI
biliapi = BilibiliAPI()
| Python | 1 |
"""Simple thumbnail image picker.
"""
from PySide2 import QtCore, QtWidgets
from ... import common
from ... import images
instance = None
def close():
"""Closes :class:`PickThumbnail`.
"""
if common.pick_thumbnail_widget is None:
return
try:
common.pick_thumbnail_widget.close()
... | Python | 1 |
(i);
}
}
/// Decodes a LEB128-encoded variable length integer from the buffer.
pub fn decode_varint<B>(buf: &mut B) -> Result<u64, ()>
where
B: Buf,
{
let bytes = buf.chunk();
let len = bytes.len();
if len == 0 {
return Err(());
}
let byte = unsafe { *bytes.get_unchecked(0) };
... | Rust | 0 |
from fastapi import Depends, HTTPException, status, Response, Request
from app.core.error.teacher_exception import TeacherNotFoundError
from app.features.teacher.dependencies import get_teacher_use_case
from app.features.teacher.domain.entities.teacher_schema import TeacherDisplay
from app.features.teacher.domain.usec... | Python | 1 |
#[doc = " @param index Index of the sum post-op."]
#[doc = " @param scale Output accumulation scaling factor."]
#[doc = " @param data_type Data type for accumulation."]
#[doc = " @returns #dnnl_success on success and a status describing the error"]
#[doc = " otherwise."]
pub fn dnnl_post_ops_... | Rust | 0 |
mulated_rpz: 200_u128,
loyalty_curve: None,
stake_in_global_pool: Balance::from(10_000_u32),
multiplier: FixedU128::from(10_u128),
canceled: false,
};
let mut ext = new_test_ext();
let farm_account_id = LiquidityMining::pool_account_id(*global_pool_id).unwrap();
let pool_account_id = LiquidityMini... | Rust | 0 |
from typing import (
Any,
Generic,
Optional,
Type,
TypeVar,
Union,
final,
overload,
)
import tomli_w
from mashumaro.codecs._builder import CodecCodeBuilder
from mashumaro.core.meta.helpers import get_args
from mashumaro.dialect import Dialect
from mashumaro.mixins.toml import TOMLDiale... | Python | 1 |
ing().is_empty() {
query_args.push(("content".to_string(), content.to_string()));
}
let query_ = serde_urlencoded::to_string(&query_args).unwrap();
let url = format!(
"/orgs/{}/teams/{}/discussions/{}/reactions?{}",
crate::progenitor_support::encode_path(&org.... | Rust | 0 |
agent_cfg = dict(
type="PPO",
gamma=0.95,
lmbda=0.95,
critic_coeff=0.5,
entropy_coeff=0,
critic_clip=False,
obs_norm=False,
rew_norm=True,
adv_norm=True,
recompute_value=True,
detach_actor_feature=True,
critic_warmup_epoch=4,
num_epoch=2,
batch_size=400,
max_... | Python | 1 |
en = unconstrained_sampling_with_temperature(last_target_logits, temperature=temperature)
fin_prompt_seq = torch.concat([fin_prompt_seq, sample_token[None,...]], dim=-1)
if fin_prompt_seq[..., -1] == tokenizer.eos_token_id:
end_flag = 1
break
n += 1
... | Python | 1 |
import argparse
import torch
from quixer.setup_training import get_train_evaluate
##################################################
# Default hyperparameters for each of the models #
##################################################
quixer_hparams = {
"qubits": 6,
"layers": 3,
"ansatz_layers": 4,
... | Python | 1 |
for buffer_id in buffer_ids:
descr = reader.get_analogsignal_buffer_description(
block_index=block_index, seg_index=seg_index, buffer_id=buffer_id
)
assert descr["type"] in ("raw", "hdf5"), "buffer_description type uncorrect"
... | Python | 1 |
ighres_face_gridpoint(1, 0),
tcell_highres_face_gridpoint(2, 0),
tcell_highres_face_gridpoint(0, 1),
tcell_highres_face_gridpoint(1, 1),
tcell_highres_face_gridpoint(2, 1),
tcell_highres_face_gridpoint(0, 2),
tcell_highres_face_gridpoint(1, 2),
tcell_highres_face_gridpoint(2, 2),
tcell_r... | Rust | 0 |
it_subclass__()
# WHEN: A derived class is defined
with patch.object(
Custom, "__init_subclass__", wraps=Custom.__init_subclass__
) as init_subclass_mock:
class Derived(Default, Custom):
def __init__(self) -> None:
super().__init__()
# THEN: The impleme... | Python | 1 |
es = vec![
Located::new(Loc::new(1, 1), Decl::Val { scope: Scope::Empty, name: a.clone() }),
Located::new(Loc::new(3, 3), Decl::Val { scope: Scope::Empty, name: b.clone() }),
];
assert_eq!(us, es);
}
#[test]
fn test_names_in_mixfix_are_unknown_multiple_occurrences()... | Rust | 0 |
ee `GreenNodeBuilder::checkpoint` for details.
#[derive(Clone, Copy, Debug)]
pub struct Checkpoint(usize);
/// A builder for a green tree.
#[derive(Default, Debug)]
pub struct GreenNodeBuilder<'cache> {
cache: CowMut<'cache, NodeCache>,
parents: Vec<(SyntaxKind, usize)>,
children: Vec<(u64, GreenElement)>,... | Rust | 0 |
marks, text)
marks = re.findall(_japanese_marks, text)
text = ''
for i, sentence in enumerate(sentences):
if re.match(_japanese_characters, sentence):
if text != '':
text += ' '
labels = pyopenjtalk.extract_fullcontext(sentence)
for n, label in enu... | Python | 1 |
import torch
import transformers
model_id = "nvidia/Llama-3.1-Nemotron-Nano-8B-v1"
model_kwargs = {"torch_dtype": torch.bfloat16, "device_map": "auto"}
tokenizer = transformers.AutoTokenizer.from_pretrained(model_id)
tokenizer.pad_token_id = tokenizer.eos_token_id
pipeline = transformers.pipeline(
"text-generation... | Python | 1 |
: I) -> K;
/// create simple table
pub fn ktd(arg1: K) -> K;
/// create timestamp / create timespan
pub fn ktj(arg1: I, arg2: J) -> K;
/// create vector
pub fn ktn(arg1: I, arg2: J) -> K;
/// create guid
pub fn ku(arg1: U) -> K;
/// create datetime
pub fn kz(arg1: F) -> K;
... | Rust | 0 |
SIZE: node_memo_size[name],
RouterNetTopo.TEMPLATE: template}
for i, name in enumerate(router_names)]
# add bsm links
cchannels, qchannels, bsm_nodes = generate_bsm_links(graph, args, bsm_name_func)
nodes += bsm_nodes
output_dict[Topology.ALL_NODE] = nodes
output_dict[Topology.ALL_Q_CHANNEL] = qchan... | Python | 1 |
#[options(free)]
key_ids: Vec<u16>,
}
impl Callable for GenerateCommand {
/// Generate an Ed25519 signing key inside a YubiHSM2 device
fn call(&self) {
if self.key_ids.is_empty() {
status_err!("must provide at least one key ID to generate");
process::exit(1);
}
... | Rust | 0 |
import re
class SpeciesString:
"""
A class to process and clean different types of chemical structure strings including InChI,
InChIKey, and SMILES.
The class takes a raw input string, determines the intended structure type, and then cleans
the string based on its type.
Attributes
----... | Python | 1 |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Data extracted from the image
data = {
'Category': [
'Afterburner 3B-SFT', 'Afterburner 3B-SFT', 'Afterburner 3B-SFT',
'Afterburner 3B-DPO', 'Afterburner 3B-DPO', 'Afterburner 3B-DPO',
'Afterburner 3B-GRPO', 'Afterburn... | Python | 1 |
=> ControllerButton::LShoulder,
input_event_codes::BTN_TR => ControllerButton::RShoulder,
input_event_codes::BTN_TL2 => ControllerButton::LShoulder2,
input_event_codes::BTN_TR2 => ControllerButton::RShoulder2,
input_event_codes::BTN_SELECT => ControllerButton:... | Rust | 0 |
shard, f"{shard.name}_q_weight", quantized_mistral_experts.q_weight)
apply_sharding(shard, f"{shard.name}_q_scale", quantized_mistral_experts.q_scale)
return quantized_mistral_experts
def forward(self, x: nn.Tensor, indptr: nn.Tensor) -> nn.Tensor: # pylint: disable=invalid-name
"""For... | Python | 1 |
ppend(mean_reward)
cost_Engine += (SOC < SOC_origin) * (SOC_origin - SOC) * (201.6 * 6.5) * 3600 /(42600000) / 0.72
cost_Engine_list.append(cost_Engine)
cost_Engine_100Km_list.append(cost_Engine * (100 / total_milage))
cost_all += (SOC < SOC_origin) * (SOC_origin - SOC) ... | Python | 1 |
},
fnetemul::ChildDef {
url: Some(COUNTER_PACKAGE_URL.to_string()),
name: Some("counter-b".to_string()),
exposes: Some(vec![COUNTER_B_SERVICE_NAME.to_string()]),
uses: Some(fnetemul::ChildUses::Capabiliti... | Rust | 0 |
import csv
import matplotlib.pyplot as plt
import os
import numpy as np
import seaborn as sns
import pandas as pd
def get_nonzero_observations(input_str):
input_str = input_str.replace('[','')
input_str = input_str.replace(']','')
input_str = input_str.replace('\n','')
input_array = input_str.split(','... | Python | 1 |
AILSINFO {}
#[cfg(feature = "Win32_UI_Shell_Common")]
impl ::core::clone::Clone for DETAILSINFO {
fn clone(&self) -> Self {
*self
}
}
pub type DFConstraint = *mut ::core::ffi::c_void;
#[repr(C)]
#[doc = "*Required features: `\"Win32_UI_Shell\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundatio... | Rust | 0 |
import pygame
from utils import *
from game import *
class GameRenderer:
def __init__(self):
'''初始化游戏渲染器'''
# Pygame初始化字体
pygame.font.init()
# 设置个性化主题 ~~
self.theme = THEMES[CURRENT_THEME]
# 创建游戏窗口
self.screen = pygame.display.set_mode((WINDOW_WIDTH, WINDO... | Python | 1 |
epnumber, tasknumber=tasknumber, carrynumber=carrynumber,
passnumber=passnumber, asserterrornumber=asserterrornumber, failnumber=failnumber,
errorratio=errorratio*100)
#获取今日反馈量
date = now().date() + timedelta(days=0) #... | Python | 1 |
from src.plugins.handler import Handler
from src.core.utils import NodeHandleResult
class HandleConst(Handler) :
"""
this is the handler for const values, including
int, double and string
"""
def process(self):
G = self.G
node_id = self.node_id
cur_type = self.G.get_node_at... | Python | 1 |
",
"contraseña",
"cinthya",
"changeme",
"zamora",
"temple",
"tanya",
"peanutbutter",
"mafer",
"ichigo",
"davids",
"christie",
"buddie",
"tyrell",
"reagan",
"mydear",
"leonor",
"garden",
"cornelia",
"cherie",
"savannah1",
"photo",
"m... | Rust | 0 |
figsize=(max(10, len(similarity_matrix) / 2), max(10, len(similarity_matrix) / 2)),
cmap='mako_r',
linewidths=5,
row_cluster=True,
col_cluster=True,
row_linkage=linkage_matrix,
col_linkage=linkage_matrix,
row_colors=row_col_colors,
col_colors=row_co... | Python | 1 |
# -*- coding:utf-8 -*-
'''
@Project : lb_toolkits
@File : downloadERA5.py
@Modify Time : 2022/8/11 15:34
@Author : Lee
@Version : 1.0
@Description :
下载ERA5 再分析廓线数据和地面分析资料
'''
import sys
import os
import cdsapi
import datetime
import numpy as np
from dateutil.relativedelta import relativedelta
class downloa... | Python | 1 |
from urllib.parse import urlparse
import requests
import hashlib
import random
import sys
def exploit(url):
try:
requests.packages.urllib3.disable_warnings()
host = urlparse(url)
url = f"{host.scheme}://{host.netloc}/rpc"
print(f"[*] Target: {url}")
print("[*] Retrieving non... | Python | 1 |
from datetime import datetime
from sqlalchemy import (
TIMESTAMP,
Integer,
String,
)
from sqlalchemy.orm import (
Mapped,
mapped_column,
)
from polar.kit.db.models import RecordModel
from polar.kit.metadata import MetadataMixin
# Basic campaign structure (alpha)
#
# Intention:
# - Add referral ... | Python | 1 |
Context<'_>) -> Poll<Option<Self::Item>> {
loop {
match self.state.clone() {
ChannelState::Closed => panic!("Polling already terminated channel"),
ChannelState::Header(mut data) => {
if data.is_empty() {
data = ready!(self.... | Rust | 0 |
}
}
}
target_pos
}
// MyShot
pub fn do_fire_myshot(player: &Player, posture: &Posture, entity: Entity, commands: &mut CommandBuffer) -> bool {
if !can_player_fire(player) {
return false;
}
let posture = Posture(&posture.0 + &calc_velocity(posture.1, 4 * ONE), posture.1);
... | Rust | 0 |
2, atol=atol * 2)
# assert paddle.allclose(delta.grad, delta_ref.grad.cast(dtype=itype), rtol=rtol * 5, atol=atol * 10)
# assert paddle.allclose(A.grad, A_ref.grad, rtol=rtolw, atol=atolw * 5)
# assert paddle.allclose(B.grad, B_ref.grad, rtol=rtolw if not is_variable_B else rtol,
# ... | Python | 1 |
}
}
impl std::fmt::Debug for AcceptAttachmentOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("AcceptAttachmentOutput");
formatter.field("attachment", &self.attachment);
formatter.finish()
}
}
/// See [`AcceptAttachment... | Rust | 0 |
returns [diep3_tsiz::R](diep3_tsiz::R) reader structure"]
impl crate::Readable for DIEP3_TSIZ {}
#[doc = "`write(|w| ..)` method takes [diep3_tsiz::W](diep3_tsiz::W) writer structure"]
impl crate::Writable for DIEP3_TSIZ {}
#[doc = "Device IN Endpoint x+1 Transfer Size Register"]
pub mod diep3_tsiz;
#[doc = "Device IN... | Rust | 0 |
},
"item_2": {
"key_2_a": "val_2_a",
"key_2_b": "val_2_b"
}
}
"#;
assert!(matches!(Format::read_json(input, &Arity::Many), Ok(Schema::Map(_))));
}
}
<filename>2021/rust/src/day20.rs
#[derive(Default)]
pub struct Day {}
impl... | Rust | 0 |
{
let center = self.intersect_height(height).to_vec().truncate();
let mut bounds = center..center;
let proj = self.get_proj_matrix();
let view = self.view_transform();
let mx = cgmath::Matrix4::from(view) * proj.inverse_transform().unwrap();
// Scale vectors in a way th... | Rust | 0 |
.
assert total_cache_size >= const_foldable_cache_size and total_cache_size >= identity_cache_size
# The total cache should also be smaller than or equal to the sum of the individual caches since
# header information should not be duplicated.
assert total_cache_size <= (c... | Python | 1 |
_velocity[1]
meas_tau_elbow[i] = measured_torque[1]
des_tau_elbow[i] = tau[1]
## Do your stuff here - END
i += 1
exec_time = time.time() - start_loop
min_freq = min(min_freq, 1.0 / exec_time)
max_freq = max(max_freq, 1.0 / exec_time)
... | Python | 1 |
header = '''
\\begin{frame}[fragile]{Problema}
\\begin{figure}[!ht]
\\begin{tikzpicture}
'''
trailer = '''
\\end{tikzpicture}
\\end{figure}
\\end{frame}
'''
hs = [5, 3, 6, 10, 5, 5, 8, 6, 11, 9, 10, 3, 6, 1, 9, 4, 5, 6, 10, 10, 10, 3, 2, 8,
3, 11, 4, 9, 1, 6, 5, 4, 8]
if __name__ == '__ma... | Python | 1 |
usize,
...
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn vips_webpsave_mime(in_: *mut VipsImage, ...) -> ::std::os::raw::c_int;
}
pub const VipsForeignTiffCompression_VIPS_FOREIGN_TIFF_COMPRESSION_NONE:
VipsForeignTiffCompression = 0;
pub const VipsForeignTiffCompression_VIPS_FOREIGN_TIFF_COMPR... | Rust | 0 |
"""unit test for ArtTransPure consistency
Note:
This test validates ArtTransPure against reference transmission data
to ensure the code implementation remains consistent.
"""
import pytest
from jax import config
import pandas as pd
import numpy as np
from exojax.test.data import get_testdata_filename
from exo... | Python | 1 |
name(name_or_id).map(|g| g.gid()))
}
let mut it = s.split(':');
let user = match it.next() {
Some("") | None => OwnerCheck::Ignore,
Some(v) if v.starts_with('!') => OwnerCheck::NotEq(get_uid(&v[1..])?),
Some(v) => OwnerCheck::Equal(get_uid(v)?),
};
... | Rust | 0 |
;
let c_bar = (chroma_0 + chroma_1) / 2.0;
let g = 0.5 * (1.0 - ( c_bar.powi(7) / (c_bar.powi(7) + 25_f32.powi(7)) ).sqrt());
let a_prime_0 = lab_0.a * (1.0 + g);
let a_prime_1 = lab_1.a * (1.0 + g);
let c_prime_0 = (a_prime_0.powi(2) + lab_0.b.powi(2)).sqrt();
let c_prime_1 = (a_prime_1.pow... | Rust | 0 |
import copy
import torch
__all__ = ['build_optimizer']
def build_optimizer(optim_config, lr_scheduler_config, epochs, step_each_epoch, model):
from . import lr
config = copy.deepcopy(optim_config)
optim = getattr(torch.optim, config.pop('name'))(params=model.parameters(), **config)
lr_config = copy... | Python | 1 |
nsts::r#mod => Self::r#mod,
_ => Self::Unknown,
}
}
pub fn with_str(ext: &str) -> Self {
match ext {
$(
strings::$field_name => Self::$field_name,
... | Rust | 0 |
conn.simple_query("select cast(NULL as nchar(8))").for_each(|row| {
assert_eq!(row.get::<_, Option<&str>>(0), None);
Ok(())
}).and_then(|conn|
conn.simple_query("select cast('test' as nchar(8))").for_each(|row| {
... | Rust | 0 |
STATUS;
pub type EFI_FILE_SET_POSITION = extern "win64" fn(
This: *mut EFI_FILE_PROTOCOL,
Position: UINT64
) -> EFI_STATUS;
pub type EFI_FILE_GET_INFO = extern "win64" fn(
This: *const EFI_FILE_PROTOCOL,
InformationType: *const EFI_GUID,
BufferSize: *mut UINTN,
Buffer: *mut VOID
) -> EFI_STATU... | Rust | 0 |
cks>(&self, clear_bits_enter: u32, clear_bits_exit: u32, wait_for: D)
-> Result<u32, FreeRtosError> {
let mut val = 0;
let r = unsafe { freertos_rs_task_notify_wait(clear_bits_enter, clear_bits_exit, &mut val as *mut _, wait_for.to_ticks()) };
... | Rust | 0 |
d41}ഞ\u{d4d}ചിരിക\u{d4d}ക\u{d41}ന\u{d4d}ന മ\u{d41}ഖം",
),
keywords: &[
"കണ\u{d4d}ണ\u{d4d}",
"കവിളിണ",
"ന\u{d3e}ണം",
"പ\u{d41}ഞ\u{d4d}ചിരി",
"പ\u{d41}ഞ\u{d4d}ചിരിക\u{d4d}ക\u{d41}ന\u{d4d}ന കണ\u{d4d}ണ\u{d41}കള\u{d41}ള\u... | Rust | 0 |
unnamed, .. }: &FieldsUnnamed,
) -> Option<impl Iterator<Item = (usize, &Type)>> {
let fields = unnamed.into_iter().collect::<Vec<_>>();
if fields.len() == 1 {
if let Type::Path(TypePath { path, .. }) = &fields[0].ty {
if let Some(path_seg) = path.segments.first() {
if path_... | Rust | 0 |
pub fn adjust_with(&mut self, new_size: usize) {
if self.size >= new_size && self.size - new_size <= 10 {
return;
}
// TODO: after tokio supports adjusting thread pool size(https://github.com/tokio-rs/tokio/issues/3329),
// adapt it.
let workers = create_tokio_r... | Rust | 0 |
let mut s = RubyString::new();
s.extend(iter);
s
}
}
impl<'a> Extend<Segment<'a>> for RubyString {
fn extend<I: IntoIterator<Item = Segment<'a>>>(&mut self, iter: I) {
iter.into_iter().for_each(move |s| self.push_segment(s));
}
}
use crate::device::IDevice;
use crate::image::IImage;... | Rust | 0 |
let dur = timer.sleep_duration(counter).div_f64(speed as f64);
if !dur.is_zero() {
thread::sleep(dur);
}
counter = 0;
for event in events {
match event {
Event::Tempo(val) => timer.change_tempo(*val),
Event::Midi(msg) => {
buf.clear();
let _ = msg.... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.