text
string
label_name
string
labels
int64
applicable_on_tuple_usage() { //Improvement: might be reasonable to allow & implement check_assist_not_applicable( assist, r#" fn main() { let t = (1,2); let v = $0t.0; } "#, ) } #[test] fn replace_all() { check_assist( ...
Rust
0
; A-Z / a-z #[inline] pub fn is_alpha(c: u8) -> bool { (c>=0x41 && c<=0x5A) || (c>=0x61 && c<=0x7A) } def_cclass!(Alpha, is_alpha); impl_display!(Alpha); // 3.2.1 // quoted-pair = ("\" (VCHAR / WSP)) / obs-qp #[derive(Debug, Clone, Copy, PartialEq)] pub struct QuotedPair(pub u8); impl Parsable for QuotedPair { ...
Rust
0
from typing import Optional from github import Github from github.Repository import Repository import time def github_search(query: str, token: Optional[str] = None, sort: str = "stars", order: str = "desc", max_results: int = 10) -> str: """ ...
Python
1
"""Utilities related to linear operators.""" import numpy as np from math import copysign, sqrt def machine_epsilon(): """Return the machine epsilon in double precision.""" return np.finfo(np.double).eps def roots_quadratic(q2, q1, q0, tol=1.0e-8, nitref=1): """Find the real roots of a quadratic. ...
Python
1
# -*- coding: utf-8 -*- """This module provides the rpcontacts package.""" __version__ = "0.1.0"
Python
1
ts.error("Only 1 input is supported in specgram mode") pdata, bins, t = calc_specgram(datas[0], options.axis) write_specgram(pdata, bins, t, options.output) else: write_frequency_response(datas, options.output) return # Draw graph if options.raw: if l...
Python
1
let lock = self.0; let ffi_result = unsafe { ::ffi::libphonenumber_sys_c_i18n_phonenumbers_AutoLock_new(lock as *mut ::lock_posix::i18n::phonenumbers::Lock) }; unsafe { ::cpp_utils::CppBox::new(ffi_result) } } } } } } <filename>http/src/request/guild/get_guild_prune_count....
Rust
0
ength, decoder_mode, top_p, temperature, repetition_penalty, history, do_reward): if len(chatbot)>0: chatbot.pop() if len(history) >0: # print(history) # print(chatbot) x = history.pop() # chatbot.pop() user_input = x[0] print("regen for Q:", user_input) ...
Python
1
import pandas as pd # Rutas a los archivos Excel archivo_existente = 'INVIERTE_2017_29febrero2024_Analisis_rev2.xlsx' #cambiar cada mes nombre archivo_nuevo = 'Inversiones_April_2024.xlsx' # Leer los datos del archivo existente y del archivo nuevo df_existente = pd.read_excel(archivo_existente, sheet_name='Data', he...
Python
1
m as usize); for i in 0..(num as usize) { bind_names.push(to_rust_str(names[i], lengths[i])); bind_values.push(SqlValue::new(conn.ctxt)); } }; Ok(Batch { conn: conn, handle: handle, statement_type: StatementType:...
Rust
0
!(format!("{}", string), "utf-8 encoded string"); } #[test] fn test_bytestring_debug_utf8() { let string: ByteString = "utf-8 encoded string".into(); assert_eq!(format!("{:?}", string), "b\"utf-8 encoded string\""); } #[test] fn test_bytestring_display_bytes() { let by...
Rust
0
($imm8:expr) => { vpsraid(a.as_i32x16(), $imm8) }; } let shf = constify_imm8_sae!(imm8, call); transmute(simd_select_bitmask(k, shf, src.as_i32x16())) } /// Shift packed 32-bit integers in a right by imm8 while shifting in sign bits, and store the results in dst using zeromask ...
Rust
0
ations # TODO # - check cho_factor and cho_solve from scipy # - create function for proxy of update of l1/l2 reguralization term # old_U = U.reshape(U.shape[0], -1) for admm_it in range(num_admm_iterations): # temp_U = U.reshape(U.shape[0], -1) # for...
Python
1
, // 0x41, 0x44, 0x49, 0x4f, 0x53, 0x00, // 0x00, 0x00, // 0x06, 0x00, 0x00, 0x00, // 0x48, 0x45, 0x4c, 0x4c, 0x4f, 0x00, // 0x00, 0x00, // 0x04, 0x00, 0x00, 0x00, // 0x42, 0x59, 0x45, 0x00, // ...
Rust
0
let pool_supply_wrap = T::MultiCurrency::total_issuance(wrapped_asset_id); let pool_data = Self::get_pool_data(underlying_asset); Self::calculate_exchange_rate( pool_supply_underlying, pool_supply_wrap, pool_data.protocol_interest, pool_data.borrowed, ) } /// Converts a specified number of underl...
Rust
0
self.get_form_element(element).setValue(val) return True except AttributeError: return False def set_is_checked(self, element, val): try: self.get_form_element(element).setChecked(val) return True except AttributeError: return...
Python
1
AFRINIC', 'APNIC', 'ARIN', 'LACNIC', 'RIPE'] @staticmethod def is_valid(value: str, sanitize: bool = False) -> bool: if sanitize: value = Registry.sanitize(value) if not UppercaseString.is_valid(value): return False if value not in Registry.ENUM: re...
Python
1
import ujson as json from consoleme.config import config from consoleme.handlers.base import BaseMtlsHandler from consoleme.lib.plugins import get_plugin_by_name stats = get_plugin_by_name(config.get("plugins.metrics", "default_metrics"))() log = config.get_logger() auth = get_plugin_by_name(config.get("plugins.auth"...
Python
1
#Não mascara a letra mascara += letra #Senão else: #Mascara a letra mascara += '_' #Remove os espaços da palavra conta os dígitos digitos_palavra = len(palavra.replace(' ', '')) letras_jogadas_texto = ...
Python
1
import tkinter as tk root = tk.Tk() root.geometry("300x200") root.title("Frame() Widget") frame = tk.Frame(root, bg="blue", bd=5) frame.place(relx=0.5, rely=0.5,anchor=tk.CENTER) label1 = tk.Label(frame, text="label1", bg="green") label2 = tk.Label(frame, text="label2", bg="red") label1.pack() label2.pack() root.ma...
Python
1
`\"Win32_System_Memory\"`*"] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Memory"))] pub struct MINIDUMP_CALLBACK_OUTPUT_0_3 { pub VmQueryStatus: ::windows_sys::core::HRESULT, pub VmQueryResult: MINIDUMP_MEMORY_INFO, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Memory"))...
Rust
0
while True: try: num = int(input("Enter a number: ")) break except ValueError: print("Input Error") for i in range(1, 11): print(num, "x", i, "=", num * i)
Python
1
from django.contrib import admin from django.contrib.admin import SimpleListFilter from orders.models import * admin.site.register(Currency) admin.site.register(Fees) admin.site.register(ActionCategory) admin.site.register(StockStatus) admin.site.register(ActionSector) admin.site.register(Strategy) admin.site.regis...
Python
1
get_by_second(&key.0).expect("no entry found for second key/value") } } /// An iterator over the K/V pairs contained in a `BidirMap`. /// /// See documentation of [`BidirMap::iter()`](struct.BidirMap.html#method.iter) for more. pub struct Iter<'a, Kv1: 'a, Kv2: 'a> { iter: slice::Iter<'a, (Kv1, Kv2)>, } impl<'a, K...
Rust
0
tina = 3 ** 3 print(tina) christy = 3 + tina + 3 print(christy) quino = christy + tina print(quino)
Python
1
nt1 = float(input('Insira a nota1: ')) nt2 = float(input('Insira a nota2: ')) nt3 = float(input('Insira a nota3: ')) nt = (n1 + n2 + n3) / 3 if nt >= 0 and nt <= 4: print(f'Nota {nt} = Reprovado.') elif nt >= 5 and nt <= 6: print(f'Nota {nt} = Recuperaçãp') elif nt >= 7 and nt <= 10: print(f'Nota {nt} = Aprovado...
Python
1
arg.is_explicit_null() } fn object_field_is_explicit_null(obj: ObjectInput) -> bool { obj.field.is_explicit_null() } } type Schema = juniper::RootNode<'static, Query, EmptyMutation<Context>, EmptySubscription<Context>>; #[tokio::test] async fn explicit_null() { let query = r#" ...
Rust
0
leep(Duration::from_secs(3)); println!("you can see log files in path: {}","target/logs/") }<filename>FRENCH/listings/ch03-common-programming-concepts/output-only-01-no-type-annotations/src/main.rs fn main() { let supposition = "42".parse().expect("Ce n'est pas un nombre !"); } <filename>src/query/range_query.r...
Rust
0
t = name.starts_with('\\'); let offset = root as usize; let mut name_parts = Vec::new(); for part in name[offset..].split('.') { assert_eq!(part.len(), 4); let mut name_part = [0u8; 4]; name_part.copy_from_slice(part.as_bytes()); name_parts.push(na...
Rust
0
ImageDesc(this: *mut GifFileType) -> c_int { unsafe { &mut *this } .decoder_mut() .map(|_| GIF_OK) .unwrap_or_else(|x| x) } #[allow(unused_unsafe)] #[no_mangle] pub unsafe extern "C" fn DGifGetLine(this: *mut GifFileType, line: *mut GifPixelType, len: c_int) -> c_int { let mut err: c_in...
Rust
0
fn main() { let env_path = env::var("WEBOTS_PATH").ok(); let webots_path = if cfg!(target_os = "linux") { WEBOTS_LINUX_PATH.to_string() } else if cfg!(target_os = "macos") { WEBOTS_MACOS_PATH.to_string() } else if let Some(path) = env_path { path } else if cfg!(target_os = "w...
Rust
0
] & LOWER_MASK); let k = (self.index + M) % N; self.state[self.index] = self.state[k] ^ (y >> 1) ^ (A * (y & 1)); let mut z = self.state[self.index] ^ ((self.state[self.index] >> U) & D); self.index = j; z ^= (z << S) & B; z ^= (z << T) & C; z ^ (z >> L) }...
Rust
0
""" Classifies: CHEBI:36683 organochlorine compound """ from rdkit import Chem def is_organochlorine_compound(smiles: str): """ Determines if a molecule is an organochlorine compound based on its SMILES string. An organochlorine compound contains at least one carbon-chlorine bond. Args: smiles...
Python
1
()) .ok() .and_then(|v| v.as_string()) .unwrap_or(String::new()) } fn set_name(&self, name: &str) { js_sys::Reflect::set(self.inner.as_ref(), &"name".into(), &name.into()).unwrap_throw(); } } impl From<DynamicFormListedElement> for web_sys::HtmlElement { fn ...
Rust
0
Code::OK)) } } #[cfg(test)] mod tests { use warp::http::StatusCode; use warp::test::request; use super::filters; use std::str; #[tokio::test] async fn try_color() { let api = filters::color(); let response = request() .method("GET") .path("/") ...
Rust
0
import rclpy from rclpy.node import Node from sensor_msgs.msg import JointState from geometry_msgs.msg import Pose from moveit_msgs.srv import GetPositionFK import pandas as pd class FKClient(Node): def __init__(self): super().__init__('fk_client') self.client = self.create_client(GetPositionFK, 'c...
Python
1
self.buffer .iter() .map(|(style, text)| style.paint(text).to_string()) .collect() } /// Get the unformatted text as a single continuous string. pub fn raw_string(&self) -> String { self.buffer.iter().map(|(_, str)| str.as_str()).collect() } } fn ren...
Rust
0
('company_id', '=', byproduct.company_id.id), ('company_id', '=', False) ] byproduct.allowed_operation_ids = self.env['mrp.routing.workcenter'].search(operation_domain) @api.onchange('product_id') def onchange_product_id(self): ...
Python
1
if (end - self.start) > self.size_limit as u64 { return Poll::Ready(Err(ReadToEndError::TooLong)); } self.end = self.end.max(end); self.read.push((chunk.bytes, chunk.offset)); } None => { ...
Rust
0
// let wasm_slice = wasm_alloc.alloc_bytes(direct_bytes)?; // wasm_slice.store_to_args(args); // return Ok(Some(wasm_slice)); // } WasmVal::ByteArray { jarray, .. } => { // This is should be safe, it's copied into while borrowed th...
Rust
0
le_id"), Index("process_rule_dataset_id_idx", "dataset_id"), Index("process_rule_account_id_idx", "account_id"), ) id = Column(UUID, nullable=False, server_default=text("uuid_generate_v4()")) account_id = Column(UUID, nullable=False) dataset_id = Column(UUID, nullable=False) mode = ...
Python
1
= pool.add(elem); println!("new Index: {}", index); assert_eq!(2, index.index()); println!("pool: {:?}\n", pool); pool.remove_by_pos(0); pool.remove_by_pos(17); // remove 42, gen=0 from 1 pool.remove_by_pos(1); println!("pool: {:?}\n", pool); // a...
Rust
0
""" Copyright (joint work) 2024 The Rockstor Project <https://rockstor.com> Rockstor 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 Foundation; either version 2 of the License, or (at your option) any later version. Rockst...
Python
1
SPIMaster4, UART0}; use hal::time::Hertz; #[cfg(feature = "usb")] use hal::usb::usb_device::bus::UsbBusAllocator; #[cfg(feature = "usb")] pub use hal::usb::UsbBus; define_pins!( /// Maps the pins to their arduino names and /// the numbers printed on the board. struct Pins, target_device: target_devic...
Rust
0
from django.utils.crypto import md5 TEMPLATE_FRAGMENT_KEY_TEMPLATE = "template.cache.%s.%s" def make_template_fragment_key(fragment_name, vary_on=None): hasher = md5(usedforsecurity=False) if vary_on is not None: for arg in vary_on: hasher.update(str(arg).encode()) hasher.upda...
Python
1
# ==================== Standard Library Imports ==================== import time # ==================== Typing Imports ==================== def custom_retry(max_retries=3, delay=2, backoff=2): """ Retry decorator with exponential backoff. delay = initial wait time backoff = multiplier (e.g. 2 → doub...
Python
1
erive(serde_derive::Deserialize)] struct DaemonConfig { ipv6: Option<bool>, } //! Helpful methods and structs for operating on the //! [flags](https://polytope.miraheze.org/wiki/Flag) of a polytope. //! //! Recall that a flag is a maximal set of pairwise incident elements in a //! polytope. For convenience, we omit...
Rust
0
import numpy as np b = np.array([[1, 2, 3, 5]]) c = b.transpose() print(b.dot(c), sum(b), sum(c)) matriz_teste = np.array([[1, 2], [3, 4]]) # print(sum(matriz_teste))
Python
1
BadHashable::new(x)); } }) } benchmark_group!( benches, insert_good_hashables_1k, insert_bad_hashables_1k, insert_good_hashables_4k, insert_bad_hashables_4k, ); benchmark_main!(benches); use crate::TimeTracker; use std::fs::OpenOptions; impl<'a> TimeTracker<'a> { pub fn clear(&self...
Rust
0
'group'] = group kw['xscale'] = xscale kw['yscale'] = yscale kw['xgrid'] = xgrid kw['ygrid'] = ygrid kw['y_range'] = y_range return create_and_build(BoxPlotBuilder, data, **kw) class BoxPlotBuilder(BarBuilder): """Produces Box Glyphs for groups of data. Handles box plot options to pr...
Python
1
>>> mols = conf_gen.transform(mols) >>> fp.transform(mols) # doctest: +SKIP array([[1.930e+00, 2.070e-01, 0.000e+00, ..., 0.000e+00, 0.000e+00, 0.000e+00], [1.790e+00, 9.990e-01, 4.160e-01, ..., 0.000e+00, 0.000e+00, 0.000e+00], [1.150e-01, 0.000e+00, 0.000e+00, ..., 0.000e+00, 0.000e+00,...
Python
1
import pm4py import pandas as pd def import_xes(filename: str): """ Reads an XES file using the pm4py library and returns the parsed event log. Parameters: filename (str): A string representing the path to the XES file to be read. Returns: pm4py.log.log.EventLog: Parsed event log object. ...
Python
1
1.4.0").unwrap() { //! println!("cargo:rustc-cfg=compiler_has_important_bugfix"); //! } //! } //! ``` extern crate semver; use semver::Identifier; use std::process::Command; use std::{env, str}; use std::ffi::OsString; // Convenience re-export to allow version comparison without needing to add // semver c...
Rust
0
m()) log_str += 'lr {:.8f} rank {}'.format(lr, rank) logging.debug(log_str) data_start = time.time() def cv(self, model, data_loader, device, args): ''' Cross validation on ''' model.eval() log_interval = args.get('log_interval', 10) ...
Python
1
from pathlib import Path import pytest from cloud_radar.cf.unit._condition import Condition from cloud_radar.cf.unit._stack import Stack from cloud_radar.cf.unit._template import Template """Tests the functionality of the Condition class.""" @pytest.fixture def template(): template_path = Path(__file__).parent...
Python
1
import torch.optim as optim import torch.nn.functional as F import torch import torchvision.transforms as transforms from torch.utils.data import DataLoader, Dataset from PIL import Image import os import torch.nn as nn from loss import CustomCTCLoss from model import CRNN from dataset import data_loader, test_data_l...
Python
1
..=i64::MAX); let stop_ramp_ts: i64 = rng.gen_range(start_ramp_ts..=i64::MAX); let current_ts: i64 = rng.gen_range(start_ramp_ts..=stop_ramp_ts); let swap_base_amount: u64 = rng.gen_range(1..=MAX_TOKENS_IN); let swap_quote_amount: u64 = rng.gen_range(1..=MAX_TOKENS_IN); ...
Rust
0
''' Circle Example ============== This example exercises circle (ellipse) drawing. You should see sliders at the top of the screen with the Kivy logo below it. The sliders control the angle start and stop and the height and width scales. There is a button to reset the sliders. The logo used for the circle's background...
Python
1
} } include!(concat!(env!("OUT_DIR"), "/oid_db.rs")); #[rustfmt::skip::macros(oid)] #[cfg(test)] mod tests { use super::*; // This test is mostly a compile test, to ensure the API has not changed #[test] fn test_lifetimes() { fn add_entry(input: &str, oid: Oid<'static>, registry: &mut Oi...
Rust
0
def evaluate_polynomial(coeffs, x): result = 0 for i, a in enumerate(coeffs): result += a * (x ** i) return result coeffs = [int(i) for i in input("Nhập các hệ số a0,a1,...,an (cách nhau bởi dấu cách): ").split()] x = int(input("Nhập giá trị x: ")) print("Giá trị của đa thức:", evaluate_polynomial(c...
Python
1
ALS: usize = {}; // YYNTOKEN", self.n_terminals)?; writeln!(out, "const MAX_SHIFT: usize = N_STATES-1; // YY_MAX_SHIFT")?; writeln!(out, "const MIN_SHIFTREDUCE: usize = {}; // YY_MIN_SHIFTREDUCE", self.n_states)?; writeln!(out, "const MAX_SHIFTREDUCE: usize = MIN_SHIFTREDUCE + N_RULES - 1; // YY_MAX_SHIFTREDUCE")...
Rust
0
t_code) html = self.generate_html(highlighted_code) self.html_frame.load_html(html) def highlight_code(self, code: str) -> str: """Подсвечивает код с использованием pygments""" formatter = HtmlFormatter(style="dracula", noclasses=True, wrapcode=True) return highlight(code, ...
Python
1
��', "yào"), ('熏', "xūn,xùn"), ('熐', "mì"), ('熑', "lián,qiān"), ('熒', "yíng,xíng,jiǒng"), ('熓', "wǔ"), ('熔', "róng"), ('熕', "gōng"), ('熖', "yàn"), ('熗', "qiàng"), ('熘', "liū"), ('熙', "xī,yí"), ('熚', "bì"), ('熛', "biāo"), ('熜', "cōng,zǒng"), ('熝', "lù,āo"), ...
Rust
0
C" { pub fn alt_IVehicle_LoadDamageDataFromBase64( _instance: *mut alt_IVehicle, base64: *mut alt_StringView, ); } extern "C" { pub fn alt_IVehicle_SetManualEngineControl(_instance: *mut alt_IVehicle, state: bool); } extern "C" { pub fn alt_IVehicle_IsManualEngineControl(_instance: *mut ...
Rust
0
_explained_panic("Could not attach ui to neovim process"); info!("Neovim process attached"); let nvim = Arc::new(nvim); start_ui_command_handler(nvim.clone()); SETTINGS.read_initial_values(&nvim).await; SETTINGS.setup_changed_listeners(&nvim).await; match io_handler.await { Err(join_...
Rust
0
# Aktualizacja stanu przycisków miejsc parkingowych for i in range(16): button_name = f"s{i + 1}" button = self.findChild(QtWidgets.QPushButton, button_name) if button: if slots[i]: button.setStyleSheet("background-color: #FF0B00") # c...
Python
1
not evaluate constant pattern //~| ERROR could not evaluate constant pattern _ => unimplemented!(), } } <filename>src/bin/loadtest.rs #[macro_use] extern crate clap; extern crate failure; extern crate faktory; extern crate rand; extern crate serde_json; use clap::{App, Arg}; use faktory::*; use ran...
Rust
0
', '\u{f84}', '⽪', 'ᕍ', '༜', '脃', '𛰕', '𐔕', '𑇪', 'ﱈ', '❦', '🆪', '𓋧', 'ꨄ', '\u{18b13}', '𛆉', '𔘵', 'ନ', '菉', 'ꆲ', '㍁', '-', 'ꗀ', '𛊭', '𖩚', '▿', '𑫆', '𐳋', 'ᅡ', '𐭟', 'ड़', '𓉔', 'ਲ', '𓆆', '⭰', '᾿', '⥓', '\u{1dcc}', '\u{e01c4}', '𒌫', '𓅁', 'D', '𝡅', '⤅', '༫', 'ᒫ', 'ଧ', '𐠷', '𓄽', 'Ჾ', '𑴀', '...
Rust
0
, 'formset/default/widgets/calendar.html': _amend_input, 'formset/default/widgets/datetime.html': _amend_input, 'formset/default/widgets/file.html': _amend_file, 'formset/default/widgets/selectize.html': _amend_select, 'formset/default/widgets/selectize_country.html': _amend_sele...
Python
1
query: Option<String>, pub valuetype: Option<String>, pub interval: Option<DashboardWidgetConfigSearchResultChartInterval>, pub renderer: Option<ChartRenderer>, pub field: Option<String>, pub series: Option<Vec<DashboardWidgetConfigStackedChartSerie>>, pub timerange: TimeRange, pub trend: O...
Rust
0
sin() * axis; q.set(h.cos(), 3); Quat { q: q } } pub fn from_axis_angle_deg(axis: &Vec4, angle_deg: f32) -> Quat { Quat::from_axis_angle_rad(axis, angle_deg * std::f32::consts::PI / 180.0) } pub fn conjugate(&self) -> Quat { Quat::from(self.q * Vec4::new(-1.0, -1.0, -1....
Rust
0
# Scrapy settings for scrapy_baidu project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # https://docs.scrapy.org/en/latest/topics/settings.html # https://docs.scrapy.org/en/latest/topics/downloader-middl...
Python
1
from django.urls import path from . import views app_name = "blog" urlpatterns = [ # Главная и категории path( "", views.index, name="index" ), path( "category/<slug:category_slug>/", views.category_posts, name="category_posts", ), # Посты ...
Python
1
ontext) } } } impl ToString for CommandInvocation { fn to_string(&self) -> String { self.command.to_string() } } use crate::db::OffsetLimit; use crate::models::article::{ArticleJson, Article, to_article_json}; use crate::common::schema::articles; use diesel; use diesel::pg::PgConnection; us...
Rust
0
the accumulator and the data must have the same type. /// In order for the results to be correct, the closure provided by the `builder` must be both /// **associative** and **commutative**. /// /// [`fold()`]: crate::api::fold::Fold::fold_partition /// /// # Example /// ``` /// # use ...
Rust
0
ons::default(), } } } impl NdpConfigurations { /// Get the value for NDP's DUP_ADDR_DETECT_TRANSMITS parameter. pub fn get_dup_addr_detect_transmits(&self) -> Option<NonZeroU8> { self.dup_addr_detect_transmits } /// Set the value for NDP's DUP_ADDR_DETECT_TRANSMITS parameter. /...
Rust
0
ions can be compared to each other. // At the moment we just remove a tailing `.git` but there are more possible optimisations. // See https://github.com/rust-lang/cargo/blob/1f6c6bd5e7bbdf596f7e88e6db347af5268ab113/src/cargo/util/canonical_url.rs#L31-L57 // for what cargo does let git_extension = ".gi...
Rust
0
import os import torch import logging from PIL import Image import numpy as np import json from pathlib import Path from typing import Dict, List, Any, Tuple, Optional, Union from tqdm import tqdm import pandas as pd import time import random from transformers import AutoProcessor, AutoModelForCausalLM class LlavaPro...
Python
1
continue } _ => { //all other params invalid return None; } } unsafe { let mut buf: [c_char; 82] = mem::zeroed(); match xiReturn::from_i32(xiapi_sys::xiapi::xiGetDeviceInfoString(device_id as DWORD, param.into(), buf.as_mut_ptr(), 80)).unwrap()...
Rust
0
# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. from __future__ import absolute_import, division, print_function import binascii import os import pytest from cryptography.hazmat.backen...
Python
1
infinite.integer.is_some() { kind.add_integer(); } if infinite.float.is_some() { kind.add_float(); } if infinite.boolean.is_some() { kind.add_boolean(); } if infinite.timestamp.is_some() { kind.add_timestamp(); }...
Rust
0
config = { 'browser': 'chrome', 'URL': 'http://localhost:4200' } class Config(object): def __init__(self): self.config = config def get_property(self,property_name:str) -> str: return self.config.get(property_name) @property def browser(self)-> str: return self.get_property('browser') @property def U...
Python
1
torch.sum(x)) features.append(x) return features class FloatGroupNorm(nn.GroupNorm): def forward(self, x): return super().forward(x.to(self.bias.dtype)).type(x.dtype) def zero_module(module): """ Zero out the parameters of a module and return it. """ for p in module....
Python
1
_0, true => HFXTIFG_A::HFXTIFG_1, } } #[doc = "Checks if the value of the field is `HFXTIFG_0`"] #[inline(always)] pub fn is_hfxtifg_0(&self) -> bool { **self == HFXTIFG_A::HFXTIFG_0 } #[doc = "Checks if the value of the field is `HFXTIFG_1`"] #[inline(always)] ...
Rust
0
ain_predictions, y_train))) print("Test R2: %0.3f" % (r2_score(test_predictions, y_test))) print("Predictions - Ground Truth (Kelvin): ", (test_predictions - y_test)) fig = plt.figure(figsize=(12, 5)) fig.add_subplot(121) sns.regplot(x=y_train, y=train_predictions, color="g") plt.title("Train Data", fontsize=16) plt....
Python
1
acy========== count_valid_classes = 0 for i in range(num_classes): if torch.sum(confuse_matrix[i,:]) != 0: mean_pixel_accuarcy += (confuse_matrix[i, i] / torch.sum(confuse_matrix[i, :])) count_valid_classes += 1 if count_valid_classes == 0: mean_pixel_accuarcy = torch...
Python
1
user specified slate images per the &quot;Input Loss Behavior&quot; configuration until the next input switch occurs (which is controlled through the Channel Schedule API).</p> #[serde(rename = "InputEndAction")] #[serde(skip_serializing_if = "Option::is_none")] pub input_end_action: Option<String>, //...
Rust
0
31.12.2023 Bereinigung KillFile-Ruinen entfernt (obsolet) # 13.08.2024 Button "abgelaufene Jobs löschen" ergänzt, Liste der # zu löschenden in JobID_list -> JobRemoveExp. # def JobListe(): # Liste, Job-Status, Jobs löschen PLog("JobListe:") li = xbmcgui.ListItem() li = home(li, ID=NAME) #...
Python
1
from setuptools import setup import imp def get_version(): ver_file = None try: ver_file, pathname, description = imp.find_module('__version__', ['cmakelint']) vermod = imp.load_module('__version__', ver_file, pathname, description) version = vermod.VERSION return version ...
Python
1
# This file is MACHINE GENERATED! Do not edit. # Generated by: tensorflow/python/tools/api/generator2/generator/generator.py script. """Public API for tf._api.v2.quantization.experimental namespace """ import sys as _sys from tensorflow.compiler.mlir.quantization.tensorflow.python.quantize_model import _QuantizationC...
Python
1
(config.device) loss_hard = F.cross_entropy(student_logits, labels, reduction="mean") loss_soft, teacher_probs = cross_entropy_loss_with_temperature_v2(student_logits, teacher_probs, config.temperature) los...
Python
1
Stf::init_state() }; debug!("decrypt the call"); let rsa_keypair = rsa3072::unseal_pair()?; let account_vec = rsa3072::decrypt(&account_encrypted, &rsa_keypair)?; let account = AccountId::decode(&mut account_vec.as_slice()) .sgx_error_with_log("[ShieldFunds] Could not decode accoun...
Rust
0
SRAM timing adjust"] pub struct PF8K_RMEA_W<'a> { w: &'a mut W, } impl<'a> PF8K_RMEA_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut...
Rust
0
_done_int_st(&self) -> SLC1_WR_RETRY_DONE_INT_ST_R { SLC1_WR_RETRY_DONE_INT_ST_R::new(((self.bits >> 23) & 0x01) != 0) } #[doc = "Bit 24"] #[inline(always)] pub fn slc1_tx_err_eof_int_st(&self) -> SLC1_TX_ERR_EOF_INT_ST_R { SLC1_TX_ERR_EOF_INT_ST_R::new(((self.bits >> 24) & 0x01) != 0) ...
Rust
0
commit_confirmation: Vec<u8>, commit_msg_sig: Vec<u8>, confirmed_transcript: Vec<u8>, ) -> Vec<u8> { let commit_auth = MLSPlaintextCommitAuthData { confirmation: commit_confirmation, signature: commit_msg_sig, } .get_encoding(); self.tree ...
Rust
0
InFile::new(arg_file_id.as_file(), parsed_args.syntax_node()), krate, resolver, diagnostic_sink, )?; let subtree = diagnostic_sink.option(to_subtree(&result), || err("failed to parse macro result"))?; if let MacroDefKind::BuiltInEager(eager, _) = def.kind { l...
Rust
0
l, FwError<E>> { let mut prev = State::Swapping; mem::swap(&mut prev, st); match prev { State::Pending(x) => { match x.try_channel(&poll) { Ok(x) => match x { NextState::Pending(x) => { *st = St...
Rust
0
els = streams_channels def run(self): for stream, channel in self.streams_channels.items(): worker = LiveStreamWorker(stream, channel) worker.start() self.workers.append(worker) while self.workers: for worker in self.workers: worker.j...
Python
1
''' The MIT License(MIT) Copyright(c) 2016 Copyleaks LTD (https://copyleaks.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights ...
Python
1
import cv2 import numpy as np import os import torch def load_yolov8_face_model(model_path=None): """ 加载YOLOv8-Face模型用于人脸检测 参数: model_path: 模型文件路径,如果为None则使用默认路径 返回: 加载好的YOLOv8-Face模型 """ from ultralytics import YOLO # 如果未指定模型路径,使用默认路径 if model_path is Non...
Python
1