text
string
label_name
string
labels
int64
"""Module: barcode.upc :Provided barcodes: UPC-A """ __docformat__ = "restructuredtext en" from functools import reduce from barcode.base import Barcode from barcode.charsets import upc as _upc from barcode.errors import IllegalCharacterError from barcode.errors import NumberOfDigitsError class UniversalProductCod...
Python
1
): """算力套餐类型 :rtype: str """ return self._BundleType @BundleType.setter def BundleType(self, BundleType): self._BundleType = BundleType @property def SystemDisk(self): """实例系统盘配置信息。若不指定该参数,则按照系统默认值进行分配。 :rtype: :class:`tencentcloud.hai.v20230812....
Python
1
: Option<String>, #[doc = "the retention policy which determines how long the associated data should persist"] #[serde(rename = "DeleteRetentionPolicy", default, skip_serializing_if = "Option::is_none")] pub delete_retention_policy: Option<RetentionPolicy>, #[doc = "The properties that enable an account...
Rust
0
< 70 { y_part + 2000 } else { y_part + 1900 } } else { y_part }; NaiveDate::from_ymd_opt(year, month as u32, day as u32) } fn dbl2date(x: f64) -> Option<NaiveDate> { if x % 1.0 == 0.0 { int2date(x as i32, true) } else { None } } ...
Rust
0
#! /usr/bin/env python import argparse, re import xml.etree.ElementTree as ET from os.path import join from resolve_paths import paths target = paths['drawable'][0] parser = argparse.ArgumentParser(description=f'count icons') parser.add_argument('-i', '--input', dest='input', ...
Python
1
.org/std/sync/struct.RwLock.html): //! //! * It implements [`Send`](https://doc.rust-lang.org/std/marker/trait.Send.html) and //! [`Sync`](https://doc.rust-lang.org/std/marker/trait.Sync.html), //! so it can be sent and used between multiple threads. //! * It implements [`Clone`](https://doc.rust-lang.org/std/clo...
Rust
0
ers if totalFingers>=5: totalFingers=5 # print(fingers.count(0)) h,w,c =overlayList[totalFingers].shape # print(h,w,c) img[0:int(h),0:int(w)]=overlayList[totalFingers] # # if len(lmList) != 0: # # finger...
Python
1
" | Sets the algorithm's chaining mode to counter with CBC-MAC mode (CCM).Windows Vista: This value is supported beginning with Windows Vista with SP1. | /// | BCRYPT_CHAIN_MODE_CFB | L"ChainingModeCFB" | Sets the algorithm's chaining mode to cipher feedback. ...
Rust
0
=> return Err(format_err!("AP provider produced invalid update.")), }; let _ = responder.send(); for update in updates { match update.state { Some(state) => match state { OperatingState::Failed => { ...
Rust
0
#!/usr/bin/env python from __future__ import division import random def add_str(a,b): carry = 0 sum = "" i = len(a)-1; j = len(b)-1 while i >= 0 and j >= 0: x, y = int(a[i]), int(b[j]) carry, z = divmod(x+y+carry, 10) sum = str(z) + sum i -= 1; j -= 1 while i >=...
Python
1
st.raises(KeyError, match="5"): ser[key] def test_getitem_generator(string_series): gen = (x > 0 for x in string_series) result = string_series[gen] result2 = string_series[iter(string_series > 0)] expected = string_series[string_series > 0] tm.assert_series_equal(result, expected) ...
Python
1
: int) -> None: """Set the aet property.""" self._cards[0].set_value("aet", value) @property def elform(self) -> int: """Get or set the Element formulation: EQ.13: plane strain (x-y plane) EQ.14: axisymmetric solid (y-axis of symmetry) - area weighted """ # nope...
Python
1
# This file is part of cloud-init. See LICENSE file for license information. """This was the canonical example module from 24.1 Ensure cloud-init still supports it.""" import logging from cloudinit.cloud import Cloud from cloudinit.config import Config from cloudinit.config.schema import MetaSchema, get_meta_doc fro...
Python
1
return tf.nest.flatten(model_variables) def _run_keras(): model_variables = tf.nest.flatten(_create_model_variables()) grad = tf.nest.map_structure(tf.ones_like, model_variables) optimizer = tf.keras.optimizers.SGD( learning_rate=lr, momentum=momentum, nesterov=nesterov) for _ in...
Python
1
ion file", long_about = "Configuration file to use", required = true )] config_file: String, } #[tokio::main] async fn main() -> KafkaRocksDBResult<()> { let opts = CommandLineOptions::parse(); setup_logger(opts.log_to_stdout)?; let settings = Settings::read(&opts.config_file)?; ...
Rust
0
import random from config import API_KEY_3 as key from Local_Search.objective_function import objective def generate_neighbors(solution): """Generate all possible neighbors by swapping middle points""" neighbors = [] available_indices = list(range(1, len(solution) - 1)) for i in available_indices: ...
Python
1
m_intermediate_factor * x.shape[-1], initializer="linear", name="right_projection", w_init=self.w_init, )(x) # now perform outter product init_pairwise_representation = jnp.einsum( "...nd, ...kd -> ...nkd ", left_proj, right_proj ) ...
Python
1
quotes = ( 'A man is not complete until he is married. Then he is finished.', 'As I said before, I never repeat myself.', 'Behind a successful man is an exhausted woman.', 'Black holes really suck...', 'Facts are stubborn things.' ) class QuoteModel: def get_quote(self, n): try: value =...
Python
1
import os import csv import infra.basetest class TestPostScripts(infra.basetest.BRTest): config = infra.basetest.BASIC_TOOLCHAIN_CONFIG + \ """ BR2_INIT_NONE=y BR2_SYSTEM_BIN_SH_NONE=y # BR2_PACKAGE_BUSYBOX is not set BR2_ROOTFS_POST_BUILD_SCRIPT="{}" BR2_ROOTFS_PO...
Python
1
, meets_msrv, msrvs, source::snippet_with_applicability, }; use rustc_errors::Applicability; use rustc_hir::Expr; use rustc_lint::LateContext; use rustc_semver::RustcVersion; pub(super) fn check<'tcx>( cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, self_arg: &'tcx Expr<'_>, radix: &'tcx Expr<'_>, ...
Rust
0
# Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above...
Python
1
"`](", stringify!($Method), "::", stringify!($field), ") field." )] fn $field(mut self, value: $FTy) -> Self { self.payload_mut().$field = Some(value); self } } }; (@setter...
Rust
0
:Error> { let msg = match self { LogType::MessageDeleted => "Deleted", LogType::MessageEdited => "Edited", LogType::UserJoined => "User join", LogType::UserLeft => "User leave", LogType::UserBanned => "User ban", LogType::ChannelCreated => ...
Rust
0
import pytest try: from playwright.sync_api import expect except ImportError: pytestmark = pytest.mark.skip('playwright not available') from panel.tests.util import wait_until pytestmark = pytest.mark.jupyter @pytest.mark.flaky(max_runs=3) def test_jupyter_server(page, jupyter_preview): page.goto(f"{jup...
Python
1
before_session_ending() { KeyMap::<T>::kill(); child::kill_storage(&ChildInfo::new_default_from_vec( TxnRegistry::<T>::prefix_hash(), )); child::kill_storage(&ChildInfo::new_default_from_vec( DoublyEncryptedQueue::<T>::prefix_hash(), )); child::ki...
Rust
0
vent['end'] = event['end'] calendar_service.events().update(calendarId=calendar_id, eventId=existing_event['id'], body=existing_event).execute() logging.info(f'Updated event for {existing_event['summary']}') break if not event_exists: logging.i...
Python
1
} else { c.set_cpu_flags(CpuFlags::C, false); } } } Ok((A::len(), in_cycles + if extra_cycle { 1 } else { 0 })) } /** * ASL - Arithmetic Shift Left * * A,Z,C,N = M*2 or M,Z,C,N = M*2 * * This operation shifts all the bits of the accumulator or memory contents...
Rust
0
2), BlockOnTimeoutRel(u64), // futex BlockOnFutexWait(u64, u64), BlockOnFutexWaitBit(u64, u64), BlockOnFutexLockPI(u64), BlockOnSignal(u64), } use crate::array::{Iter2, Iter3, Local2i, Local3i, Stride}; use building_blocks_core::prelude::*; /// Used for both 2D and 3D strided iteration. (Z ...
Rust
0
from logging.config import fileConfig from sqlalchemy import engine_from_config from sqlalchemy import pool from alembic import context from models import Base from config import config as project_config # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config =...
Python
1
n compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, e...
Rust
0
"""Scoring evaluators. This module contains evaluators for scoring on a 1-10 the output of models, be they LLMs, Chains, or otherwise. This can be based on a variety of criteria and or a reference answer. Example: >>> from langchain_community.chat_models import ChatOpenAI >>> from langchain.evaluation.scoring...
Python
1
r indices are in the same block. let mut block = ALL_ONES << (from % BLOCK_SIZE); if to % BLOCK_SIZE != BLOCK_SIZE - 1 { block &= Self::mask_bit(to + 1) - 1; } self.bits[(from / BLOCK_SIZE) as usize] |= block; return; } // Larg...
Rust
0
def for_slug(self, slug): return self[slug.upper()] class CreateDateTimeField(models.DateTimeField): def __init__(self, *args, **kwargs): kwargs['default'] = datetime.utcnow kwargs['blank'] = True models.DateTimeField.__init__(self, *args, **kwargs) class LastModifiedDateTi...
Python
1
/// pub fn result(&self) -> Option<Result<Vec<String>>> { if let Ok(mut state) = self.state.lock() { if let Some(state) = state.take() { return match state { JobState::Request(_) => None, JobState::Response(result) => Some(result), ...
Rust
0
match match != foo (foo, match) [foo, match] {foo, match} match; match: int match, match.foo match / foo match << foo match and foo match is not foo
Python
1
} } }); // todo: Workaround due to a PAC bug, where M0 is missing. #[cfg(any(feature = "f3", feature = "f4"))] result.regs.cr1.write(|w| unsafe { w.bits( result.regs.cr1.read().bits() | ((word_len_bits.0 as u32) << 28) ...
Rust
0
_P2P\"`*"] pub const PEER_GRAPH_EVENT_NEIGHBOR_CONNECTION: PEER_GRAPH_EVENT_TYPE = 5i32; #[doc = "*Required features: `\"Win32_NetworkManagement_P2P\"`*"] pub const PEER_GRAPH_EVENT_INCOMING_DATA: PEER_GRAPH_EVENT_TYPE = 6i32; #[doc = "*Required features: `\"Win32_NetworkManagement_P2P\"`*"] pub const PEER_GRAPH_EVENT_...
Rust
0
vation), "kernel_initializer": initializers.serialize(self.kernel_initializer), "recurrent_initializer": initializers.serialize(self.recurrent_initializer), "bias_initializer": initializers.serialize(self.bias_initializer), "use_bias": self.use_bias, "unit_for...
Python
1
kind == "absent": raise ValueError(f"absent record: {record.key}") record_keys.append(record.key) # Note that currently --2a format repositories do this correctly, but # KnitPack format repositories do not. if isinstance(self.stacked_repo.texts, knit.KnitVersionedFile...
Python
1
SIZE: u32 = 2048; const MIN_SAMPLE_RATE: u32 = 44100; pub fn run(audio_recv: Receiver<f32>, sample_rate_send: Sender<u32>) { thread::spawn(move || { let host = cpal::default_host(); let device = host .default_output_device() .expect("no audio output device available"); ...
Rust
0
import os import logging from typing import List, Dict, Any, Optional import sys # services 폴더를 Python 경로에 추가 current_dir = os.path.dirname(os.path.abspath(__file__)) services_dir = os.path.join(os.path.dirname(os.path.dirname(current_dir)), 'services') if services_dir not in sys.path: sys.path.append(services_dir...
Python
1
=> Err(Error::new(ErrorKind::BadParameters)), } } pub fn new_tls_session(session_id: u32) { let tls_config = make_config(); let tls_session = rustls::ServerSession::new(&tls_config); TLS_SESSIONS .write() .unwrap() .insert(session_id, Mutex::new(tls_session)); } pub fn close_t...
Rust
0
(250070690292783730); bitmap.insert(250070690272783732); assert_eq!(bitmap.cardinality(), 2); assert_eq!(bitmap.chunks.len(), 1); bitmap.insert(188740018811086); assert_eq!(bitmap.cardinality(), 3); assert_eq!(bitmap.chunks.len(), 2); // Operation works accross c...
Rust
0
lambda x: {'fillColor': 'red'}) # Создаем текст для маркера popup_text = f"Полигон {way_dictionary_names[id]} - {id}" popup = folium.Popup(popup_text) # Добавление маркера в центр полигона lat_center = np.mean([coord[1] for coord in polygon.exterior.coords]) ...
Python
1
import math import cv2 import numpy as np from scipy import io as scio from scipy import linalg from scipy import signal from scipy import sparse from skimage.util import img_as_float from sklearn.metrics import mean_squared_error def detrend(input_signal, lambda_value): signal_length = input_signal.shape[0] ...
Python
1
# Import necessary libraries import numpy as np from qiskit import QuantumCircuit, execute from qiskit.providers.aer import AerSimulator # Define a function to simulate a complex financial scenario using quantum computing def simulate_financial_scenario(initial_investment, interest_rate, time_steps): # Create a ...
Python
1
(root: &str) -> Model { let mut m = Model::new(); let input = m.new(Node::Input(vec![1, 1, 28, 28].into())); let conv_weight = m.new( Tensor::new(vec![8, 1, 5, 5].into()) .with_data(read_f32_list_from(Path::new(root).join("conv1").to_str().unwrap()).into()) .into(), ); ...
Rust
0
egate)] pub struct ServiceResolveParams { flags: DNSServiceFlags, interface_index: u32, name: *const c_char, regtype: *const c_char, domain: *const c_char, callback: DNSServiceResolveReply, context: *mut c_void, } /// Holds parameters for `ManagedDNSServiceRef::get_address_info()`. #[derive...
Rust
0
; let wire_len = { let mut b = octets::OctetsMut::with_slice(&mut d); frame.to_bytes(&mut b).unwrap() }; assert_eq!(wire_len, 7); let mut b = octets::Octets::with_slice(&d); assert_eq!(Frame::from_bytes(&mut b, packet::Type::Short), Ok(frame)); ...
Rust
0
'category': 'display', 'fields': ('diagonal', 'matrix', 'screen_frequency'), }, { 'category': 'connecting', 'fields': ('connection_types', 'sim_number', 'sim_size'), }, { 'category': 'memory', 'fields': ('ram', 'rom', 'max_siz...
Python
1
.unwrap(); let mut bytes: Vec<u8> = Vec::new(); let mut line_start: u32 = 0; // Module push_u8(&mut bytes, TYPE_MODULE); push_span(&mut bytes, 0, js_len - 1); let num_lines: u32 = lines.len().try_into().unwrap(); push_u32(&mut bytes, num_lines); for line in &lines { // Parse line let cap...
Rust
0
), OfferDraw(String), Resign, } impl From<&str> for CwChessAction { fn from(make_move: &str) -> CwChessAction { CwChessAction::MakeMove(make_move.to_string()) } } impl From<&CwChessAction> for GameAction { fn from(action: &CwChessAction) -> GameAction { match action { C...
Rust
0
ion_writes() .unwrap() .first() .unwrap() .table_batches() .first() .unwrap() .row_count(), 554 ); let clock_value = ClockValue::new(23); group.bench_function("new_from_entry_bytes", |b| { b.iter(|| { ...
Rust
0
b"#747474\n#040404\n#FCE484\n#98AC44\n#3CAC80\n#78AC3C\n#78AC3C\n#78AC3C\n#78AC3C\n" ); } #[test] fn test_dominant_color_as_rgb_to_stdout() { let mut result = Vec::new(); let path = fixture_path("image-fixture.png"); let image = Image::new(&path); let matches = App::new("myprog") ....
Rust
0
// TODO: this feels like a cluster. Improve? fn try_from(n: u16) -> Result<Identifier<C>, Self::Error> { let mut bytes = Vec::from(<<C::Group as Group>::Field as Field>::Serialization::default().as_ref()); for (i, byte) in n.to_le_bytes().iter().enumerate() { bytes[i] = ...
Rust
0
"results": { "operating_points": { "world_1": {"tpr": 0.9, "fpr": 0.08}, # outside window "world_0": {"tpr": 0.7, "fpr": 0.0}, }, "j_statistic": {"empirical": 0.2, "confidence_interval": {"lower": 0.1, "upper": 0.3, "method": "bootstrap"}}, ...
Python
1
URL to fetch the next set of operations."] #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, #[doc = "Array of operations"] pub value: Vec<Operation>, } impl OperationsList { pub fn new(value: Vec<Operation>) -> Self { Self { next_...
Rust
0
ror_q01 = np.sum(np.abs(np.array(pred_list[1]) - np.array(true_list[1]))) print("Error q01: ", error_q01/n) print("Error lambda0: ", error_lambda_0/n) np.save("/data/pred_bisse_GNN_PhyloPool2.npy", pred_list) sys.exit() # Training loop while epoch < n_epochs and trigger <= patience: start_time =...
Python
1
def get_dynamic_axes(self): return {'images': {(0): 'B', (2): '8H', (3): '8W'}, 'latent': {(0): 'B', (2): 'H', (3): 'W'}}
Python
1
int64) return ( note_lengths_array, note_consonants_array, note_vowels_array, phonemes_array, phoneme_keys_array, phoneme_note_ids, ) def _hira_to_kana(text: str) -> str: """ひらがなをカタカナに変換する""" return "".join(chr(ord(c) + 96) if "ぁ" <= c <= "ゔ" else c for...
Python
1
(Clone, Copy, Debug, PartialEq)] pub enum IBE11_A { #[doc = "0: Pin interrupt edge is configured through the IEV register"] IEV, #[doc = "1: Pin interrupt is triggered on both rising and falling edges (if edge-sensitive)"] BOTH, } impl From<IBE11_A> for bool { #[inline(always)] fn from(variant: ...
Rust
0
ror("Anomaly Detection: \"x_m_next\" contains +/-inf!") elif anomaly_flags[3]: raise ValueError("Anomaly Detection: \"x_m_next\" contains NaN!") elif anomaly_flags[4]: raise ValueError("Anomaly Detection: \"eps\" contains +/-inf!") elif anomaly_flags[5]: raise...
Python
1
1]^2*Q^(4)[1] - Q^(2)[1]*Q^(3)[1]^2 """ return self.parent().sum_of_terms((tl*tr, cl*cr) for tl,cl in self for tr,cr in x) def is_tamely_laced(ct): r""" Check if the Cartan type ``ct`` is tamely-laced. A (symmetrizable) Cartan type wit...
Python
1
.abs().max() plt.scatter( row['log2FC'], row['KEGG通路'], s=size, c=row['neg_log10_p'], cmap=cmap, norm=norm, marker='o', edgecolor='k', linewidth=0.5 ) # # 添加p值标注(排除靠近原点的点) # if abs(row['log2FC']) > 0.1: # 只给log2FC绝对值大于0.1的点加标注 ...
Python
1
#Este programa calcula el área de un círculo y un rectángulo, y convierte una temperatura de Celsius a Fahrenheit. import math def calcular_area_circulo(radio: float) -> float: #Calcula el área de un círculo dado su radio. #:return: El área del círculo. return math.pi * (radio ** 2) def calcular_a...
Python
1
Output = A> + Copy>( array: &mut Array2<A>, ) { let raw_dim = array.raw_dim(); array[(0, 0)] = (array[(1, 0)] + array[(0, 1)]) * 0.5; array[(0, raw_dim[1] - 1)] = (array[(1, raw_dim[1] - 1)] + array[(0, raw_dim[1] - 2)]) * 0.5; array[(raw_dim[0] - 1, 0)] = (array[(raw_dim[0] - 1, 1)] + array[(raw_d...
Rust
0
| 21 | 23 | 25 => a0, _ => unreachable!(), } } #[macro_export] macro_rules! ambiguous_arith_rhs_elem { ('+') => (0); ('-') => (1); ('*') => (2); ('/') => (3); ('0') => (4); ('1') => (5); ('2') => (6); ('3') => (7); ('4') => (8); ('5') => (9); ('6') => (10); ...
Rust
0
e equity for each player /// /// # Arguments /// /// * `hand_ranges` Array of hand ranges /// * `board_mask` 64 bit mask of public cards /// * `n_threads` Number of threads to use in simulation /// /// # Example /// ``` /// use rust_poker::hand_range::{HandRange, get_card_mask}; /// use rust_poker::equity_calculator::e...
Rust
0
import numpy as np from typing import Tuple def transpose(imlist): """ Replacing the x-axis and y-axis of an image in the list of images """ return [ img.T for img in imlist] def invert(imlist): """ Invert the color of an image in the list of images """ return [ 255-img for img in imli...
Python
1
{config['clips'][index-1]['background']}" ), text=page.get('text', ''), text_size=page.get('text_size', 70), ) elif page['type'] == 'finger_and_object': make_finger_and_object_page( config, page['duration'], obj=f"{config['input...
Python
1
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 在预处理前自动修复视频与描述不匹配的问题 可以作为独立脚本运行,也可以被其他脚本导入 """ import os import json import shutil import argparse from pathlib import Path import logging from typing import Tuple, List, Set # 设置日志 logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(l...
Python
1
from types import FunctionType from Script.Core import cache_control, game_type, get_text, flow_handle from Script.Design import map_handle, update, constant from Script.UI.Model import panel cache: game_type.Cache = cache_control.cache """ 游戏缓存数据 """ _: FunctionType = get_text._ """ 翻译api """ def own_charcter_move(...
Python
1
from itertools import product ans = 0 for num in product('0123456', repeat=5): num = ''.join(num) if num[0] != '0': for i in '0246': num = num.replace(i, '*') cnt1 = num.count('***') cnt2 = num.count('**') if cnt1 == 0 and cnt2 >= 2: ans += 1 print(ans)
Python
1
import heapq def initialize(): # Define the initial state of the tubes, represented as a list of lists initial_state = [['Red', 'Green', 'Green', 'Blue'], ['Red', 'Green', 'Red', 'Blue'], ['Blue', 'Red', 'Green', 'Blue']] num_tubes = 3 tube_capacity = 6 visited_costs = {} visited_costs[str(initial_...
Python
1
, &CodepointMono, b as f64, width_cache, task.start), Width(w) => RewrapCtx::new(text, client, w, width_cache, task.start), None => unreachable!(), }; let start_line = cursor.cur_line; let max_lines = max_lines.unwrap_or(MAX_LINES_PER_BATCH); // always wrap at le...
Rust
0
pub const ONE_YEAR_SEC: TimestampSec = 365 * ONE_DAY_SEC; pub const GENESIS_TIMESTAMP_SEC: TimestampSec = 1_600_000_000; pub const NEAR: &str = "near"; pub const TOKEN_ID: &str = "token.near"; pub const FT_LOCKUP_ID: &str = "ft-lockup.near"; pub const OWNER_ID: &str = "owner.near"; pub const T_GAS: Gas = 10u64.pow(1...
Rust
0
") if response.status_code == 503: error = str(mini_sentry.test_failures.get(timeout=1)) assert "aggregator limit exceeded" in error error = str(mini_sentry.test_failures.get(timeout=1)) assert "Health check probe 'aggregator'" in error return ...
Python
1
schema = idx.schema(); let has_tokenizer = schema.fields().find(|(_, entry)| match entry.field_type() { tantivy::schema::FieldType::Str(ref opts) => opts .get_indexing_options() .map(|to| to.tokenizer() == cang_jie::CANG_JIE) .unwrap_or(false), _ => false, })...
Rust
0
e, avoid_if_shorter_than=1, ): """This function prepares the Tedlium2 dataset. Download link: https://lium.univ-lemans.fr/ted-lium2/ Arguments --------- data_folder : str Path to the folder where the original Tedlium2 dataset is stored. utt_save_folder : list Path where to s...
Python
1
# -*- coding: utf-8 -*- # <Lettuce - Behaviour Driven Development for python> # Copyright (C) <2010-2012> Gabriel Falcão <gabriel@nacaolivre.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundatio...
Python
1
tChar, GetChar, CoreDump, Loop(Vec<Ast>), } #[derive(Debug,PartialEq)] enum Token { SymWithOffset(char, isize), Symbol(char), } fn tokenize(s: &str) -> Result<Vec<Token>, String> { let inputs = s.split("\n") .map(|line| if let Some(pos) = line.find('#') { &line[0..pos] } else { line ...
Rust
0
ms[:2]: # Limit to 2 synonyms if synonym != token and "_" not in synonym: new_tokens = tokens.copy() new_tokens[i] = synonym expanded_queries.append(" ".join(new_tokens)) return expanded_que...
Python
1
])) for err in new_errors ] if wrap_error_message: message += '\n'.join( textwrap.fill(msg, initial_indent=' - ', subsequent_indent=' ') for msg in new_error_messages ) else: error_message = '\n'.join(new_error_messages) if error_message: message += '- ' + error_messa...
Python
1
from fastapi import FastAPI from routes.student import router app = FastAPI() app.include_router(router) @app.get("/") def home(): return { 'msg': "welcome" }
Python
1
s] codes = codes.astype("int32") n = len(ids) packed_codes = np.zeros((n, index.rq.code_size), dtype="uint8") index.rq.pack_codes( n, faiss.swig_ptr(codes), faiss.swig_ptr(packed_codes), -1, faiss.swig_ptr(norms), No...
Python
1
[0] != 0: # image에 nan값이 포함되어 있을 경우 (== scan을 도중에 멈추었을 경우) # # if i < np.min(np.where(np.isnan(z))[0]): # nan이 등장하는 line 이전에 대해서 linear fit. 이후는 모두 nan으로 밀기. # if i not in set(np.where(np.isnan(z))[0]): # nan이 등장하는 line 만 선택. 방법: nan인 모든 point의 line을 다 불러들인후 list(set()). set은 중복 원소 제거 위함...
Python
1
chunk = update_data_chunk_crc(chunk) self.data_chunks.append(chunk[:-2]) self.data_chunks_crc.append(chunk[-2:]) def post_build(self, pkt, pay): cnk_len = self.chunk_len pay_len = len(pay) pkt_len = len(pkt) total = pkt_len + pay_len chunks = pay_len /...
Python
1
da a, p: [1. / p[0] if a == (10,) else 1. / (p[0] - 1.)] # noinspection PyPep8 sa_gen_func = lambda p, n: [((10,) if x == 1 else (-10,)) for x in binomial(1, p[0], n)] adp_pg_obj = ADPPolicyGradient( mdp_rep_for_adp_pg=mdp_rep_obj, reinforce=reinforce_val, num_state_samples=num_state...
Python
1
= 3; const BR_TMP_OFFSET: usize = 12; const BR_REF_CAT: usize = 4; pub const LEVEL_CONTEXTS: usize = 21; pub const NUM_BASE_LEVELS: usize = 2; pub const BR_CDF_SIZE: usize = 4; const COEFF_BASE_RANGE: usize = 4 * (BR_CDF_SIZE - 1); const COEFF_CONTEXT_BITS: usize = 6; const COEFF_CONTEXT_MASK: usize = (1 << CO...
Rust
0
scan_one_script(mod_script_dir, modded_script_path, debug_output_file, global_result=global_result, output_folder=output_folder) if global_result.missing_char_detected: print("<<<<<<<<<<< WARNING: one or more missing from the mod_to_name or og_to_name table, please update or matching will be incomplete! >>>>>>>>>...
Python
1
h to checkpoint file" ) parser.add_argument("--input_name", type=str, required=True, help="path to image file name") parser.add_argument("--text_prompt", type=str, required=True, help="text prompt") parser.add_argument("--box_threshold", type=float, default=0.3, help="box threshold") parser.add_arg...
Python
1
"""price, promocode from str to int Revision ID: 2f7dd4b3e4ec Revises: Create Date: 2024-02-19 21:00:44.932415 """ from typing import Sequence, Union from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision: str = '2f7dd4b3e4ec' down_revision: Union[str, None] = None branch...
Python
1
trict_dict is not None: flag = True for re_key, re_value in restrict_dict.items(): if sample[re_key] != re_value: flag = False if flag is True: test_reward.appe...
Python
1
files.push_str(&format!("COPY {} ./\n", file)); } // https://hub.docker.com/_/rust String::from(format!( r####" # Dockerfile.rockerize FROM rust:alpine AS builder LABEL maintainer="<EMAIL>" # Add unprivileged user/group RUN mkdir /user && \ echo 'nobody:x:65534:65534:nobody:/:' > /user/passw...
Rust
0
{ Ok(HString::wrap(out)) } else { err(hr) } }} #[inline] pub fn set_camera_model(&self, value: &HStringArg) -> Result<()> { unsafe { let hr = ((*self.lpVtbl).put_CameraModel)(self as *const _ as *mut _, value.get()); if hr == S_OK { Ok(()) } else { err(hr) } }} #[inline] pub fn get_ori...
Rust
0
#!/usr/bin/env python # This file should be run using a non-ros unit test framework such as nose using # nosetests test_dotname.py. import unittest import rostest from dotname_cases import DotnameLoadingTest, NotTestCase, DotnameLoadingSuite class TestDotnameLoading(unittest.TestCase): def test_class_basic(sel...
Python
1
import streamlit as st import tensorflow as tf import numpy as np from PIL import Image import gdown import os # ID file dari Google Drive file_id = "1ncmFW6XbXAXHj_9Ort-QFA5bzXbZh-EB" model_file = "pneumonia_model.h5" # Download model jika belum ada @st.cache_resource def load_model(): if not os.path.exists(mode...
Python
1
ymm_k1z_ymm_xmmm128 0x232A_00F3,// EVEX_Vpsllq_zmm_k1z_zmm_xmmm128 0x2002_00F4,// Pmuludq_mm_mmm64 0x200A_00F4,// Pmuludq_xmm_xmmm128 0x224A_00F4,// VEX_Vpmuludq_xmm_xmm_xmmm128 0x22CA_00F4,// VEX_Vpmuludq_ymm_ymm_ymmm256 0x222A_00F4,// EVEX_Vpmuludq_xmm_k1z_xmm_xmmm128b64 0x22AA_00F4,// EVEX_Vpmuludq_ymm_k1z_ym...
Rust
0
#!/usr/bin/env python import os, sys import about BINDIR = "bin" def main(): pkg_dir = os.path.dirname(__file__) for dirname in sys.path: # Find graphterm installation in path (but not in current directory) if not dirname: continue if os.path.isfile(os.path.join(dirname, ...
Python
1
_base_ = [ '../_base_/models/ocrnet_hr18.py', '../_base_/datasets/ade20k.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_80k.py' ] crop_size = (512, 512) data_preprocessor = dict(size=crop_size) norm_cfg = dict(type='SyncBN', requires_grad=True) model = dict( data_preprocessor=data_prepro...
Python
1