text
string
label_name
string
labels
int64
ay() .unwrap(), &vec![] as &Vec<String>, ); Ok(()) } } <gh_stars>10-100 use serde::de::DeserializeOwned; use serde::ser::Serialize; use serde_json; use std::fs::File; use errors::{Result, ResultExt}; pub fn write_json_file<T: Serialize>(file_name: &str, obj: &T) -> Result<...
Rust
0
from common.constants.models import DEFAULT_MAX_LENGTH from core.models.geo_custom_zone_category import GeoCustomZoneCategory from core.models.geo_zone import GeoZone from django.db import models class GeoCustomZoneStatus(models.TextChoices): ACTIVE = "ACTIVE", "ACTIVE" INACTIVE = "INACTIVE", "INACTIVE" cla...
Python
1
COMMETHOD([], HRESULT, "IsAppIdPinned", (["in"], LPCWSTR, "appId"), (["out"], POINTER(BOOL), "isPinned"), ), STDMETHOD(HRESULT, "PinAppID", (LPCWSTR,)), STDMETHOD(HRESULT, "UnpinAppID", (LPCWSTR,)), COMMETHOD([], HRESULT, "IsViewPinned", (["in"], POINT...
Python
1
from __future__ import absolute_import from django import forms from django.utils.safestring import mark_safe from esp.themes.forms import ThemeConfigurationForm from esp.utils.widgets import NavStructureWidgetWithIcons, ContactFieldsWidget class ConfigForm(ThemeConfigurationForm): titlebar_prefix = forms.CharFie...
Python
1
(feature = "unsupported")] ITopicMessage::HypeTrainEventsV1Rewards(topic) => TopicData::HypeTrainEventsV1Rewards { topic, reply: serde_json::from_str(&reply.message).map_err(serde::de::Error::custom)?, }, #[cfg(feature = "unsupported")] ITo...
Rust
0
ctors, Witnesses}; use crate::composer::mimc::MimcC; #[derive(Debug, Eq, PartialEq, Clone, Copy, Hash, Ord, PartialOrd)] pub struct Variable(usize); #[derive(Debug)] pub struct Composer<F: Field> { n: usize, q_0: Vec<F>, q_1: Vec<F>, q_2: Vec<F>, q_3: Vec<F>, q_m: Vec<F>, q_c: Vec<F>, ...
Rust
0
cc) } let transaction_fees = self.account_blocks.full_transaction_fees(); let mut expected_fees = transaction_fees.clone(); expected_fees.add(&self.value_flow.fees_imported)?; expected_fees.add(&self.value_flow.created)?; expected_fees.add(&fees_import)?; if self...
Rust
0
blockhash fn set_blockhash(&mut self, hash: Hash); /// Get this invocation's blockhash fn get_blockhash(&self) -> &Hash; /// Set this invocation's lamports_per_signature value fn set_lamports_per_signature(&mut self, lamports_per_signature: u64); /// Get this invocation's lamports_per_signature...
Rust
0
info!("{:#?}", x); }; accept(acc); Ok(()) } fn accept<F>(f: F) where F: FnOnce(&str), { let s = "Hello world"; f(s); } use vergen::Config; fn main() { let mut config = Config::default(); *config.build_mut().timestamp_mut() = false; *config.git_mut().semver_mut() = false...
Rust
0
import importlib import sys import accelerate import transformers import torchacc _ACCELERATE_HF_TRAINER = False RETURN_TRUE = lambda check_device=True: True RETURN_FALSE = lambda: False def _func_check_and_set(module_name, func_name, func_value): err_msg = f'''{func_name} not found in {module_name}. ...
Python
1
import numpy as np import matplotlib.pyplot as plt import os import numpy as np import pandas as pd import matplotlib.pyplot as plt import numpy as np from scipy.signal import butter, sosfiltfilt, iirnotch, filtfilt def denoise_ecg(signal: np.ndarray, fs: float = 256, lp_cut: float = 4...
Python
1
m_layers] layer_T = GRID_RESTART.LAYER_T.values[0:num_layers] layer_LWC = GRID_RESTART.LAYER_LWC.values[0:num_layers] layer_IF = GRID_RESTART.LAYER_IF.values[0:num_layers] new_snow_height = np.float64(GRID_RESTART.new_snow_height.values) new_snow_timestamp = np.float64(GRID_RESTART.new_snow_timesta...
Python
1
mismatches = np.where(distances>d_thresh)[0] weights[mismatches] = 0 weights[mouth_mask] =0 mesh_matches = np.where(weights > 0)[0] # print("Setting up D and V...") B = sparse.lil_matrix((4 * e + n, 3), dtype=np.float32) DL = sparse.lil_matrix((nL, 4 * n), dtype=...
Python
1
: '✅ Ping выполнен успешно - ProjectX2' if is_online else '❌ Ping не удался - ProjectX2', 'template': ''' <h2>Результат выполнения Ping</h2> <p>Здравствуйте, {username}!</p> <p>Результат ping для <strong>{ip_address}</strong>:</p> <p><strong>Статус:</strong> {...
Python
1
import streamlit as st from utils.config_manager import ConfigManager from utils.plugins import obtener_plugins from streamlit_theme import st_theme def render(): st.subheader("Dashboard") # Cargar configuración global del dashboard config_path = "config.yaml" config = ConfigManager(config_path) ...
Python
1
ets.get_unchecked(i) * item_size as isize; } let pad = *row_byte_offsets.get_unchecked(rows_offsets.len() - 1); for i in 0..4 { *row_byte_offsets.get_unchecked_mut(rows_offsets.len() + i) = pad; } MatrixStoreSpec::OffsetsAndPtrs { col_byte_offsets, row_byte_offsets, n...
Rust
0
from random import randint, seed for i in range(1, 101): print ("{}\t".format(randint(0, 99))), if (i % 10 == 0): print print for i in range(1, 101): print ("{}\t".format(randint(0, 99))), if (i % 10 == 0): print
Python
1
""" pygments.lexers.func ~~~~~~~~~~~~~~~~~~~~ Lexers for FunC. :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from pygments.lexer import RegexLexer, include, words from pygments.token import Text, Comment, Operator, Keyword, Name, St...
Python
1
\ref agora::media::IAudioFrameObserver::onMixedAudioFrame "onMixedAudioFrame" callback. @param sampleRate Sets the sample rate (@p samplesPerSec) returned in the *onMixedAudioFrame* callback, which can be set as 8000, 16000, 32000, 44100, or 48000 Hz. @param samplesPerCall Sets the number of samples (`sampl...
Rust
0
lors.Normalize(vmin=np.min(true_model), vmax=np.max(true_model)) cbar = mpl.colorbar.ColorbarBase(ax2, norm=norm, orientation="vertical", cmap=mpl.colormaps['viridis'], format="%.1e") cbar.set_label("SI", r...
Python
1
from django.shortcuts import render, get_object_or_404 from django.utils.text import slugify from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import BlogPost from django.urls import reverse_lazy class BlogPostListView(ListView): model = BlogPost template_n...
Python
1
; let ink_in: *mut f64 = ink.as_mut_ptr(); let x_in: i32 = x; let y_in: i32 = y; let test_in: *mut bindings::VipsImage = draw_flood_options.test.ctx; let test_in_name = utils::new_c_string("test")?; let equal_in: i32 = if draw_flood_options.equal { 1 } else { 0 }; ...
Rust
0
Serialize, PartialEq)] pub struct UsersResponse(pub Vec<UserResponse>); #[derive(Clone, Debug, Deserialize, Serialize, Validate)] pub struct CreateUserRequest { #[validate(length( min = 3, message = "first_name is required and must be at least 3 characters" ))] pub first_name: String, ...
Rust
0
} #[doc = "Write proxy for field `RDWR_SET_EN`"] pub struct RDWR_SET_EN_W<'a> { w: &'a mut W, } impl<'a> RDWR_SET_EN_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)] pu...
Rust
0
"\t/// Contextual rule required for Others Unicode codepoints." )?; writeln!(file, "\tContextO,")?; writeln!( file, "\t/// Those code points that are not permitted in any PRECIS string class." )?; writeln!(file, "\tDisallowed,")?; writeln!( ...
Rust
0
::{GeoKind, Scratchpad}; use crate::StrError; use russell_chk::assert_vec_approx_eq; use russell_lab::Vector; // to test if variables are cleared before sum const NOISE: f64 = 1234.56; // generates pad Lin2 for tests fn gen_pad_lin2(l: f64) -> Scratchpad { let mut pad = Scratchpad:...
Rust
0
#!/usr/bin/python3 def element_at(my_list, idx): ''' Retrieve an element from given index ''' if idx < 0 or idx > (len(my_list) - 1) or my_list == []: return None return my_list[idx]
Python
1
hits[pc as usize] = true; pc += match instr[pc as usize] { Instr::Nop(..) => 1, Instr::Acc(val) => { acc += val; 1 } Instr::Jmp(val) => val, }; } } pub fn run() { let text = read_to_string("input/day08.txt").unwra...
Rust
0
name = seed.deserialize(de)?; Ok((name, VariantAccess { de: self.de })) } } pub struct VariantAccess<'de, 'a, R: BorrowingReader<'de>> { de: &'a mut Deserializer<'de, R>, } impl<'de, 'a, R: BorrowingReader<'de>> de::VariantAccess<'de> for VariantAccess<'de, 'a, R> { type Error = DeError; fn ...
Rust
0
uest).unwrap(); new_identity } pub fn sign_and_send_request( identity: &Identity, pool: &TestPool, mut request: &mut PreparedRequest, ) -> Result<String, String> { identity.sign_request(&mut request); pool.send_request(&request) } pub fn sign_and_send_full_request( pool: &TestPool, tr...
Rust
0
import pygame from Level.levelManager import LevelManager from player.player import Player from collisionHandler import CollisionHandler from superPower import doSuperPower from Menu.menu import Menu from music import music from Menu.escapeMenu import EscapeMenu pygame.init() #Window Settings baseWidth, baseHeight = ...
Python
1
for path in paths: print(path) curve = Curve() curve.From_SVG(tag) self.gr_curve.append(curve) elif tag['type'] == "gr_poly": paths = parse_path(tag['d']...
Python
1
"Upload-Metadata", "Upload-Defer-Length", "Upload-Concat", "Upload-Offset", ]) .max_age(86400); // We allow any origin by default if no origin is specified. if origins.is_empty() { return cors.allow_any_origin(); } // Adding origins...
Rust
0
.Tensor]) -> Dict[str, paddle.Tensor]: """ Forward pass of the network. Args: x (Dict[str, paddle.Tensor]): Input tensor of shape (batch_size, 3, num_points). Returns: Dict[str, paddle.Tensor]: A dictionary where the key is the first element of `self.output_keys...
Python
1
Position { x: 0, y: 1 }; const EAST: Position = Position { x: 1, y: 0 }; const SOUTH: Position = Position { x: 0, y: -1 }; const WEST: Position = Position { x: -1, y: 0 }; impl Position { fn move_direction(&mut self, units: i32, vector: &Position) { self.x += units * vector.x; self.y += units * ve...
Rust
0
(_("Carteira no banco Itaú é obrigatória")) @api.constrains("boleto_discount_perc") def _check_discount_perc(self): for record in self: if record.boleto_discount_perc > 100 or record.boleto_discount_perc < 0: raise ValidationError( _("O percentual deve se...
Python
1
#!/usr/bin/python3 """ Check if all the boxes can be unlocked. """ def canUnlockAll(boxes): """ Check if all the boxes can be unlocked Args: boxes (list): list of lists of keys, where each sublist represents the keys in a particular box Returns: bool: True if all the box...
Python
1
from __future__ import annotations from datetime import UTC, datetime import pytest pytest.importorskip( "swisseph", reason="pyswisseph not installed; install extras with `pip install -e .[ephem,providers]`.", ) from astroengine.core.time import to_tt from astroengine.engine.returns import find_return_insta...
Python
1
tps://atominik.com/2YTd"; let expanded_url = unshorten(url, None); assert!(expanded_url.is_some()); assert!(expanded_url.unwrap().contains("weebly.com")); } #[test] fn test_bit_ly() { let url = "https://bit.ly/3alqLKi"; let expanded_url = unshorten(url, None); assert!(expanded_url.is_some()); ...
Rust
0
as Currency<<T as system::Trait>::AccountId>>::Balance; pub trait Trait: frame_system::Trait { type Event: From<Event<Self>> + Into<<Self as frame_system::Trait>::Event>; type Randomness: Randomness<Self::Hash>; type KittyIndex: Parameter + AtLeast32BitUnsigned + Bounded + Default + Copy; type Currency: Cur...
Rust
0
'SCRN_GRP_CD': '화면그룹코드', 'CTGR_ID': '용도코드', 'CTGR_FULL_NM': '용도', 'BID_MNMT_NO': '입찰번호', 'CLTR_NM': '물건명', 'CLTR_MNMT_NO': '물건관리번...
Python
1
ongs_ref == st_id: related_equipment.append({ 'id': equip_id, 'type': equip['type'], 'name': equip['name'] }) # Find related connectivity nodes related_nodes = [] for node...
Python
1
avg300: f32, pub total: u64, } #[derive(Debug, Clone, Default)] pub struct PressureStore { pub some: PressureAvg, pub full: PressureAvg, } impl PressureStore { pub fn new(t: Pressure) -> Option<Self> { match t { Pressure::Cpu => { if KERNEL_VERSION.version_code >= ...
Rust
0
requested by the run. :param total_o_cpu: The total_o_cpu of this RunSummary. :type: int """ self._total_o_cpu = total_o_cpu @property def time_created(self): """ **[Required]** Gets the time_created of this RunSummary. The date and time the resource wa...
Python
1
nd_changes_id_list = page_object.ids.split(',') try: for account_fund_changes_id in account_fund_changes_id_list: await AccountFundChangesDao.delete_account_fund_changes_dao(query_db, AccountFundChangesModel( id=account_fund_changes_id)) ...
Python
1
-1., 1.), rand::gen_range(-1., 1.)).normalize() * screen_width().min(screen_height()) / 2., vel: Vec2::new(rand::gen_range(-1., 1.), rand::gen_range(-1., 1.)), rot: 0., rot_speed: rand::gen_range(-2., 2.), size: screen_width().min(s...
Rust
0
stone_color = goban.stones.get(&point).copied(); group = group.add(draw_selected(point.0, point.1, stone_color, options.style)); } group } fn build_dimmed_group(goban: &Goban, _options: &MakeSvgOptions) -> element::Group { let mut group = element::Group::new().set("id", "markup-dimmed"); for p...
Rust
0
} '*' => { buf_flush(&mut buf, &mut nums, &mut opts, Operators::Multiplication); } '/' => { buf_flush(&mut buf, &mut nums, &mut opts, Operators::Division); } '%' => { buf_flush(&mut buf, &mut nums, &m...
Rust
0
import logs CELLS = {} LEAFS = {} SELFS = {} KINDS = {} def help_main(Env): Mod = Env.Current print("MODULE %s" % Mod.Module) countCells(Mod,Env) LL = [] for Module in CELLS: if CELLS[Module]>1: LL.append((CELLS[Module],Module)) LL.sort() LL.reverse() for Num,Modu...
Python
1
= "RX")] bytes_in: String, } impl From<&tunnelblick::Configuration> for HumanConfiguration { fn from(config: &tunnelblick::Configuration) -> Self { return Self { autoconnect: config.autoconnect.clone(), state: config.state.clone(), name: config.name.clone(), ...
Rust
0
) .file("./libbacktrace/backtrace.c") .file("./libbacktrace/dwarf.c") .file("./libbacktrace/fileline.c") .file("./libbacktrace/posix.c") .file("./libbacktrace/sort.c") .file("./libbacktrace/state.c"); let any_debug = env::var("RUSTC_DEBUGINFO").unwrap_or_default() ==...
Rust
0
} } } model = _init_group_wise_weight_quantization(model, ds_config) assert type(model.layer_0) is QuantizedLinear assert type(model.layer_1) is QuantizedLinear assert type(model.layer_2) is QuantizedLinear assert type(model.la...
Python
1
efund(refund_count)).into()) } else { Self::deposit_event(RawEvent::PartiallyRefunded(index)); // No weight to refund since we did not finish the loop. Ok(().into()) } } /// Remove a fund after the retirement period has ended and all funds have been returned. #[weight = T::WeightInfo::dissolve(...
Rust
0
inserted = ndb.transaction(lambda: insert_if_absent_sometimes(note_key, note)) # [END gae_ndb_transactions_insert_sometimes_callback] elif choice == 4: inserted = insert_if_absent_indep(note_key, note) elif choice == 5: inserted = insert_if_absent_taskq(note_key, note) return insert...
Python
1
::replace(&mut boxed_node.next, None); // boxed_node 退出时自动drop } } }use crate::common::FilePath; pub trait PreludePackageDownloader { fn download( &self, external_packages_directory_path: &FilePath, ) -> Result<(), Box<dyn std::error::Error>>; } <reponame>shradej1/aoc202...
Rust
0
def split_words(txt): ''' Given a string of words, return a list of words split on whitespace, if no whitespaces exists in the text you should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the alphabet, ord('a') = 0, ord('b') = 1, ... ord('z...
Python
1
_deletion_passed() { run_test!(|client, conn| { // Create a food to be deleted. let res = client .post("/") .header(ContentType::Form) .body("name=deletiontest&expiry_date=2020-03-01") .dispatch(); assert_eq!(res.status(), Status::SeeOther); ...
Rust
0
# createdb speakpeak_test # export TEST_DATABASE_URL=postgresql:///speakpeak_test import os class Config: SECRET_KEY = os.environ.get('SECRET_KEY', "it's a secret") SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL', 'postgresql:///speakpeak') SQLALCHEMY_TRACK_MODIFICATIONS = False SQLALCHEMY_...
Python
1
oat32' X_train = preprocessWavs.set_type(X_train, X_data_type) X_val = preprocessWavs.set_type(X_val, X_data_type) X_test = preprocessWavs.set_type(X_test, X_data_type) y_data_type = 'int32' y_train = preprocessWavs.set_type(y_train, y_data_type) y_val = preprocessWavs.set_type(y_val, y_data_type) y_test = preprocessW...
Python
1
request_id's sent to core request_track: Tracker<RealEngineTrackerData>, /// Multiplexer holding the network gateway multiplexer: Detach<GatewayParentWrapper<GhostEngine<'engine>, TransportMultiplex<P2pGateway>>>, /// Cached this_peer of the multiplexer this_net_peer: PeerData, /// Store active...
Rust
0
= searcher.segment_reader(2u32); let ff_reader = segment.fast_fields().u64s(int_field).unwrap(); ff_reader.get_vals(0, &mut vals); assert_eq!(&vals, &[20]); } // Merging the segments { let segment_ids = index.searchable_segment_ids()?; ...
Rust
0
for input_value in input_values: with patch('builtins.input', side_effect = input_value): delete_username_password(tenant_id) class TestChangePassword: ''' Positive Scenarios ''' @pytest.mark.parametrize("login_username, password, expected_output, tenant_id",[ ...
Python
1
ing, names of fields. Returns: First name that is either 'pageToken' or 'nextPageToken' if one exists, otherwise None. """ return next( (tokenName for tokenName in _PAGE_TOKEN_NAMES if tokenName in fields), None ) def _methodProperties(methodDesc, schema, name): """Get properties of a...
Python
1
Retry the assert immediately."] pub const SDL_ASSERTION_RETRY: Type = 0; #[doc = "< Make the debugger trigger a breakpoint."] pub const SDL_ASSERTION_BREAK: Type = 1; #[doc = "< Terminate the program."] pub const SDL_ASSERTION_ABORT: Type = 2; #[doc = "< Ignore the assert."] pub const SDL_ASSERTION_IGNORE...
Rust
0
Self::from_split(offset, &self.inner[slice_index..]) } /// Trim the end of the string from any white space characters. /// This will not work correctly with RTL fn trim_end(&self) -> Self { let mut slice_index = self.inner.len(); let mut char_index = 0; let mut slice_len ...
Rust
0
from .. import IconBase class IconScrollText(IconBase): class_name = "lucide lucide-scroll-text" svg_data = { "attrs": { "width": "24", "height": "24", "view_box": "0 0 24 24", "fill": "none", "stroke": "currentColor", "stroke_width": "2", "stroke_li...
Python
1
(), errored_files: Vec::new(), exif_error_count: 0, exif_errored_files: Vec::new(), }; // run the same command again. all files should get skipped. cmd.assert() .success() .stdout(predicate::str::contains(strip_timestamp_from_summary( expected_summary_sec...
Rust
0
}) if not timestamps: logging.warning("Whisper未能从音频中提取任何时间戳。") return [] logging.info(f"成功生成 {len(timestamps)} 条词级别时间戳。") return timestamps except Exception as e: logging.error(f"使用Whisper生成时间戳时发生错误: {e}", exc_info=True) ...
Python
1
kQuery): logger.info("button delete_stop", extra={"user_id": callback.from_user.id} ) # getting callback data callback_data = callback.data.split(":") city_id, stop_id = map(int, callback_data[1:]) await db.delete_user_stop(callback.from_user.id, city_id, stop_id) ...
Python
1
ve(Clone, Debug)] pub struct Config { pub rust_log: String, pub default_queue: bool, pub bot_id: u64, pub rabbit_host: String, pub rabbit_port: u64, pub rabbit_username: String, pub rabbit_password: String, pub redis_host: String, pub redis_port: u64, pub andesite_host: String, ...
Rust
0
5_cm() { test_eval("3 m 15 cm", "3.15 m"); } #[test] fn five_percent() { test_eval("5%", "5%"); } #[test] fn five_percent_plus_point_one() { test_eval("5% + 0.1", "15%"); } #[test] fn five_percent_plus_one() { test_eval("5% + 1", "105%"); } #[test] fn point_one_plus_five_percent() { test_eval("0...
Rust
0
hasNetDemand = False firstLine = inFile.readline() date, hour, rest = firstLine.split(",", maxsplit=2) restSplit = rest.rstrip().split(",") hourKey = hour.strip() timeKey = date.rstrip()+"_"+hourKey outDict[timeKey] = [] outDict[hour] = [] otherKeys = restSplit fo...
Python
1
r cls in classes: bpy.utils.register_class(cls) bpy.types.VIEW3D_MT_mesh_add.append(menu_func_bolt) bpy.types.VIEW3D_MT_object_context_menu.prepend(Bolt_contex_menu) def unregister(): bpy.types.VIEW3D_MT_object_context_menu.remove(Bolt_contex_menu) bpy.types.VIEW3D_MT_mesh_add.remove(menu_func...
Python
1
# dataset settings dataset_type = 'VSPWDataset2' data_root = 'data/vspw/VSPW_480p' img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) crop_size = (480, 480) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', reduce_zero_label=True), ...
Python
1
""" @FileName:8_2_Deformable_object_simulation.py @Description: @Author:Ferry @Time:2024/12/27 下午12:51 @Copyright:©2024-2024 ShanghaiTech University-RIMLAB """ import genesis as gs gs.init() scene = gs.Scene( sim_options=gs.options.SimOptions( dt=4e-3, substeps=10, ), mpm_options=gs.options...
Python
1
sp1: Span, sp2: Span) -> bool { if sp1 == sp2 { return true; } let lo1 = cm.lookup_byte_offset(sp1.lo()); let hi1 = cm.lookup_byte_offset(sp1.hi()); let src1 = lo1.sf.src.as_ref() .unwrap_or_else(|| panic!("source of file {} is not available", lo1.sf.name)); let lo2 = cm.looku...
Rust
0
# if the best pair of the tail of i chain is the head of j chain, then i chain links j chain elif best_pairs.get(chains[i][-1], (None,))[0] == chains[j][0]: new_chain = chains[i] + chains[j][1:] # if the best pair of the tail of j chain is the head of i chain, then j chain l...
Python
1
ice").unwrap()), username: Username::from_str("alice").unwrap(), asset_scale: 6, asset_code: "XYZ".to_string(), max_packet_amount: 1000, min_balance: Some(-1000), ilp_over_http_url: Some("http://example.com/ilp".to_string()), ilp_over_http_incoming_token: Some(Sec...
Rust
0
cont = 0 multi = 0 num = int (input("Enter a number: ")) while cont < 10: cont += 1 multi = num * cont print(f'{num} x {cont} = {multi}') if mult
Python
1
t AttributeError: pass else: try: # a kind of QueryInterface return table[cls._iid_] except KeyError: raise TypeError(f"Interface {cls._iid_} not supported") return value.QueryInterface(cls.__com_interface__) # type: ig...
Python
1
from fastapi import FastAPI from sqladmin import Admin from app.core.database import engine from app.core.config import settings from app.routers import ( ingest_router, incedents_router, recommendations_router, events_router, auth_router, report_router, ) from app.admin import ( UserAdmin,...
Python
1
import pytest from django.conf import settings from v2.schema import V2ScoreResponse @pytest.fixture def internal_auth_headers(): return {"HTTP_AUTHORIZATION": settings.CGRANTS_API_TOKEN} @pytest.mark.django_db class TestScoreV2Endpoint: def test_score_v2_done_status( self, client, scorer_community...
Python
1
: i32 = 1; pub const AL_FLANGER_PHASE: i32 = 2; pub const AL_FLANGER_RATE: i32 = 3; pub const AL_FLANGER_DEPTH: i32 = 4; pub const AL_FLANGER_FEEDBACK: i32 = 5; pub const AL_FLANGER_DELAY: i32 = 6; pub const AL_FREQUENCY_SHIFTER_FREQUENCY: i32 = 1; pub const AL_FREQUENCY_SHIFTER_LEFT_DIRECTION: i32 = 2; pub const AL_FR...
Rust
0
(); secp256r1_verify_signature(pubkey, &reg_report_bytes, &reg_report.aas_signature) } pub fn aas_sign_reg_report( prvkey: &Secp256r1PrivateKey, reg_report: AasRegReport, ) -> Result<AasRegReport, CryptoError> { let reg_report_bytes = reg_report.to_check_bytes(); let signed_msg = secp256r1_sign_msg...
Rust
0
class RecomendadorSpotify: def __init__(self, spotify_client): self.spotify_client = spotify_client async def recomendar_para_usuario(self, usuario): recomendaciones = [] for genero in usuario.generos_favoritos: canciones = await self.spotify_client.obtener_canciones_por_gen...
Python
1
#!/usr/bin/env python # Copyright (c) 2015 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that kext bundles are built correctly. """ import TestGyp import TestMac import os import plistlib import subprocess import s...
Python
1
import csv import json import sys # Convert a CSV file following the Spanish ENS - Esquema Nacional de Seguridad - RD2022 benchmark into a Prowler v3.0 Compliance JSON file # CSV fields: # ['Id', 'Description', 'Marco', 'Categoria', 'Descripcion_Control', 'Nivel', 'Dimensiones', 'Checks', 'ChecksV2', 'Tipo'], # get t...
Python
1
files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following condition...
Rust
0
#![allow(bare_trait_objects)] use async_trait::async_trait; #[async_trait] trait Trait { async fn f(&self); } #[async_trait] impl Trait for Send + Sync { async fn f(&self) {} } #[async_trait] impl Trait for dyn Fn(i8) + Send + Sync { async fn f(&self) ...
Rust
0
#[serde(rename = "job")] Job(Job), #[serde(rename = "story")] Story(Story), #[serde(rename = "comment")] Comment(Comment), #[serde(rename = "poll")] Poll(Poll), #[serde(rename = "pollopt")] PollOption(PollOption), } #[derive(Serialize, Des...
Rust
0
, radius: 1000.0, material: Box::new(Lambertian { albedo: checker }) }) ]; for a in -11..11 { for b in -11..11 { let choose_mat = rng.gen::<f32>(); let center = V3 { x: a as f32 + 0.9*rng.gen::<f32>(), y: 0.2, ...
Rust
0
VOLTAGE_SELECT_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bit 0"] #[inline(always)] pub fn voltage_select(&mut self) -> VOLTAGE_SELECT_W { VOLTAGE_SELECT_W { w: self } } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self...
Rust
0
if len(expected_batches) >= MAX_BATCHES_TO_TEST: break # step 4: to mimic a continued experiment: # set original seed and create new dataloader under the same seed environment # load the saved state and continue from the saved point set_seed(seed) ...
Python
1
# Use the LFA heatmap generation pc_box_hm = self.lfa.generate_lfa_pc_box_hm_torch(batch, z, 'val') z['pc_box_hm'] = pc_box_hm else: # Use Nabatis heatmap generation pc_hm = batch.get('pc_hm', None) pc_hm_add = batch.get('pc...
Python
1
_msg.nonce, secret_msg.user_public_key)?; Ok(output) }) .map_err(|err| { *used_gas = engine.gas_used(); err })?; *used_gas = engine.gas_used(); Ok(QuerySuccess { output, signature: [0; 64], // TODO this is not needed anymore as output is already authenticated...
Rust
0
("明日の一時"), Ok(TimeRangeSpecifier::At(TimeSpecifier::At( AtTimeSpecifier::Hour { hour: Hour::from_u8(1).unwrap(), is_tomorrow: true } ))) ); assert_eq!( parser::time_range("明日の10時15分"), ...
Rust
0
from django.shortcuts import render,HttpResponse,redirect from app1.models import Department,UserInfo # Create your views here. def index(request): return HttpResponse("登录成功") def login(request): if request.method == "GET": return render(request,"login.html") else: username = request.POST...
Python
1
//println!("{:?}", response); //echo let trimmed_response = response.trim(); if trimmed_response.trim().len() != 1 { println!("must be a single letter ( 'h' or 's' )") } else if trimmed_response.contains("h") { println!("hit!"); deck.deal(1, &mut user);...
Rust
0
from("/="), Punctuator::RBrace => String::from("}"), Punctuator::Instanceof => String::from("instanceof"), // ES2020 Punctuator::QMarkDot => String::from("?."), Punctuator::DoubleQMark => String::from("??"), } } } impl From<&str> for Punctuator { ...
Rust
0
ROOT); if controllers_result.is_err() { debug!( "could not retrieve cgroup controllers: {:?}", controllers_result ); return false; } if !controllers_result .unwrap() .into_iter() .any(|c| c == ControllerType::Cpu) { debug!(...
Rust
0