text
string
label_name
string
labels
int64
it (name of the packfile, paths of the PackedFiles, type of the PackFile). let pack_file_type: u32 = serde_json::from_slice(&data).unwrap(); // We choose the right option, depending on our PackFile. match pack_file_type { 0 => unsafe ...
Rust
0
", }) } } <reponame>vivijj/franklin-crypto use crate::bellman::pairing::{ Engine, }; use crate::bellman::pairing::ff::{ Field, PrimeField, PrimeFieldRepr, BitIterator }; use crate::bellman::{ SynthesisError, }; use crate::bellman::plonk::better_better_cs::cs::{ Variable, ...
Rust
0
st] fn test8() { let inp: Sexpr = "(lam ((x A)) x)".parse().unwrap(); let out = Term::try_from(inp); let res = Term::Lam( "x".into(), Type::Var("A".into()), Term::Var("x".into()).into(), ); assert_eq!(out, Ok(res)); } #[test] f...
Rust
0
# Generated by Django 1.11.3 on 2017-10-05 19:31 import django_extensions.db.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('course_metadata', '0062_courserun_license'), ] operations = [ migrations.RemoveField( model...
Python
1
# 题目:给你一个字符串 s ,找出其中最长的回文子序列,并返回该序列的长度。 # 思路:与647.回文子串区别是子串是连续的,子序列可以不连续 ''' 1.确定dp数组及下标含义 dp[i][j] 表示区间范围[i,j] (注意是左闭右闭)的子串是否是回文子串 i,j分别表示字符子串的左右区间 2.确定递推公式 - s[i] == s[j] - s[i] != s[j] 3.初始化 单个字符的最长回文序列是 1 首先要考虑当i 和j 相同的情况,从递推公式:dp[i][j] = dp[i + 1][j - 1] + 2; 可以看出递推公式是计算不到 i 和j相同时候的情况。 3. 确定遍历顺序 画个状态转移图就知道了 必...
Python
1
".into())) ); } } pub mod tokenizer { use super::*; #[test] fn tokenizer1_u8() { assert_eq!( Tokenizer::tokenize("200 OK\r\nsomething".as_bytes()), Ok(( "\r\nsomething".as_bytes(), ("200".as_bytes(), "OK".as_bytes()).into() ...
Rust
0
{ let __start0 = __0.0.clone(); let __end0 = __0.0.clone(); let __temp0 = __action111( errors, input, &__start0, &__end0, ); let __temp0 = (__start0, __temp0, __end0); __action106( errors, input, __temp0, __0, ) } #[allow(unus...
Rust
0
ert a quaternion to its equivalent 3x3 matrix form using /// preallocated storage. /// /// The following example shows the result of converting an arbitrary /// quaternion to its matrix form using the Euler-Rodrigues formula. /// /// # Example /// /// ``` /// # use cglinalg::{ ...
Rust
0
(all_preds), axis=1) all_labels = np.concatenate(all_labels) acc = np.mean((all_preds > 0.5) == all_labels) stats_tracker.add_stat('acc', -1 * acc, 1) auc = roc_auc_score(y_true=all_labels, y_score=all_preds) stats_tracker.add_stat('auc', -1 * auc, 1) el...
Python
1
foreground for class c if classes == "present" and fg.sum() == 0: continue if C == 1: if len(classes) > 1: raise ValueError("Sigmoid output possible only with 1 class") class_pred = probas[:, 0] else: class_pred = probas[:, c] ...
Python
1
VSL_SS_ED_4C_MOM: u32 = 13; pub const VSL_SS_ED_SUM: u32 = 67; pub const VSL_SS_ED_2R_SUM: u32 = 68; pub const VSL_SS_ED_3R_SUM: u32 = 69; pub const VSL_SS_ED_4R_SUM: u32 = 70; pub const VSL_SS_ED_2C_SUM: u32 = 71; pub const VSL_SS_ED_3C_SUM: u32 = 72; pub const VSL_SS_ED_4C_SUM: u32 = 73; pub const VSL_SS_ED_KURTOSIS:...
Rust
0
"""Data models and constants.""" from dataclasses import dataclass from typing import Tuple, Deque import time from collections import deque TRIGGER_KEYWORDS = ["princess", "selene", "how are you", "joke", "fun", "guys", "jema"] MESSAGE_HISTORY_LIMIT = 1000 MESSAGE_HISTORY_TIME_LIMIT = 3600 # 1 hour in seconds @data...
Python
1
from __future__ import absolute_import, division, print_function import boost_adaptbx.boost.python as bp ext = bp.import_ext("scitbx_graphics_utils_ext") from scitbx_graphics_utils_ext import * from cctbx.array_family import flex def color_by_property( properties, selection, color_all=False, gradient_t...
Python
1
": "MSASCui.exe", "avast": "AvastUI.exe", "avg": "AVGUI.exe", "norton": "Norton.exe", "mcafee": "mcuimgr.exe", "kaspersky": "avpui.exe", "bitdefender": "bdagent.exe", # Virtualization "vmware": "vmware.exe", ...
Python
1
Spec for _0_RXPKTU_E_DSCR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [_0_rxpktu_e_dscr::R](R) reader structure"] impl crate::Readable for _0_RXPKTU_E_DSCR_SPEC { type Reader = R; } #[doc = "`reset()` method sets _0_RXPKTU_E_DSCR to value 0"] impl crate::Resettable for _0_RXPKTU_E_DSCR_SPEC { #...
Rust
0
(u32, u32), pub background: ImageConf, pub a: Option<ImageConf>, pub b: Option<ImageConf>, pub x: Option<ImageConf>, pub y: Option<ImageConf>, pub up: Option<ImageConf>, pub down: Option<ImageConf>, pub left: Option<ImageConf>, pub right: Option<ImageConf>, pub start: Option<Imag...
Rust
0
ake_credential_response) => { let AuthenticatorMakeCredentialResponse { fmt, auth_data, att_stmt, } = make_credential_response; // The expected response is split to only assert the non-random parts. ...
Rust
0
# Import the numpy and scipy packages import numpy as np from scipy.sparse import csr_matrix from snowdrop.src.numeric.solver.AIM.Shifts import Shiftright def Obstruct(cof,cofb,neq,nlag,nlead): """ Construct the coefficients in the observable structure. Input arguments: cof structura...
Python
1
g("[误错奖抽盘转".split("").reverse().join("") + _0xefa201 + " :]".split("").reverse().join("") + _0x323f95); } } } catch (_0x1a5486) { console.log(_0x1a5486); } } async ["userTask"]() { console.time("[号账".split("").reverse().join("") + this.index + "]" + "耗时"); const...
Python
1
from pyupbit.quotation_api import * def test_get_tickers_defaults(): tickers = get_tickers() assert "KRW-BTC" in tickers assert len(tickers) != 0 def test_get_tickers_with_fiat(): fiats = ["KRW", "BTC", "USDT"] for fiat in fiats: fiat_tickers = get_tickers(fiat) for ticker in f...
Python
1
# RN-Fs aren't nodes in CMN, but we can list RN-F ports print("RN-F ports:") for port in S.ports(properties=cmn_enum.CMN_PROP_RNF): print(" %s" % port) if opts.home_nodes: print("Home node ports:") for port in S.ports(): if port.has_properties(cmn_enum.CM...
Python
1
// a resource can be written to an AccessPath if the data does not exists or // it was deleted (MoveFrom) let can_write = match data_store.borrow_resource(addr, &ty) { Ok(None) => true, Ok(Some(_)) => false, Err(e) => match e.major_status() { StatusCode::MISSING_DATA => ...
Rust
0
"""Proxy requests to GA4GH TRS servers (e.g. Dockstore). Information on TRS can be found at https://github.com/ga4gh/tool-registry-service-schemas. """ import logging from galaxy.web import expose_api from galaxy.workflow.trs_proxy import ( parse_search_kwds, TrsProxy, ) from . import ( BaseGalaxyAPICont...
Python
1
分母最小为1,得分不会大于1 new_matches = counts - matched_count max_possible = max(1, len(gen_nodes) - 1) granu_score[meta] = min(new_matches, max_possible) / max_possible matched_count = counts # 确保边匹配的严谨性,检查真正匹配的边 gen_edges = [] for i in range(len(gen_nodes) - 1): gen_edge...
Python
1
oker.start() # Register agents for i in range(5): await broker.register_agent(f"agent_{i}") # Send multiple messages concurrently tasks = [] for i in range(10): message = AgentMessage( ...
Python
1
under the License. //===----------------------------------------------------------------------===// #![feature(async_closure)] mod plt; mod polkadot; use std::collections::HashMap; use std::sync::Arc; use async_trait::async_trait; use futures; use futures::FutureExt; use tesseract::Error; use tesseract::ErrorKin...
Rust
0
) { biome.presets.iter().for_each(|preset| { self.presets .add(vec![preset[0], preset[1]], biome.to_owned()) .expect("Unable to add biome preset.") }) } /// Sample the closet possible #`count` biomes pub fn get_biomes(&self, temperature: f64, humi...
Rust
0
keyPublicFromXprv", "inputs": [ {"name":"answerId","type":"uint32"}, {"name":"xprv","type":"bytes"} ], "outputs": [ {"name":"pub","type":"uint256"} ] }, { "name": "naclSignKeypairFromSecretKey", "inputs": [ {"name":"answerId","type":"uint32"}, {"name":"secret","type":"uint256"}...
Rust
0
name = 'tRNA-Ser1' if name == 'tRNA-Ser' else "S1" else: # 单独把序列生成出来 trnaName = self.factory.refineName(self.usedName + "_" + str(self.start) + "_" + str(self.end), remain_words=".-") self.leu_ser...
Python
1
ZendeskCustomFieldsNames.HAS_PUBLISHED_COLLECTIVE_OFFERS.value: has_collective_offers, ZendeskCustomFieldsNames.JURIDIC_NAME.value: venue.name, ZendeskCustomFieldsNames.PC_PRO_STATUS.value: pc_pro_status, ZendeskCustomFieldsNames.PRODUCT_VENUE_ID.value: ven...
Python
1
# Copyright 2021 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
Python
1
QuadrupleOrigin(error)) if error==format!("Quadruple transcript `key_times_lambda` expected to have type `Masked` with origin of type `UnmaskedTimesMasked({:?},_)`, but found transcript of type {:?}", key_transcript.transcript_id, quadruple.unwrap().key_times_lambda().transcript_type)) ); } // A randomized...
Rust
0
= 4.0, cls_embed = True, sep_pos_embed = True, trunc_init = False, no_qkv_bias = False, if_mask = False, mask_ratio_min = 0.5, mask_ratio_max = 1.0, mask_ratio_mu = 0.55, mask_ratio_std = 0.25, ).to(device) feature = torch.randn(4, 1, 64,...
Python
1
about: "Converts a PNG to a TXTR.") (@arg input: -i --input +takes_value +required "Input PNG file to convert.") (@arg output: -o --output +takes_value +required "Output path to write the TXTR file.") (@arg format: -f --format +takes_value +required { ...
Rust
0
bg_attr_hi_shift = 0; self.frame.clear(); self.frame_count = 0; self.odd_frame = false; } /// Debug function to show the cartridge CHR Patterns #[allow(dead_code)] fn render_chr_pattern(&mut self) { for tile_y in 0..16 { for tile_x in 0..16 { ...
Rust
0
# Reverse a Word word = input("Enter a word") # Reversed a word reversed_word = word[::-1] #print the reversed word print("Reversed_Word:",reversed_word)
Python
1
-proxy //! A middleware that applies a layer to the inner `Service`'s (or //! `NewService`'s) response. use futures::{try_ready, Future, Poll}; /// Layers over services such that an `L`-typed Layer is applied to the result /// of the inner Service or NewService. #[derive(Clone, Debug)] pub struct OnResponseLayer<L>(L...
Rust
0
0.4124564, 0.3575761, 0.1804375, 0.2126729, 0.7151522, 0.0721750, 0.0193339, 0.1191920, 0.9503041 ]; let computed = rgb_to_xyz_matrix::<Srgb, f64>(); for (e, c) in expected.iter().zip(computed.iter()) { assert_relative_eq!(e, c, epsilon = 0.000001) } ...
Rust
0
"""Liquid Sense LPC."""
Python
1
, pub sread: Option<unsafe extern "C" fn(cq: *mut fid_cq, buf: *mut c_void, count: usize, cond: *const c_void, timeout: c_int) -> isize>, pub sreadfrom: Option<unsafe extern "C" fn(cq: *mut fid_cq, buf: *mut c_void, count: usize, src_addr: *mut fi_addr_t, cond: *const c_void, timeout: c_int) -> isize>, pub signal: O...
Rust
0
from connector.dockercommand import Container import regex as re import json from logging import getLogger logger = getLogger("ServerStates") logger.info("Loading...") def get_health_status(container: Container) -> str: """ Get State.Health.Status of the container """ try: responce = container.in...
Python
1
yboardInput::Function(42)); t(KeyboardInput::Char('a')); t(KeyboardInput::Char('☃')); } #[test] fn example() { use super::KeyboardInput; use std::collections::BTreeMap; let mut map = BTreeMap::new(); map.insert(KeyboardInput::Up, "UP"); map.insert(Key...
Rust
0
import boto3 from pydantic import SecretStr def fetch_secret(secret_name: str) -> SecretStr: """Fetch a secret using Boto3.""" client = boto3.client("secretsmanager") response = client.get_secret_value(SecretId=secret_name) return SecretStr(response["SecretString"])
Python
1
); result } fn execute_and_import_block( &self, operation: &mut ClientImportOperation<Block, Blake2Hasher, B>, origin: BlockOrigin, hash: Block::Hash, import_headers: PrePostHeader<Block::Header>, justification: Option<Justification>, body: Option<Vec<Block::Extrinsic>>, new_cache: HashMap<CacheKe...
Rust
0
s targets are removed. Args: blender_object (bpy.types.Object): The Blender object from which to remove shape keys. cutoff (float): The weight threshold below which shape keys will be removed. Defaults to 0.0001. """ keys = blender_object.data.shape_keys if keys...
Python
1
_resource, mcp_tool @get("/decorator-tool") @mcp_tool(name="decorator_tool") async def decorator_tool(message: str) -> dict[str, str]: """A tool marked with decorator.""" return {"message": f"Processed: {message}"} @get("/decorator-resource") @mcp_resour...
Python
1
Request = (Framed<Io, v3::codec::Codec>, Option<Delay>), Response = (), Error = MqttError<Err>, >, V5: Service< Request = (Framed<Io, v5::codec::Codec>, Option<Delay>), Response = (), Error = MqttError<Err>, >, { type Request = Io; type Response = (); ...
Rust
0
7C3B65A.root' #'rfio:/afs/cern.ch/user/a/asakharo/scratch0/events/run_66740_FED_errors.root' #'rfio:/castor/cern.ch/user/a/asakharo/CMSevents/run_66740_FED_errors.root' #'/store/data/Commissioning09/Cosmics/RAW/v1/000/079/035/422F78CA-7019-DE11-A599-001617E30CD4.root' '/store/data/Commissioning09/Cosmic...
Python
1
| object providing access to the document-level settings for this document. Creates a default settings part if one is not present. """ try: return self.part_related_by(RT.SETTINGS) except KeyError: settings_part = SettingsPart.default(self.package) ...
Python
1
66c2-a9f4-11eb-bcbc-0242ac130002"] struct TestDeriveStruct<T> where T: Clone, { _value: T, } fn test_impl_type_uuid(_: &impl TypeUuid) {} #[test] fn test_generic_type_uuid_derive() { let test_struct = TestDeriveStruct { _value: 42 }; test_impl_type_uuid(&tes...
Rust
0
e_list { let editor = match env::var("EDITOR") { Ok(editor) => editor, Err(_) => return Err(io::Error::new(io::ErrorKind::Other, "EDITOR environment variable has to be set")), }; let mut editor_split = editor.split(" "); ...
Rust
0
rlatecol(&mut self) -> RTRYLMTORLATECOL_W { RTRYLMTORLATECOL_W { w: self } } #[doc = "Bit 6 - Enable transmit frame corruption due to AMBA (AHB) error interrupt"] #[inline(always)] pub fn ambaerr(&mut self) -> AMBAERR_W { AMBAERR_W { w: self } } #[doc = "Bit 7 - Enable transmit c...
Rust
0
from flask import Flask, render_template from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField from wtforms.validators import DataRequired, Email, Length class LoginForm(FlaskForm): email = StringField('Email', validators=[DataRequired(), Email(allow_empty_local=True)]) pa...
Python
1
# This is a demo file for using AES for it's main purposes in this project. # Once this, and other files like it, are no longer needed, a gist will be made from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad from Crypto.Random import get_random_bytes # The passphrase and message to be passed aro...
Python
1
context_id, "failed to free callout-lock after auth response: {}", e ); } } } use crate::pipeline::*; use crate::opcodes::*; use crate::structs::*; use crate::memory::*; use crate::flags::*; use crate::decoding::*; #[allow(dead_code)] //remove after design stuff is done /// The...
Rust
0
uctOpt; // COPY-PASTED from cargo-geiger, review this later. Is it needed for all cargo plugins? #[derive(StructOpt)] #[structopt(bin_name = "cargo")] pub enum Opts { #[structopt(name = "walk")] /// Run a command for each level of a Rust crate dependency tree. Walk(Args), } #[derive(StructOpt)] pub struct...
Rust
0
func: Arc<Mutex<FnMut(ArrayViewMutD<f32>, Option<&OpInstance>)>>, op_id: Option<OpID>, } impl Initialiser { pub fn new<F: 'static + FnMut(ArrayViewMutD<f32>, Option<&OpInstance>)>(name: String, func: F) -> Self { Initialiser { name: name, func: Arc::new(Mutex::new(func)), op_id: None, } } pub fn wra...
Rust
0
fn start_p2p_session(mut p2p_session: ResMut<P2PSession>, cmd: Res<CommandLineArgs>) { for (player_handle, player_address) in cmd.players.iter().enumerate() { if player_address == "local" { p2p_session .add_player(PlayerType::Local, player_handle) .unwrap(); ...
Rust
0
# apps/users/urls.py from django.urls import path from . import views urlpatterns = [ path("register/", views.register, name="register"), ]
Python
1
#[test] fn exec_from_witness_100times_no_load() { let from = ExecFrom::Witness; let res = Ok(101); test_exec(0b0000, 100, 101, 1, from, res); } #[test] fn exec_from_witness_1times_and_load_before() { let from = ExecFrom::Witness; let res = Ok(5); test_exec(0b0001, 1, 1, 1, from, res); } #[test...
Rust
0
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from scalar_fastapi.scalar_fastapi import get_scalar_api_reference from slowapi import _rate_limit_exceeded_handler from slowapi.errors import RateLimitExceeded from slowapi.middleware import SlowAPIMiddleware from app.core.settings import ...
Python
1
ol_interest_accumulated - dot_pool_protocol_interest) DOT * 2 + 170 ETH * 3 = (150 + 0.00294 - 0.000294) * 2 + 170 * 3 pool_total_interest: dot_pool_protocol_interest * 2 = 0.000294 * 2 */ assert_eq!( get_protocol_total_values_rpc(), Some(ProtocolTotalValue { pool_total_supply_in_usd: dollars(670_...
Rust
0
import pygame SCREEN_WIDTH = 1200 SCREEN_HEIGHT = 800 FPS = 60 TITLE = "Inversion" # icon = pygame.image.load("assets/images/icon.png") # 색깔 WHITE = (255, 255, 255) BLACK = (0, 0, 0)
Python
1
> { fn from((typ, flags): (Type<Id, ArcType<Id>>, Flags)) -> ArcType<Id> { ArcType::with_flags(typ, flags) } } #[derive(Clone)] pub struct TypeFieldIterator<'a, T: 'a> { typ: &'a T, current: usize, } impl<'a, Id: 'a, T> Iterator for TypeFieldIterator<'a, T> where T: TypePtr<Id = Id>, { ...
Rust
0
_tags.txt"); static ANSIBLE_ROLES: &str = include_str!("../data/ansible_roles.txt"); static ANSIBLE_TASKS: &str = include_str!("../data/ansible_tasks.txt"); lazy_static::lazy_static! { pub static ref BOOTLOG_LIST: Vec<&'static str> = BOOTLOG.lines().collect(); pub static ref CFILES_LIST: Vec<&'static str> = CF...
Rust
0
blem( fine_model, coarse_model, parameter_extraction, method="sd", max_iter=8, tol=2.5e-1, use_backtracking_line_search=False, ) space_mapping.solve() assert np.abs(fine_model.cost_functional_value - 0.008607376518100516) <= 2e-8 def test_ocsm_ncg_FR...
Python
1
ved: Option<&'input HashMap<String, Span>>, } #[derive(Debug)] pub struct SubTypeConstraint<'input> { sub_type_strategy: &'input RpSubTypeStrategy, reserved: &'input HashMap<String, Span>, field_idents: &'input HashMap<String, Span>, field_names: &'input HashMap<String, Span>, untagged: &'input mut...
Rust
0
KEY_ID | KEY_NAME | KEY_YIELD | KEY_TEMPERATURE | KEY_PH | KEY_POSITIVE_ION | KEY_NEGATIVE_ION | KEY_UNDISSOCIATED | KEY_GAS | KEY_MINOR | KEY_TOTAL_POSITIVE_ION | KEY_TOTAL_NEGATIVE_ION | KEY_TOTAL_UNDISSOCIATED | KEY_TOTAL_GAS | KEY_TOTAL_MINOR | ...
Rust
0
import numpy as np import torch import torch.nn as nn import torch.optim as optim import matplotlib.pyplot as plt # 设置中文字体为黑体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 正常显示负号 plt.rcParams['axes.unicode_minus'] = False # --------------------------------------------- # 1. 参数配置:确保使用GPU(NVIDIA 4060 Laptop, CUDA 12) # ...
Python
1
mod commit_analyzer; mod config; mod config_context; mod diff_analyzer; mod error; mod event; mod file_analyzer; mod git_blame; mod hunk_analyzer; mod identity; mod line_analyzer; mod person; mod repo; mod repo_analyzer; mod repo_config; mod repo_info; pub mod test; mod utils; mod work_stats; mod workspace; mod worksp...
Rust
0
g()); classes } } impl IntoPropValue<StyleSource<'static>> for Sheet { fn into_prop_value(self) -> StyleSource<'static> { self.into() } } #[cfg_attr(documenting, doc(cfg(feature = "parser")))] #[cfg(feature = "parser")] mod feat_parser { use std::borrow::Cow; use super::*; im...
Rust
0
<T: SimdComplexField, D: Dim, S: Storage<T, D, D>> SquareMatrix<T, D, S> { /// The symmetric part of `self`, i.e., `0.5 * (self + self.transpose())`. #[inline] pub fn symmetric_part(&self) -> OMatrix<T, D, D> where DefaultAllocator: Allocator<T, D, D>, { assert!( self.is_...
Rust
0
_RESOURCE_ENUM_ITEM_VERSION: u32 = 1u32; #[doc = "*Required features: `\"Win32_Networking_Clustering\"`*"] pub const CLUSTER_RESOURCE_ENUM_ITEM_VERSION_1: u32 = 1u32; #[doc = "*Required features: `\"Win32_Networking_Clustering\"`*"] pub type CLUSTER_RESOURCE_RESTART_ACTION = i32; #[doc = "*Required features: `\"Win32_N...
Rust
0
: `\"Win32_Storage_OfflineFiles\"`*"] pub const OFFLINEFILES_ITEM_TYPE_FILE: OFFLINEFILES_ITEM_TYPE = 0i32; #[doc = "*Required features: `\"Win32_Storage_OfflineFiles\"`*"] pub const OFFLINEFILES_ITEM_TYPE_DIRECTORY: OFFLINEFILES_ITEM_TYPE = 1i32; #[doc = "*Required features: `\"Win32_Storage_OfflineFiles\"`*"] pub con...
Rust
0
from pathlib import Path import os, dotenv import openai from openai import OpenAI dotenv.load_dotenv() openai.api_key = os.getenv("OPENAI_API_KEY") client = OpenAI() def get_or_create_assistant() -> str: NAME = "Study Q&A Assistant" for a in client.beta.assistants.list().data: if a.name == NAME: ...
Python
1
.") args = parser.parse_args() # Meta-config exp_name = args.exp_name exp_config = load_config(f"configs/{exp_name}.yaml") num_test_samples = args.num_test_samples debug_indices = args.debug_indices if args.debug_indices is None \ else [int(x) for x in args.debug_indices.split(",")] ...
Python
1
import pandas as pd import matplotlib.pyplot as plt import statsmodels.formula.api as smf w = pd.read_csv('ch5-1.csv') w_n = w.iloc[:,1:5] model_lm = smf.ols(formula = 'weight ~ food', data = w_n) result_lm = model_lm.fit() result_lm.summary() print(result_lm.summary()) plt.figure(figsize = (10,7)) plt.scatter(w.fo...
Python
1
() } fn len_q_byte(byte: u8) -> usize { match byte { b' ' => 1, b'-' | b'!' | b'*' | b'+' | b'/' | b'0'..=b'9' | b'a'..=b'z' | b'A'..=b'Z' => 1, _ => 3, } } // -- Base64 fn decode_b<T: AsRef<[u8]>>(encoded: T) -> (Vec<u8>, Vec<Defect>) { let mut defects = Vec::new(); let conf...
Rust
0
import asyncio import numpy as np async def left_or_right(frame, coordinates): frame_horizontal_center = frame.shape[1] / 2 frame_vertical_center = frame.shape[0] / 2 object_center_x = (coordinates[0] + coordinates[2]) / 2 object_center_y = (coordinates[1] + coordinates[3]) / 2 if object_center_x...
Python
1
: str}, ) # drop rows with missing values df = df.dropna(subset=["subject_id", "hadm_id", "hcpcs_cd"]) # sort by sequence number (i.e., priority) df = df.sort_values(["subject_id", "hadm_id", "seq_num"], ascending=True) # group by patient and visit group_df = df.g...
Python
1
from pyspark.sql import SparkSession spark = ( SparkSession.builder.appName("CSV to Iceberg REST Catalog") .config("spark.sql.catalog.iceberg", "org.apache.iceberg.spark.SparkCatalog") .config("spark.sql.catalog.iceberg.type", "rest") .config("spark.sql.catalog.iceberg.uri", "http://127.0.0.1:8181") ...
Python
1
(words(( '__FILE__', '__LINE__', 'break', 'case', 'catch', 'classdef', 'continue', 'do', 'else', 'elseif', 'end', 'end_try_catch', 'end_unwind_protect', 'endclassdef', 'endevents', 'endfor', 'endfunction', 'endif', 'endmethods', 'endproperties', 'endsw...
Python
1
def format_bytes(bytes: int) -> str: if not isinstance(bytes, int) or bytes < 0: return "Invalid" LABELS = ("MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB") BASE = 1024 value = bytes / BASE for label in LABELS: value /= BASE if value < BASE: return f"{value:.3f}...
Python
1
Helper method for stabilize. Return each frame of the input video as a NumPy array along with miscellaneous video features. Input: * input_path: The path to the unstabilized video. Output: A tuple of the following items in order. * unstabilized_frames:...
Python
1
#!/usr/bin/env python import sys sys.path.append('/usr/share/inkscape/extensions') # or another path, as necessary sys.path.append('/Applications/Inkscape.app/Contents/Resources/extensions') sys.path.append('C:\Program Files\Inkscape\share\extensions') #import xml.etree.ElementTree as ET #ET.register_namespace('figuref...
Python
1
# Copyright 2023 Google LLC # # 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 writing, s...
Python
1
ap::Map<K, (V, AtomicU64)>>, } impl<K, V> TimeBasedCache<K, V> where K: 'static + Hash + Ord + Sync + Send + Display, V: 'static + Clone + Sync + Send + CountedObject { pub fn new(ttl_sec: u64, name: String) -> Self { let map = Arc::new(lockfree::map::Map::new()); Self::gc(map.clone(), tt...
Rust
0
{ fn summarize_author(&self) -> String; fn summarize(&self) -> String { format!("Read more from {}...", self.summarize_author()) } } pub struct NewsArticle { pub headline: String, pub location: String, pub author: String, pub content: String, } /* impl Summary for NewsArticle { ...
Rust
0
import datetime as dt from django import forms from bridge import context from bridge.choices import FIELDS_CHOICES from .models import Storage DECIMAL_FORMAT = dict(decimal_places=2, max_digits=9, min_value=0.01, max_value=100, ...
Python
1
let pieces = op.id_pieces(); macro_rules! overlap { [$name:expr] => {{ lints.error.push(lint::Lint::id_overlap( format!( "Attempting to operate twice on {}", $name ) )); }}} if pieces.new_id == ...
Rust
0
else { '\0' } } use sp_cid::Cid; use sp_ipld::Ipld; use std::{ path::PathBuf, rc::Rc, }; use structopt::StructOpt; use yatima_cli::file::store::{ FileStore, FileStoreOpts, }; #[cfg(not(target_arch = "wasm32"))] use yatima_cli::repl; use yatima_core::{ name::Name, parse::parse_cid, }; use yatima_...
Rust
0
self.state.reg_sp = val, } } #[allow(dead_code)] fn check_condition(&self, cond_id: CondId) -> bool { return match cond_id { CondId::NZ => !self.state.flags.zf, CondId::Z => self.state.flags.zf, CondId::NC => !self.state.flags.cf, CondId::C ...
Rust
0
/ Block::SPRITESHEET_WIDTH as f32; const UV_TILE_SIZE_PADDED_Y: f32 = Block::TILE_SIZE_PADDED as f32 / Block::SPRITESHEET_HEIGHT as f32; const FACES: [[usize; 4]; 6] = [ [5, 4, 0, 1], // Close; RTC, LTC, LBC, RBC [7, 6, 2, 3], // Far; LTF, RTF, RBF, LBF [6, 5, 1, 2], // Right;...
Rust
0
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By import time, json cService = webdriver.ChromeService() driver = webdriver.Chrome(service=cService) # driver.get('https://www.lafeltrinelli.it/indici/libri-autori') # div_element = driver.find_e...
Python
1
as usize); if abs_pruning_horizon > metadata.effective_pruned_height { txn.set_metadata( MetadataKey::EffectivePrunedHeight, MetadataValue::EffectivePrunedHeight(abs_pruning_horizon), ); } commit(db, txn)?; ...
Rust
0
credit(): driver.switch_to.default_content() driver.find_element_by_xpath('//*[@id="SmallNextBtnImage"]').click() driver.switch_to.frame(driver.find_element_by_xpath('//*[@id="ifrmBookStep"]')) wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="YYMMDD"]'))).send_keys(birth_entry.get()) drive...
Python
1
); assert_eq!(::std::mem::align_of::<Compositor_OverlaySettings>() , 4usize); } impl Clone for Compositor_OverlaySettings { fn clone(&self) -> Self { *self } } #[repr(C)] #[derive(Debug, Copy)] pub struct CameraVideoStreamFrameHeader_t { pub eFrameType: EVRTrackedCameraFrameType, pub nWidth: u32, pu...
Rust
0
ough)?; // 解除原质押资产 T::Currency::unreserve(&who, T::KittyReserve::get()); Owner::<T>::insert(kitty_id, Some(her.clone())); Self::deposit_event(Event::KittyTransfer(who,her,kitty_id)); Ok(()) } #[pallet::weight(0)] pub fn breed(origin: OriginFor<T>, kitty_id_mom: T::KittyIndex, kitty_id_dad: T::K...
Rust
0
import pandas as pd import os wsFolder = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") output_file = f"{wsFolder}/saves/project_contrast_distance_as_prompt_ranker/baseline/step_1.txt" rows = [] PROMPT_ID_PREFIX = "**Prompt " PROMPT_ID_SUFFIX = "**\n" current_row = None STATE = "WAITING_PROMPT" with o...
Python
1
Mode: ///# Monochrome Gameboy, SGB and CGB in Non-CGB Mode: BG Display /// When Bit 0 is cleared, both background and window become blank (white), /// and the Window Display Bit is ignored in that case. /// Only Sprites may still be displayed (if enabled in Bit 1). /// /...
Rust
0