text
string
label_name
string
labels
int64
import matplotlib.pyplot as plt import os # Script for generating plots from survey data save_dir = 'D:/Dev/BA/jarlhengstmengel/Survey_Plots' # Plotting number of analogies categorized as racist per demographic group RasCount = [26, 27, 20, 24, 28, 26] RasCountLabel =['Gesamt', 'Weiblich', 'Männlich', 'Rassismus-\ne...
Python
1
fig_prob.canvas.restore_region(background_prob) for act, rect in enumerate(bar): if train_args["continuous_actions"]: rect.set_height(pi[0][act]) color_val = np.abs(pi[0][act]) / max(np.max(envs.action_space.high), ...
Python
1
social else : vel_cognitive = self._c1 * r1 vel_social = self._c2 * r2 velocity_list[i][j] = w * velocity_list[i][j] + vel_cognitive + vel_social return velocity_list # update position based on updated velocity def update_pos...
Python
1
U >kg& @sddlZddlZdZdZeddZddZdd Zd d Zd d Z ddZ ddZ ddZ ededdede ddededdede ddede ddede ddgZ dS) Ng4@g?InputShaperCfg)name init_funcmin_freqcCsggfS)NrrrS/usr...
Python
1
""" Constructs the reachable space of the end effectors of Draco3 assuming the base is fixed. The reachable space is randomly sampled, then a convex hull is created using these points, and finally the polytopes are simplified using a decimation process. This follows more or less the approach from Tonneau, Steve, et al...
Python
1
break; } } } } #[no_mangle] pub unsafe extern "C" fn tunet_model_details_grouped_foreach( model: native::Model, f: native::DetailsGroupedForeachCallback, data: *mut c_void, ) { if let Some(f) = f { for (date, flux) in read_model(model) .details ...
Rust
0
from typing import List, Optional from pydantic import field_validator, Field from pydantic_settings import BaseSettings from pydantic_core.core_schema import FieldValidationInfo class ApiSettings(BaseSettings): """Api settings that can be set using environment variables. """ # Api title and version ...
Python
1
tuples = [] for answer in answers: answer_tokens = self.truncate_tokens(answer[C.ANSWER_TEXT], self.max_answer_len) answer_ids = self.vocab.indices_from_token_list(answer_tokens) answersDict.append(answer_ids) answerId += 1...
Python
1
import numpy as np import scipy as sp from dml.SVM import SVMC import matplotlib.pyplot as plt X=[ [10.75,14.95], [11.35,14.05], [12,13.65], [12.75,13.75], [14.2,14.85], [13.2,15.8], [12.1,16.55], [11.3,15.8], [12.7,14.7], [12.8,14.55], [12.35,15.75], [8.55,17.2], [8.15,15.4], [8.7,13.95], [9.75,12.25], [11.9,11.1], [1...
Python
1
TS!(Bar), /// field_tstr= TS!(0), /// field_type= u32, /// } /// } /// /// /// impl FieldType<FP!(::Bar.1)> for Foo{ /// type Ty=u64; /// } /// /// unsafe impl GetVariantField<TS!(Bar),TS!(1)> for Foo{ /// fn get_vfield_(&self, _:TS!(Bar), _:TS!(1)) -> Option<&u64>{ /// match self {...
Rust
0
#!/usr/bin/env python3 import pandas as pd import numpy as np from sklearn.linear_model import LinearRegression, Lasso, Ridge, ElasticNet def analyse_linear(data,excluded=[]): cols = data.columns.difference([ "ratio", ]+ excluded) x = data[cols] # x = (x-x.mean())/x.std() x = (x-x.min())/(x.max()-x.m...
Python
1
.or_else(|| self.find_inode_udp(tt, c, true, true)) // case 4: we only compare local port => this will give the right inode in most cases, but a port can be claimed by two processes (can be ambigous) } TransportType::Tcp => { self.find_inode_tcp(tt, c) }...
Rust
0
k_dir); if let Some(since) = options.since { cmd.args(&["--since", &since.format(DATE_FORMAT).to_string()]); } if let Some(until) = options.until { cmd.args(&["--until", &until.format(DATE_FORMAT).to_string()]); } if let Some(duration) = options.duration { cmd.args(&["--dura...
Rust
0
use it, but alas write!(f, "PdfObject::String({:?})", &*v) } PdfObject::Name(ref v) => { // here we are directed to use utf-8 (end of § 7.3.5 and // Note 4 thereof) write!( f, "PdfObject::Nam...
Rust
0
strip_utf8_bom(mut data: Vec<u8>) -> Vec<u8> { if data.get(..3) == Some(&[0xEF, 0xBB, 0xBF]) { data.drain(..3); } data } /// Simple function to decrypt a SafeInCloud.db pub fn decrypt(mut source: impl Read, password: &[u8]) -> Vec<u8> { let _ = source.read_be_u16(); let _ = source.read_u8(...
Rust
0
braille_jung = "" braille_jong = "⠿" elif jung == "ㅜ": if jong == "ㄴ": # 글자 속에 "ㅜㄴ"이 포함된 경우 braille_jung = "" braille_jong = "⠛" elif firstjong == "ㄴ": braille_jun...
Python
1
ruction & Study / Theory", "MUS042000" => "Music / Instruction & Study / Voice", "MUS045000" => "Music / Genres & Styles / Military & Marches", "MUS046000" => "Music / Genres & Styles / Musicals", "MUS047000" => "Music / Genres & Styles / Reggae", "MUS048000" => "Music / Religious / General", "M...
Rust
0
bdataset (.tar) format, and store in `output_folder/split`. Labels must be lists of strings, with no newlines. Read the documentation of `convert_dataset` for more information. """ # Create output directory os.makedirs(os.path.join(output_folder, split), exist_ok=True) # Multiprocessed dataloa...
Python
1
return [], [], [], [] # remove unused data while len(path_x) >= 1 and path_x[-1] == 0.0: path_x.pop() path_y.pop() path_yaw.pop() directions.pop() return path_x, path_y, path_yaw, directions def plot_arrow(x, y, yaw, length=1.0, width=0.5, fc="r", ec="k"): # pragma: no ...
Python
1
try: tempvar = "welcome to elegent"\ "have study a lot!" print(tempvar) tempvar="""welcome to elegent have study a lot! """ print (tempvar) except Exception as e: print(e)
Python
1
99; println!("{}",y); //PRINTS 99 } //Y VAR IS DROPPED { let mut x = 5; //MUTABLE VARIABLE let x = x; //MAKES IMMUTABLE } println!("{}",y); //PRINT STRING println!("{}", bunnies); //RUNTIME let enigma: i32; if true{ enigma = 42; }else{ en...
Rust
0
ynthesisError}; use nimiq_bls::pedersen::pedersen_generators; use crate::gadgets::mnt4::VKCommitmentGadget; use crate::utils::{prepare_inputs, unpack_inputs}; /// This is the merger circuit. It takes as inputs an initial state commitment, a final state commitment /// and a verifying key and it produces a proof that ...
Rust
0
ering-archive-api.html>`_ .. warning:: This API is **experimental** so may include breaking changes or be removed in a future version :arg node_id: Comma-separated list of node IDs or names used to limit returned information. :arg max_archive_version: Speci...
Python
1
from .publickey import PublicKey from .privatekey import PrivateKey from dissononce.dh.x25519.x25519 import X25519DH from dissononce.dh.x25519.keypair import KeyPair as X25519KeyPair class KeyPair(object): def __init__(self, public, private): """ :param public: :type public: PublicKey ...
Python
1
from image_correction import ImageCorrection from clustering import Clustering from color_inference import ColorInference from calculate_deltaE import ColorSimilarityCalculator ######################################################################################################### # 1) 이미지 보정 # 2) 클러스터링 # 3) 색상 추론 #...
Python
1
"int_bits_const", since = "1.53.0")] pub const BITS: u32 = $BITS; /// Converts a string slice in a given base to an integer. /// /// The string is expected to be an optional `+` or `-` sign followed by digits. /// Leading and trailing whitespace represent an error. Digits are a ...
Rust
0
import sys sys.path.append('.') import bcrypt from pymongo.mongo_client import MongoClient from config import Config from lib.utils import dt_utcnow from lib.enums.vertical import VerticalKeywordGroup ADMIN_USERNAME = 'admin@gmail.com' ADMIN_PASSWORD = 'admintools' ADMIN_ROLES = ['admin', 'users'] ADMIN_NAME = 'ad...
Python
1
in rfResult: # raise Exception("How come there's no drf_model in this RF result? %s" % h2o.dump_json(rfResult)) h2o_jobs.pollWaitJobs(timeoutSecs=300) rfView = h2o_cmd.runSpeeDRFView(None, model_key, timeoutSecs=60) print "rfView:", h2o.dump_json(rfView) r...
Python
1
} let r = ripemd160(&mut cs, &input_bits).unwrap(); assert!(cs.is_satisfied()); let mut s = hash_result .iter() .flat_map(|&byte| (0..8).map(move |i| (byte >> i) & 1u8 == 1u8)); for b in r { match b { ...
Rust
0
from __future__ import annotations import hashlib import logging from pathlib import Path from unstructured.ingest.interfaces import ( StandardConnectorConfig, ) def update_download_dir_remote_url( connector_config: StandardConnectorConfig, remote_url: str, logger: logging.Logger, ) -> str: hash...
Python
1
cked_bindings # Can't use detect_fake_mode here, # # python test/distributed/_tensor/test_dtensor_compile.py -k # test_tp_compile_fullgraph_is_seq_parallel_False # # will fail. Very strange, it probably isn't right for them to be using # two fake modes there... fake_mode = torch._C._ge...
Python
1
le self.connect_network(self.wd, device, 'ssidCCMP') self.wd.unregister_psk_agent(psk_agent) # # Rewrite the known frequencies file to move the valid network # frequencies to the end, past the maximum for a quick scan # config = ConfigParser() config.rea...
Python
1
)) }) } } impl RustType<ProtoNaiveDateTime> for NaiveDateTime { fn into_proto(&self) -> ProtoNaiveDateTime { ProtoNaiveDateTime { year: self.year(), ordinal: self.ordinal(), secs: self.num_seconds_from_midnight(), frac: self.nanosecond(), ...
Rust
0
import numpy as np from clustering.agglomerate_clustering import AgglomerateClustering, Linkage from clustering.clustering_algorithm import Clustering from clustering.dbscan import Dbscan from clustering.expectation_maximization import CovarianceType, ExpectationMaximization from helper.argument_helper import Argument...
Python
1
align: usize) -> Address { debug_assert!(mem::is_page_aligned(size)); debug_assert!(mem::is_page_aligned(align)); let align_minus_page = align - page_size(); let unaligned = reserve(size + align_minus_page); let aligned: Address = mem::align_usize(unaligned.to_usize(), align).into(); let gap...
Rust
0
50", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_50")))] use std::fmt; #[cfg(any(feature = "v1_50", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_50")))] #[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Clone, Copy)] #[non_exhaustive] #[doc(alias = "PangoLayoutDeser...
Rust
0
t: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum DSP_PRAM3_ACCESS_A { #[doc = "0: DSP PRAM3 access disabled"] DSP_PRAM3_ACCESS_DISABLE = 0, #[doc = "1: DSP PRAM3 access enabled"] DSP_PRAM3_ACCESS_ENABLE = 1, } impl From<DSP_PRAM3_ACCESS_A> for bool { #[inline(always)] fn from(variant: DS...
Rust
0
r(nums: &[i32]) -> Option<Rc<RefCell<TreeNode>>> { if nums.is_empty() { return None; } let mid = nums.len() / 2; Some(Rc::new(RefCell::new(TreeNode { val: nums[mid], left: sorted_list_to_bst_r(&nums[..mid]), right: sorted_list_to_bst_r(&nums[mid + 1..]), }))) } imp...
Rust
0
#Itineraciones - Operadores Relacionales ##Bucle while. nos permite ejecutar un bloque de código varias veces ##Estructura ##while expresion_condicional: ## Bloque de instrucciones ## Más instrucciones... #Ejemplo contador = 5 while contador > 0: print("Estoy dentro del bucle... Quedan", contador, "iter...
Python
1
where S: Serializer, { match self { Self::Enabled => serializer.serialize_unit_variant("SendAadLogsStatus", 0u32, "Enabled"), Self::Disabled => serializer.serialize_unit_variant("SendAadLogsStatus", 1u32, "Disabled"), Self::UnknownValue(s) => serializer.serialize_...
Rust
0
"""Epsonprinter component constants.""" DEFAULT_VERIFY_SSL = False PROTOCOL_HTTP = "http" PROTOCOL_HTTPS = "https"
Python
1
(options.cert_path.unwrap())?; } let tls_conn = builder.build(); let tcp_stream = tcp_stream(url, &options.tcp_options)?; let tls_stream = tls_conn.connect(host, tcp_stream)?; Stream::Tls(tls_stream) } }; let p...
Rust
0
&from_utf8(next_sibling_element_name).unwrap().to_string(), ) .finish(), NodeData::Instruction { code, ended } => f .debug_struct("Instruction") .field("code", &from_utf8(code).unwrap().to_string()) .field("...
Rust
0
let error = apply_unary(op, rhs, EvalConstraints { as_64_bit: false }).expect_err( &format!("Test #{} did not produce an error", (test_num + 1)), ); assert_eq!(error, expect_error, "Test #{} failed", (test_num + 1)); } } } use std::convert::TryInto; use st...
Rust
0
let mut x = self; x.arguments.corpus_out = path.map(Path::to_path_buf); x } #[no_coverage] pub fn artifacts_folder(self, path: Option<&Path>) -> Self { let mut x = self; x.arguments.artifacts_folder = path.map(Path::to_path_buf); x } #[no_coverage] pub fn ...
Rust
0
#!/usr/bin/env python2 from pwn import * from struct import pack,unpack SYSTEM_OFFSET = 0x4F440 BIN_SH_OFFSET = 0x1B3E9A POP_RDI_ADDR = 0x400a83 EXIT_GOT_PLT = 0x602068 SETBUF_GOT_PLT = 0x602030 SETBUF_OFFSET = 0x884D0 PUTS_TIMEOUT_ADDR = 0x400846 DOUBLE_POP_ADDR = 0x400a80 MAIN_ADDR = 0x400993 VULN_FUNC_ADDR = 0x40085...
Python
1
_b11_1 - t_b11_2 + t_b11_3 - t_b11_4 + t_b11_5 - t_b11_6 + t_b11_7 - t_b11_8 + t_b11_9 - t_b11_10 + t_b11_11); let t_b1_rot = self.rotate.rotate(t_b1); let t_b2_rot = self.rotate.rotate(t_b2); let t_b3_rot = self.rotate.rotate(t_b3); let t_b4_rot = self.rotate.rotate(t_b4); let ...
Rust
0
import google.generativeai as genai import os from dotenv import dotenv_values config = dotenv_values(".env") genai.configure(api_key=config.get("Gemini_API_KEY")) # Upload the video file video_file_name = "microsoft_ai_mvp_talk_2023.mp4" print(f"Uploading file...") video_file = genai.upload_file(path=video_file_name...
Python
1
# Pyrofork - Telegram MTProto API Client Library for Python # Copyright (C) 2017-present Dan <https://github.com/delivrance> # Copyright (C) 2022-present Mayuri-Chan <https://github.com/Mayuri-Chan> # # This file is part of Pyrofork. # # Pyrofork is free software: you can redistribute it and/or modify # it under ...
Python
1
_texture).unwrap(); let mut mesh = Mesh::new(&context, &cpu_mesh).unwrap(); mesh.cull = CullType::Back; LoadedImageMesh {mesh, texture_2d} } fn color_mesh(context: &Context) -> Mesh { let mut cpu_mesh = CPUMesh { positions: hourglass_positions(), ..Default::default() }; cpu_...
Rust
0
task = loop.run_in_executor(executor, process_files, file, doc_id, session_id, file_path, user_task, filename_with_timestamp, support_multi_modal, if_use_muilt, fileId) tasks.append(task) # 等待所有任务完成 await asyncio.gather(*tasks, return_exceptions=True) user_task["is_fin...
Python
1
'defaults': 6} _power_levels = [chirp_common.PowerLevel("Low", watts=5), chirp_common.PowerLevel("Mid", watts=10), chirp_common.PowerLevel("High", watts=25)] # Base radio has offset zero to distinguish from sub devices _offset = 0 def get_features(self): ...
Python
1
se_execute_mandos("mandos/transfer_Other-Positive.scen.json", &contract_map()); } #[test] fn transfer_other_stillnooverflow() { parse_execute_mandos( "mandos/transfer_Other-StillNoOverflow.scen.json", &contract_map(), ); } #[test] fn transfer_other_zero() { parse_execute_mandos("mandos/transfer_Other-Zero.scen...
Rust
0
method: HTTP method headers: HTTP headers body: Request body """ if method != "POST": self._send_http_error(client_socket, 405, "Method Not Allowed") return try: # Decode request body request_data = json.load...
Python
1
system. Defaults to None. body_sendAlertsOnceMutingPeriodHasEnded (bool, optional): Controls notifications after the muting period ends. Defaults to None. body_startTime (int, optional): Starting timestamp of the muting rule in Unix time (milliseconds). Defaults to None. body_stopTime (int, opt...
Python
1
sat), 10_000_000) # clamp into [0, 10k sat] if fee_millionths != millionths_clamped: _logger.warning( f"PaymentFeeBudget. found insane fee millionths in config. " f"clamped: {fee_millionths}->{millionths_clamped}") if fee_cutoff_msat != cutoff_clamped: ...
Python
1
continue; } _ => { *ifa = (**ifa).ifa_next; continue; } } } Ok(interfaces) } } /// Retrieves the name of a interface address unsafe fn get_ifa_name(ifa: *mut *mut ifaddrs) -> Result<String, Error> {...
Rust
0
} 3u8 => { assert_eq!(v.valid_bits_per_sample, 24u8); AudioSampleFormat::TwentyFourPacked { unsigned: is_unsigned, invert_endian: false, } } 4u8 => ...
Rust
0
oat(epsilon) if epsilon <= 0 or epsilon >= 1: raise ValueError( f"`eta_cutoff` has to be a float > 0 and < 1, but is {epsilon}" ) self.min_tokens_to_keep = min_tokens_to_keep = int(self.min_tokens_to_keep) if min_tokens_to_keep < 1: raise Valu...
Python
1
be non-zero ensure!(!locked_balance.amount.is_zero(), Error::<T>::InvalidAmount); // lock duration MUST increase ensure!(unlock_height > locked_balance.end, Error::<T>::InvalidHeight); // height MUST NOT be greater than max let max_period = T::MaxPeriod::ge...
Rust
0
.map(|x| (&x.field.vis, &x.column_ident)) .unzip::<_, _, Vec<_>, Vec<_>>(); quote! { #[allow(dead_code, unreachable_code)] impl<M> #filterable_ident<M> { #(#field_vis fn #column_ident<E, X>(mut self, #column_ident: E) -> Self where ...
Rust
0
def add(a, b): return a + b def sub(a, b): return a - b def mul(a, b): return a * b def div(a, b): if b == 0: return "Error! Can't divide by zero!" return a / b def mod(a, b): if b == 0: return "Error! Can't modulus by zero!" return a % b print("=== Simple Calculator ===...
Python
1
for &node_idx in untreated_nodes { for i in 0..solution_dim { coo.push(solution_dim * node_idx + i, solution_dim * node_idx + i, 0.0); // Below was for old block diagonal preconditioning // for j in 0 .. solution_dim { // coo.push(solution_dim * node_idx + i,...
Rust
0
oard_size_half.y + (pos.y as f32 * snake_resources.cell_size), 0., ); } } fn food_spawner( mut commands: Commands, config: Res<SnakeConfig>, mut meshes: ResMut<Assets<Mesh>>, ) { commands .spawn_bundle(PbrBundle { material: config.food_material.clone(), ...
Rust
0
{ Ok(x) => x, // Unsafe unwrap as this error cannot be recovered at runtime Err(err) => panic!("{err}"), } }; } pub const READ_PRIMITIVE: fn() -> Vec<PrimitiveEntry> = || { let bin = fs::read_to_string(&LANG_PATH.constructed_path).unwrap(); serde_json::from_str(&bin).unwrap() }; pub const WRITE_PRIM...
Rust
0
, 0xb6)] interface ID3D11LibraryReflection(ID3D11LibraryReflectionVtbl): IUnknown(IUnknownVtbl) { fn GetDesc( pDesc: *mut D3D11_LIBRARY_DESC, ) -> HRESULT, fn GetFunctionByIndex( FunctionIndex: INT, ) -> *mut ID3D11FunctionReflection, }} DEFINE_GUID!{IID_ID3D11FunctionReflection, 0x2...
Rust
0
nd(C) * 0.001 bias = torch.rand(C) * 0.0001 running_mean = torch.zeros(C) running_var = torch.ones(C) inputs = torch.randn((6, C, 4, 33, 42), requires_grad=False) model = SimpleQuantizedBatchNorm( C, weight, bias, running_mean, ...
Python
1
from django.urls import path from . import views app_name = 'item' urlpatterns = [ path('', views.items, name = 'items'), path('new/', views.new, name='new'), path('<int:pk>/', views.detail, name='detail'), path('<int:pk>/delete/', views.delete, name='delete'), path('<int:pk>/edit/', views.edit...
Python
1
# # Copyright (c) 2023 Airbyte, Inc., all rights reserved. # azure_storage_account_name_key_name = "storage_account_name" azure_storage_access_key_key_name = "storage_access_key" azure_storage_endpoint_suffix_key_name = "storage_endpoint_suffix" results_per_page = 999 table_name_regex = "^[a-z0-9](?!.*--)[a-z0-9-]{1,6...
Python
1
"); } #[panic_handler] fn panic(_info: &core::panic::PanicInfo) -> ! { loop { cortex_m::asm::bkpt(); } } //! API for system configuration (SYSCON) //! //! The entry point to this API is [`SYSCON`]. Please refer to [`SYSCON`]'s //! documentation for additional information. //! //! This module mostly pro...
Rust
0
"> <div style="display: flex; align-items: center;"> <div style="font-size: 2rem; margin-right: 1rem;">ℹ️</div> <div> <div style="font-weight: 600; font-size: 1.1rem; margin-bottom: 0.25rem;">No Alert Triggered</div> ...
Python
1
orm": discrete_uniform_schedule, "linear": partial(linear_schedule, dtype=int), "constant": constant_schedule, "random_decay": random_decay_schedule, "polynomial": partial(polynomial_schedule, dtype=int), "hifa": hifa_t_schedule, "piecewise_linear": partial(piecewise_line...
Python
1
'''Code for creating the subcommand switch code in Bash''' from . import utils from .str_utils import indent def get_subcommand_path(commandline): commandlines = commandline.get_parents(include_self=True)[1:] prognames = ['root'] + [c.prog for c in commandlines] return ':'.join(prognames) def make_subc...
Python
1
B::Apply(_, sp!(_, TN::ModuleType(m, s)), tys) => { assert!(context.module_handle_index(&m).unwrap().0 == 0); let def_idx = context.struct_definition_index(&s); let local_sig = F::LocalsSignature(base_types(context, tys)?); let tys_idx = context.locals_signature_in...
Rust
0
ual(num_onnxified_ops, 1) workspace.SwitchWorkspace("glow_test_ws", True) workspace.FeedBlob("X", X) workspace.CreateNet(pred_net_ref) workspace.CreateNet(pred_net_onnxified) workspace.FeedBlob("X", X) # Run caffe2 net workspace.RunNet(pred_net_ref.name) ...
Python
1
"""empty message Revision ID: 992013af402f Revises: 496427d03f87 Create Date: 2017-04-24 17:51:15.481079 """ from alembic import op import sqlalchemy as sa import imp import os from GeoHealthCheck.migrations import alembic_helpers # revision identifiers, used by Alembic. revision = '992013af402f' down_revision = '49...
Python
1
import logging from django.core.exceptions import ObjectDoesNotExist from swapper import load_model from .. import settings as app_settings logger = logging.getLogger(__name__) Organization = load_model("openwisp_users", "Organization") OrganizationRadiusSettings = load_model("openwisp_radius", "OrganizationRadiusS...
Python
1
{ use crate::schema::general_comments; use crate::schema::general_comments::dsl; let id = diesel::insert_into(dsl::general_comments) .values(( general_comments::eleve_id.eq(eleve_id), general_comments::comment.eq(comment.clone()), )) ...
Rust
0
0f32 } else { (self.base_writer.values[self.base_writer.off - 1] - self.base_writer.values[0]) as f32 / (self.base_writer.off - 1) as f32 }; let mut min = self.base_writer.values[0]; // adjust min so that all deltas will be positive for i i...
Rust
0
{ let tip_header: HeaderView = node.rpc_client().get_tip_header().into(); let tip_epoch = tip_header.epoch(); let target_epoch = EpochNumberWithFraction::new(number, index, length); assert_eq!( tip_epoch, target_epoch, "current tip epoch is {}, but expect epoch {}", tip_epoch, t...
Rust
0
'''Crie um programa que lei nome e duas notas de vários alunos e guarde tudo em uma lista composta. No final, mostre um boletim contendo a média de cada yn e permita que o usuário possa mostras as notas de cada aluno individualmente.''' ficha = [] while True: nome = str(input("Nome: ")) nota1 = float(input("Nota ...
Python
1
import nltk import sys TERMINALS = """ Adj -> "country" | "dreadful" | "enigmatical" | "little" | "moist" | "red" Adv -> "down" | "here" | "never" Conj -> "and" | "until" Det -> "a" | "an" | "his" | "my" | "the" N -> "armchair" | "companion" | "day" | "door" | "hand" | "he" | "himself" N -> "holmes" | "home" | "i" | "...
Python
1
"""StackExchange API toolkit."""
Python
1
nr_blocks = int(sys.argv[2]) nr_subbands = int(sys.argv[3]) bitpool = int(sys.argv[4]) allocation_method = int(sys.argv[5]) force_channel_mode = int(sys.argv[6]) print("force_channel_mode %d"%force_channel_mode) fin = wave.open(infile, 'rb...
Python
1
// specific args needed for documentation $format:expr, ($($mod_path:expr),*), $seq1:expr, $seq2:expr, [$seq2_owned1:expr, $seq2_owned2:expr] ) => { _impl_reader!( $Reader, $RefRecord, $OwnedRecord, $RecordSet, $Error, $RecordStoreTrait, $DefaultPositionStore, $...
Rust
0
None => { return Err(InvalidStateError::InvalidInput(String::from( "Reference to the activation function object is not set." ))); } }; let mut nd: Vec<f64> = Vec::with_capacity(this.units[l].0 + 1); nd.resize(this.units[l].0 + 1, 0f64); ...
Rust
0
# File: app/extensions.py from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_login import LoginManager from flask_wtf.csrf import CSRFProtect from flask_session import Session # If using Flask-Session from flask_apscheduler import APScheduler from flask_babel import Babel from flask_ht...
Python
1
uest::Scan { req, txn, .. } => Ok(scan(sme, txn, req) .await .unwrap_or_else(|e| error!("Error handling a scan transaction: {:?}", e))), ClientSmeRequest::Connect { req, txn, .. } => Ok(connect(sme, txn, req) .await .unwrap_or_else(|e| error!("Error handling a con...
Rust
0
} // Note: local_bind_group_layout needs to be passed in from the pipeline. // Be careful here to make sure the layout of the pipeline matches our layout here. pub(crate) fn create_bind_group( &mut self, images: &HashMap<String, Image>, device: &wgpu::Device, local_bind_...
Rust
0
while day <= *end { paths.push(path_for_date(&day, config)); day = day.succ(); } let paths = paths.into_iter().unique(); let mut activities = Vec::new(); for path in paths { debug!("Reading path {:?}", &path); let mut for_path = read_activities(&path) .with_...
Rust
0
Vec`](https://crates.io/crates/smallvec) and //! [`Cow`](https://doc.rust-lang.org/std/borrow/enum.Cow.html) (`Small` + `Cow` = `Calf`). //! Additionally this crate provides a //! [`CalfString`](https://docs.rs/calf-vec/latest/calf_vec/string/struct.CalfString.html) //! for small copy-on-write strings //! based on `Cal...
Rust
0
let value2 = frame.stack.pop().ok_or(EvalError::ExpectedStackValue)?; // verifier assures that these aren't category 2 types debug_assert!(!value1.is_category_2()); debug_assert!(!value2.is_category_2()); frame.stack.push(value1)?; frame.stack.push(value2)?; fr...
Rust
0
"""Scan for iBeacons. Copyright (c) 2022 Koen Vervloesem SPDX-License-Identifier: MIT """ import asyncio from uuid import UUID from construct import Array, Byte, Const, Int8sl, Int16ub, Struct from construct.core import ConstError from bleak import BleakScanner from bleak.backends.device import BLEDevice from bleak...
Python
1
i::PyObject, default: Option<NonNull<pyo3_ffi::PyObject>>, opts: Opt, ) -> Result<NonNull<pyo3_ffi::PyObject>, String> { let mut buf = BytesWriter::new(); let obj = PyObjectSerializer::new(ptr, opts, 0, 0, default); let res; if opts & INDENT_2 != INDENT_2 { res = serde_json::to_writer(&m...
Rust
0
_name.display().to_string()); } fn find_mod_inverse(a: i64, n: i64) -> i64 { let mut prev_r = n; let mut curr_r = a; let mut prev_t = 0; let mut curr_t = 1; while curr_r != 0 { let quotient = prev_r / curr_r; let new_r = prev_r - quotient * curr_r; prev_r = curr_r; ...
Rust
0
usize), String> { check_pos(pos, toks.len())?; // need to match match &toks[pos] { lexer::TokType::Minus| lexer::TokType::SingleAnd| // '&', different with '&&' as TokType::And lexer::TokType::Multi| lexer::TokType::Exclamation| // '!' lexer::TokType::Tilde |...
Rust
0
from transformers import AutoTokenizer from transformers import T5TokenizerFast import torch import json import numpy as np from .Basic import BasicFormatter class movierationalesPromptT5Formatter(BasicFormatter): def __init__(self, config, mode, *args, **params): self.config = config self.mode = m...
Python
1
if !syncd { let synchronized = PiecewiseQuadratic::synchronize(work, fns); let synchronized_refs = synchronized.iter().collect::<Vec<_>>(); PiecewiseQuadratic::synchronized_sum_pwq(&synchronized_refs) } else { PiecewiseQuadratic::synchronized_sum_pwq(fns) ...
Rust
0
tor if self._debug.enabled: self._debug(None, "begin", kwargs[BlockKwargs.hidden_dims], kwargs) fw_input = input_ hidden_states = self.norm_1(input_) if self._debug.enabled: self._debug(hidden_states, "norm 1", kwargs[BlockKwargs.hidden_dims], kwargs) hidd...
Python
1
rows.iter_mut() .zip(array.iter()) .take(row_count) .for_each(|(row, value)| { row.insert( col_name.to_string(), value .map(|x| write_array(x.as_ref())) ...
Rust
0