text string | label_name string | labels int64 |
|---|---|---|
import re
import nltk
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
nltk.download("stopwords", quiet=True)
nltk.download("wordnet", quiet=True)
stop_words = set(stopwords.words("english"))
lemmatizer = WordNetLemmatizer()
def clean_text(text):
text = text.lower()
text = re.sub(r"[... | Python | 1 |
below is temporary.
// In the following work, the mutation will also take `CanisterIdRanges` as input.
let ranges = CanisterIdRanges::try_from(vec![canister_id_range])
.expect("canister ID ranges are not well formed.");
routing_table.assign_ranges(ranges, destination)... | Rust | 0 |
"""
Algorithm:chinese_remainder_theorem|extended_chinese_remainder_theorem|ex_crt|crt
Description:equation|same_mod
====================================LeetCode====================================
=====================================LuoGu======================================
p1495(https://www.luogu.com.cn/problem/... | Python | 1 |
eritance, so the superclass method
# (this one) needs to have a name other than `forward` that can be accessed in a subclass
x = self.features(x)
# Cannot use "squeeze" as batch-size can be 1
x = F.relu(x)
x = torch.mean(x,(2,3))
#x = torch.flatten(x, 1)
x = self.... | Python | 1 |
\xcf\
r/TP1g]\xaa\xc7=\xc8\xbdQ@\xc5\x9d\
v\xab\x1c\xf7\x22\xf5E\x03\x16u\xda\xacs\xdf\x81\xf4\
\x1a\x8f!\x8a\xf4\xdd\xa1[\x90>\x83Q\xe41^\x9b\
\xb4+r\x07\xd0j<\x86+\xd3v\x85n@\xfa\x0d\
G\x90\xc5zn\xd0\xad\xc8\x1fA\xa8\xf2\x18\xafM\xda\
\x15\xb9\x03\xe85\x1eC\x15\xe9\xbbB\xb7\xe0}\x06\xa3\
\xc8b\xbd7hV\xe4\x0f\xa0\xd4y... | Python | 1 |
_expr(c)?;
}
Ok(())
}
#[test]
fn test_parse_charstr() -> anyhow::Result<()> {
for c in vec![
(
"''",
Expr::charstr_lit(CharStr {
charset: None,
first: "",
rest: vec![],
}),
),
(
"'123'",
... | Rust | 0 |
-----------
# Operations with timedelta-like others
@pytest.mark.parametrize('names', [(None, None, None),
('Egon', 'Venkman', None),
('NCC1701D', 'NCC1701D', 'NCC1701D')])
def test_tdi_mul_int_series(self, names):
# GH#1... | Python | 1 |
) -> bool {
*self == PORTSEL6R::GPIO_PORT_3
}
#[doc = "Checks if the value of the field is `GPIO_PORT_4`"]
#[inline]
pub fn is_gpio_port_4(&self) -> bool {
*self == PORTSEL6R::GPIO_PORT_4
}
#[doc = "Checks if the value of the field is `GPIO_PORT_5`"]
#[inline]
pub fn is_g... | Rust | 0 |
/holidays for a consistent dataset
merged_df = merged_df.ffill()
print(f"Successfully merged data for all symbols. Final shape: {merged_df.shape}")
return merged_df
from src.database.session import SessionLocal
if __name__ == '__main__':
db_session = SessionLocal()
collector = MacroDa... | Python | 1 |
# -*- coding: utf-8 -*-
import numpy as np
#
# EXERCISE 2
#
def main():
npts = 64 # number of data points per cartesian direction
sz = 10 # size of the cubic unit cell
# load datasets
mo5 = np.load('../data/mo5.npy')
mo6 = np.load('../data/mo6.npy')
# perform FFT transform
ct ... | Python | 1 |
Ipc,
/// Unshare user namespace. This allows unprivileged user to be root
/// user in new namespace and/or change mappings between real (outer)
/// user namespace and the inner one.
///
/// This one is required if you want to unshare any other namespace without
/// root privileges (it's not ... | Rust | 0 |
let tx = gen_tx(&mut data_loader, lock_args, message.to_vec().into());
let tx = tx
.as_advanced_builder()
.set_witnesses(vec![WitnessArgs::new_builder()
.lock(Some(signature.clone()).pack())
.build()
.as_bytes()
.pack()])
.build();
let res... | Rust | 0 |
import sys
import os
# Add the framework directory to the Python path
# This allows us to import the agent module directly
framework_path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'mahbub_agent_framework'))
sys.path.insert(0, framework_path)
from agent.agent import Agent
def main():
"""
Main ... | Python | 1 |
#[test]
fn triangles() {
let mut rp = rust_protobuf_protos::triangle::Triangle::new();
let mut pr = prost_protos::Triangle::default();
rp.description = "The triangle".to_owned();
pr.description = "The triangle".to_owned();
rp.color = rust_protobuf_protos::triangle::Colo... | Rust | 0 |
`.
// This test checks that the we do not call `Duration::new()`.
let encoded = (num_secs, num_nanos).encode();
assert!(Duration::decode(&mut &encoded[..]).is_err());
}
#[test]
fn string_invalid_utf8() {
// `167, 10` is not a valid utf8 sequence, so this should be an error.
let mut bytes: &[u8] = &[20, 11... | Rust | 0 |
# 这里有浅显易懂的Python教程
# 更多教程和代码案例,请关注公众号:Crossin的编程教程
import requests
import json
from datetime import datetime
import matplotlib.pyplot as plt
money = 100
fundCode = '160135' #基金代码
pageIndex = 1
startDate = '2018-08-21' #起始时间
endDate = '2020-03-03' #截止时间
header = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Wi... | Python | 1 |
// M-2
for name in &names {
println!("{}", name);
}
//--------------------------------------------------------------
// M-3
// If this line doesn't exist, then it throws error like 'can't be used' as already used before in `for-range`
let names: Vec<&str> = vec!["Abhi", "Sam", "McLaren... | Rust | 0 |
derive(Clone,Hash,Eq,PartialEq,strum_macros::Display)]
pub enum LaneKey {
Proto(u64),
Ultima(UltimaLaneKey)
}
impl LaneKey {
pub fn is_proto(&self) -> bool {
match self {
Self::Proto(_) => true,
_ => false
}
}
}
impl TryInto<UltimaLaneKey> for LaneKey {
ty... | Rust | 0 |
been used
/// to initiate an overlapped I/O operation, and returns either the
/// successful number of bytes transferred during the operation or an error
/// if one occurred, along with the results of the `lpFlags` parameter of
/// the relevant operation, if applicable.
///
/// # Unsafety
/... | Rust | 0 |
image%7C1%2C2%2C3&assets=image&collection=naip"
)
response = await client.get(url)
assert response.status_code == 200
async def test_info_path_with_searchid(
client: AsyncClient, register_search: REGISTER_TYPE
) -> None:
# route source code is in titiler/mosaic/titiler/mosaic/factory.py#L157
#... | Python | 1 |
}
}
cfg_if! {
if #[cfg(target_arch = "x86")] {
mod x86;
pub use self::x86::*;
} else if #[cfg(target_arch = "x86_64")] {
mod x86_64;
pub use self::x86_64::*;
} else if #[cfg(target_arch = "aarch64")] {
mod aarch64;
pub use self::aarch64::*;
} else if #[cf... | Rust | 0 |
from dataclasses import dataclass
from typing import Dict, Sequence
import omegaconf
import torch
import transformers
@dataclass
class DataCollatorForSupervisedDataset(object):
"""Collate examples for supervised fine-tuning."""
tokenizer: transformers.PreTrainedTokenizer
def __call__(self, instances: S... | Python | 1 |
ions['DEFAULT']
self.test_configs_factory.add_new_config(chain,
self.received_configurations)
self.test_contract_alerter._initialise_rabbitmq()
method = pika.spec.Basic.Deliver(
routing_key=CL_CONTRACT_TRANSFORMED_DATA_ROUTING_KEY)
... | Python | 1 |
import math
import scipy.special
time: float = 0.0
p1: float = 4.00000000000000
p2: float = 25.0000000000000
compartment: float = 1.00000000000000
S1: float = 1.00000000000000
S2: float = 0.0
# Initial assignments
S1_conc = S1 / compartment
S2_conc = S2 / compartment
reaction1 = scipy.special.factorial(math.ceil(S1_... | Python | 1 |
from __future__ import annotations
import pandas as pd
from pytest import approx
from pymatgen.analysis.magnetism.heisenberg import HeisenbergMapper
from pymatgen.core.structure import Structure
from pymatgen.util.testing import TEST_FILES_DIR
TEST_DIR = f"{TEST_FILES_DIR}/analysis/magnetic_orderings"
class TestHe... | Python | 1 |
lib.rs
#![feature(box_patterns)]
#![feature(refcell_replace_swap)]
#![recursion_limit="1024"]
#[macro_use]
extern crate immut_send;
#[macro_use]
extern crate log;
#[macro_use]
extern crate error_chain;
#[macro_use]
extern crate serde_derive;
extern crate service_pre;
extern crate serde;
extern crate serde_json;
extern ... | Rust | 0 |
# Copyright (c) June 02, 2017 CareerMonk Publications and others.
# E-Mail : info@careermonk.com
# Creation Date : 2017-06-02 06:15:46
# Last modification : 2017-06-02
# Modified by : Narasimha Karumanchi
# Book Title : Algorithm Design Techniques
# Warranty : This software is pro... | Python | 1 |
xelFormat = 167;
pub const AVPixelFormat_AV_PIX_FMT_GRAY12BE: AVPixelFormat = 168;
pub const AVPixelFormat_AV_PIX_FMT_GRAY12LE: AVPixelFormat = 169;
pub const AVPixelFormat_AV_PIX_FMT_GRAY10BE: AVPixelFormat = 170;
pub const AVPixelFormat_AV_PIX_FMT_GRAY10LE: AVPixelFormat = 171;
pub const AVPixelFormat_AV_PIX_FMT_P016... | Rust | 0 |
e = true;
objects.push(stairs);
map
}
fn place_objects(room: Rectangle, map: &Map, objects: &mut Vec<Object>, level: u32) {
// monster random table
let max_monsters = from_dungeon_level(
&[
Transition { level: 1, value: 2 },
Transition { level: 4, value: 3 },
... | Rust | 0 |
}
}
impl<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9> CombinConcat<(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9)> for () {
type Out = (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9);
#[allow(unused_variables)]
fn concat(self, target: (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9)) -> Self::Out {
(target.0, target.1, targe... | Rust | 0 |
[16:])
f.close()
print('')
print('Output MOBI file: %s' % outmobi)
with open(outmobi, 'wb') as f:
self.f.seek(0)
f.write(self.f.read(78))
# replace srcs section with 2-zero bytes
recordlist_data = array.array('B', self.f.read(8 * self.h... | Python | 1 |
SpeechWordType,
SWTAdded,
SWTDeleted,
DISPID_SpeechLexiconWord,
DISPID_SLWLangId,
DISPID_SLWType,
DISPID_SLWWord,
DISPID_SLWPronunciations,
DISPID_SpeechLexiconProns,
DISPID_SLPsCount,
DISPID_SLPsItem,
DISPID_SLPs_NewEnum,
DISPID_SpeechLexiconPronunciation,
DISPID... | Rust | 0 |
decomposition.
pub fn into_pl(mut self) -> ArrayBase<S, Ix2> {
if self.pivots.len() < self.lu.nrows() {
let next = self.pivots.len();
self.pivots.extend(next..self.lu.nrows());
}
for i in (0..self.pivots.len()).rev() {
let target = self.pivots[i];
... | Rust | 0 |
server).unwrap();
Status::ok(edit_transaction.add(&mut make_rule().into()).await.unwrap()).unwrap();
assert_eq!(Status::from_raw(edit_transaction.commit().await.unwrap()), Status::ACCESS_DENIED);
assert_eq!(get_rules(&env.proxies.rewrite_engine).await, vec![]);
env.stop().await;
}
#[fasync::run_singl... | Rust | 0 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'imgModule.ui'
#
# Created by: PyQt5 UI code generator 5.15.9
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, Qt... | Python | 1 |
is_empty(&self) -> bool;
fn get(&self, h: NodeHandle) -> Option<&T>;
fn get_mut(&mut self, h: NodeHandle) -> Option<&mut T>;
fn insert(&mut self, val: &T) -> Result<u32, ()>;
fn remove(&mut self, h: NodeHandle) -> Option<T>;
fn contains(&self, h: NodeHandle) -> bool;
}
impl SlabView<AnyNode> for S... | Rust | 0 |
import os
from requests import get
from core.colors import info, good
def updater():
print('%s Checking for updates' % run)
changes = '''--exclude option to exclude urls with regex;minor refactor''' # Changes must be seperated by ;
latest_commit = get('https://raw.githubusercontent.com/s0md3v/Kozmo/master/... | Python | 1 |
"""绘制标量正态逆卡方分布"""
import numpy as np
import matplotlib.pylab as plt
from gaussInvWishart import gauss_inv_wishart_log_prob
from mpl_toolkits.mplot3d import axes3d
plt.rcParams["figure.figsize"]=(21,6)
mu = [0, 0, 0]
k = [1, 5, 1]
v = [1, 1, 5]
s = [1, 1, 1]
n_points = 100
fig = plt.figure()
for m in range(len(mu)):
... | Python | 1 |
strum(props(Red="0",Blue="0",Green="255"))]
//! Green,
//! }
//!
//! fn main() {
//! let my_color = Color::Red;
//! let display = format!("My color is {:?}. It's RGB is {},{},{}", my_color
//! , my_color.get_str("Red").unwrap()
//! ... | Rust | 0 |
from .dump_handler import BackUp | Python | 1 |
h, self.s, self.l ,self.a)
}
}
impl HslColor
{
pub fn new(h : u16, s : u8, l : u8) -> Self
{
Self::from_hsla(h, s, l, 255)
}
pub fn from_hsla(h : u16, s : u8, l : u8, a : u8) -> Self
{
Self
{
h : utils::crop_range(h,0,360),
s : utils::crop_range... | Rust | 0 |
from microbit import i2c
from microbit import sleep
# dopredna_rychlost v je float
# rotace je uhlova rychlost omega a take float
# Poznámka: samotná velikost čísel ještě nebude dávat smysl,
# tzn dopredna_rychlost NENÍ v m/s, ale v nějakých nedefinovaných jednotkách…
# tento problém odstraníme příští hodinu
def jed(... | Python | 1 |
#
# Copyright (c) 2023 Airbyte, Inc., all rights reserved.
#
import os
import pytest
import yaml
from octavia_cli.generate.commands import generate_source_or_destination
pytestmark = pytest.mark.integration
@pytest.mark.parametrize(
("definition_type, definition_id, resource_name"),
[
("source", "6... | Python | 1 |
self.shared.borrow().fetch_shared::<T>()
}
}
#[derive(Debug, Clone)]
pub struct UnifiedResources<'a> {
pub local: SharedResources<'a>,
pub global: SharedResources<'a>,
}
impl<'a> UnifiedResources<'a> {
pub fn new() -> Self {
Self {
local: SharedResources::new(),
... | Rust | 0 |
#8[9, 27], #9[10, 30], #10[19, 14]
let a = get_complex_polygon("rand54r");
let b = get_complex_polygon("rand55r");
let r = Snipper::union(a, b);
assert!(r.is_ok(), "{:?}", r.err());
}
#[test]
fn forty_second_random_fiasco_test() {
// When builder follows chain, the search_start information is los... | Rust | 0 |
mentor = {}
mentore = {}
def add_mentor():
nom_mentor = input("nom du mentor:")
expertise = input("Expertise du mentor:")
mentor[nom_mentor] = expertise
if nom_mentor in mentor:
print(f"mentor{nom_mentor} ajouté avec succes.")
def add_mentore():
nom_mentor = input("nom du mento... | Python | 1 |
"""
Normals on front and back
=========================
This example validates that normals are handled such that both the front
and back faces are lit. Further it validates the appearance of the
normal lines material.
This shows a flattened cylinder, with normal lines sticking out both
at the front and back faces.
"... | Python | 1 |
>Edit</b> permission for <b>Chat Messages</b>.</p>
*
* **Scopes:** `chat_message:read`, `chat_message:read:admin`<br>**[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Medium`
*
* **Parameters:**
*
* * `to_contact: &str` -- The email address of... | Rust | 0 |
def add_entry(dictionary):
word = input("Enter the word: ")
meaning = input("Enter the meaning: ")
dictionary[word] = meaning
print(f"Entry added: {word}: {meaning}")
def search_word(dictionary):
word = input("Enter the word to search: ")
if word in dictionary:
print(f"Meaning of '{word... | Python | 1 |
== 4 {
num_allies + 1 // skip player position
} else {
num_allies
} as i32;
let row = ind / 3 - 1;
let col = ind % 3 - 1;
(row as f32 * 32.0, col as f32 * 32.0)
};
let (p_transform, allies_count, p_entity) = {... | Rust | 0 |
{1faa0}', 'ჾ', '🡇', '𑰎', '🝐',
'𝚤', '‘', '\u{116b4}', '𝈞', '𔗁', '𛁥', '𑊀', 'ᡲ', '⤝', '⥙', '𝝸',
'ⱳ', '🥩', '𑄇', 'Ծ', 'ꓛ', 'ㄠ', '⬋', '𐜳', '𞸶', 'પ', 'ﲶ', '𘫠',
'𐳁', 'ᾤ', '𓍾', 'ﳛ', 'ഴ', '🎧', 'द', '\u{18bfa}', 'Α', '𒂹', '\u{fb4}',
'Ⳣ', 'ࡠ', 'イ', '\u{18bed}', '𐅀', '⭔', '⺈', '𖫪', '⻣', '㉘', 'Ⳁ',... | Rust | 0 |
s.add(objname)
else:
# We were given a schema.*; we'll process those below
schemas.append(objname.only_schema())
for schema in schemas:
# For schemas, we wish to have privileges for all existing objects, so get all
# existing objects not owned... | Python | 1 |
"""
聚类相关工具函数,用于PatchSearch防御中的特征聚类。
"""
import torch
import torch.nn as nn
import numpy as np
import faiss
from sklearn.metrics import pairwise_distances
def faiss_kmeans(train_feats, nmb_clusters):
"""
使用FAISS对特征进行k-means聚类
参数:
train_feats: 特征张量,形状为[N, D]
nmb_clusters: 聚类数量
... | Python | 1 |
let (res_meta, doc_opt, doc_meta_opt) =
resolver.resolve(&id, &res_input_meta).await;
let (mut parts, _) = Response::<Body>::default().into_parts();
if res_meta.error == Some(ERROR_NOT_FOUND.to_string()) {
parts.status = StatusCode... | Rust | 0 |
zip
/log.tgz
/log.tar.bz2
/log.7z
/env
/.env
/.ssh/
/phpmyadmin/index.php
/phpMyAdmin/index.php
/pma/index.php
"""
globals()['web_path_data'] = web_path_data.split()
class VulnChecker(VulnCheck):
def __init__(self, ip_and_port_list):
self._name = 'web_sensitive'
self.info = "Scan the Web sensitive ... | Python | 1 |
n self._WorkId
@WorkId.setter
def WorkId(self, WorkId):
self._WorkId = WorkId
@property
def WorkName(self):
return self._WorkName
@WorkName.setter
def WorkName(self, WorkName):
self._WorkName = WorkName
@property
def WorkType(self):
return self._WorkTy... | Python | 1 |
(32-bit)
/// floating-point elements in `a` and `b`, and pack the results.
///
/// [Intel's documentation](https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_hsub_ps)
#[inline]
#[target_feature(enable = "sse3")]
#[cfg_attr(test, assert_instr(hsubps))]
#[stable(feature = "simd_x86", since = "1.27.0"... | Rust | 0 |
::ok(()).boxed();
}
(self.0).0.channels_voice.insert(entity.id(), entity);
future::ok(()).boxed()
}
}
impl VoiceChannelRepository<InMemoryBackend> for InMemoryVoiceChannelRepository {
fn guild(
&self,
channel_id: ChannelId,
) -> GetEntityFuture<'_, GuildEntity, InM... | Rust | 0 |
);
if let Some(line_number) = self.line_number {
write!(output, "#L{}", line_number)?;
}
Ok(output)
}
}
fn get_reference(repository: &Repository, ref_type: RefType) -> Result<String> {
match ref_type {
RefType::Commit => {
let head = repository.revparse_... | Rust | 0 |
_SHADER_EXT: GLenum = GLenum(0x9307);
pub const GL_REFERENCED_BY_TESS_CONTROL_SHADER_OES: GLenum = GLenum(0x9307);
pub const GL_REFERENCED_BY_TESS_EVALUATION_SHADER: GLenum = GLenum(0x9308);
pub const GL_REFERENCED_BY_TESS_EVALUATION_SHADER_EXT: GLenum = GLenum(0x9308);
pub const GL_REFERENCED_BY_TESS_EVALUATION_SH... | Rust | 0 |
because we want to change both bytes of the program's address. We
// resize the memory so that it contains zeros until 0xF101.
program.resize(0x101, 0);
// Finally, the second program. It stores 2 at 0x0000.
program.extend_from_slice(&[opcodes::LDX_IMM, 2, opcodes::STX_ZP, 0]);
let mut cpu = cpu_w... | Rust | 0 |
class SelectDB:
def __init__(self):
self.select_query = None
def select_external_source(self, application_id=None):
self.select_query = f"SELECT stage, source, request_status, request_time, response_time " \
f"FROM external_source es " \
... | Python | 1 |
a8e4}\u{a8e4}\u{a8e4}\u{a8e4}\u{34f}\u{a8c4}\u{a8e4}\u{a8e4}\u{a8e4}\u{a8e4}Z");
assert_eq!(TextString::from_text_lossy("A\u{a8e1}\u{324}\u{a8c4}\u{a8e4}\u{a8e4}\u{a8e4}\u{a8e4}\u{a8e4}\u{a8e1}\u{324}\u{a8c4}\u{a8e4}\u{a8e4}\u{a8e4}\u{a8c4}\u{a8e4}\u{a8e4}\u{a8c4}\u{a8e1}\u{324}\u{a8c4}\u{a8e4}\u{a8e4}\u{a8e4}\u{a8... | Rust | 0 |
::UART1_RX);
fpioa::set_function(io::WIFI_EN, fpioa::function::GPIOHS8);
fpioa::set_io_pull(io::WIFI_EN, fpioa::pull::DOWN);
gpiohs::set_pin(8, true);
gpiohs::set_direction(8, gpio::direction::OUTPUT);
buffered_uart::init();
let mut wa = WriteAdapter::new();
let mut sh = SerialNetworkHandle... | Rust | 0 |
bpy.props.FloatVectorProperty(name="目标骨骼位置", size=3, default=(0.0, 0.0, 0.0))
# 存储计算的偏移量
calculated_offset: bpy.props.FloatVectorProperty(name="计算的偏移", size=3, default=(0.0, 0.0, 0.0))
# === UI 面板 ===
class BONEOFFSET_PT_Panel(bpy.types.Panel):
bl_label = "骨骼偏移工具"
bl_idname = "BONEOFFSET_PT_Panel"
... | Python | 1 |
.open_subkey_with_flags("Software\\Valve\\Steam", KEY_READ).expect("Cannot open steam registry key!");
let steam_location: String = steam_key.get_value("SteamPath").expect("Cannot read SteamPath key!");
return Path::new(&steam_location).to_path_buf();
}
/// Returns (VersionsDirectory, CurrentPlayerLauncherPath... | Rust | 0 |
DeprecatedModule(
pipelines,
deprecated_attributes=[
"JoinDocuments",
"Docs2Answers",
],
),
)
setattr(pipelines, "preprocessor", DeprecatedModule(preprocessor, deprecated_attributes=["utils", "cleaning"]))
setattr(pipelines, "ranker", DeprecatedModule(ranker))
setattr... | Python | 1 |
"""
MCP Repository - MCP服务器数据访问层
"""
from typing import Optional, List, Dict, Any
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, and_, or_, update, delete
from datetime import datetime
from ..core.repository import BaseRepository
from ..domain.models.mcp import MCPServer
from ..core.log... | Python | 1 |
: Key length
// // [2] : Value length
// // [3] : Height
// // [3..height] : Next nodes
// nodeData []int
// prevNode [tMaxHeight]int
// maxHeight int
// n int
// kvSize int
// }
#[allow(non_camel_case_types)]
struct db<T: Comparer> {
cmp: T,
// rnd:rand
// 存储实际key,va... | Rust | 0 |
opt_state_enc = tx_enc.init(params_enc)
opt_state_head = tx.init(params_head)
else:
opt_state_enc, opt_state_head = None, None
return cls(step=1,
apply_fn=model_def,
params=params,
tx=tx,
tx_en... | Python | 1 |
sert!(is_valid_jcb("3588337499926343"));
assert!(!is_valid_jcb("3588337499926345"))
}
}<gh_stars>1-10
// Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <<EMAIL>>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in... | Rust | 0 |
rmute(1, 0)
vascular_scores = torch.matmul(Q, K)
# softmax获取权重
vascular_weights = F.softmax(vascular_scores, dim=-1)
output = torch.matmul(vascular_weights, V)
# 将输出的形状调整回原来的形状
output = output.permute(1, 0)
return output
class Pixel_Extractor(nn.Module):
def __init__(self):
supe... | Python | 1 |
ue::GenericValueTypeChecker<Self>;
unsafe fn from_value(value: &'a glib::Value) -> Self {
from_glib(glib::gobject_ffi::g_value_get_flags(value.to_glib_none().0))
}
}
#[cfg(any(feature = "v1_24", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v1_24")))]
impl ToValue for ClientInstanc... | Rust | 0 |
orphan child "
"processes behind: {1!r}",
tests_pid,
sorted({proc.pid for proc in leftover_processes}),
)
for proc in leftover_processes:
log.warning(
"WatchDog-{0} killing orphaned test child process (pid={1})",
tests_pid... | Python | 1 |
import matplotlib.pyplot as plt
from dython.nominal import associations
import pickle
import os
# unsensitized group, those who had NO Ab prior
# all group, all p's unsensitized and presensitized
dataset_dict = {
'unsens': {'f': 'cleaned_df_with_missing_no_pre_spec', 'suffix': '_unsens'},
'all': {'f': 'cleaned_df_wi... | Python | 1 |
G_WORKER.deserialize_from_bytes_event):
handler = BytesIO(serialized_content_bytes)
ret, close_handler = deserialize_from_handler(
handler, show_exception, logger
)
if close_handler:
handler.close()
return ret
def serialize_objects(to_serialize: list, lo... | Python | 1 |
:
# Test the dialogue logger
logger = DialogueLogger("1")
# Log a complete exchange
logger.log_complete_exchange(
system_prompt="You are a code implementation assistant.",
user_message="Implement the transformer model",
assistant_response="I'll implement the transformer model st... | Python | 1 |
"""
Drop an entire schema (`app`).
Example SQL:
DROP SCHEMA `app`;
We would expect the schema and it's children to be removed.
"""
from app.revisioner.tests.e2e import inspected
from app.revisioner.tests.test_e2e import mutate_inspected
preload_fixtures = ['datastore']
inspected_tables = mutate_inspected(inspec... | Python | 1 |
'''
1. 연구소를 돌아다니면서 0인 셀 3개를 정해서 벽을 세움.
2. 벽 3개가 정해졌을 때 바이러스를 퍼뜨리고 0의 개수 구하기
'''
# import sys, copy
# sys.stdin= open('input.txt')
n,m=list(map(int,input().split()))
lab=[[0]*m for _ in range(n)]
spaces=[]
viruss=[]
for i in range(n):
temp =list(map(int,input().split()))
for j in range(m):
lab[i][j] = ... | Python | 1 |
border*2, border*2,)), (0, tileSize + border, tileSize + border*2, tileSize + border*2))
b_im.paste(t_im.crop((0, tileSize, tileSize + border*2, tileSize + border)), (0, 0, tileSize + border*2, border))
t_im.save(output + tilesStr + str(level) + "/tile_" + str(level) + "_" + str(i) + "_" + str((maxTiles >> (l... | Python | 1 |
# ==============================================================================
# Copyright 2018-2020 Intel Corporation
#
# 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://ww... | Python | 1 |
ct = _PollUntilBuildCompletes(build_op_ref)
return response_dict, build_log_url, build_response.baseImageUri
def _PollUntilBuildCompletes(build_op_ref):
client = cloudbuild_util.GetClientInstance()
poller = waiter.CloudOperationPoller(
client.projects_builds, client.operations
)
operation = waiter.Pol... | Python | 1 |
#!/usr/bin/env python
#
# Script name : allied-tftp-server-sploit.py
# Req Modules : netifaces
# Author : wetw0rk
# Discovered by : liuqx@nipc.org.cn
# Version : 1.0
# Python Vers. : 2.7
# Description : This exploit allows for remote code execution on
# the Allied Telesyn AT-TFTP Server/Daemon 1.9
#
import sys, soc... | Python | 1 |
}
impl fmt::Display for ApArgument<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use ApArgument::*;
match self {
InitPeerId => write!(f, "%init_peer_id%"),
LastError(error_accessor) => display_last_error(f, error_accessor),
Literal(str) => wri... | Rust | 0 |
uld you like to examine? (Enter the number): ")) - 1
if 0 <= choice < len(self.evidence):
item = self.evidence[choice]
print(f"\n{item.get_description(self.murder_weapon == item)}")
else:
print("\nInvalid choice.")
except ValueError:
... | Python | 1 |
"Found ",
str(len(hu_matched_img_json_pairs))
+ " pairs of images and HUMAN detection data to try to ID",
)
# Example Pair
print("example human detection and json pair:")
if(len(hu_matched_img_json_pairs)>0):
print(hu_matched_img_json_pairs[0])
print(
"Found "... | Python | 1 |
shoot = int_to_bool(b);
}
#[no_mangle]
pub extern "C" fn toggle_boost(b: c_int) {
let data = &mut DATA.lock().unwrap();
data.actions.boost = int_to_bool(b);
}
#[no_mangle]
pub extern "C" fn toggle_turn_left(b: c_int) {
let data = &mut DATA.lock().unwrap();
data.actions.rotate_left = int_to_bool(b);
}
... | Rust | 0 |
"""Tests for gee_is_derived."""
from checker import test_utils
from checker.node import gee_provider_ids
from absl.testing import absltest
PROVIDER_ID_1 = 'ONE23-ID4_5'
PROVIDER_ID_2 = 'WX-YZ'
class ValidGeeProviderIdsTest(test_utils.NodeTest):
def setUp(self):
super().setUp()
self.check = gee_provider_i... | Python | 1 |
-> None:
"""Test behaviour if device already configured."""
entry = MockConfigEntry(
domain=config_flow.DOMAIN,
data={CONF_IP_ADDRESS: "172.100.123.4"},
unique_id="abcd0123ef5678",
)
entry.add_to_hass(hass)
feature: AsyncMock = mock_feature(
"sensors",
blebox... | Python | 1 |
# -*- coding: utf-8 -*-
import logging
from operator import attrgetter
from django.db import models
from system.official_account.models import OfficialAccount
from system.rule.models import Rule
logger_keyword = logging.getLogger(__name__)
class KeywordManager(models.Manager):
"""
微信关键字表 Manager
"""
... | Python | 1 |
oduct_code2, ... ],
'category': [ category1, category2, ... ],
'tradings': [ trading_period1, trading_period2, ... ],
}
market: str 市场代码
codeRegex: str 代码匹配规则
product_code: str 产品代码
category: int 证券分类
通过指定stock_code获取到的交易时段信息已经是和这个品种匹配的,
... | Python | 1 |
# Generated by Django 5.0.2 on 2024-02-25 20:44
import authentik.lib.utils.time
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
("authentik_core", "0033_alter_user_options"),
("authentik_flows",... | Python | 1 |
: results,
}
return await loop.run_in_executor(None, perform_search)
# Execute all queries concurrently
tasks = [process_single_query(query) for query in search_queries]
search_docs = await asyncio.gather(*tasks)
return search_docs
async def select_and_execute_search(
search... | Python | 1 |
ushort,
pub http_minor: libc::c_ushort,
pub _extended_status: libc::uint32_t,
// Public Interface
pub data: *mut libc::c_void
}
unsafe impl Send for HttpParser { }
impl HttpParser {
pub fn new(parser_type: ParserType) -> HttpParser {
let mut p: HttpParser = unsafe { mem::uninitialized() }... | Rust | 0 |
original username
'''
base_username = user_username
if user := await exists_checker(base_username):
return user
sep = "_"
hash_str = username_hash(base_username)
while True:
user_username = f"{user_username}{sep}{hash_str}"
if len(user... | Python | 1 |
Header(Type=213)]
def __init__(self, with_options=False, with_security=False, **kwargs):
Layer3NAS.__init__(self, with_security)
self.extend([
Int('ESMCause', Pt=0, Type='uint8', Dict=ESMCause_dict),
Type4_TLV('ProtConfig', ReprName='Protocol Config Options',
... | Python | 1 |
<LittleEndian>().unwrap(),
);
let wheel_speed = WheelData::new(
reader.read_f32::<LittleEndian>().unwrap(),
reader.read_f32::<LittleEndian>().unwrap(),
reader.read_f32::<LittleEndian>().unwrap(),
reader.read_f32::<LittleEndian>().unwrap(),
);
let wheel_slip = WheelData:... | Rust | 0 |
import streamlit as st
import json
from crewai import Crew
from pydantic import BaseModel
from crewagents import run
@st.cache_data
def generate_response(tour_place, tour_budget, Hotel_budget, Duration):
# run this function from cache if exists otherwise it will run the "run" from crewagent.py file
return run(... | Python | 1 |
codec(index = 42)]
CumulusXcm(cumulus_xcm::Event),
#[codec(index = 43)]
DmpQueue(dmp_queue::Event),
#[codec(index = 50)]
Oracle(oracle::Event),
#[codec(index = 51)]
Tokens(tokens::Event),
#[codec(index = 52)]
Factory(factory::Event),
#[codec(index = 53)]
Vault(vault::Event),
#[codec(index = 54)]... | Rust | 0 |
SRAM2W {
_SRAM2W { w: self }
}
#[doc = "Bit 4 - This bit is 1 if power is supplied to SRAM GROUP1"]
#[inline]
pub fn sram1(&mut self) -> _SRAM1W {
_SRAM1W { w: self }
}
#[doc = "Bit 3 - This bit is 1 if power is supplied to SRAM GROUP0"]
#[inline]
pub fn sram0(&mut self) ... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.