text string | label_name string | labels int64 |
|---|---|---|
-> OVFFRMCNT_R {
OVFFRMCNT_R::new(((self.bits >> 17) & 0x07ff) as u16)
}
#[doc = "Bit 16 - This bit is set every time Missed Frame Counter (Bits\\[15:0\\]) overflows"]
#[inline(always)]
pub fn miscntovf(&self) -> MISCNTOVF_R {
MISCNTOVF_R::new(((self.bits >> 16) & 0x01) != 0)
}
... | Rust | 0 |
deState,
}
impl ApCodec {
pub fn new(send_key: &[u8], recv_key: &[u8]) -> ApCodec {
ApCodec {
encode_nonce: 0,
encode_cipher: Shannon::new(send_key),
decode_nonce: 0,
decode_cipher: Shannon::new(recv_key),
decode_state: DecodeState::Header,
... | Rust | 0 |
from shelf.mips.mips import mips_make_shellcode, MipsShellcode
from shelf.intel.x32 import intel_x32_make_shellcode, IntelX32Shellcode
from shelf.intel.x64 import intel_x64_make_shellcode, IntelX64Shellcode
from shelf.arm.x32 import arm_x32_make_shellcode, ArmX32Shellcode
from shelf.arm.x64 import arm_x64_make_shellcod... | Python | 1 |
import dsp
from dsp.utils import deduplicate
from .retrieval.combine import rerank
from .utils import make_str_disambig
class ToC:
def __init__(self, root):
self.root = root
self.n_nodes = 0
self.valid_qas = []
self.valid_nodes = []
self.slt_psgs = []
self.leaf_dept... | Python | 1 |
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
dictionary = {}
for num in nums:
if num in dictionary:
dictionary[num] += 1
else:
dictionary[num] = 1
sorted_dictionary = sorted(dictionary.item... | Python | 1 |
#[doc = "Bit 0 - Receive Packet Ready"]
#[inline(always)]
pub fn usb_rxcsrl7_rxrdy(&self) -> USB_RXCSRL7_RXRDYR {
let bits = ((self.bits >> 0) & 1) != 0;
USB_RXCSRL7_RXRDYR { bits }
}
#[doc = "Bit 1 - FIFO Full"]
#[inline(always)]
pub fn usb_rxcsrl7_full(&self) -> USB_RXCSRL7... | Rust | 0 |
oolean() {
assert_eq!(super::write(&false, &mut [0; 5]).unwrap(), "false");
assert_eq!(super::write(&true, &mut [0; 4]).unwrap(), "true");
}
#[test]
fn u8() {
assert_eq!(super::write(&0u8, &mut [0; 3]).unwrap(), "0");
assert_eq!(super::write(&10u8, &mut [0; 3]).unwrap(), "10... | Rust | 0 |
the smaller set of classes
# by taking the max or average syn
concept_logits = logits.new_zeros((logits.shape[0], num_concepts))
for concept_id, class_ids in enumerate(concept_to_class):
# logits for class i is the maximum logit of synonym logits
if op == "mean":
concept_logits[:... | Python | 1 |
def get_num_stops_upper_bound(G,
max_capacity,
num_stops=None,
distribution_collection=False):
"""
Finds upper bound on number of stops, from here :
https://pubsonline.informs.org/doi/10.1287/trsc.1050.0118
A knap... | Python | 1 |
e value.
pub fn or_insert(self, default: V) -> &'a mut V {
self.or_insert_with(|| default)
}
/// Insert the default value from the provided function if there
/// was no value already, and return a mutable reference to the
/// value.
pub fn or_insert_with<F>(self, default: F) -> &'a mut ... | Rust | 0 |
# Initialize chatbot
chatbot = MultiModalRAGChatbot()
# Test basic functionality
print("\n🧪 Testing multi-modal capabilities...")
test_input = MultiModalInput(
text="Hello, this is a test of the multi-modal system. Can you tell me about your capabilities?",
metadata={"test": T... | Python | 1 |
int('今日还没回答竞猜')
else:
error_message = response.get('errorMessage') if response else '无返回'
print(f'查询每日口令竞猜奖励失败: {error_message}')
# 向API发送答题请求
def anniversary2024_answer(self, answer_info):
url = 'https://mcs-mimp-web.sf-express.com/mcs-mimp/commonPost/~memberNonactivity... | Python | 1 |
to_cpu.read.next = false;
wait_clock_cycles!(sim, clock, x, 5);
}
sim.done(x)
});
sim.add_testbench(move |mut sim: Sim<ControllerTest>| {
let mut x = sim.init()?;
wait_clock_true!(sim, clock, x);
for iter in 0..10 {
wait_clock_cycles!(sim, clock, x... | Rust | 0 |
if len(out_of_range) > 0:
issues.append(f"Estrellas fuera de rango en {col}: {len(out_of_range)} registros")
# Verificar duplicados en la misma combinación
for other_col in ['e1', 'e2']:
if col != other_col:
duplicates = self.df[self.df[c... | Python | 1 |
# Copyright 2024 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | Python | 1 |
h open(test_script_path, 'w') as f:
f.write(test_script)
os.chmod(test_script_path, 0o755)
result = subprocess.run(
[test_script_path],
cwd=install_tester.temp_dir,
env=install_tester.mock_env,
capture_output=True,
text=Tru... | Python | 1 |
xtIteratorStreamer(
tokenizer=tokenizer, timeout=60, skip_prompt=True, skip_special_tokens=True
)
generate_kwargs = {
"input_ids": model_inputs["input_ids"],
"attention_mask": model_inputs["attention_mask"],
"streamer": streamer,
"max_new_token... | Python | 1 |
#[derive(Copy, Clone)]
struct RuntimeToken {
#[cfg(test)]
_created_from: RuntimeCosts,
weight: Weight,
}
impl<T> Token<T> for RuntimeToken
where
T: Config,
T::AccountId: UncheckedFrom<T::Hash> + AsRef<[u8]>
{
fn weight(&self) -> Weight {
self.weight
}
}
bitflags! {
/// Flags used to change the behaviour of ... | Rust | 0 |
# default arguments = a default value for certain parameters
# default is used when that argument is omitted
# make your fn more flexible, reduces # of arguments
# 1. positional, 2.DEFAULT, 3.Keyword, 4. Arbitrary
def net_price(list_price,discount=0,tax=0.05):
return list_price * (1-discount) * (1+tax)
#print(ne... | Python | 1 |
import os
import redshift_connector
from redshift_connector.error import ProgrammingError
__all__ = ['ProgrammingError']
def run_query(query):
conn = redshift_connector.connect(
host=os.environ['RS_HOST'],
database=os.environ['RS_DATABASE'],
user=os.environ['RS_USER'],
password=o... | Python | 1 |
ss_cost = (
pos_cost_class[:, tgt_ids] - neg_cost_class[:, tgt_ids]
) # min (1-alpha) * log(1e-8) max alpha * -log(1e-8)
# Compute the L1 cost between boxes
bbox_cost = torch.cdist(out_bbox, tgt_bbox, p=1) # min 0 max 4
# Compute the giou cost between boxes
giou_c... | Python | 1 |
timeout=self.app.pargs.timeout,
tags=tags,
)
def get_instance_profile(self):
profile_name = self.app.pargs.instance_profile
if profile_name is None:
try:
profile_name = fileoperations.get_instance_profile()
except NotInitializedError:
... | Python | 1 |
torchvision_instance:
model = torchvision_instance.models.resnet50(kwargs)
if return_jit:
return torch.jit.script(model)
return model
return get
@pytest.fixture(scope="function")
def torchscript_test_setup(torchvision_model_fixture):
path = os.path.expan... | Python | 1 |
::new();
for mono in &self.monos {
if i < mono.category.len() {
menu.insert(mono.category[i].as_str());
}
}
if menu.len() >= 2 {
return menu.iter().map(|m| m.t... | Rust | 0 |
for i in range(len(txtmp.vin)):
if i != inIdx:
txtmp.vin[i].nSequence = 0
elif (hashtype & 0x1f) == SIGHASH_SINGLE:
outIdx = inIdx
if outIdx >= len(txtmp.vout):
return (HASH_ONE, "outIdx %d out of range (%d)" % (outIdx, len(txtmp.vout)))
tmp = txtm... | Python | 1 |
# Code generated by Lark OpenAPI.
import lark_oapi as lark
from lark_oapi.api.admin.v1 import *
def main():
# 创建client
client = lark.Client.builder() \
.app_id(lark.APP_ID) \
.app_secret(lark.APP_SECRET) \
.log_level(lark.LogLevel.DEBUG) \
.build()
# 构造请求对象
request: L... | Python | 1 |
biggest peak
and then uses the minimum value either side of this peak as the terminal points of the
Shirley background.
The tolerance sets the convergence criterion, maxit sets the maximum number
of iterations.
"""
# Make sure we've been passed arrays and not lists.
x = array(x)
y = ... | Python | 1 |
"""
Write a python function to find the difference between largest and smallest value in a given list.
assert big_diff([1,2,3,4]) == 3
"""
def big_diff(array):
return max(array) - min(array)
print(big_diff([1, 2, 3, 4]))
print(big_diff([10, 5, 2, 7]))
print(big_diff([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
print(big_d... | Python | 1 |
b fn arg_or_query_required(matches: &ArgMatches, name: &str, prompt: &str) -> Result<String> {
match matches.value_of(name) {
Some(value) => Ok(String::from(value)),
None => query_required(prompt),
}
}
pub fn arg_or_query_optional(matches: &ArgMatches, name: &str, prompt: &str) -> Result<Option... | Rust | 0 |
file under the key `context_rules`.
Args:
filepath: The .json file containing modifier rules. Must contain `context_rules` key containing the rule
JSONs.
Returns:
A list of ConTextRules objects read from the JSON.
"""
with open(filepath) as file... | Python | 1 |
89d6a41b1505a3071169f8d0d028ba9ad6f952",
"name": "Twitter Web App",
"url": "https://mobile.twitter.com",
},
{
"id": "e6528b505bcfd811fdd40ff2d46665dbccba2024",
"name": "Twitter for Mac",
"url": "http://itunes.apple.com/us/app/twitter/id40978999... | Python | 1 |
"""
Generate SSL test certificates.
"""
import os
import shlex
import shutil
import subprocess
import textwrap
ROOT_CA = "trusted-root"
SUBJECT = "example.mitmproxy.org"
def do(args):
print("> %s" % args)
args = shlex.split(args)
output = subprocess.check_output(args)
return output
def genrsa(cert:... | Python | 1 |
# -*- encoding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from . import controllers
from . import models
from . import wizard
import odoo
from odoo import api, SUPERUSER_ID
from functools import partial
def uninstall_hook(cr, registry):
# Cleanup records which are rela... | Python | 1 |
) -> EvalResult {
let ParsedLambda {
name,
simple_args,
restarg,
body,
} = env.attach_st_box(parse_lambda(&args))?;
Ok(LispObject::Fn(object::Function::new_interpreted(
name,
simple_args,
restarg,
body,
)))
}
fn set_fn(mut env: Env, args:... | Rust | 0 |
Use it until
//! Google releases a Cloud Storage Client Library for Rust. Shoutout to
//! [MyEmma](https://myemma.io/) for funding this free and open source project.
//!
//! Google Cloud Storage is a product by Google that allows for cheap file storage, with a
//! relatively sophisticated API. The idea is that storage ... | Rust | 0 |
fault = alicloud.vpc.get_flow_log_service(enable="On")
```
:param _builtins.str enable: Setting the value to `On` to enable the service. If has been enabled, return the result. Default value: `Off`. Valid values: `On` and `Off`.
> **NOTE:** Setting `enable = "On"` to open the Vpc Flow L... | Python | 1 |
_act = hidden_act
self.initializer_range = initializer_range
self.attention_probs_dropout_prob = attention_probs_dropout_prob
@classmethod
def from_backbone_config(cls, backbone_config: PretrainedConfig, **kwargs):
"""Instantiate a [`TvpConfig`] (or a derived class) from a pre-trained b... | Python | 1 |
let i = ij >> 1;
let j = ij & 1;
if i == 1 {
children[pos].uv.x.hi = self.uv.x.hi;
children[pos].uv.x.lo = uv_mid.x;
} else {
children[pos].uv.x.lo = self.uv.x.lo;
children[pos].uv.x.hi = uv_mid.x;
... | Rust | 0 |
format!("{}", parse_int("12.5").unwrap_err()),
r#"Int error "12.5": invalid digit found in string"#
);
}
#[test]
fn debug_context() {
fn parse_int(s: &str) -> i32 {
s.parse().context(s).unwrap()
}
assert_eq!(parse_int("12"), 12);
assert_eq!... | Rust | 0 |
from .functional import acs_conv_f
from .base_acsconv import _ACSConv
class ACSConv(_ACSConv):
"""
Vallina ACS Convolution
Args:
acs_kernel_split: optional, equally spit if not specified.
Other arguments are the same as torch.nn.Conv3d.
Examples:
>>> import ACSConv
... | Python | 1 |
import asyncio
import typer
from rich.console import Console
from quantalogic_codeact.codeact.plugin_manager import PluginManager
from quantalogic_codeact.commands.toolbox import (
get_tool_doc,
install_toolbox,
list_toolbox_tools,
uninstall_toolbox,
)
app = typer.Typer()
console = Console()
class D... | Python | 1 |
es in the dataset
if len(batch) >= 1 and len(batch[0]) >= 1 and isinstance(batch[0][0], bytes):
batch = [[word.decode('utf-8') for word in s] for s in batch]
sentences = [' '.join(s) for s in batch]
if max_length == 500:
sentences = [tokenizer.decode(tokenizer.encode(s, ... | Python | 1 |
y::dispatch_as(
Origin::signed(1),
MockAsOriginId::Account2,
Box::new(ensure_signed_call)
),
BadOrigin,
);
});
}
#[test]
fn schedule_dispatch_at_work() {
ExtBuilder::default().build().execute_with(|| {
let ensure_root_call = Call::System(frame_system::Call::fill_block { ratio: Perbill::one() })... | Rust | 0 |
synchronization session && have pending requests.
pub active: usize,
}
/// Set of peers selected for synchronization.
#[derive(Debug, Default)]
pub struct PeersTasks {
/// All known peers ids
all: HashSet<PeerIndex>,
/// All unuseful peers
unuseful: HashSet<PeerIndex>,
/// All peers without pending headers reque... | Rust | 0 |
collect(),
trits,
)
}
/// Generates a buffer of unbalanced trits.
pub fn gen_buf_unbalanced<T: raw::RawEncodingBuf>(len: Range<usize>) -> (TritBuf<T>, Vec<i8>) {
let len = thread_rng().gen_range(len.start..len.end);
let trits = (0..len).map(|_| gen_trit_unbalanced()).collect::<Vec<_>>();
(
... | Rust | 0 |
1, 2], 'b', lw=2)
plot.grid()
plot.ylim([-1.1, 1.1])
if dump_figures:
fig_name = '{}'.format(os.path.join(dump_folder, '{}.png'.format(file_cnt)))
print('saving figure : {}'.format(fig_name))
plot.savefig(fig_name, dpi=100)
... | Python | 1 |
q(i: usize, spectrum : &ComplexBuffer, sample_rate: usize) -> f32 {
(i * sample_rate) as f32 / (spectrum.len() as f32)
}
/// Return max frequency
pub fn max_freq(spectrum : &ComplexBuffer, sample_rate: usize) -> f32 {
let idx = vectors::argmax(&spectrum);
if idx < spectrum.len() / 2 {
item_freq(idx... | Rust | 0 |
pub rbct: crate::Reg<rbct::RBCT_SPEC>,
_reserved17: [u8; 0x3c],
#[doc = "0x150 - TX Buffer Status Register"]
pub tbsr: crate::Reg<tbsr::TBSR_SPEC>,
#[doc = "0x154 - TX Buffer Data Register"]
pub tbdr: crate::Reg<tbdr::TBDR_SPEC>,
#[doc = "0x158 - Tx Buffer Control Register"]
pub tbct: cr... | Rust | 0 |
]].destroyed = true;
if destroyed_count == 200 {
result_b_destroyed_coords = 100 * target_list[curr_targets[j]].x + target_list[curr_targets[j]].y;
}
}
curr_targets.clear();
if destroyed_count == target_list.len() {
break;
}
}
println!("Result B: {}", result_b_destroyed_coords);
}<filename>vmm/... | Rust | 0 |
TE::new(CKA_PRIVATE).with_bool(&private),
CK_ATTRIBUTE::new(CKA_MODIFIABLE).with_bool(&modifiable),
CK_ATTRIBUTE::new(CKA_COPYABLE).with_bool(©able),
CK_ATTRIBUTE::new(CKA_LABEL).with_string(&label),
CK_ATTRIBUTE::new(CKA_VALUE).with_bytes(&value[..]),
];
let oh = ctx.create_object(sh, &template... | Rust | 0 |
r = self.current_node;
if let Some(current) = self.current_node {
if let Some(child) = self.tree.first_child[current.index()] {
self.current_node = Some(child);
} else {
if self.current_node != Some(self.start_node) {
let mut temp = S... | Rust | 0 |
_loc(*attr_id),
"Loop invariants must be declared at the beginning of the loop header in a \
consecutive sequence",
);
}
LoopAnnotation { fat_loops }
}
}
<gh_stars>1-10
#[cfg(test)]
mod test;
use crate::{clock::ClockTime, StartTime};
use super::{Tween, ... | Rust | 0 |
/// The memory protection when the region was initially allocated.
pub allocation_protection: md::MemoryProtection,
/// The state of the pages in the region (whether it is freed or not).
pub state: md::MemoryState,
/// The access protection of the pages in the region.
pub protection: md::MemoryProte... | Rust | 0 |
roup.foreach_execution(validate_func, clients)
results = {
"ce_loss": np.average(
[metric["ce_loss"] for metric in evaluate_results],
weights=[metric["length"] for metric in evaluate_results],
),
"acc_top_1": np.average(
[metric... | Python | 1 |
f2815b16f81798, 0x029bfcdb2dce28d9, 0x55a06295ce870b07, 0x79be667ef9dcbbac]),
y: Uint256([0x9c47d08ffb10d4b8, 0xfd17b448a6855419, 0x5da4fbfc0e1108a8, 0x483ada7726a3c465]),
curve: &SECP256K1
}
};
fn clock_add(a: &Uint256, b: &Uint256, p: &Uint256) -> Uint256 {
let mut res = Uint512::from(*a) + Uint512::from(*b);
... | Rust | 0 |
6g\x1e\xc6@\
v\xcf\xdaZ%\x02x\xbb\xf5\xe9%\x80\xf1K\xc30\
\x8c\x0f\xd5b'\xa4S\x9aU\x92{\xfd\xb3\xb87\x07\
&\xc09\xe8\xda\xc1\x01m\x8ax\xb0\x06\x0e\xd8\xb8|\
\x12\xc1\x9e\x83\xfa\xcaV\xcf\xfdY\x19\xb9o\xe0\x0d\xca\
\x5c\xa4\x0ch\xaegcU\x06A!8Qh\xf9\xd3\
\xa1\xde\xfa\xa6\x16\x93\x11v\xee\x90)\x893+\xc5\xf3\
\xf9\xa0\xafu... | Python | 1 |
representer)
@dataclass
class _MemProfInternalState:
can_collect: Dict[str, bool] = field(default_factory=dict)
curr_pid: Optional[Process] = None
snap_indices: Dict[str, int] = field(default_factory=dict)
configured_hooks: Dict[str, Any] = field(default_factory=dict)
hook_handles: DefaultDict[str... | Python | 1 |
Sets the baseline of the histogram.
See [`Histogram`] for more information and examples.
*/
pub fn baseline(mut self, baseline: A) -> Self
where
A: Clone,
{
self.baseline = Box::new(move |_| baseline.clone());
self
}
/**
Sets the histogram bar baselines using ... | Rust | 0 |
# Copyright 2020 Toolchain Labs, Inc. All rights reserved.
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from django.core.management.base import BaseCommand
from toolchain.base.toolchain_error import ToolchainAssertion
from toolchain.crawler.pypi.models import PeriodicallyProcessChangelog
from toolc... | Python | 1 |
dict_users = cifar_noniid(dataset_train, args.num_users)
else:
exit('Error: unrecognized dataset')
img_size = dataset_train[0][0].shape
# build model
if args.model == 'cnn' and args.dataset == 'cifar':
net_glob = CNNCifar(args=args).to(args.device)
elif args.model == 'c... | Python | 1 |
": "Selection End",
"steb": "Start of Eye Blink Artifact",
"eneb": "End of Eye Blink Artifact",
"sexc": "Start of Excursion Artifact",
"eexc": "End of Excursion Artifact",
"ssat": "Start of Saturation Artifact",
"esat": "End of Saturation Artifact",
"sspk": "Start of Spike Artifact",
"es... | Python | 1 |
from ByteStream.Reader import Reader
from Protocol.Messages.Server.AvailableServerCommandMessage import AvailableServerCommandMessage
from Protocol.Messages.Server.AvatarNameChangeFailedMessage import AvatarNameChangeFailedMessage
class SetNameMessage(Reader):
def __init__(self, client, player, initial_bytes):
... | Python | 1 |
social share text",
"highlights":
[
{
"start_time": "MM:SS",
"end_time": "MM:SS",
"audio_transcribe": "relevant game audio/commentary",
"highlight_reason": "explanation of why this is a highlight moment",
"commentary":
{
... | Python | 1 |
import chromadb
from google import genai
client = genai.Client()
db_client = chromadb.PersistentClient(path="./chroma_db") # folder bisa kamu atur
collection = db_client.get_or_create_collection(name="gemini_memory")
# 3. Teks yang ingin kamu embed
# texts = [
# "What is the meaning of life?",
# "What is the... | Python | 1 |
#!/usr/bin/python
# Python imports
import bisect
import sys
import io
# Package imports
from dwarf.defines import UINT32_MAX, UINT64_MAX
from dwarf.ranges import AddressRange, AddressRangeList
class debug_ranges:
def __init__(self, dwarf):
self.dwarf = dwarf
self.ranges = {}
def get_debug_r... | Python | 1 |
ana as u8,
Katakana as u8,
Katakana as u8,
Kanji as u8,
Kanji as u8,
Hiragana as u8,
Other as u8,
],
boundaries: vec![
NotWordBoundary,
NotWordBoundary,
... | Rust | 0 |
# utils/images.py
from pathlib import Path
import re
from typing import List, Union
import streamlit as st
IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".webp", ".bmp", ".gif"}
def _natural_key(p: Union[str, Path]):
s = Path(p).stem
return [int(t) if t.isdigit() else t.lower() for t in re.split(r"(\d+)", s)]
@st.c... | Python | 1 |
import easygopigo3 as easy
import time
import numpy as np
import heapq
gpg = easy.EasyGoPiGo3()
servo = gpg.init_servo()
distance_sensor = gpg.init_distance_sensor()
# Directions are [up, right, down, left]
directions = [(-1, 0), (0, 1), (1, 0), (0, -1)]
# Grid matrix
grid = np.array([
[0, 0, 0, 0, 0, 0, 1, 1],
... | Python | 1 |
xt and what is the question).
sequence_ids = tokenized_examples["token_type_ids"][i]
context_index = 1
# One example can give several spans, this is the index of the example containing this span of text.
sample_index = sample_mapping[i]
tokenized_examples["ex... | Python | 1 |
import argparse
import random
from .share_args import add_shared_args
def obtain_search_args():
parser = argparse.ArgumentParser(
description="Train a classification model on typical image classification datasets.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argu... | Python | 1 |
.and_then(|b| b.downcast::<T>().ok())
.map(|b| *b)
}
/// Moves a value out of the `State` storage and returns ownership.
///
/// # Panics
///
/// If a value of type `T` is not present in `State`.
///
/// # Examples
///
/// ```rust
/// # extern crate gotham;
/... | Rust | 0 |
CompiledSymbol::Completed(rule.0)
}
/// Borrow the name of a non-terminal given its ID.
///
/// Passing an invalid SymbolId results in a panic.
pub fn nt_name<'a>(&'a self, sym: SymbolId) -> &'a str {
&self.nonterminal_table[sym as usize]
}
/// Convert the name of non-terminal to... | Rust | 0 |
token}
status, _dummy, _dummy = self.microsoft_service._do_request(url, json.dumps(values), headers, method='POST', timeout=timeout)
return status not in RESOURCE_NOT_FOUND_STATUSES
#####################################
## MANAGE CONNEXION TO MICROSOFT ##
##############################... | Python | 1 |
bool {
// yes we are matching against a tab character, \t, to determine
// whether to escape, we are already messing around with the semantics
// of the characters anyway
matches!(
lit.kind,
ast::LiteralKind::Special(ast::SpecialLiteralKind::Tab)
)
}
impl TryFrom<&ast::Literal> for ... | Rust | 0 |
import socket
import threading
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
uploads_dir = os.path.join(BASE_DIR, "uploads")
def handle_client(client_socket: socket.socket, client_addr: str) -> None:
print(f"New connection: {client_addr}")
client_socket.send("Please login: ".encode('utf-8'))... | Python | 1 |
u32) << OFFSET;
self
}
# [ doc = "Bit 24 - Interrupt Status Flag" ]
pub fn isf(&mut self, value: bool) -> &mut Self {
const OFFSET: u8 = 24u8;
if value {
self.bits |= 1 << OFFSET;
} else {
self.bits &= !(1 << OFFSET);
}
self
}
}
#... | Rust | 0 |
nstance")
with open('{}/dev_input.json'.format(config.finetune_dir), 'w') as f:
json.dump(dev_inputs, f, indent=4)
with open('{}/dev_target.json'.format(config.finetune_dir), 'w') as f:
json.dump(dev_targets, f, indent=4)
with open('{}/dev_all.pkl'.format(config.finetune_dir), 'wb') as f:... | Python | 1 |
"input": input,
"prompt": prompt,
"output": output,
"raw": raw,
"tool": tool,
"tool_args": tool_args,
"system_prompt": system_prompt,
"server_names": server_names
}
run_command(cmd.cmd_run, config_file, servers, user_specified, extra_params)
... | Python | 1 |
uint = 0x9533;
pub const SUBPIXEL_BITS: c_uint = 0x0D50;
pub const SUBPIXEL_PRECISION_BIAS_X_BITS_NV: c_uint = 0x9347;
pub const SUBPIXEL_PRECISION_BIAS_Y_BITS_NV: c_uint = 0x9348;
pub const SUBSAMPLE_DISTANCE_AMD: c_uint = 0x883F;
pub const SUBTRACT: c_uint = 0x84E7;
pub const SUBTRACT_ARB: c_u... | Rust | 0 |
from nonebot.matcher import Matcher
from nonebot.adapters import Message
from nonebot import require, on_command
from nonebot.plugin import PluginMetadata
from nonebot.params import CommandArg, ArgPlainText
# from nonebot import on_regex
# from nonebot.adapters import Event
# from nonebot.params import RegexDict
requ... | Python | 1 |
fmx_Text,
fontScript: fmx_CharacterStyle_FontScript,
env: *const fmx_ExprEnv,
_x: *mut fmx__fmxcpt,
) -> fmx_CharacterStyle_FontID;
}
extern "C" {
pub fn FM_Data_GetPostscriptFontID(
_self: *const ::std::os::raw::c_void,
fontPostscriptName: *const fmx_Text,
env: ... | Rust | 0 |
s.path.join(self.data_transformation_dir, training_pipeline.DATA_TRANSFORMATION_TRANSFORMED_DATA_DIR,
training_pipeline.DATA_TRANSFORMATION_TEST_FILE_PATH)
self.transformed_object_file_path: str = os.path.join(self.data_transformation_dir, training_pipeline.DATA_TRANSFORMATION_TRANSFORMED_OBJECT_DI... | Python | 1 |
),
Some(Token::Operator(Operator::Sub)) => make_unary(Operator::Neg, ctor),
Some(Token::Operator(Operator::Mul)) => make_unary(Operator::Splat, ctor),
Some(Token::Operator(Operator::Pow)) => make_unary(Operator::SplatSplat, ctor),
Some(tkn) => { ctor.put_back(Ok(tkn)); Ok(None) }
None => Ok(None),
}
... | Rust | 0 |
state_dict = {
"epoch": current_epoch,
"net_state": self.net.state_dict(),
"opti_state": self.opti.state_dict(),
}
torch.save(state_dict, full_net_path)
torch.save(self.net.state_dict(), state_net_path)
def resume_checkpoint(self, load_path, mode="all"... | Python | 1 |
.ok()
}
}
}
#[cfg(feature = "actix-web")]
mod actix_support {
use crate::PreEscaped;
use actix_web_dep::{Error, HttpRequest, HttpResponse, Responder};
use alloc::string::String;
use futures_util::future::{ok, Ready};
impl Responder for PreEscaped<String> {
type Error = Error;
... | Rust | 0 |
String(Rc::new(Concat { funs })))
}
fn create_concat_bin(args: Arguments) -> CreateFunctionResult {
let funs = args.get_required_varargs(CONCAT_ARG_NAME, 0, AnyFunction::require_bin)?;
Ok(AnyFunction::Bin(Rc::new(Concat { funs })))
}
pub const CONCAT_BUILTIN: &BuiltinFunctionPrototype = &BuiltinFunctionProtot... | Rust | 0 |
API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestEr... | Rust | 0 |
dled")
if vaBTS != 0 and vaBTSD == 0xff:
print("varia tile D : {}/{}".format(vaLevelData.displayLayoutTile(vaTileD), hex(vaBTSD)))
print("WARNING: v-copy down not handled")
if vaBTS != 0 and vaBTSU == 0x01:
print("varia tile U : {}/{}".format(vaLevelData.displayLayoutTile(vaTileU),... | Python | 1 |
[2**12] * 4
mat, mons = Sequence([g]).coefficients_monomials()
print(mat.dimensions(), len(mons))
print(f"{mons = }")
# mons = mons.change_ring(ZZ)
vals = [int(x(*bounds)) for x in mons]
scale = [max(vals) // x for x in vals]
L = block_matrix(ZZ, [[identity_matrix(len(mons)), mat.T], [0, M]])
W = diagonal_matrix(ZZ, ... | Python | 1 |
JsPath2D>(){
true => (cx.argument(0)?, 1),
false => (this, 0)
};
let x = float_arg(&mut cx, shift, "x")?;
let y = float_arg(&mut cx, shift+1, "y")?;
let rule = fill_rule_arg_or(&mut cx, shift+2, "nonzero")?;
let is_in = cx.borrow_mut(&mut container, |mut obj| {
cx.b... | Rust | 0 |
import numpy as np
from typing import Optional, List
import torch_em
from torch_em.util.debug import check_loader
from torch_em.data.datasets import get_bcss_loader
# set this path to where you have downloaded the bcss data
BCSS_ROOT = "/scratch/projects/nim00007/data/bcss/"
class BCSSLabelTrafo():
def __init_... | Python | 1 |
$generics)* ]
@delegate [ $delegate_type ]
$(@exclude [ $($exclude_props)* ])?
$(@include [ $($include_props)* ])?
@bounds [
$delegate_type: $crate::core::GraphDerefMut,
<$delegate_type as $crate::core::GraphDeref>::Graph:
$crate::core::property::NewVertex,
$($bounds)*
]
@trait_id New... | Rust | 0 |
from typing import List
"""
Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.
You must so... | Python | 1 |
class Solution:
def findCircleNum(self, isConnected: List[List[int]]) -> int:
n = len(isConnected)
self.parent = [ i for i in range(n)]
self.rank = [1] * n
def find(i):
if self.parent[i] == i:
return i
else:
self.parent[i] = f... | Python | 1 |
it.
fn main() -> Result<()> {
let mut args = CmdArgs::new();
let input = args.required_free();
args.done();
let boundary_pts = LonLat::read_osmosis_polygon(&input)?;
// For now, just use the boundary's center. Some boundaries might cross multiple geofabrik
// regions; don't handle that yet.
... | Rust | 0 |
ency().ws5());
// PLLPをシステムクロックとして使う設定
peripheral.RCC.cfgr.modify(|_, w| w.sw().pll());
while peripheral.RCC.cfgr.read().sws().is_pll() == false {}
// APB1を分周(最大45MHz)
peripheral.RCC.cfgr.modify(|_, w| w.ppre1().div4());
// APB2を分周(最大90MHz)
peripheral.RCC.cfgr.modify(|_, w| w.ppre2().div2... | Rust | 0 |
import pytest
from src.note.note_collection import *
def test_catatan_constructor():
catatan = Note(1, 1, 1, "hello")
assert catatan.get_idCatatan() == 1
assert catatan.get_idBuku() == 1
assert catatan.get_halamanBuku() == 1
assert catatan.get_kontenCatatan() == "hello"
def test_catatan_setter():... | Python | 1 |
ket::ignite().mount("/", routes![index]).launch();
}
//! Baja error
//!
//! ## Authors
//!
//! The Veracruz Development Team.
//!
//! ## Licensing and copyright notice
//!
//! See the `LICENSE.markdown` file in the Veracruz root directory for
//! information on licensing and copyright.
use err_derive::Error;
#[derive... | Rust | 0 |
# coding: utf-8
from typing import List
from marshmallow import Schema, fields
class DiscordGuildWidgetSchema(Schema):
id = fields.Str()
name = fields.Str()
invite_link = fields.Str()
member_count = fields.Int()
members = fields.List(fields.Nested('DiscordGuildWidgetMemberSchema'))
class Disco... | Python | 1 |
mod ppu;
mod palette;
mod serde;
use std::env;
use std::process;
use crate::console::Console;
use crate::ines::CartridgeError;
fn main() {
env_logger::init();
if let Some(rom) = env::args().skip(1).next() {
match Console::new_nes_console(&rom) {
Ok(mut console) => {
conso... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.