text string | label_name string | labels int64 |
|---|---|---|
# Copyright 2013 The Servo Project Developers. See the COPYRIGHT
# file at the top-level directory of this distribution.
#
# 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
#... | Python | 1 |
import subprocess
import sys
import pytest
import sqlparse
def test_cli_main_empty():
with pytest.raises(SystemExit):
sqlparse.cli.main([])
def test_parser_empty():
with pytest.raises(SystemExit):
parser = sqlparse.cli.create_parser()
parser.parse_args([])
def test_main_help():
... | Python | 1 |
from colorama import Fore
import json
from modules.utils import custom_serializer
import modules.globals as my_globals
from botocore.config import Config
from modules.logger import *
def code_commit_init_enum(victim_session, attacker_session):
enable_print_logging()
list_code_commit_repos(victim_session)
def ... | Python | 1 |
e) enum MicroSteps {
AluOp0, // (alu operation 0)
MemStore, // (memory store - RAM)
RtbSel0, // (return bus select 0)
PcSrc0, // (program counter select source 0)
RtbSel1, // (return bus select 1)
AliOp1, // (alu operation 1)
TakeBranch, // (conditional branch)
PcSrc1... | Rust | 0 |
an alias for `Reg<ADC12MCTL27_SPEC>`"]
pub type ADC12MCTL27 = crate::Reg<adc12mctl27::ADC12MCTL27_SPEC>;
#[doc = "ADC12 Memory Control 27"]
pub mod adc12mctl27;
#[doc = "ADC12MCTL28 register accessor: an alias for `Reg<ADC12MCTL28_SPEC>`"]
pub type ADC12MCTL28 = crate::Reg<adc12mctl28::ADC12MCTL28_SPEC>;
#[doc = "ADC1... | Rust | 0 |
nal[List["BasicMessage"]]:
"""
Gets the messages of the anchor.
Returns:
The messages of the anchor.
"""
from .message import BasicMessage
return (
[BasicMessage(message.id) for message in self.anchor.messages.iterable]
if self.an... | Python | 1 |
t_tx, fut_rx) = oneshot::channel();
let _ = self.rpc_send_tx.unbounded_send(RpcMessage {
rpc_json: rpc.to_owned(),
session: rpc_session.clone(),
send_back: fut_tx,
});
wasm_bindgen_futures::spawn_local(async {
if let Ok(fut) = fut_rx.await {
fut.await;
}
});
wasm_bindgen_futures::spawn_loc... | Rust | 0 |
class Book:
animal_catalogue = "Animal Catalogue"
book_of_mysteries = "Book of Mysteries"
book_of_stars = "Book Of Stars"
stardew_valley_almanac = "Stardew Valley Almanac"
bait_and_bobber = "Bait And Bobber"
mining_monthly = "Mining Monthly"
combat_quarterly = "Combat Quarterly"
woodcutt... | Python | 1 |
'''
3412. Find Mirror Score of a String
URL := https://leetcode.com/problems/find-mirror-score-of-a-string/description/
Complexity
T = O(N)
S = O(1) ( E ) O(1) ( I )
'''
class Solution:
def calculateScore(self, s: str) -> int:
totalScore = 0
# when alphabet is revrsed
MIRROR = 25
B... | Python | 1 |
assert "やまだ^たろう" == pn.phonetic
def test_not_equal(self):
"""PN3: Not equal works correctly (issue 121)..."""
# Meant to only be used in python 3 but doing simple check here
from pydicom.valuerep import PersonName
pn = PersonName("John^Doe")
assert not pn != "John^Doe"
... | Python | 1 |
self) {
if let Some(waker) = {
let mut status = self.guarder.status.lock();
//释放异步共享锁,并返回是否准备解锁共享锁
if status.0 <= UNLOCKED {
//当前锁状态错误,则立即抛出异常,并释放当前共享锁
panic!("Free shared lock failed, current: {:?}, reason: invalid current status", stat... | Rust | 0 |
from django.contrib import admin
# Register your models here.
from about_all.models import About_Section
class About_SectionAdmin(admin.ModelAdmin):
fieldsets = [
('Title Descriptions 1 EN ', {'fields': ['ASTitle_en', 'UsDescription_en']}),
('Title Descriptions 1 AR ', {'fields': ['ASTitle_ar', '... | Python | 1 |
idx)
v_first = torch.zeros_like(x)
for i in range(len(self.blocks)):
block = self.blocks[i]
state = states[i]
if int(args.grad_cp) == 1 and self.training:
x, v_first, state = deepspeed.checkpointing.checkpoint(
block, x, v_first, s... | Python | 1 |
mage
im = pdf_page.render(scale=4).to_pil()
fp = io.BytesIO()
im.save(fp, format='png')
num_lines += len(page_data)
max_lines_in_page = max(len(page_data), max_lines_in_page)
#... | Python | 1 |
import yt_dlp
import ffmpeg
# tentative variables for tetsing
merge_video_path = 'C:\\Users\\Abdul\\Desktop\\videos\\v2.mp4'
merge_audio_path = 'C:\\Users\\Abdul\\Desktop\\audio\\a2.webm'
output_merge_video_path = 'C:\\Users\\Abdul\\Desktop\\after_merge\\merge_test.mp4'
# def download_video(video_url):
# try:
... | Python | 1 |
# Copyright © 2021 United States Government as represented by the Administrator of the National Aeronautics and Space Administration. All Rights Reserved.
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
from numpy import array
from typing import List
def plot_hist(
samples: array, fig: Figu... | Python | 1 |
result = get_results(
left_image,
right_image,
0.0f32,
false,
None,
&base,
&block_out,
);
if let Some((_, image)) = result {
imageops::overlay(&mut greyscale, &image, 0, 0);
}
let size = greyscale.dimensions();
ImageBuf::from_raw(
... | Rust | 0 |
aryValidate")
entitlements = app.get("entitlements")
no_sign_target = app.get("noSignTarget")
no_deep = app.get("noDeep")
tccutil = app.get("tccutil")
auto_handle_setapp = app.get("autoHandleSetapp")
auto_handle_helper = app.get("autoHandleHelper")... | Python | 1 |
duce_locals(&mut bx);
// Codegen the body of each block using reverse postorder
// FIXME(eddyb) reuse RPO iterator between `analysis` and this.
for (bb, _) in traversal::reverse_postorder(&mir) {
fx.codegen_block(bb);
}
// For backends that support CFI using type membership (i.e., testing ... | Rust | 0 |
-> Iter<'_, dyn StackItem>
{
self._array.iter()
}
pub fn RemoveAt(&mut self, index: i32)
{
self.ReferenceCounter?.RemoveReference(_array[index], this);
_array.RemoveAt(index);
}
pub fn Reverse(&mut self)
{
self._array.reserve(0);
}
}
use std::{convert:... | Rust | 0 |
_message = f"✅ RSS Лента ID:{editing_feed_id} успешно обновлена!"
# Reschedule the job if frequency or channels changed (or just always reschedule on edit)
# Remove old job first just to be safe, although replace_existing should handle it
old_job_id = f'rss_check_{edit... | Python | 1 |
bound` - The width of the screen
/// * `y_bound` - The height of the screen
///
/// # Return
/// A vec of Triangle's that are on the screen and can replace the original
///
pub fn clip(&mut self, x_bound: f32, y_bound: f32, mut depth: i32) -> Vec<Triangle> {
depth = depth + 1;
//... | Rust | 0 |
PhantomData<I>,
}
impl<I> Unify<I> for Ty<I>
where
I: Interner,
{
fn unify(
context: &mut I::UnificationContext,
a: &Self,
b: &Self,
) -> unify::UnificationResult<()> {
todo!()
}
}
impl<I: Interner> GenericTerm<I> for Ty<I> {
}
pub trait DomainGoal<I: Interner, T: Gene... | Rust | 0 |
from sympy import symbols, div, Poly, factorial, sympify
import pandas as pd
def poly_div(var, exp1, exp2):
n = symbols(var)
dividendo = Poly(sympify(exp1), n, domain='QQ')
divisor = Poly(sympify(exp2), n, domain='QQ')
# Quociente e resto normal (pode ter fração)
quociente, resto = div(dividendo... | Python | 1 |
#!/usr/bin/env python3
"""
License Generator Tool
用于生成My Tools Assistant的授权码
"""
import argparse
import json
import sys
import os
from datetime import datetime, timedelta
# 添加backend目录到Python路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'backend'))
from modules.license_module import LicenseManager
de... | Python | 1 |
outFile.write('''\
#%s WEAVE_DEVICE_CONFIG_ENABLE_TEST_DEVICE_IDENTITY == %d
''' % ('if' if isFirst else 'elif', idNum))
isFirst = False
outFile.write('''\
const uint64_t TestDeviceId = 0x%sULL;
const uint8_t TestDeviceCert[] =
{
''' % (macAddr))
outFile.write(indent(toArrayIn... | Python | 1 |
if let Some(position) = obstacle_map.first_position_to_place_obstacle() {
return Err(H3mError::Internal(InternalError::new(format!(
"failed to place obstacle in position (row: {}, column: {}).",
position.row(),
position.column()
))));
}
... | Rust | 0 |
'''
This is a pretrained 0.992 accuracy mnist classifier using convolutional NN
Author: Liqun Chen
4.23.2017
'''
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
import tensorflow as tf
import os
GPUID = 1
import numpy as np
os.environ["CUDA_VISIB... | Python | 1 |
# credentials.py -- support for git credential helpers
# Copyright (C) 2022 Daniele Trifirò <daniele@iterative.ai>
#
# Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
# General Public License as public by the Free Software Foundation; version 2.0
# or (at your option) any later version. You ... | Python | 1 |
"""Tests for the Rituals Perfume Genie sensor platform."""
from homeassistant.components.rituals_perfume_genie.sensor import SensorDeviceClass
from homeassistant.const import (
ATTR_DEVICE_CLASS,
ATTR_ICON,
ATTR_UNIT_OF_MEASUREMENT,
PERCENTAGE,
EntityCategory,
)
from homeassistant.core import HomeAs... | Python | 1 |
0.5)
)
# Create all gates first
gates = VGroup(xor1, xor2, and1, and2, or_gate)
self.play(Create(gates))
self.play(Write(gate_labels))
# Add inputs and outputs
self.play(
Write(inputs),
Write(outputs)
)
# Create connectio... | Python | 1 |
Ok(Library {
LogiLedInit: mem::transmute(symbols[0].1),
LogiGetConfigOptionNumber: mem::transmute(symbols[1].1),
LogiGetConfigOptionBool: mem::transmute(symbols[2].1),
LogiGetConf... | Rust | 0 |
(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
extern crate libc;
use ::std::os::raw::c_char;
use lazy_static::lazy_static;
use std::sync::{Arc, Mutex, RwLock};
use std::{
borrow::BorrowMut,
ffi::{CStr, CString},
};
use std::{
collections::HashMap,
f... | Rust | 0 |
flag"]
#[inline]
pub fn pwr_vdd18_rst_bad(&mut self) -> _PWR_VDD18_RST_BADW {
_PWR_VDD18_RST_BADW { w: self }
}
#[doc = "Bit 8 - VRTC Comparator Tripped event detected flag"]
#[inline]
pub fn pwr_vrtc_rst_bad(&mut self) -> _PWR_VRTC_RST_BADW {
_PWR_VRTC_RST_BADW { w: self }
... | Rust | 0 |
hars[2], chars[1], chars[0]
return ffi.cast("int *", chars)[0]
def get_pixel(self, x: int, y: int) -> int:
return self.reverse(self.pixels[y][x])
def set_pixel(self, x, y, color):
self.pixels[y][x] = self.reverse(color)
class _PyAccessF(PyAccess):
"""32 bit float access"""
d... | Python | 1 |
_id_us(id) }, self)
}
}
#[repr(u64)] pub enum Refed3TableID{ C2, C1, }
impl Refed3TableID{
pub fn from_str(id : &str) -> Option<Self>{
match id{
"c2" => Some(Self::C2),
"c1" => Some(Self::C1),
_ =>{ None }
}
}
pub fn from_num(id : usize) -> Self{
match id{
0 => Self::C2,
1 => Sel... | Rust | 0 |
#Faça um Programa que peça as 4 notas bimestrais e mostre a média.
n1 = int(input('Digite a primeira nota: '))
n2 = int(input('Digite a segunda nota: '))
n3 = int(input('Digite a terceira nota: '))
n4 = int(input('Digite a quarta nota: '))
media = (n1+n2+n3+n4)/4
print('A média é: '+str(media)) | Python | 1 |
"[Optional] Restore the latest checkpoint from `train_dir` if True")
flags.DEFINE_boolean(
"validate",
default=False,
help="[Optional] Use the validation set or not for hyperparameter search")
flags.DEFINE_string(
"dataset",
default="cifar-10",
help="[Optional] The dataset used; ... | Python | 1 |
# #[macro_use] extern crate point_nd; fn main() {
# use point_nd::dims;
let index_arr = dims![x,x, y,y, z,z];
assert_eq!(index_arr, [0,0, 1,1, 2,2]);
# }
```
This can be especially useful with the ```apply_dims``` method available to ```PointND```'s
```
# #[macro_use] extern crate point_nd; fn main() {
# ... | Rust | 0 |
let contract = Arc::clone(&principal.contract);
let child = thread::spawn(move || {
let event = WorkersParameterizedEvent::new();
let event_sig = event.0.signature();
let filter = FilterBuilder::default()
.address(vec![contract.address()])
... | Rust | 0 |
bit_mask = 1 << (7 - (i % 8));
if read_bit(delay, pin)? {
byte |= bit_mask;
}
}
Ok(byte)
}
pub fn read_raw<P, E>(delay: &mut dyn Delay, pin: &mut P) -> Result<[u8; 4], DhtError<E>>
where
P: InputOutputPin<E>,
{
pin.set_low().ok();
delay.delay_ms(18_u8);
pin.set_high... | Rust | 0 |
t("--output", default="test_results/understat_coverage_corrected.json",
help="Fichier de sortie JSON")
args = parser.parse_args()
print("🧪 Test UnderstatClient - Coverage EPL 2025-26 & Championship 2024-25")
print("=" * 75)
# Run test
results = test_understat_c... | Python | 1 |
ask_range_str.split(b',')
for r in job_id_ranges:
if b'-' in r:
lower, upper = r.split(b'-')
else:
lower = upper = r
job_dict[array_id][0].append(range(int(lower), int(uppe... | Python | 1 |
p> for TestCircuit {
fn synthesize<CS: ConstraintSystem<Fp>>(
&self,
cs: &mut CS,
) -> Result<(), SynthesisError> {
let mut expected = (u128::from(self.a) * u128::from(self.b))
+ u128::from(self.c)
+ u128::fr... | Rust | 0 |
"""The RAAML Modeling Language module is the entrypoint for RAAML related
assets."""
from collections.abc import Iterable
from gaphor.abc import ModelingLanguage
from gaphor.core import gettext
from gaphor.diagram.diagramtoolbox import (
DiagramType,
ElementCreateInfo,
ToolboxDefinition,
)
from gaphor.dia... | Python | 1 |
) {
super::some_function(unsafe { * Box::from_raw(arg) })
}
})
}
fn expected_swift_code() -> ExpectedSwiftCode {
ExpectedSwiftCode::ContainsAfterTrim(
r#"
func some_function(_ arg: SomeType<UInt32>) {
__swift_bridge__$some_function({arg.is... | Rust | 0 |
RecvState::Recv { .. } => false,
_ => true,
}
}
/// All data read by application
pub fn is_closed(&self) -> bool {
self.state == self::RecvState::Closed
}
/// Offset after the largest byte received
pub fn limit(&self) -> u64 {
self.recvd.max().map_or(0,... | Rust | 0 |
fig.update_layout(title='Income Statement Metrics', barmode='group')
st.plotly_chart(fig, use_container_width=True)
# Balance Sheet
balance_sheet = stock.balance_sheet
if not balance_sheet.empty:
st.write("📊 Balance Sheet")
balance_sheet_metr... | Python | 1 |
&x19; // 1*159 0*1 1*19
t1 = t1.square_rep(4) * &x3; // 0*1 1*3
t1 = t1.square_rep(6) * &x3; // 0*3 1*3
let r = &t1 * &t1;
let r2 = &r * &r;
CtOption::from((CtEqual::ct_eq(&r2, self), r))
}
}
fiat_field_ops_impl!(
#[doc = "Element of the prime field Fp for scalar where... | Rust | 0 |
ND1", **round_config)
mocker.patch("pre_award.fund_store.api.routes.get_all_funds", return_value=[mock_fund])
mocker.patch("pre_award.fund_store.api.routes.get_fund_by_id", return_value=mock_fund)
mocker.patch("pre_award.fund_store.api.routes.get_fund_by_short_name", return_value=mock_fund)
mocker.patch... | Python | 1 |
otation: Rotation) -> Vec<Vec<&'a str>> {
match rotation {
Rotation::Degree0 |
Rotation::Degree180 => {
return
vec![
vec![" ", "X", "X"],
vec!["X", "X"]
]
;
... | Rust | 0 |
bytes, $sizes).prop_map(data_to_db),
key in prop::array::uniform32($bytes)
) {
let table: ProofMapIndex<_, [u8; 32], u64> =
ProofMapIndex::new(INDEX_NAME, db.snapshot());
prop_assert!(!table.contains(&key));
let proof = tab... | Rust | 0 |
included)
exon_files = ['exon1.fasta', 'exon2.fasta', 'exon3.fasta', 'exon4.fasta']
exon_files = [file for file in exon_files if os.path.exists(file)] # Filter out non-existent files
if exon_positions:
print(f"Orientation: {orientation}")
# Step 1: Concatenate exons based on orientation
... | Python | 1 |
DateTime<Utc>,
}
impl Policy {
fn get_by_id(id: &str) -> Result<Policy> {
Ok(Policy {
id: id.into(),
name: "".into(),
updated_on: Utc::now(),
})
}
#[observed(namespace = "foo")]
pub fn create_policy(name: &str) -> Result<Policy> {
std::threa... | Rust | 0 |
{}", id))?;
let json: Instance = serde_json::from_slice(&resp)?;
Ok(json)
}
/// Get all DICOM tags of an instance in a simplified format
///
/// See related Orthanc documentation
/// [section](https://book.orthanc-server.com/users/rest.html#accessing-the-dicom-fields-of-an-instance-... | Rust | 0 |
#[test]
fn test_robust_rand_backprop(){
_robust_rand_backprop().unwrap();
}
fn _robust_rand_backprop() -> Result<()>{
use graph::GraphDef;
use ops::numeric_check::numeric_test;
use rand;
use rand::distributions::{Range, Distribution};
let mut rng = rand::thread_rng();
let range = Range::new(0.1, 1.0);
let ... | Rust | 0 |
S227 = undo_php_mt_rand(R227)
seed = undo_php_mt_reload(S000, S227, offset, flavour)
if seed:
print(seed)
def test_do_undo(do, undo):
for i in range(10000):
rand = random.randrange(1, MAX)
done = do(rand)
undone = undo(done)
if not... | Python | 1 |
let mut sorted_def_ids: Vec<&DefId> = def_ids.iter().collect();
sorted_def_ids.sort();
for def_id in sorted_def_ids {
if tcx.is_mir_available(*def_id) {
let mir = tcx.optimized_mir(*def_id);
let mut ccx = ConvCx::new(tcx, *def_id, mir);
let pack = ccx.lower();
... | Rust | 0 |
_COMPAT_URL".to_string(), std_file_url())],
});
itest!(test_runner_esm {
args: "test --compat --unstable -A --quiet compat/test_runner/esm.mjs",
exit_code: 1,
output: "compat/test_runner/esm.out",
envs: vec![("DENO_NODE_COMPAT_URL".to_string(), std_file_url())],
});
// Top level assertion test mostly just mak... | Rust | 0 |
# Atividade 04:
# Contagem Regressiva:
# Desenvolva um programa que use um laço while para exibir
# uma contagem regressiva de 10 até 1 e, em seguida, exiba
# "Feliz Ano Novo!".
c = 0
while c != 0:
| Python | 1 |
unreachable!(),
})
.clamp(-0x8000, 0x7fff) as i16;
// this behaviour is documented by nocash FullSNES
let sample = if sample > 0x3fff {
-0x8000 + sample
} else if sample <... | Rust | 0 |
n<NanoSecond>;
/// Get the number of iterations the `Simulator` has executed so far.
///
/// When `Self` is `par::Simulator`, i.e. a parallel simulator is used,
/// this returns the number of iterations made by the parallel simulator itself.
fn iterations(&self) -> u64;
/// Get the current popul... | Rust | 0 |
:connect(&configuration.database.connection_string())
.await
.expect("Failed to connect to Postgres");
let address = format!("127.0.0.1:{}", configuration.application_port);
let listener = TcpListener::bind(address)?;
run(listener, connection)?.await
}
<reponame>FL33TW00D/async-stripe
use c... | Rust | 0 |
patch(OBSERVER_OPEN) as mock_file:
mock_file.return_value.__enter__.side_effect = [
FileNotFoundError,
mock_open(read_data="empty").return_value,
]
span, _ = observer._init_tracing([TEST_OBSERVER_CONF], ".")
simple_method = span(self.simple_me... | Python | 1 |
,
".text section offset and address must be identical");
assert_eq!(elf.segments.len(), 2,
"expect exactly two segments");
let phdr_segments :Vec<&segment::SegmentHeader> = elf.segments.iter().filter(|x| x.phtype == types::SegmentType::PHDR).collect();
assert_eq!(phdr_segments.len(), 1,
... | Rust | 0 |
ook_name()
other_dictionary[str(uuid.uuid4())] = second_books_mock
main_dictionary[books_name[0].upper()] = other_dictionary.copy()
third_books_mock = Book("", "", "")
third_books_mock.set_book_name("FakeTitleSecond")
third_books_mock.set_availability("available")
third_... | Python | 1 |
text = ' tOSh bOlTA oSHiq '
# capitalized() - Bosh harfni doim katta harf qilib beradi.
# print(text.capitalize())
print(f"{text}.capitalize() ==> {text.capitalize()}")
print(f"{text}.title() ==> {text.title()}")
print(f"{text}.strip() ==> {text.strip()}")
print(f"{text}.rstrip() ==> {text.rstrip()}")
print(f... | Python | 1 |
g only, then impose the order Narrow, Wide, Tall.
# So if something is missing or out of order everything still gets built correctly.
f = None
gotlang = {}
for i in range(1, numcols):
#if i > 6: break # Testing
col = columns[i]
lang, style = col['lang'], col['style']
# If we haven't already open... | Python | 1 |
HashMap, iter};
#[derive(Clone)]
struct Node {
bit_counter: u8,
}
pub struct Fuzzer {
nodes: Vec<Node>,
sancov_index_map: HashMap<u32, usize>,
sancov_edge_dict: HashMap<u32, Vec<(u32, Vec<usize>)>>,
}
impl Fuzzer {
pub fn new(struct_graph: &StructureGraph, cfg: ControlFlowGraph) -> Self {
... | Rust | 0 |
|_e| ())
}
}
#[derive(Debug)]
enum Control {
Log(String, oneshot::Sender<()>),
#[allow(dead_code)]
Sleep(u64, oneshot::Sender<()>),
Finish(JobResult),
}
struct LoggerControl(mpsc::Sender<Control>);
impl LoggerControl {
fn new() -> (Self, mpsc::Receiver<Control>) {
let (tx, rx) = mpsc:... | Rust | 0 |
atched() }
}
}
/// Matches if the asserted collection contains *all* (possibly more) of the expected elements.
pub struct ContainsSubset<T> {
expected_elements: Vec<T>
}
/// Matches if the asserted collection contains *all* (possibly more) of the expected elements.
///
/// #Examples
/// ```rust
/// # #[macro_... | Rust | 0 |
self.instance_size = 256
else:
self.exemplar_size = 127
self.instance_size = 255
# total_stride = 8
# score_size = (instance_size - exemplar_size) // total_stride + 1 + 8 # for ++
self.total_stride = stride
self.score_size = int(round(self.insta... | Python | 1 |
tools can suggest correct setters to build the struct. Also, `build`
//! function is allowed only the all of required fields are provided. **No Result**, **No Unwrap**. Just use it.
//! - **Lazy evaluation and asynchronous**: Lazy evaluation and asynchronous are supported.
//! The values will be evaluated when the str... | Rust | 0 |
'''
run as: python3 get_ftx_embeddings.py <fasttext_model> <vocabulary_file> <output_file>
example: python3 get_ftx_embeddings.py wiki.en.bin Xf.txt fasttextB_embeddings_300d.npy
Compute fasttext embeddings for a given vovabulary file
* input file format: a token in each line
* pre-trained fasttext model is av... | Python | 1 |
position_triforce += dx * direction;
if position_triforce > 10.0 || position_triforce < -10.0 {
vhat_triforce = -vhat_triforce;
direction = -direction;
}
let trans_mat = Matrix4::from_affine_translation(&(vhat_triforce * dx));
let model_mat = context.entit... | Rust | 0 |
import unittest
from Crypto.Cipher import DES, AES
from unittest.mock import Mock
from codeql_cwe327_0 import send_encrypted
class Channel:
def __init__(self):
self.messages = []
def send(self, message):
self.messages.append(message)
class TestCWE327_0(unittest.TestCase):
def test_correct... | Python | 1 |
.2 += 1
} //gene
_ => (),
};
nreads += 1.0;
}
let mut max_gene_this_umi: Vec<u8> = Vec::new();
let mut max_allele_this_umi: usize = 0;
let mut max_reads_this_umi: usize = 0;
for (g, frq) ... | Rust | 0 |
prometheus.example.com/api/"))
.arg(Arg::with_name("user")
.long("user")
.short("u")
.takes_value(true)
.help("Basic Auth username"))
.arg(Arg::with_name("pass")
.long("password")
.short("p")
.takes_value(true)
.requires("us... | Rust | 0 |
import pytest
import torch
from laia.callbacks import LearningRate
from laia.dummies import DummyEngine, DummyLoggingPlugin, DummyMNIST, DummyTrainer
def test_learning_rate_warns(tmpdir):
trainer = DummyTrainer(
default_root_dir=tmpdir,
max_epochs=1,
callbacks=[LearningRate()],
)
... | Python | 1 |
},
'ai_thinking': {
'title': '🧠 AI正在深度思考' if lang == Language.ZH_CN else '🧠 AI Deep Thinking',
'description': f"正在第{context.get('step', 1)}步处理,进度{context.get('progress', 0)}% - 分析{user_query}" if lang == Language.ZH_CN else f"Processing step {context.get('step', 1)}, progr... | Python | 1 |
(item)
self._Filters.append(obj)
self._By = params.get("By")
self._Order = params.get("Order")
memeber_set = set(params.keys())
for name, value in vars(self).items():
property_name = name[1:]
if property_name in memeber_set:
memeber... | Python | 1 |
gging.Handler]) -> None:
"""サードパーティのロガーを設定する"""
for logger_name in logger_names:
module_logger = logging.getLogger(logger_name)
module_logger.setLevel(level)
module_logger.propagate = False
# 既存のハンドラーをクリアしてから新しいハンドラーを追加
module_logger.handlers = []
for handler in ... | Python | 1 |
# extends Base Market
from models.Market import Market
from models.Orderbook import Orderbook
from platforms.BasePlatform import BasePlatform
from models.PlatformType import PlatformType
from random import randint, random
import time
import string
import random
from random import randint
from models.Order import Order
... | Python | 1 |
import typer
from typing import Annotated, Optional
from frappe_manager import CLI_BENCHES_DIRECTORY
from frappe_manager.site_manager.SiteManager import BenchesManager
from frappe_manager.site_manager.site import Bench
from frappe_manager.site_manager.site_exceptions import BenchSSLCertificateNotIssued
from frappe_mana... | Python | 1 |
read_obj<T: DeserializeOwned, P: AsRef<Path> + Debug>(filename: P) -> T {
let f = match std::fs::File::open(&filename) {
Err(err) => panic!("couldn't open file {:?}: {}", filename, err),
Ok(f) => f,
};
let mut reader = std::io::BufReader::new(f);
deserialize_from(&mut reader)
.u... | Rust | 0 |
Time::from_hms(12, 5, 15),
mnemonic: "FOO",
text: Some("Text"),
};
assert_eq!(format!("{}", record), expected_string);
}
proptest! {
#[test]
#[allow(unused_must_use)]
fn parse_doesnt_crash(s in "E\\PC*") {
ERecord::parse(&s);
... | Rust | 0 |
s (except maybe the first) are lower case, for now.
@todo: Handle upper-case
>>> how_many(0, 'error')
'zero errors'
>>> how_many(1, 'error')
'one error'
>>> how_many(0, 'zero')
'zero zeroes'
>>> how_many(-99, 'penny')
'minus ninety-nine pennies'
>>> how_many(42, 'radius')
'fo... | Python | 1 |
c_error_code_OTC_INVALID_PARAM => Err(OtcError::InvalidParam("")),
ffi::otc_error_code_OTC_FATAL => Err(OtcError::Fatal),
ffi::otc_error_code_OTC_CONNECTION_DROPPED => Err(OtcError::ConnectionDropped),
ffi::otc_error_code_OTC_CONNECTION_TIMED_OUT => Err(OtcError::TimedOut),
... | Rust | 0 |
ble for SYNCBUSY_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
<gh_stars>0
// Take a look at the license at the top of the repository in the LICENSE file.
use crate::{Expression, StringFilter};
use glib::translate::*;
impl StringFilter {
#[doc(alias = "gtk_string_filter_n... | Rust | 0 |
import numpy as np
import matplotlib.pyplot as plt
def load_data(filename):
data = np.loadtxt(filename, delimiter=',')
X = data[:,:2]
y = data[:,2]
return X, y
def sig(z):
return 1/(1+np.exp(-z))
def map_feature(X1, X2):
"""
Feature mapping function to polynomial features
"""
... | Python | 1 |
)
if len(attribute_sets_names) == 0:
return target
if len(attribute_sets_names) == 1:
attribute = attribute_sets_names[0]
elif len(attribute_sets_names) == 2:
attribute = attribute_sets_names[0] + " and " + attribute_sets_names[1]
else:
... | Python | 1 |
_scenic as scenic, futures::prelude::*};
#[cfg(feature = "flatland")]
static NEXT_IMAGE_INSTANCE_ID: AtomicUsize = AtomicUsize::new(1);
/// An implementation of the wl_compositor global.
pub struct Compositor;
impl Compositor {
/// Creates a new `Compositor`.
pub fn new() -> Self {
Self
}
}
impl... | Rust | 0 |
,
**extra_arguments,
)
class MultinodeConstraintFunctions(MultinodePenaltyFunctions):
pass
class MultinodeConstraintFcn(FcnEnum):
"""
Selection of valid multinode constraint functions
"""
STATES_EQUALITY = (MultinodeConstraintFunctions.Functions.states_equality,)
CONTROL... | Python | 1 |
xisting_prescription.dosage
existing_prescription.observations = prescription.observations or existing_prescription.observations
existing_prescription.diagnosis = prescription.diagnosis or existing_prescription.diagnosis
existing_prescription.diseases_type = prescription.diseases_type or existing_prescripti... | Python | 1 |
from PyInstaller.utils.hooks import collect_data_files, get_hook_config
# Recognition backends are imported with `importlib.import_module()`.
hiddenimports = ['easyocr.model.vgg_model', 'easyocr.model.model']
def hook(hook_api):
lang_codes = get_hook_config(hook_api, 'easyocr', 'lang_codes')
if not lang_code... | Python | 1 |
"""
ASGI config for career_navigator project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/5.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJA... | Python | 1 |
w: bool,
/// Number of rows that occur before either the header row (if `has_header_row` is `true), or
/// the first data row.
pub num_preamble_rows: usize,
}
/// Metadata about the quoting style of the CSV file.
#[derive(Clone, PartialEq)]
pub enum Quote {
/// Quotes are not used in the CSV file.
... | Rust | 0 |
trict']} {job['businessDistrict']}")
column += 1
row += 1
column = 1
# 添加新的sheet并写入相关的行列数据
extra_sheet = workbook.create_sheet(title='就业反欺诈')
extra_data = [
['主题', '链接'],
['就业形势分析及预防欺诈对策', 'https://nbviewer.org/github/hoochanlon/scrip... | Python | 1 |
Result<proto::MessageOut, tonic::Status>,
>,
ctx: &Context,
execute_span: Span,
) -> TofndSignOutput {
// try to create sign with context
let sign = new_sign(
ctx.group(),
&ctx.share,
&ctx.sign_parties,
ctx.msg_to_s... | Rust | 0 |
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# 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 appli... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.