text string | label_name string | labels int64 |
|---|---|---|
T::SubmissionDeposit::get();
let imb = T::Currency::withdraw(
&creator,
deposit,
WithdrawReasons::TRANSFER,
ExistenceRequirement::AllowDeath,
)?;
let index = <FundCount<T>>::get();
// not protected against overflow, see safemath section
<FundCount<T>>::put(index + 1);
// No fees are ... | Rust | 0 |
from sympy.assumptions.ask import Q
from sympy.core.basic import Basic
from sympy.core.expr import Expr
from sympy.core.mul import Mul
from sympy.core.symbol import symbols
from sympy.logic.boolalg import (And, Or)
from sympy.assumptions.sathandlers import (ClassFactRegistry, allargs,
anyarg, exactlyonearg,)
x, y... | Python | 1 |
< HashSet< DataId > > >
}
impl ClientLifetime {
fn new( clients: &Arc< Mutex< HashSet< DataId > > >, id: DataId ) -> Option< ClientLifetime > {
let mut guard = clients.lock().unwrap();
if guard.contains( &id ) {
return None;
}
guard.insert( id );
Some( ClientLif... | Rust | 0 |
({
"update_id": 1,
"message": {
"message_id": 1111,
"date": 0,
"from": {"id": 1, "is_bot": false, "first_name": "test"},
"chat": {"id": 1, "type": "private", "first_name": "test"},
"text": "test message from private ... | Rust | 0 |
= 3,
}
#[repr(C)]
pub struct RawNode {
subject: Key,
product: TypeConstraint,
// The Value represents a union tagged with RawStateTag.
state_tag: u8,
state_value: Value
}
impl RawNode {
fn create(subject: &Key, product: &TypeConstraint, state: Option<RootResult>) -> RawNode {
let (state_tag, state_val... | Rust | 0 |
d_(Lowered::new(&x));
// Try tricking `new_async` into thinking the future was awaited by polling on it
let waker = nop_waker();
let mut fake_cx = Context::from_waker(&waker);
Box::pin(future).as_mut().poll(&mut fake_cx);
// .. but await a different future instead
NopFu... | Rust | 0 |
_arbitrary(any::<u32>().prop_map(TestEnum::A));
}
#[test]
fn auto_bound_any_attribute() {
#[derive(Arbitrary, Debug, PartialEq)]
struct TestStruct<T>(#[any(std::default::Default::default())] T);
assert_arbitrary(any::<u16>().prop_map(TestStruct));
assert_arbitrary(any::<u32>().prop_map(TestStruct));
}... | Rust | 0 |
} else {
i += 1;
}
}
nums.len() as i32
}
}
// -----------------------------------------------------------------------------
<gh_stars>0
#![allow(unused)]
pub struct Solution {}
impl Solution {
// Time O(k + M * N) Space O(M * N) k is length of positions
pub f... | Rust | 0 |
# 落子者
from enum import Enum, unique
PLAYER_BLACK = 1
PLAYER_WHITE = -1
PLAYER_EMPTY = 0
KL_TARG = 0.02
# 赢棋者
@unique
class Winner(Enum):
EMPTY = PLAYER_EMPTY
BLACK = PLAYER_BLACK
WHITE = PLAYER_WHITE
if __name__ == "__main__":
print(Winner.WHITE.value.real)
| Python | 1 |
(0 as *const sfInputStream)).userData as *const _ as usize },
32usize,
concat!(
"Alignment of field: ",
stringify!(sfInputStream),
"::",
stringify!(userData)
)
);
}
impl Clone for sfInputStream {
fn clone(&self) -> Self {
*self
... | Rust | 0 |
}
})
}
}
impl Function {
pub fn args_compatible(
&self,
args: &[NameUnion],
ctx: &Context,
pos: &Position
) -> TypeResult<()> {
for pair in self.arguments.iter().zip_longest(args) {
match pair {
EitherOrBoth::Both(fun_param, arg) =... | Rust | 0 |
import json
from typing import Any, Dict, Optional
from tau_bench.envs.tool import Tool
class GetFunds(Tool):
@staticmethod
def invoke(data: Dict[str, Any], filters: Optional[Dict[str, Any]] = None) -> str:
funds = data.get("funds", {})
results = []
if not filters:
... | Python | 1 |
import argparse
import time
import mlx.core as mx
from decoder import SpeculativeDecoder
from mlx.utils import tree_unflatten
from model import Model
from transformers import T5Config
def load_model(model_name: str):
config = T5Config.from_pretrained(model_name)
model = Model(config)
weights = mx.load(f"... | Python | 1 |
ypes.DevEUI\xe2\xde\x1f\x06DevEUI\x12\x20\n\x06app_id\x18\x03\x20\
\x01(\tR\x05appIdB\t\xe2\xde\x1f\x05AppID\x12\x20\n\x06dev_id\x18\x04\
\x20\x01(\tR\x05devIdB\t\xe2\xde\x1f\x05DevID\x12Q\n\x08dev_addr\x18\x05\
\x20\x01(\x0cR\x07devAddrB6\xda\xde\x1f2github.com/TheThingsNetwork/ttn/\
core/types.DevAddr... | Rust | 0 |
from_objc_protocol("A"), Usr("c:objc(pl)A".into()));
}
use crate::ast::{Expr, ExprNode, Expression, Exprs, Id, Node, Op};
/// An assignment.
/// The expression(s) in targets should be one of Id, Subscript, or Attribute.
#[derive(Debug, PartialEq)]
pub struct Assign<'a> {
pub targets: Exprs<'a>,
pub expr: ExprN... | Rust | 0 |
from enum import Enum
class TokenType(Enum):
LPAREN = "("
RPAREN = ")"
LBRACE = "{"
RBRACE = "}"
LBRACKET = "["
RBRACKET = "]"
QUOTE = "'"
DOUBLE_QUOTE = '"'
STRING = "STRING"
NUMBER = "NUMBER"
IDENTIFIER = "IDENTIFIER"
BOOLEAN = "BOOLEAN"
NIL = "NIL"
DOT = "."
... | Python | 1 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | Python | 1 |
import json
import subprocess
import sys
import time
import random
from typing import Any, Dict
def start_mcp_server() -> subprocess.Popen:
proc = subprocess.Popen(
["python", "main.py"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
... | Python | 1 |
from unittest import TestCase
from django.db import reset_queries
from everbug.utils.queries import wrap_queries
from tests.stub.models import AltEntity, Entity
def run_queries(multi_db=False, multi_query=False):
def run(db_model=None, multi=False):
list(db_model.objects.all())
if multi:
... | Python | 1 |
c = ncurses::ncurses;
// use t = ncurses::types;
use ncurses::window::{initscr};
use ncurses::window::Window;
fn status(line: int, win: &Window, b: bool, s: ~str) {
if b {
win.addstr(line, 2, ~" True: " + s);
} else {
win.addstr(line, 2, ~"False: " + s);
}
}
fn main() {
// Start curses... | Rust | 0 |
-13 n: ntnnnnnnnnknsn
1-7 d: lsddrwzzddhxddq
12-17 q: qjqqqrlqdqqvqwqqd
2-3 z: crzz
3-4 d: dtsd
3-5 k: hkgstlvxr
18-19 d: hswndtgrdtwtdddddpl
9-12 x: xxxqxxxxxxxjhxx
1-2 b: dpbb
8-15 h: bhhzkqhghhtphfzh
13-17 d: dnddddddddddddddxd
15-17 m: mmmmmmmmmmmmmmmmmmmm
5-11 r: rrrrwrrrrrwrr
4-6 v: vvvhvf
7-10 l: lllllltxlfllfll... | Rust | 0 |
parsityScheduler(magnitude_algo_mock, params=params)
mock = magnitude_algo_mock.set_sparsity_level
per_epoch_ref_level_sequences = [
[0.1, 85 / 810, 97 / 810],
[117 / 810, 145 / 810, 181 / 810],
[225 / 810, 277 / 810, 337 / 810],
[0.5, 0.5, 0.5],
... | Python | 1 |
import asyncio
import json
from aio_pika import IncomingMessage
from backend.notify_service.app.broker.connection import get_connection
from backend.notify_service.app.handlers import email, telegram
from backend.notify_service.app.utils.parse_body import (
parse_email_body,
parse_telegram_body,
)
from backen... | Python | 1 |
f):
# Status CPU
cpu_list = [{} for i in range(len(self._cpu))]
cpu_online = []
# Add cpu status with frequency and idle config
for cpu, data in enumerate(self._cpu):
# store all data
cpu_list[cpu] = read_system_cpu(data['path'], cpu_list[cpu])
... | Python | 1 |
istory[f'val_{metric}'])] += 1
train_avgs /= train_counts
val_avgs /= val_counts
# 绘制平均曲线
plt.plot(range(1, max_epochs+1), train_avgs, '-', label='Average Train', color='blue')
plt.plot(range(1, max_epochs+1), val_avgs, '-', label='Average Validat... | Python | 1 |
.fit_transform(eigenvecs.T, eigenvecs3.T)
print(time() - t0)
ccmat = np.corrcoef(evec1_c.T, evec3_c.T, )
np.diag(ccmat[50:,:50])
#%%
t0 = time()
n_comp = 100
cca_corr = cca_correlation(eigenvecs.T, eigenvecs3.T, n_comp=n_comp)
cca_corr_baseline = cca_correlation(eigenvecs.T, np.random.r... | Python | 1 |
# coding=utf-8
# 这是为instagram镜像配置的示例配置文件
#
# 使用方法:
# 1. 复制本文件到 zmirror 根目录(wsgi.py所在目录), 并重命名为 config.py
# 2. 修改 my_host_name 为你自己的域名
#
# 各项设置选项的详细介绍请看 config_default.py 中对应的部分
# 本配置文件假定你的服务器本身在墙外
# 如果服务器本身在墙内(或者在本地环境下测试, 请修改`Proxy Settings`中的设置
#
# instagram所有功能完整可用(暂时还没发现不能用的功能),
# 由于instagram官方的设定, 网页版是无法上传文件的, ... | Python | 1 |
error::{context, VerboseError},
// multi::{count, many0, many1, many_m_n},
// sequence::{preceded, separated_pair, terminated, tuple},
// AsChar, Err as NomErr, IResult, InputTakeAtPosition,
IResult
};
use crate::lexer::*;
type Res<T, U> = IResult<T, U, VerboseError<T>>;
#[derive(Debug, PartialEq... | Rust | 0 |
igs), `3` for eulertigs, `4` for greedy matchtigs and `5` for matchtigs.
/// `matchtig_file_prefix` must be a path to a file used to communicate with the matcher (blossom5).
/// `matcher_path` must be a path pointing to a binary of blossom5.
///
/// The output is passed through the last three parameters `tigs_edge_out`... | Rust | 0 |
_INFO_VERSION = 1i32;
#[doc = "*Required features: `\"Win32_Storage_Vhd\"`*"]
pub const SET_VIRTUAL_DISK_INFO_IDENTIFIER: SET_VIRTUAL_DISK_INFO_VERSION = 2i32;
#[doc = "*Required features: `\"Win32_Storage_Vhd\"`*"]
pub const SET_VIRTUAL_DISK_INFO_PARENT_PATH_WITH_DEPTH: SET_VIRTUAL_DISK_INFO_VERSION = 3i32;
#[doc = "*... | Rust | 0 |
prefix = "main_page"
path = "main_page"
x_y_range = {
'bus': (107, 9, 190, 36), # 业务区
'home-feature': (1203, 24, 1240, 60), # 右上角菜单(作为主页标志)
'quick-home': (1215, 5, 1255, 42), # 快速回到首页,右上
# 'login-feature': (1105, 601, 1142, 640), # 登录界面
'skip-notice': (509, 309, 761, 353), # 跳过公告
'insuffici... | Python | 1 |
m.cdup().unwrap();
let pwd = ftp_stream.pwd().unwrap();
assert_eq!(std::path::Path::new(&pwd), std::path::Path::new("/"));
}
#[test]
fn dele() {
let addr = "127.0.0.1:1243";
let root = std::env::temp_dir();
start_server!(addr, root);
let mut ftp_stream = FtpStream::connect(addr).unwrap();
... | Rust | 0 |
shold(y_true_va_bin, y_prob_va_eval[mask_va])
else:
calibrator = None
thr_j, thr_f1 = 0.5, 0.5
# Test 분류 메트릭(참고용)
mask_te = wcls_te > 0
if mask_te.sum() > 0:
y_true_cls = (ycls_te[mask_te] > 0.5).astype(int)
y_prob_eval = apply_calibrator(calibrator, y_prob) if calibrato... | Python | 1 |
(|issue| issue.issue_number == self.number)
}
}
impl AssignedTo<Issue> for OrganisationMember {
fn assigned_to(&self, assignable: &Issue) -> bool {
assignable
.assignees
.iter()
.any(|organisation_member| organisation_member.login == self.login)
}
}
#[cfg(test)]... | Rust | 0 |
o_buffer,
0,
std::ptr::null(),
)
};
if status != 0 {
return Err(status.to_ne_bytes());
}
// Now that we've created the audio queue an enqueued a buffer, we can start it.
let status = unsafe { AudioQueueStart(audio_queue, st... | Rust | 0 |
xmm_xmmm128
0x0003_0001,// VEX_Vtestps_ymm_ymmm256
0x0003_0001,// VEX_Vtestpd_xmm_xmmm128
0x0003_0001,// VEX_Vtestpd_ymm_ymmm256
0x0003_0000,// Pblendvb_xmm_xmmm128
0x6003_0202,// EVEX_Vpsrlvw_xmm_k1z_xmm_xmmm128
0x6003_0282,// EVEX_Vpsrlvw_ymm_k1z_ymm_ymmm256
0x6003_0302,// EVEX_Vpsrlvw_zmm_k1z_zmm_zmmm512
0x6... | Rust | 0 |
"""
This script profile different parts of numdifftools.
"""
from __future__ import absolute_import, print_function
import numpy as np
import numdifftools as nd # numdifftools.nd_statsmodels as nd
from numdifftools.profiletools import do_profile
from numdifftools.example_functions import function_names, get_function
... | Python | 1 |
Property("bar");
var bar = foo.isPrototypeOf(bar);
var bar = foo.propertyIsEnumerable("bar");
```
## Correct Code Examples
```js
var bar = Object.prototype.hasOwnProperty.call(foo, "bar");
var bar = Object.prototype.isPrototypeOf.call(foo, bar);
var bar = Object.propertyIsEnumerabl... | Rust | 0 |
d::{self, JoinHandle};
use std::sync::mpsc::{self, Sender, Receiver};
use std::sync::{Arc, Mutex};
use std::cell::RefCell;
use lazy_static::lazy_static;
use anyhow::{anyhow, Result};
use midir::{MidiOutput, MidiOutputConnection};
use midly::Smf;
use log::*;
mod midi_container;
mod time_controller;
use self::midi_con... | Rust | 0 |
state for model: {model}")
if model in self.rate_limited_models:
del self.rate_limited_models[model]
logger.info(f"Reset rate limit for model: {model}")
def _cleanup_expired_rate_limits(self):
"""Remove expired model rate limits"""
current_time = datetim... | Python | 1 |
no problem? I meant 'no: problem.'"}
)
self.request.match_info = {"cred_ex_id": "dummy"}
with (
mock.patch.object(test_module, "V20CredManager", autospec=True),
mock.patch.object(
test_module, "V20CredExRecord", autospec=True
) as mock_cred_e... | Python | 1 |
1.0.0")]
impl AsRef<[u8]> for str {
#[inline]
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> Default for &'a str {
/// Creates an empty str
fn default() -> &'a str { "" }
}
#[stable(feature = "default_mut_str", since = "1.28.0")]
impl... | Rust | 0 |
transformers.models.bart.configuration_bart.BartOnnxConfig._flatten_past_key_values_
def _flatten_past_key_values_(self, flattened_output, name, idx, t):
if self.task in ["default", "seq2seq-lm"]:
flattened_output = super()._flatten_past_key_values_(flattened_output, name, idx, t)
else:... | Python | 1 |
!("../input/day14");
pub const DAY15_INPUT: &str = include_str!("../input/day15");
pub const DAY16_INPUT: &str = include_str!("../input/day16");
pub const DAY17_INPUT: &str = include_str!("../input/day17");
pub const DAY18_INPUT: &str = include_str!("../input/day18");
pub const D... | Rust | 0 |
const EMPH_RED = 0b00100000;
const EMPH_GREEN = 0b01000000;
const EMPH_BLUE = 0b10000000;
const RENDERING = Self::BACKGROUND.bits | Self::SPRITES.bits;
}
}
bitflags! {
struct PPUSTATUS: u8 {
const SPRITE_OVERFLOW = 0b00100000;
const SPRITE_ZERO_H... | Rust | 0 |
&'de str) -> RegexFieldDeserializer<'de> {
RegexFieldDeserializer { data }
}
}
impl<'de> Deserializer<'de> for RegexFieldDeserializer<'de> {
type Error = Error;
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error>
where
V: Visitor<'de>,
{
visitor.visit_borrow... | Rust | 0 |
Result<Sysctl> {
let mut mib = Vec::new();
let mut value_type = SysctlType::Int32;
let mut changeable = false;
match names[0].as_str() {
"machine" => {
mib.push(HW_MACHINE);
value_type = SysctlType::SysString;
},
"model" => {
mib.push(HW_MODE... | Rust | 0 |
where F: Fn(bool) -> ClapApp<'static, 'static> {
#[cfg(windows)]
let _ = ansi_term::enable_ansi_support();
let interactive_output = atty::is(Stream::Stdout);
Ok(Self {
matches: Self::matches(clap_build_func, interactive_output)?,
interactive_output,
... | Rust | 0 |
== 'sum':
mol_embedding = mol_atom_embedding + mol_reaction_embedding
elif self.graph_agg == 'cat':
mol_embedding = torch.cat([mol_atom_embedding, mol_reaction_embedding], dim=1)
elif self.graph_agg == 'linear':
mol_embedding = self.combine(torch.cat([mol_atom_embeddi... | Python | 1 |
_text("from setuptools import setup; setup()")
(dep5 / "folder_name_dep").mkdir()
(dep5 / "folder_name_dep" / "__init__.py").write_text("")
# Create project referencing these deps
(project / "requirements.yaml").write_text(
textwrap.dedent(
"""\
dependencies:
... | Python | 1 |
ref(self.ptr) }
}
}
<reponame>jhg/ole-compound-document-parser
// DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
// Version 2, December 2004
//
// Copyright (C) 2018 <NAME> <<EMAIL>>
//
// Everyone is permitted to copy and distribute verbatim or modified
// copies of this license documen... | Rust | 0 |
() -> &'static [Self] {
static values: &'static [AmountUnit] = &[
AmountUnit::BITCOIN,
AmountUnit::MILLIBITCOIN,
AmountUnit::MICROBITCOIN,
AmountUnit::SATOSHI,
];
values
}
fn enum_descriptor_static() -> &'static ::protobuf::reflect::EnumDe... | Rust | 0 |
# coding:utf-8
import jieba
import xlrd
import numpy as np
import re
import string
#(Begin), I 表示内部(inside), O 表示外部(outside), E 表示这个词处于一个实体的结束为止, S 表示,这个词是自己就可以组成一个实体(Single)
def Creat_Txt():
f=open('../资料/全部/jieba_data.txt','a+',encoding='utf-8')
return f
def Add():
print("添加字典进入jieba\n--------")
# 将字典添加到jieba
... | Python | 1 |
const MD_MKT: u32 = 275;
pub const QUOTE_CONDITION: u32 = 276;
pub const TRADE_CONDITION: u32 = 277;
pub const MD_ENTRY_ID: u32 = 278;
pub const MD_UPDATE_ACTION: u32 = 279;
pub const MD_ENTRY_REF_ID: u32 = 280;
pub const MD_REQ_REJ_REASON: u32 = 281;
pub const MD_ENTRY_ORIGINATOR: u32 = 282;
pub const LOCATION_ID: u3... | Rust | 0 |
header)
}
// Warning: pay attention to parameter order
// Note: this is valid UTF-8, but gets used as bytes later
fn signing_input(protected_header: &[u8], payload: &[u8]) -> Vec<u8> {
let hlen = BASE64URL_NOPAD.encode_len(protected_header.len());
let plen = BASE64URL_NOPAD.encode_len(payload.len());
let m... | Rust | 0 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Warehouse Management: Batch Transfer',
'version': '1.0',
'category': 'Inventory/Inventory',
'description': """
This module adds the batch transfer option in warehouse management
===============... | Python | 1 |
FALLUPDW {
_PWM_3_CTL_DBFALLUPDW { w: self }
}
#[doc = "Bit 16 - Fault Condition Source"]
#[inline(always)]
pub fn pwm_3_ctl_fltsrc(&mut self) -> _PWM_3_CTL_FLTSRCW {
_PWM_3_CTL_FLTSRCW { w: self }
}
#[doc = "Bit 17 - Minimum Fault Period"]
#[inline(always)]
pub fn pwm_3_... | Rust | 0 |
import sys
from typing import TYPE_CHECKING
if sys.version_info < (3, 7) or TYPE_CHECKING:
from ._valueformat import ValueformatValidator
from ._suffix import SuffixValidator
from ._relative import RelativeValidator
from ._reference import ReferenceValidator
from ._prefix import PrefixValidator
... | Python | 1 |
lename>tests/basics.rs
use serde_indexed::{DeserializeIndexed, SerializeIndexed};
/// buffer should be big enough to hold serialized object.
fn cbor_serialize<T: serde::Serialize>(
object: &T,
buffer: &mut [u8],
) -> Result<usize, serde_cbor::Error> {
let writer = serde_cbor::ser::SliceWrite::new(buffer);
... | Rust | 0 |
::Perlin::new(),
}
}
fn update(_app: &App, model: &mut Model, _update: Update) {
model.time += 0.05;
for i in 0..=model.resolution {
for j in 0..=model.resolution {
let index = (i + j * model.resolution) as usize;
model.flow_field[index] = model.flow_field[index].rotate(0.0... | Rust | 0 |
# Generated by Django 3.0.7 on 2020-07-27 17:45
import os
import json
from django.db import migrations
def load_data(apps, schema_editor):
Workshop = apps.get_model("workshop_app", "Workshop")
cur_dir = os.path.dirname(os.path.abspath(__file__))
db_json = os.path.join(cur_dir, 'db.json')
if os.path.e... | Python | 1 |
ata"]["status"] == REPORT_REQUEST_PENDING
assert response["data"]["report_type"] == REPORT_REQUEST_NOTIFICATIONS
assert response["data"]["parameter"] == {
"notification_type": "sms",
"notification_status": "failed",
}
process_task_mock.assert_called_once_with(
kwargs={
... | Python | 1 |
board[cur_y, cur_x] == 0:
break
# 先手の場合
if first_move:
# 先手の駒に出会ったらひっくり返せる枚数を記録
if self.board[cur_y, cur_x] == 1:
start_to_end = True
break
... | Python | 1 |
from pep600_compliance.images import base, package_manager
class AlmaLinux(base.Base):
def __init__(self, image, eol, packages, machines):
_, version = image.split(":")
self._packages = packages
super().__init__(
image, "almalinux", version, eol, package_manager.DNF(), machines... | Python | 1 |
nd,
KEY_XF86AudioStop,
KEY_XF86Away,
KEY_XF86Back,
KEY_XF86BackForward,
KEY_XF86Battery,
KEY_XF86Blue,
KEY_XF86Bluetooth,
KEY_XF86Book,
KEY_XF86BrightnessAdjust,
KEY_XF86CD,
KEY_XF86Calculater,
KEY_XF86Calculator,
KEY_XF86Calendar,
KEY_XF86Clear,
KEY_XF86ClearGrab,
KEY_XF86Close,
KEY_XF86Community,
KEY_XF86ContrastAdju... | Rust | 0 |
on(run(Version::V1));
async_std::task::block_on(run(Version::V1Lazy));
}
#[test]
fn select_proto_serial() {
async fn run(version: Version) {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let listener_addr = listener.local_addr().unwrap();
let server = async_std::task:... | Rust | 0 |
{
vx = -vx - 1;
}
int neg_m = 0;
if (m < 0)
{
if (((vx + m + 1) > 0) || (vx != (int)vx))
{
neg_m = 1;
mx = -m;
}
else
{
// We don't handle cases where DLMF 14.9.3 doesn't help
return CUDART_NAN;
}
... | Python | 1 |
from mmseg.registry import DATASETS
from mmseg.datasets import CityscapesDataset
@DATASETS.register_module()
class DELIVER(CityscapesDataset):
"""Cityscapes dataset.
The ``img_suffix`` is fixed to '_leftImg8bit.png' and ``seg_map_suffix`` is
fixed to '_gtFine_labelTrainIds.png' for Cityscapes dataset.
... | Python | 1 |
(pos_zs[start_index:frame]))
if update_extra[index] is not None:
update_extra[index](frame)
plt.tight_layout()
interval = 30
if filename is not None and filename.endswith('.gif'):
interval = 60
anim_obj = animation.FuncAnimation(fig, anim_func, frames, interval=interval,... | Python | 1 |
PoeModule::revoke_claim(Origin::signed(1), claim.clone()),
Error::<Test>::NoSuchProof
);
});
}
#[test]
fn revoke_claim_failed_when_owner_is_wrong() {
new_test_ext().execute_with(|| {
let claim = vec![0, 1];
let owner_1 = Origin::signed(1);
let owner_2 = Origin::signed(2);
let _ = PoeModule::create_clai... | Rust | 0 |
ryption key
// is only harming herself as the ciphertexts under her key sent to her by other peers
// will be compromised.
if n <= &BigNumber::zero()
|| n.bit_length() < MODULUS_MIN_SIZE
|| n.bit_length() > MODULUS_MAX_SIZE
{
return false;
}
... | Rust | 0 |
import tensorflow as tf
import tensorflow_hub as hub
import h5py
import numpy as np
import json
print tf.__version__
from util import set_gpus
def Elmo(fn, outfn):
with open(fn) as f:
dev_examples = [json.loads(jsonline) for jsonline in f.readlines()]
sents = [example["sentences"] for example i... | Python | 1 |
import requests
import time
class SSRFScanner:
def __init__(self):
self.name = "SSRF Scanner"
self.description = "Scans for Server-Side Request Forgery vulnerabilities"
def scan(self, url, verbose=False, delay=0.5):
results = []
test_payloads = [
"http://127... | Python | 1 |
# Code generated by Lark OpenAPI.
from typing import Any, Optional, Union, Dict, List, Set, IO, Callable, Type
from lark_oapi.core.model import BaseRequest
from lark_oapi.core.enum import HttpMethod, AccessTokenType
from .node import Node
class CreateSpaceNodeRequest(BaseRequest):
def __init__(self) -> None:
... | Python | 1 |
i in range(num_nodes):
non_adj = set(range(num_nodes)) - adj_list[i] - {i} # Exclude self and adjacent vertices
non_adj_list.append(list(non_adj))
# Initialize selection
selected = []
# Randomly select non-adjacent vertices for each vertex
for i in range(num_nodes):
no... | Python | 1 |
import torch
import numpy as np
from torch.utils.data import DataLoader
from lib.datasets.kitti.kitti_dataset import KITTI_Dataset
# init datasets and dataloaders
def my_worker_init_fn(worker_id):
np.random.seed(np.random.get_state()[1][0] + worker_id)
def build_dataloader(cfg, workers=4):
assert cfg['type'... | Python | 1 |
from typing import (
Callable,
)
from web3._utils.rpc_abi import (
RPC,
)
from web3.method import (
Method,
)
from web3.types import (
TxPoolContent,
TxPoolInspect,
TxPoolStatus,
)
content: Method[Callable[[], TxPoolContent]] = Method(
RPC.txpool_content,
mungers=None,
)
inspect: Met... | Python | 1 |
el)
# wrong pred dimension
with pytest.raises(AssertionError):
accuracy = Accuracy()
accuracy(pred[:, :, None], true_label)
def test_lovasz_loss():
from mmseg.models import build_loss
# loss_type should be 'binary' or 'multi_class'
with pytest.raises(AssertionError):
loss... | Python | 1 |
fs, _cache, _db, _tree_id) = harness4k().await;
let name0 = OsStr::from_bytes(b"x");
let name1 = OsStr::from_bytes(b"y");
let dotdotname = OsStr::from_bytes(b"..");
let root = fs.root();
let fd0 = fs.mkdir(&root, name0, 0o755, 0, 0).await.unwrap();
let fd1 = fs.mkdir(&fd... | Rust | 0 |
"*Required features: `\"Win32_Graphics_Gdi\"`*"]
pub const ERR_PARAMETER16: u32 = 1116u32;
#[doc = "*Required features: `\"Win32_Graphics_Gdi\"`*"]
pub const ERR_PARAMETER2: u32 = 1102u32;
#[doc = "*Required features: `\"Win32_Graphics_Gdi\"`*"]
pub const ERR_PARAMETER3: u32 = 1103u32;
#[doc = "*Required features: `\"... | Rust | 0 |
# This file makes API calls to the Dictionary API
import requests
import json
import os
from dotenv import load_dotenv
from scripts.utils import exit_program, read_and_process_json
load_dotenv()
DICT_API_KEY = os.getenv('DICT_API_KEY')
def get_word_data(word_param):
base_url = 'https://www.dictionaryapi.com'
... | Python | 1 |
zer1QSubsetTester, self).setUp()
self.options.update(
pspec=fixture_3Q.pspec,
absolute_compilation=fixture_3Q.clifford_abs,
paulieq_compilation=fixture_3Q.clifford_peq,
qubit_labels=['Q1', ],
algorithm='COiCAGE',
paulirandomize=False
... | Python | 1 |
"""def find_index(arr, element):
try:
index = arr.index(element)
return index
except ValueError:
return f"The element '{element}' is not present in the array."
# Example usage:
my_array = [10, 20, 30, 40, 50]
search_element = 30
result = find_index(my_array, search_element)
print(resu... | Python | 1 |
pub totalram: ::c_ulong,
pub freeram: ::c_ulong,
pub sharedram: ::c_ulong,
pub bufferram: ::c_ulong,
pub totalswap: ::c_ulong,
pub freeswap: ::c_ulong,
pub procs: ::c_ushort,
pub pad: ::c_ushort,
pub totalhigh: ::c_ulong,
pub freehigh: ::c... | Rust | 0 |
import pytest
from threading import Event
from teos.carrier import Carrier
from teos.utils.rpc_errors import RPC_VERIFY_ALREADY_IN_CHAIN, RPC_DESERIALIZATION_ERROR
from test.teos.conftest import generate_blocks, create_commitment_tx, bitcoin_cli
from test.teos.unit.conftest import (
bitcoind_connect_params,
g... | Python | 1 |
uired features: `\"Win32_Graphics_Direct3D11\"`*"]
pub const D3D11_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_INVALIDARG_RETURN: D3D11_MESSAGE_ID = 2097351i32;
#[doc = "*Required features: `\"Win32_Graphics_Direct3D11\"`*"]
pub const D3D11_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_OUTOFMEMORY_RETURN: D3D11_MESSAGE_ID = 2097352i32... | Rust | 0 |
: [u8; 518],
pub len_code: [u16; 518],
pub dist_bits: [u8; 64],
pub dist_code: [u8; 64],
pub dict_bits: u32
}
/// The default code table, contains settings used by the standard PKWARE DCL.
/// Use this if you need to read files compressed by the DCL.
pub static DEFAULT_CODE_TABLE: CodeTable = CodeTable... | Rust | 0 |
онкретно список но ладно
f"\tlong_str = {long_str},\n"
f"\tlong_str.split(' ') = {long_str.split(' ')}\n")
print("\n======================================================================")
str_nums = "12, 23 , 33, 111 , 3, 15"
my_str = str_nums.replace(' ', '')
mew_list = my_str.split(',')
print(f"Теперь м... | Python | 1 |
_9']]
hist_df = hist_df[['primary_key', 'volume_hist_12_26_9', 'value_traded_hist_12_26_9', 'turnover_hist_12_26_9']]
stock_daily_df = pd.merge(stock_daily_df, slope_df, on='primary_key')
stock_daily_df = pd.merge(stock_daily_df, hist_df, on='primary_key')
stock_daily_df = diff(stock_daily_df)... | Python | 1 |
res: 'Win32_System_DeploymentServices'*"]
pub const WDS_TRANSPORTCLIENT_RECEIVE_METADATA: TRANSPORTCLIENT_CALLBACK_ID = 3i32;
#[doc = "*Required features: 'Win32_System_DeploymentServices'*"]
pub const WDS_TRANSPORTCLIENT_SESSION_STARTEX: TRANSPORTCLIENT_CALLBACK_ID = 4i32;
#[doc = "*Required features: 'Win32_System_De... | Rust | 0 |
_object_or_404(GeneratedCoverLetter, user=request.user, job=job)
# Create response with cover letter content
response = HttpResponse(cover_letter.content, content_type='text/plain')
response['Content-Disposition'] = f'attachment; filename="cover_letter_{job.company}_{job.title}.txt"'
return re... | Python | 1 |
te):
"""Aggiunge metadata per tracking"""
return {
"metadata": {
"timestamp": datetime.now().isoformat(),
"pipeline_version": "2.0",
"model": "gemini-2.0-flash",
"num_docs_used": len(state.get("context", []))
}
... | Python | 1 |
#!/usr/bin/env python
# Now you'll be able to read those encoded/compressed
# responses in your vcrpy test artifacts!
# References:
# https://github.com/kevin1024/vcrpy/issues/249
# http://stackoverflow.com/questions/36366234
# Thanks to Reti43 on StackOverflow
import sys
import yaml
# decode_response doesn't exist... | Python | 1 |
ED1: i32 = 0x0300;
pub const IPV6_PRIORITY_BULK: i32 = 0x0400;
pub const IPV6_PRIORITY_RESERVED2: i32 = 0x0500;
pub const IPV6_PRIORITY_INTERACTIVE: i32 = 0x0600;
pub const IPV6_PRIORITY_CONTROL: i32 = 0x0700;
pub const IPV6_PRIORITY_8: i32 = 0x0800;
pub const IPV6_PRIORITY_9: i32 = 0x0900;
pub const IPV6_PRIORITY_10: ... | Rust | 0 |
from nose.tools import assert_equal
from dronekit import connect
from dronekit.test import with_sitl
import time
@with_sitl
def test_reboot(connpath):
"""Tries to reboot the vehicle, and checks that the autopilot ACKs the command."""
vehicle = connect(connpath, wait_ready=True)
reboot_acks = []
de... | Python | 1 |
5 => PERIODS_CFG_A::AUDIO_SINK_PERIODS_6,
6 => PERIODS_CFG_A::AUDIO_SINK_PERIODS_7,
7 => PERIODS_CFG_A::AUDIO_SINK_PERIODS_8,
8 => PERIODS_CFG_A::AUDIO_SINK_PERIODS_9,
9 => PERIODS_CFG_A::AUDIO_SINK_PERIODS_10,
10 => PERIODS_CFG_A::AUDIO_SINK_PERIODS_11,
... | Rust | 0 |
// assertd((ll_i as i32) < s.nInUse, "generateMTFValues(2a)");
if yy[0] == ll_i {
zPend += 1;
} else {
if zPend > 0 {
zPend -= 1;
loop {
if (zPend & 1) != 0 {
mtfv[wr] = BZ_RUNB as u16;
... | Rust | 0 |
del
successful_count = 0
for index, model in enumerate(models, 1):
try:
name = model.get('name', f'model-{index}')
slug = slugify(name)
filename = f"{index:02d}-{slug}.md"
filepath = output_dir / filename
# Generate the markdown co... | Python | 1 |
# PyAlgoTrade
#
# Copyright 2011-2018 Gabriel Martin Becedillas Ruiz
#
# 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 ap... | Python | 1 |
suError::NotFound), _) => {
let content = format!("User `{name}` was not found");
return data.error(&ctx, content).await;
}
(Err(err), _) => {
let _ = data.error(&ctx, OSU_API_ISSUE).await;
return Err(err.into());
}
(_, Err(err)) => {
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.