text
string
label_name
string
labels
int64
# Import standard python modules import sys, os, pytest, json, threading # Set system path and directory root_dir = os.environ["PROJECT_ROOT"] sys.path.append(root_dir) os.chdir(root_dir) # Import device utilities from device.utilities.logger import Logger from device.utilities.accessors import get_peripheral_config ...
Python
1
# Source: https://github.com/stopwords-iso/stopwords-eu # https://www.ranks.nl/stopwords/basque # https://www.mustgo.com/worldlanguages/basque/ STOP_WORDS = set( """ al anitz arabera asko baina bat batean batek bati batzuei batzuek batzuetan batzuk bera beraiek berau berauek bere berori beroriek beste bezala da dag...
Python
1
onto the master node.\n%s' % KEY_PAIR_FILE_HELP_TEXT) ARG_TABLE = [ {'name': 'cluster-id', 'required': True, 'help_text': 'Cluster Id of cluster you want to put file onto'}, {'name': 'key-pair-file', 'required': True, 'help_text': 'Private key file to use for log...
Python
1
id) if id.is_null() => return Err(DeserializeError::ObjectIsNull), Payload::ObjectId(id) => $ty::new($con, id), _ => return Err(DeserializeError::UnexpectedType), } }; } macro_rules! from_payload { ($ty:ident, $v:expr) => { match ($v).clone() { Payload::$ty(v...
Rust
0
use crate::board::Board; pub fn solve(numbers: Vec<u8>, boards: Vec<Board>) -> u32 { if let Some(bingo_board) = find_board(numbers, boards) { sum_unchecked(&bingo_board.board) * (bingo_board.last_number as u32) } else { 0 } } fn sum_unchecked(board: &Board) -> u32 { board.all_numbers()...
Rust
0
00\x00\ \x00\x00IEND\xaeB`\x82\ \x00\x00\x0eB\ \x89\ PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\ \x00\x00H\x00\x00\x00I\x08\x06\x00\x00\x00\x9e\xb1`\xe2\ \x00\x00\x00\x09pHYs\x00\x00\x0b\x13\x00\x00\x0b\x13\ \x01\x00\x9a\x9c\x18\x00\x00\x00\x01sRGB\x00\xae\xce\ \x1c\xe9\x00\x00\x00\x04gAMA\x00\x00\xb1\x8f\x0b\xfc\ a\x...
Python
1
4core3ptr6unique1 ..." R_ANGLE@183..184 ">" "# ); } #[test] fn test_objdump_plus() { assert_listing!( r#" a.out: file format elf64-littleaarch64 Disassembly of section .text: 210640: b4000040 cbz x0, 210648 <call_weak_fn+0x10>"#, r#"ROOT@0..131 WHITESPACE@0..1 "\n" METADAT...
Rust
0
"""Helpers for presenting diagnosis predictions with clinical guidance.""" from typing import Any, Dict, Iterable, List from ..data.red_flags import RESPIRATORY_RED_FLAGS def enrich_differential_with_guidance( ranked_predictions: Iterable[Dict[str, Any]] ) -> List[Dict[str, Any]]: """Attach red-flag and esc...
Python
1
efault', 'jhadmin', '" + apivar['dataPath'] + "', " + apivar['jobid'] + \ # ", '2017-05-31 17:59:55', null);" # apivar['dml'] = "inst" # apivar['datainfo'] = tool.operatepsql(apivar) # dataapi.spoolersbyname(apivar) # putlog.info("case 4-1 test end ...\n") # # 给定正确的数据目录名称 # putlog.info("cas...
Python
1
import math radius = float(input("Enter the radius of a circle: ")) circumstance = 2 * math.pi * radius print(f"The circumstance of the circle is: {round(circumstance, 2)} cm")
Python
1
Solid { ParamSolid { density: 2.7, // Mg/m² stress_strain: ParamStressStrain::LinearElastic { young: 10_000.0, // kPa poisson: 0.2, // [-] }, } } /// Returns example parameters for a porous medium with liquid and gas pub...
Rust
0
ifier, self.region) elif self.identifier is not None and self.failover is not None: rr += ' (FAILOVER id=%s, failover=%s)' % (self.identifier, self.failover) return rr def endElement(self, name, value, connection): if name == 'Name': self.name = value elif n...
Python
1
based on //! trending headlines. #![warn( clippy::all, missing_debug_implementations, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unsafe_code, unused_import_braces, unused_qualifications )] use std::{ collections::HashMap, convert::TryInto, env, ...
Rust
0
import matplotlib from keras.preprocessing.image import ImageDataGenerator,img_to_array from keras.optimizers import Adam from keras.utils import to_categorical from imutils import paths import matplotlib.pyplot as plt import numpy as np import os,cv2,sys import argparse import random,pdb from model import class_mode...
Python
1
def get_model_name(): if os.path.exists('trained_models/trainedResnet.h5'): return 'trainedResnet' else: return 'pretrainedResnet'
Python
1
let mut a = Archive::new(unzipped); a.unpack(extract_to).unwrap(); } fn main() { let out_dir = PathBuf::from(var("OUT_DIR").unwrap()); for (archive, uri, md5) in mkl::DLS { let archive_path = out_dir.join(archive); if archive_path.exists() && calc_md5(&archive_path) == *md5 { ...
Rust
0
bool) -> TRIGMR { match value { false => TRIGMR::_0, true => TRIGMR::_1, } } #[doc = "Checks if the value of the field is `_0`"] #[inline] pub fn is_0(&self) -> bool { *self == TRIGMR::_0 } #[doc = "Checks if the value of the field is `_1`"] #...
Rust
0
from django.core.cache import cache from django.urls import reverse from django.utils.translation import gettext as _ from wagtail_modeladmin.helpers import PageButtonHelper from wagtail import hooks from wagtail_modeladmin.options import ( ModelAdmin, ModelAdminGroup, modeladmin_register, ) from .models...
Python
1
# Copyright 2018- The Pixie Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
Python
1
pub const FEATURE_TELEPHONY : &'static str = "android.hardware.telephony"; /// public static final [FEATURE_TELEPHONY_CDMA](https://developer.android.com/reference/android/content/pm/PackageManager.html#FEATURE_TELEPHONY_CDMA) pub const FEATURE_TELEPHONY_CDMA : &'static str = "android.hardware.te...
Rust
0
, outlet: OutletId, by: OutletId) -> TractResult<()> { self.shunt_outlet_by.insert(outlet, by); Ok(()) } /// Convenience method creating a patch that replace a single operation. pub fn replace_single_op<O: Into<Box<Op>>>( patched_model: &Model<TI>, node: &Node<TI>, i...
Rust
0
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("wagtailforms", "0001_initial"), ] operations = [ migrations.AlterModelOptions( name="formsubmission", options={"verbose_name": "Form Submission"}, ), ...
Python
1
sinstance(path, bytes): curdir = b'.' sep = b'/' pardir = b'..' else: curdir = '.' sep = '/' pardir = '..' if start is None: start = curdir else: start = os.fspath(start) try: start_list = [x for x in abspath(start).split(sep) if ...
Python
1
a.sext(-width_diff as u32).srem(&b), t1 | t2), } } } } #[inline] pub fn asr(self, rhs: Value, sz: u32) -> Value { //println!("{:?}, {:?}, {:?}", self, rhs, sz); match (self, rhs) { (Value::Concrete(a, t1), Value::Concrete(b, t2)) => { ...
Rust
0
>PtrMan/20NAR1<gh_stars>1-10 //! utilities for terms and manipulation of terms use crate::Term::*; /// decodes a operator into the arguments and name /// returns None if the term can't be decoded /// expects term to be <{(arg0 * arg1 * ...)} --> ^opname> pub fn decodeOp(term:&Term) -> Option<(Vec<Term>,String)> { ...
Rust
0
or public key not found") .clone() .try_into() .unwrap(); PublicKey::from_hex(&key).unwrap() }) .collect(); let client = RpcClient::from(rpc.clone()); let mut anchoring_config = AnchoringNodeConfig::new(S...
Rust
0
003000d, RPI_FIRMWARE_UNLOCK_MEMORY = 0x0003000e, RPI_FIRMWARE_RELEASE_MEMORY = 0x0003000f, RPI_FIRMWARE_EXECUTE_CODE = 0x00030010, RPI_FIRMWARE_EXECUTE_QPU = 0x00030011, RPI_FIRMWARE_SET_ENABLE_QPU = 0x00030012, RPI_FIRMWARE_GET_DISPMANX_RESOURCE_MEM_HANDLE = 0x00030014, RPI_FIRMWARE_GET_ED...
Rust
0
mmitStatuses; pub use self::statuses::CommitStatusesBuilder; pub use self::statuses::CommitStatusesBuilderError; pub use self::merge_requests::MergeRequests; pub use self::merge_requests::MergeRequestsBuilder; pub use self::merge_requests::MergeRequestsBuilderError; <filename>fkactor/src/system.rs use std::cmp::Orderi...
Rust
0
#!/usr/bin/env python3 import re from lib.args import args from lib.output import * from lib.googlesearch import search def phone_us_format(phone_number, delimiter): clean_phone_number = re.sub('[^0-9]+', '', phone_number) formatted_phone_number = re.sub( "(\d)(?=(\d{3})+(?!\d))", r"\1" + delimiter, ...
Python
1
import numpy as np import matplotlib.pyplot as plt trials = 100 dim = range(1,1000) std = .01 y = [] rng = np.random.RandomState([1,2,3]) for cur_dim in dim: print cur_dim sample_greater = 0 sample_unchanged = 0 vertex = rng.randn(cur_dim) vertex /= np.sqrt(np.square(vertex).sum()) norm_sq ...
Python
1
from sage.all import * from pwn import * from Crypto.Util.number import * import struct p = (1 << 130) - 5 R = PolynomialRing(GF(p), 'x') x = R.gen() conn = remote("activist-birds.picoctf.net", 51396, level='debug') conn.recvuntil(b"Ciphertext (hex): ") c1_hex = conn.recvline().decode().strip() conn.recvuntil(b"Ciphe...
Python
1
orshDeserialize, BorshSerialize}; use near_sdk::collections::UnorderedMap; use near_sdk::json_types::{Base58PublicKey, ValidAccountId, WrappedBalance, WrappedTimestamp}; use near_sdk::serde::{Deserialize, Serialize}; use near_sdk::serde_json::json; use near_sdk::{env, near_bindgen, AccountId, Balance, PanicOnDefault, P...
Rust
0
r: ") if user_input.lower() in ["quit", "exit", "q"]: print("Goodbye!") break elif user_input == "": stream_graph_updates_by_none() elif user_input == "update": update_graph_state() elif user_input == "replay": replay_chat() ...
Python
1
0..config.number_of_dice { rolls.push(rng.gen()); } // Format and display them in rows no larger than dice_per_row. for group in rolls.as_slice().chunks(config.dice_per_row as usize) { print_row(group); } } use composer::{Builder, ComposeTest, RpcHandle}; use rpc::mayastor::{ AddCh...
Rust
0
omplete::{tag, take}, character::complete::{self as character, anychar, line_ending}, combinator::{opt, recognize, verify}, error::ParseError, multi::many0_count, sequence::terminated, IResult, }; use crate::*; /// ALPHA = %x41-5A / %x61-7A ; A-Z / a-z pub fn alpha<'a, E: ParseError<&'a str>>(...
Rust
0
OLFSSL_CTX, arg2: CallbackRsaEnc); } extern "C" { pub fn wolfSSL_SetRsaEncCtx(ssl: *mut WOLFSSL, ctx: *mut ::std::os::raw::c_void); } extern "C" { pub fn wolfSSL_GetRsaEncCtx(ssl: *mut WOLFSSL) -> *mut ::std::os::raw::c_void; } pub type CallbackRsaDec = ::std::option::Option< unsafe extern "C" fn( s...
Rust
0
="protocol/protocols/fast/illumina_nextera_xt_library_prep_part1.py", versions={APIVersion(2, 12), APIVersion(2, 13)}, settings=Settings( smoothie=SmoothieSettings( left=PipetteSettings(model="p20_multi_v2.1", id="P20SV202020070101"), right=PipetteSettings(model="p20_single_v2.0"...
Python
1
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # ht...
Python
1
finish() } } macro_rules! declare_test_case_fns { ( $Ty:ty ) => { impl_fmt! { impl[] Delegating<&$Ty>; const fn const_debug_fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { self.0.const_debug_fmt(f) } } const fn inner_delegat...
Rust
0
} /// Parses a string that may contain parameter bindings on the form `$abc_123`. This is the same /// function that is called when passing dynamically generated strings to the `query_dyn!` /// macro. /// /// Because this is a function there will some runtime overhead unlike the `query!` macro ...
Rust
0
#Faça um Programa que leia três números e mostre o maior deles. a = float(input("Digite um numero: ")) b = float(input("Digite um numero: ")) c = float(input("Digite um numero: ")) maior = max(a, b, c,) print("O maior numero é",maior)
Python
1
not enabled.") model_provider = model.name.split(".")[0] if model_provider == Provider.AMAZON.value: return _generate_embeddings_amazon(model, input, bedrock) elif model_provider == Provider.COHERE.value: return _generate_embeddings_cohere(model, input, task, bedrock) else: rai...
Python
1
# 1 - Contagem regressiva: Escreva um programa que peça ao usuário um número inteiro positivo e, usando um laço while, imprima uma # contagem regressiva de esse número até zero. c = 0 n = int(input('Digite um numero: ')) while c < n: n 1
Python
1
_takes_an_acceptable_time { use super::*; use std::time::{Duration}; #[allow(unused)] const ACCEPTABLE_TIME: Duration = Duration::from_millis(8); // Short for assert. We can be this brief becasue this is local to this module macro_rules! a { ( $tiles: expr, $from: expr, $t...
Rust
0
continue metadata = col_meta['metadata'] if not metadata: continue metadata_tz = metadata.get('timezone') if metadata_tz and metadata_tz != col.type.tz: converted = col.to_pandas() ...
Python
1
.z, mat_ptr: mat_ptr.clone(), }, Xyrect { x0: p0.x, x1: p1.x, y0: p0.y, y1: p1.y, k: p0.z, mat_ptr: mat_ptr.clone(), }, ...
Rust
0
fn to_dot(&self) -> String { self.alt.to_dot() } } } } macro_rules! implement_alternations { ($name: ident, $($alt: ident),*) => { $(impl<'a> $alt<'a> for $name<'a> {})* } } define_alternation!(Number, NumberAlt); define_alternation!(AbsNumber, AbsNumAlt); define_alternation!(UnMathO...
Rust
0
"""A grok.ContentProvider instance has references to the components it was registered for:: >>> grok.testing.grok(__name__) >>> from zope import component >>> from zope.contentprovider.interfaces import IContentProvider >>> from zope.publisher.browser import TestRequest >>> ctxt = AContext() >>> request = ...
Python
1
le_capacity_interval': (187, 375), 'vehicle_cost_min': 10.14, 'vehicle_cost_max': 393.75, 'n_vehicle_types': 252, 'demand_std_deviation': 600, 'n_scenarios': 10, 'carbon_emission_limit': 5000, 'renewable_energy_percentage': 0.66, 'special_treatment_capacit...
Python
1
; // regular: invalid signature // Proof is not a valid point, so Deserialize will result in an error. tx.proof[72] = tx.proof[72] % 250 + 1; assert_eq!( AccountType::verify_outgoing_transaction(&tx), Err(TransactionError::InvalidSerialization( SerializingError::InvalidValue...
Rust
0
# Test the vtkCellIntegrator from paraview import smtesting import os import os.path import sys import paraview paraview.compatibility.major = 3 paraview.compatibility.minor = 4 from paraview import servermanager from paraview import util smtesting.ProcessCommandLineArguments() servermanager.Connect() file1 = os.pa...
Python
1
""" Main class for data loading trained model and data. """ import torch from flex.tools.vposer_model_loader import load_model from flex.models.vposer_model import VPoser from flex.tools.registry import registry from pathlib import Path class Trainer: def __init__(self, cfg): # Setup cuda. ...
Python
1
f' % (np.mean(vina_min), np.median(vina_min))) if args.docking_mode == 'vina_dock': vina_dock = [r['vina']['dock'][0]['affinity'] for r in results] logger.info('Vina Dock : Mean: %.3f Median: %.3f' % (np.mean(vina_dock), np.median(vina_dock))) # check ring distribution print_ri...
Python
1
String, } #[allow(non_snake_case)] #[derive(Clone, Debug, Serialize, Deserialize)] struct AfreecaHlsKey { RESULT: usize, AID: String, } #[allow(non_snake_case)] #[derive(Clone, Debug, Serialize, Deserialize)] struct AfreecaChannelInfoData { //geo_cc: String, //geo_rc: String, //acpt_lang: String,...
Rust
0
from agency_swarm.tools import BaseTool from pydantic import Field from pytrends.request import TrendReq import pandas as pd import time class TrendAnalyzer(BaseTool): """ Analyzes keywords using Google Trends via pytrends. """ keywords: list = Field(..., description="List of keywords to analyze") ...
Python
1
::apply_to_event(json.as_bytes(), &mut event).unwrap(); assert_annotated_snapshot!(Annotated::new(event), @r###" { "logentry": { "formatted": "Public key pinning validation failed for 'example.com'" }, "request": { "url": "example.com" }, ...
Rust
0
# -*- coding: utf-8 -*- { 'name': "snailmail_account", 'description': """ Allows users to send invoices by post ===================================================== """, 'category': 'Hidden/Tools', 'version': '0.1', 'depends': ['account', 'snailmail'], 'data': [ 'views/res_confi...
Python
1
pr}; use combine::EasyParser; use hir::expr::{Assign, Binary, BinaryType, PlaceExpr}; #[test] fn group() { let src = "(foo)"; let expected: Expr<()> = Expr::Place(PlaceExpr::Var("foo")); assert_eq!(expr(0).easy_parse(src), Ok((expected, ""))); } #[test] fn precedence...
Rust
0
from factory import DatabaseFactory factory = DatabaseFactory() database = factory.process("mysql") print(database.get_db_uri())
Python
1
import torch from torch import nn from torch.nn import Sequential as Seq, Linear as Lin, Conv2d # 活性か関数を生成する関数 def act_layer(act, inplace=False, neg_slope=0.2, n_prelu=1): act = act.lower() if act == 'relu': layer = nn.ReLU(inplace) elif act == 'leakyrelu': layer = nn.LeakyReLU(neg_slope, i...
Python
1
inference service print("Testing math agent...") test_response = await agent.answer(["What is 2+2?"], max_tokens=50) print(f"Test response: {test_response[0]}") # Create pipeline pipeline = SyncGRPOPipeline( train_service=train_service, agent=agent, batch_size=batch_size, ...
Python
1
correct, len( self.data_transformation_artifact.transformed_test_object.dataset ), 100.0 * correct / len( self.data_transformation_artifact.transformed_test_object.dataset ...
Python
1
papi_SubscriptionItrerator; #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct blpapi_Identity { _unused: [u8; 0], } pub type blpapi_UserHandle = blpapi_Identity; pub type blpapi_UserHandle_t = blpapi_Identity; pub type blpapi_Identity_t = blpapi_Identity; pub type va_list = *mut ::std::os::raw::c_char; extern "C"...
Rust
0
import base58 import pytest from iscc_crypto.keys import key_generate from iscc_crypto.signing import sign_raw @pytest.fixture def test_keypair(): """Create a test keypair.""" return key_generate() def test_sign_raw_valid_signature(test_keypair): """Test that sign_raw produces a valid signature for simp...
Python
1
""" Contains classification rule and conclusion classes. """ from __future__ import annotations from typing import Union import numpy as np from decision_rules.core.condition import AbstractCondition from decision_rules.core.rule import AbstractConclusion from decision_rules.core.rule import AbstractRule class Clas...
Python
1
i', 'tr': 'Kuzeybatı Kafkasya', 'yue': '旁狄希臘文', 'yue-Hans': '旁狄希腊文', 'yue-Hant': '旁狄希臘文', 'zh-Hant': '旁狄希臘文'}, 'pnu': {'en': 'Jiongnai Bunu'}, 'pnv': {'en': 'Pinigura'}, 'pnw': {'en': 'Banyjima'}, 'pnx': {'en': 'Phong-Kniang'}, 'pny': {'en': 'Pinyin'}, 'pnz': {'en': 'Pana (Central African Republ...
Python
1
_or(Ordering::Equal)); for &strain in strains.iter() { difficulty += strain * weight; weight *= decay_weight; } difficulty * STAR_RATING_CONSTANT } <reponame>FlukerGames/ever-wallet-api<filename>src/sqlx_client/token_balances.rs<gh_stars>1-10 use crate::models::*; use crate::prelude::*; us...
Rust
0
izeFunction.getInputHistory` method # which lets us see all points it was evaluated on since its creation. # %% inputSample = rastrigin.getInputHistory() graph = rastrigin.draw(lowerbound, upperbound, [100] * dim) graph.setTitle("Rastrigin function") cloud = ot.Cloud(inputSample) cloud.setPointStyle("bullet") cloud.se...
Python
1
#!/usr/bin/env python def iit_index(a): i, last_i, k = 0, 0, 1 for i in range(0, len(a), 2): a[i][2] = a[i][1] last, last_i = a[i][2], i while 1<<k < len(a): i0, step, x = (1<<k) - 1, 1<<(k+1), 1<<(k-1); for i in range(i0, len(a), step): end_left = a[i - x][2]; end_right = a[i + x][2] if i + x < len(a...
Python
1
#[inline(always)] pub fn dma_in_dscr_empty_ch2_int_st(&self) -> DMA_IN_DSCR_EMPTY_CH2_INT_ST_R { DMA_IN_DSCR_EMPTY_CH2_INT_ST_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 6"] #[inline(always)] pub fn dma_out_dscr_err_ch2_int_st(&self) -> DMA_OUT_DSCR_ERR_CH2_INT_ST_R { ...
Rust
0
if reduced_const_vars: # only Bint types are supported assert all(var.output.dtype != "real" for var in reduced_const_vars) size = reduce(ops.mul, (var.output.size for var in reduced_const_vars)) # other ops like min/max can also be supported if necessary if op is ops.add: ...
Python
1
# Copyright (c) 2008 Twisted Matrix Laboratories. # See LICENSE for details. import sys try: from twisted.python import dist except ImportError: raise SystemExit("twisted.python.dist module not found. Make sure you " "have installed the Twisted core package before " ...
Python
1
ageProcessor, autospec=True) mock_oob_processor.find_oob_record_for_inbound_message = mock.CoroutineMock( return_value=None ) request_context.injector.bind_instance(OobMessageProcessor, mock_oob_processor) request_context.message = V20CredRequest() handler = test_mod...
Python
1
# -*- coding: utf-8 -*- # Generated by Django 1.11.27 on 2020-03-17 18:09 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("chroma_core", "0012_ha_json_notify"), ] operations = [ migrations.DeleteModel( ...
Python
1
from linguagempt1 import * if __name__ == '__main__': while True: op = menu() if op == 'C': create() elif op == "R": read() elif op == "U": update() elif op == "D": delete() elif op == "E": print("Exit") ...
Python
1
from machine import Pin import time class StepperMotor(object): def __init__(self,a,b,c,d): self.a=Pin(a, Pin.OUT) self.b=Pin(b, Pin.OUT) self.c=Pin(c, Pin.OUT) self.d=Pin(d, Pin.OUT) self.a.value(False) self.b.value(False) self.c.value(False)...
Python
1
% did) self.files[split].append({ 'img': img_file, 'lbl': lbl_file, }) def __getitem__(self, index): data_file = self.files[self.split][index] # load image img_file = data_file['img'] img = PIL.Image.open(img_fi...
Python
1
pos(1, 21), Msg::ShadowConst("foo".into()), ); err( "const foo: Int = 0; struct foo {}", pos(1, 21), Msg::ShadowConst("foo".into()), ); } } <reponame>evanacox/fuchsia<filename>src/connectivity/bluetooth/examples/bt-le-battery-service/s...
Rust
0
: if len(self.chat_history) >= 2: self.chat_history = self.chat_history[:-2] return f"[Client Logic Error] Agent provided an empty response with finish reason: {finish_reason_name}." else: return "[Client Logic Info] Agent prov...
Python
1
n(): pkits_pdf_path, output_path = sys.argv[1:] pkits_txt_file = tempfile.NamedTemporaryFile() subprocess.check_call(['pdftotext', '-layout', '-nopgbrk', '-eol', 'unix', pkits_pdf_path, pkits_txt_file.name]) test_descriptions = pkits_txt_file.read().decode('utf-8') # Extract secti...
Python
1
string = input() letters = set(list(string)) total = -1 for c in letters: count = string.count(c) if count%2==1: total += 1 if total == -1: print(0) else: print(total)
Python
1
.sockfd = x;} drop { /* c::close(self.sockfd); */ } } } use anyhow::{anyhow, Context, Result}; use biliup::client::{Client, LoginInfo}; use biliup::line::Probe; use biliup::video::{BiliBili, Studio, Video}; use biliup::{line, load_config}; use clap::{IntoApp, Parser, Subcommand}; use dialoguer::theme::ColorfulTheme...
Rust
0
|tr,||S|dkrB|jS|j|S(sg Construct a CommandSpec from a parameter to build_scripts, which may be None. N(RRRftfrom_environmentt from_string(R@tparam((sw/private/var/folders/vy/31wknkcs30l6xb2fzgwnrkh80000gn/T/pip-...
Python
1
mod com { use std::ops::{Deref, DerefMut}; use std::ptr; use winapi::Interface; use winapi::shared::winerror; use winapi::um::unknwnbase::IUnknown; // Based on Microsoft's `CComPtr`. pub struct ComPtr<T>(pub *mut T) where T: Interface; impl<T> ComPtr<T> where T: Interface { #...
Rust
0
/// /// # Safety /// /// The number of `config.columns` must not be zero. pub fn open(config: &DatabaseConfig, path: &str) -> io::Result<Database> { assert!(config.columns > 0, "the number of columns must not be zero"); let opts = generate_options(config); let block_opts = generate_block_based_options(confi...
Rust
0
ACCESS_KEY_ID)) elif len(response['Configuration']) <= 0: print("[-] GetFunction allowed for {} but no results [-]" .format(region)) else: print(response['Configuration']) print("\n") # print(response['Code']) print("Download link for {}:{}".fo...
Python
1
[0, 1], ls="--", lw=1.0, color="0.6") ax.scatter([fpr_a, fpr_b], [tpr_a, tpr_b], s=60, marker="o", color=CBLUE) ax.text(fpr_a, tpr_a, " A", va="center", ha="left") ax.text(fpr_b, tpr_b, " B", va="center", ha="left") # policy α-cap (vertical line at upper bound of I0 if provided) if alpha_cap is ...
Python
1
#hashing n = [5, 6, 4, 3, 3, 5, 6, 2, 2, 1, 1, 10] m = [10, 10, 5, 4, 3, 4, 3, 4, 5, 5, 1] for num in m: count = 0 for x in n: if x == num: count += 1 print(f"{num} occurs {count} times in n") #tc=o(n*m) #sc=o(1)
Python
1
"); match position { 0 => println!("{}", OUT_OF_SPEC), 0xFF => println!("{}", UNKNOWN), _ => println!("{}", position), } } pub fn dmi_mapped_address_interleave_position(position: u8) { if position != 0 { print!("\tInterleave Position: "); match position { ...
Rust
0
374e, 0x01, 0x81, 0x82)); m.insert(0x374f, STLinkInfo::new("V3", 0x374f, 0x01, 0x81, 0x82)); // Bridge m.insert(0x3753, STLinkInfo::new("V3", 0x3753, 0x01, 0x81, 0x82)); // 2VCP m }; } /// A helper struct to match STLink deviceinfo. #[derive(Clone, Default)] pub struct S...
Rust
0
{:.1f}%, early stopping F1 score: {:.3f}" .format(stopping_accuracy * 100, stopping_f1_score)) valtest_accuracy, valtest_f1_score = sess.run( [model.accuracy, model.f1_score], feed_dict=valtest_inputs) valtest_name = 'Test' if test else 'Validation' logging.log(22,...
Python
1
*from)) } else { match serde_json::from_str::<RemoveAgentPayload>(data) { Ok(payload) => Ok(uuid::Uuid::parse_str(&payload.agent_id)?), Err(_) => { if data == "null" || data.is_empty() || serde_json::from_str::<std::collections:...
Rust
0
42, "nameserver"), (43, "nicname"), (44, "mpm-flags"), (45, "mpm"), (46, "mpm-snd"), (47, "ni-ftp"), (48, "auditd"), (49, "tacacs"), (50, "re-mail-ck"), (53, "domain"), (54, "xns-ch"), (55, "isi-gl"), (56, "xns-auth"), (58, "xns-mail"), (61, "ni-mail"), (62, "...
Rust
0
64 (0x0000_0038, 0x1E00_0002),// EVEX_Vpbroadcastq_zmm_k1z_r64 (0x0000_00B6, 0x2500_0002),// EVEX_Vpermt2b_xmm_k1z_xmm_xmmm128 (0x0000_00B6, 0x2500_0002),// EVEX_Vpermt2b_ymm_k1z_ymm_ymmm256 (0x0000_00B9, 0x1600_0002),// EVEX_Vpermt2b_zmm_k1z_zmm_zmmm512 (0x0000_00B6, 0x2A00_0002),// EVEX_Vpermt2w_xmm_k1z_xmm_xmmm...
Rust
0
me, u16> for SmallLexer { fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = Result<TestLexeme, LexError>> + 'a> { Box::new(self.lexemes.iter().map(|x| Ok(*x))) } } impl<'input> NonStreamingLexer<'input, TestLexeme, u16> for SmallLexer { fn span_str(&self, _: Span) -> &'input ...
Rust
0
[0]) xtick_grid, ytick_grid = numpy.meshgrid(xtick_pos, ytick_pos) vmax = numpy.nanmax(matrix) vmin = numpy.nanmin(matrix) if not kwargs.get("color", None) and cmap is not None: use_cmap = True norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax, clip=False) else: use_...
Python
1
for name, c2_output, device in zip( self.net.Proto().external_output, c2_outputs, output_devices ): if not isinstance(c2_output, np.ndarray): raise RuntimeError( "Invalid output for blob {}, received: {}".format(name, c2_output) ) ...
Python
1
}) } else { let has_tail_zero = string.as_bytes().last() == Some(&0); if has_tail_zero { string.truncate(string.len() - 1); } Ok(StringZ { string, has_tail_zero }) } } } impl<'de> Deserialize<'de> for StringZ { fn deserialize<D>(de...
Rust
0
*Required features: `\"Win32_Networking_Clustering\"`*"] pub const CLUSCTL_RESOURCE_NETNAME_SET_PWD_INFOEX: CLUSCTL_RESOURCE_CODES = 16778010i32; #[doc = "*Required features: `\"Win32_Networking_Clustering\"`*"] pub const CLUSCTL_RESOURCE_NETNAME_DELETE_CO: CLUSCTL_RESOURCE_CODES = 16777598i32; #[doc = "*Required featu...
Rust
0
.iter().enumerate() { let width = name.len(); let s0 = format!(" {:>width$}", format!("({})", i + 1), width = width); let s1 = format!(" {:>width$}", name, width = width); h0.push_str(&s0); h1.push_str(&s1); } println!("#{}\n#{}\n# {}", h0, h1,...
Rust
0