text string | label_name string | labels int64 |
|---|---|---|
'''
We are using modules: 'openai', 'python-dotenv', 'os'.
make sure these versions >= 'python-dotenv 0.21.0', 'openai 1.0.0'.
When using this file. PLEASE make sure to use your own API key from OpenAI and place it in a .env file
with the name 'API_KEY'. Otherwise, you will need to make adjustments to match your named... | Python | 1 |
0x02: ('1', '!'),
0x03: ('2', '@'),
0x04: ('3', '#'),
0x05: ('4', '$'),
0x06: ('5', '%'),
0x07: ('6', '^'),
0x08: ('7', '&'),
0x09: ('8', '*'),
0x0a: ('9', '('),
0x0b: ('0', ')'),
0x0c: ('-', '_'),
0x0d: ('=', '+'),
0x... | Python | 1 |
contains a nonnullable pointer, we don't use a
// separate discriminant. Instead we use that pointer field to differentiate
// between the 2 cases.
// Also, if the variant with the nonnullable pointer has no other fields
// then we simply express the enum as just a pointer and not wrap it
// in a struct.
use std::me... | Rust | 0 |
if _M_X64 || _M_ARM64
if cfg!(any(target_arch = "x86_64", target_arch = "aarch64")) {
if !is_wow {
access_type = KEY_READ;
alt_access_type = KEY_READ;
needs_alt = false;
}
}
// 64-bit key on WIN64 || is_wow, 32-bit key on WIN32 && !is_wow
RegOpenKeyE... | Rust | 0 |
load_metadata(input_file_4)
# Process videos
#process_videos(video_paths2, metadata)
#Reorder keys in metadata
#for video_name in metadata:
#metadata[video_name] = reorder_keys(metadata[video_name], key_order)
# Save updated metadata
#save_metadata(metadata, output_file)
... | Python | 1 |
type Target = BitSlice<C, T>;
fn deref(&self) -> &Self::Target {
self.pointer.into()
}
}
impl<C, T> DerefMut for BitBox<C, T>
where C: Cursor, T: Bits {
fn deref_mut(&mut self) -> &mut Self::Target {
self.pointer.into()
}
}
impl<C, T> Drop for BitBox<C, T>
where C: Cursor, T: Bits {
fn drop(&mut self) {
... | Rust | 0 |
.tagName != 'div':
continue
has_p = False
for pChildren in divNode.childNodes:
if isinstance(pChildren, Element) is False:
continue
if pChildren.tagName == 'span':
raise InvalidTextCue(
... | Python | 1 |
::from_raw_parts(self.ptr, self._mem_len, 0) }
}
/// Copies the given memory area into a Vector.
fn cpy_into_vec(&self) -> Vec<u8> {
let mut vec = vec![0u8; self.len];
vec.copy_from_slice(&self.deref());
vec
}
/// Copies the given memory area into a Box.
fn cpy_into_box(&self) -> Box<[u8]> {
let mut vec... | Rust | 0 |
use parser::{Source, Unit};
use crate::print::ValuePrinter;
use crate::Result;
pub(crate) fn print(source: &Source, w: &mut dyn ValuePrinter, unit: &Unit) -> Result<()> {
if let Some(path) = source.path(unit) {
write!(w, "{}", path)?;
if source.line() != 0 {
write!(w, ":{}", source.li... | Rust | 0 |
MotionType::Rapid => {[1.0, 0.1, 0.0, 1.0]}
MotionType::Linear => {[0.0, 0.4, 1.0, 1.0]}
};
path.extend_from_slice(&[
Vertex {
pos : (p0.pos).into(),
// col : [0.2, 0.2, 0.2, 1.0],
col,
... | Rust | 0 |
= (*todos).clone();
for t in &mut v {
t.done = *toggle_all;
}
todos.set(v);
toggle_all.set(!*toggle_all);
})
};
html! {
<section class="todo-app">
<ToDoHeader {onedit} />
<ToDoList todos={(*todos).clone()} {onremove} {... | Rust | 0 |
# Generated by Django 5.1.2 on 2024-10-24 07:19
import django.utils.timezone
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
]
operations = [
migrations.CreateModel(
... | Python | 1 |
import threading
import time
def eat_breakfast():
time.sleep(3)
print("you drink coffee")
def drink_coffee():
time.sleep(4)
print("you sleep ")
def study():
time.sleep(5)
print("you study")
x = threading.Thread(target=eat_breakfast,args=())
x.start()
y = threading.Thread(t... | Python | 1 |
, "fruiting", "mature"]
for stage in valid_growth_stages:
plant_data = {
"name": f"{catalog_plant.name}_{stage}",
"species": catalog_plant.species,
"position_x": 1.0,
"position_y": 1.0,
"garden_id": test_garden.... | Python | 1 |
T], x: f64) -> T;
}
pub struct NearestNeighbor;
impl<T: Lerp> Interpolation<T> for NearestNeighbor {
fn interpolate(&self, image: &Image<T>, x: f64, y: f64) -> T {
if 0.0 <= x && x < image.width as f64 && 0.0 <= y && y < image.height as f64 {
image.vec[y as usize * image.width + x as usize].cl... | Rust | 0 |
return average_precision
def compute_precision_recall_(self, class_index, interpolated=True):
precisions = []
recalls = []
for acc in self.total_accumulators:
precisions.append(acc[class_index].precision)
recalls.append(acc[class_index].recall)
if interpol... | Python | 1 |
tSpeakerType(3)
sm.sendSay("Ha! I'd be careful about what you say around old Black Bark. He never forgets a debt!")
sm.sendDelay(500)
sm.setSpeakerID(9270089)
sm.removeEscapeButton()
sm.setPlayerAsSpeaker()
sm.setSpeakerType(3)
sm.sendNext("#b(These outlaws should be the perfect bunch to keep me hidden for now. All... | Python | 1 |
2] = subl[17];
subkey[17 * 2 + 1] = subr[17];
tl = subl[15] ^ (subr[15] & !subr[17]);
dw = tl & subl[17];
tr = subr[15] ^ camellia_rl1!(dw);
subkey[18 * 2] = tl ^ subl[19];
subkey[18 * 2 + 1] = tr ^ subr[19];
subkey[19 * 2] = subl[18] ^ subl[20];
subkey[19 * 2 + 1] = subr[18] ^ subr[20]... | Rust | 0 |
pub data: [u32; 17usize],
}
#[repr(C)]
pub struct SwkbdLearningData {
pub data: [u32; 10523usize],
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct SwkbdExtra {
pub initial_text: *const ::libc::c_char,
pub dict: *const SwkbdDictWord,
pub status_data: *mut SwkbdStatusData,
pub learning_data: *mu... | Rust | 0 |
}
}
NixLambda::Builtin(builtin) => write!(f, "{:?}", builtin),
},
NixValue::List(_) => write!(f, "[ ... ]"),
NixValue::Map(map) => write!(
f,
"{{ {} }}",
map.keys().cloned().collect::... | Rust | 0 |
256 = U256::from(self.total_stake.amount());
let total_staked_near_balance: U256 = U256::from(total_staked_near_balance.value());
// (staked_near_compensation + total_staked_near_balance) current_stake_near_value
// ------------------------------------------------------ = -------... | Rust | 0 |
inner.max(),
IpBlock::Range(ref inner) => inner.max(),
}
}
/// Formats the block as a IPv4 block.
pub fn fmt_v4(self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
IpBlock::Prefix(prefix) => prefix.fmt_v4(f),
IpBlock::Range(range) => range.fmt_v4... | Rust | 0 |
t adapter = RpcConnection::new("http://root:none@192.168.1.173:8332/");
// Below balance is what the test account started with
assert!(adapter.get_address_balance(TEST_ADDR).await.unwrap() > 0.00016927);
}
#[actix_rt::test]
async fn test_has_paid_for_month() {
// A test address tha... | Rust | 0 |
_wstr()` using `stdscr()` as window `handle`.
pub fn get_wstr() -> result!(WideString) {
let mut buf: [wint_t; LINE_MAX] = unsafe { mem::zeroed() };
let ptr: *mut wint_t = buf.as_mut_ptr();
match unsafe { ncurses::get_wstr(ptr) } {
EINTR => Err(NCurseswError::InterruptedCall),
KEY_RESI... | Rust | 0 |
_radians(), 0.0);
assert_approx_eq!(154.6f32.to_radians(), 2.698279);
assert_approx_eq!((-332.31f32).to_radians(), -5.799903);
assert_eq!(180.0f32.to_radians(), pi);
assert!(nan.to_radians().is_nan());
assert_eq!(inf.to_radians(), inf);
assert_eq!(neg_inf.to_radians(), ne... | Rust | 0 |
_rx.recv()?;
let idx;
if rc < 0 {
idx = threads_id.iter().position(|&id| id == -rc).expect("Failed to Find the parsed thread handler");
error!("File Could Not Use the following File: {}", paths[(-rc) as usize].display());
}else{
... | Rust | 0 |
rllib.parse.quote_plus(str(v)))
else:
base_path = '#'
# add pagination if any
pagination = render_pagination(base_path, pagination_page, pagination_total_pages)
output = render_template_from_string(
"""
<div class="list-pa... | Python | 1 |
metadata| metadata.target_directory)
.unwrap_or_else(|| "target".into());
let custom = get_cargo_config(home)
.and_then(|config| config.build)
.and_then(|build| build.target)
.map(|target_triple| host.join(target_triple.name()));
CrateTargetDirs { host, custom }
}
pub(crate) fn ... | Rust | 0 |
t dungeon_level:
logger.error(f"レベル {player_pos.level} が見つかりません")
return False
# エンカウンター生成
location = (player_pos.x, player_pos.y, player_pos.level)
encounter_event = self.encounter_manager.generate_encounter(
encounter_typ... | Python | 1 |
0, (bs, n_samples)
)
P, Q, W = list_knn_gather([corr_P, corr_Q, weights[:, :, None]], idxs)
T = kabsch_algorithm(P.flatten(0, 1), Q.flatten(0, 1), W.view(-1, n_hot))
R, t = T.R.unflatten(0, (bs, n_samples)), T.T.view(bs, n_samples, 1, 3)
delta = (cor... | Python | 1 |
# Bonsai - OpenBIM Blender Add-on
# Copyright (C) 2021 Dion Moult <dion@thinkmoult.com>
#
# This file is part of Bonsai.
#
# Bonsai is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Licen... | Python | 1 |
to be
* deterministic.
*/
let params = child.create_params;
let saga_id = params.saga_id;
self.do_saga_create(
params.ack_tx,
saga_id,
params.template_params,
params.template_name,
params.serialized_params,
... | Rust | 0 |
#!/usr/bin/env python3
"""
Test script for the new iLLuMinator-powered Nexus CLI
"""
import sys
import os
# Add the current directory to Python path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
try:
from model.illuminator_api import iLLuMinatorAPI
print("✓ iLLuMinator API import successful"... | Python | 1 |
def read_gpu_slice(tp: TraceProcessor, cpu_input_slice: dict) ->dict:
"""
Input: Perfetto handler and CPU slice
Output: GPU kernel slice
"""
cuda_slice = None
slice_id_origin = cpu_input_slice['slice_id']
slice_id_destination = tp.query_dict(
f'select * from flow where slice_out={sli... | Python | 1 |
next_back(), Some(Symbol::new(u32::MAX - 1)));
}
#[test]
fn one_offset_count() {
let interner = OffByOneInterner::default();
let all_symbols = interner.all_symbols();
assert_eq!(all_symbols.count(), 0);
let interner = OffByOneInterner(100);
let all_symbols = interne... | Rust | 0 |
_le_bytes([255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0])
.checked_sub(1_u128)
.unwrap();
<NftInstanceSequencer<Test>>::set(last_nft_sequencer_num);
assert_eq!(
<NftInstanceSequencer<Test>>::get(),
79_228_162_514_264_337_593_543_950_334
);
assert_eq!(
LiquidityMining... | Rust | 0 |
relPath
def override_encoding(encoding=None):
"""
Decorator to override the system default encoding for a test; this is usually
used to trigger errors that occur when the system default encoding is ASCII.
"""
def decorator(test_function):
@functools.wraps(test_function)
def wrappe... | Python | 1 |
import os
import sys
import openai
import json
from tqdm import tqdm
openai.api_key = os.getenv("OPENAI_API_KEY")
dataset = sys.argv[1] # omniobject3d, objaverse_lvis
llm_name = sys.argv[2] # gpt-3.5-turbo, gpt-4
# NOTE replace the category_list with the desired categories
category_list = []
if dataset == "omniobje... | Python | 1 |
#!/usr/bin/env python3
import json
import sys
import os
project_dir = os.path.realpath(os.path.dirname(os.path.dirname(sys.argv[0])))
version_full, version_major, version_minor, version_patch = (None, ) * 4
if len(sys.argv) == 2:
version_full = sys.argv[1]
version_major, version_minor, version_patch = version... | Python | 1 |
(())
}
pub fn load(path: &Path) -> CollectionResult<Self> {
let config_path = path.join(COLLECTION_CONFIG_FILE);
let mut contents = String::new();
let mut file = File::open(config_path)?;
file.read_to_string(&mut contents)?;
Ok(serde_json::from_str(&contents)?)
}
}
<... | Rust | 0 |
name: Some(name.clone()),
annotations: Some(annotations),
..Default::default()
},
spec,
..Default::default()
};
let api: kube::Api<Project> = kube::Api::all(client.clone());
let _ = api.create(&PostParams::default(), &project).await?;
let mut last_summar... | Rust | 0 |
from flask import Blueprint, render_template, current_app, session
from flask import abort, jsonify
from flask_login import current_user
import ishuhui.tasks.task as task
from ..models.chapter import Chapter
from ..models.comic import Comic
from ..tasks.celery_task import refresh_chapters_task
bp_admin = Blueprint('a... | Python | 1 |
eld is `_1`"]
#[inline(always)]
pub fn is_1(&self) -> bool {
*self == TDMAS_A::_1
}
}
#[doc = "Write proxy for field `TDMAS`"]
pub struct TDMAS_W<'a> {
w: &'a mut W,
}
impl<'a> TDMAS_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TDM... | Rust | 0 |
from .metadata_schema import DocumentMetadata
__all__ = ["DocumentMetadata"] | Python | 1 |
ment_enhance
from core.cliptemplate.coze.video_big_word import get_big_word
from core.cliptemplate.coze.video_catmeme import get_video_catmeme
from core.cliptemplate.coze.video_clicktype import get_video_clicktype
from core.cliptemplate.coze.video_clothes_diffrenent_scene import get_video_clothes_diffrent_scene
from co... | Python | 1 |
#Embedded file name: /Users/versonator/Jenkins/live/output/Live/mac_64_static/Release/python-bundle/MIDI Remote Scripts/Push2/transport_state.py
from __future__ import absolute_import, print_function, unicode_literals
from ableton.v2.base import listenable_property, listens
from ableton.v2.control_surface import Compon... | Python | 1 |
_examples/AbdomenAtlasPredict_temp/BDMAP_A0000002/predictions'
pred, pred_temp = trans_lab(path), trans_lab(path_temp)
print(np.unique(pred), np.unique(pred_temp))
h, w, c = pred.shape
cmap = color_map()
for j in range(c):
la = pred[:, :, j]
g = pred_temp[:, :, j]
if len(... | Python | 1 |
import torch
import torchvision
from typing import List, Callable
from robomimic.models.obs_core import VisualCore
def get_resnet(input_shape: List[int], output_size: int):
"""Get ResNet model from torchvision.models
Args:
input_shape: Shape of input image (C, H, W).
output_size: Size of outpu... | Python | 1 |
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as img
import torch
from torch import nn
from sklearn.preprocessing import normalize
from sklearn.cluster import KMeans
def rgb2gray(rgb):
return np.dot(rgb[...,:3], [0.2989, 0.5870, 0.1140])
if __name__ == '__main__':
x_tra... | Python | 1 |
# Set up a basic scene for rendering.
from paraview.simple import *
import os
import sys
script = """
from paraview.vtk.util import numpy_support
import matplotlib.style
import matplotlib as mpl
mpl.style.use('classic')
# Utility to get next color
def getNextColor():
colors = 'bgrcmykw'
for c in colors:
yiel... | Python | 1 |
import frappe
from frappe.utils import add_days, nowdate, getdate
def create_gift_card_journal_entries():
company_name = frappe.get_doc("Global Defaults").default_company
company = frappe.get_doc("Company", company_name)
previous_date = add_days(nowdate(), -1)
expired_gift_cards = frappe.get_all("Gift C... | Python | 1 |
*mut symtable;
#[cfg(not(Py_LIMITED_API))]
#[cfg(Py_3_4)]
pub fn Py_SymtableStringObject(
str: *const c_char,
filename: *mut PyObject,
start: c_int,
) -> *mut symtable;
pub fn PyErr_Print() -> ();
pub fn PyErr_PrintEx(arg1: c_int) -> ();
pub fn PyErr_Display(arg1: *... | Rust | 0 |
us']} "
span_attributes += f"response.statusText=\"{loaded_item['response']['statusText']}\" "
span_attributes += f"response.httpVersion={loaded_item['response']['httpVersion']} "
span_attributes += f"response.content.size={loaded_item['response']['content']['size']} "
sp... | Python | 1 |
00, CHUNK_SIZE=1024):
def compute_loss(input_chunk, weight, target):
logits = torch.mm(input_chunk, weight.t())
logits = logits.float()
loss = torch.nn.functional.cross_entropy(logits, target, ignore_index=ignore_index)
return loss
grad_weight = torch.zer... | Python | 1 |
import AVFoundation
import objc
from PyObjCTools.TestSupport import TestCase, min_os_level, min_sdk_level
class TestAVAssetWriterHelper(AVFoundation.NSObject):
def assetWriter_didOutputSegmentData_segmentType_segmentReport_(self, a, b, c, d):
pass
def assetWriter_didOutputSegmentData_segmentType_(sel... | Python | 1 |
from sklearn.datasets import load_boston
datasets = load_boston()
x = datasets.data
y = datasets.target
from sklearn.model_selection import train_test_split
from keras.models import Sequential
from keras.layers import Dense
import numpy as np
from sklearn.svm import LinearSVC, SVC
from sklearn.linear_model import Perc... | Python | 1 |
nableRuleCount(self, EnableRuleCount):
self._EnableRuleCount = EnableRuleCount
@property
def NetworkPolicyPluginStatus(self):
return self._NetworkPolicyPluginStatus
@NetworkPolicyPluginStatus.setter
def NetworkPolicyPluginStatus(self, NetworkPolicyPluginStatus):
self._NetworkPo... | Python | 1 |
# -*- mode:python -*-
# Copyright (c) 2014,2017 ARM Limited
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implemen... | Python | 1 |
.into_input().unwrap();
gpio
}};
($pin_ty:ty, Output) => {{
let gpio = unsafe { <$pin_ty>::new() };
let gpio = gpio.into_output().unwrap();
gpio
}};
}
/// A macro for configure a pin as input or output and insert it into
/// either a map for input pins or one for output pin... | Rust | 0 |
se_hyperparams(hyperparameter_batch)
batch_size = x.shape[0]
e_obs = x_f + torch.multiply(torch.randn(x.shape[:2], device=self.get_device(device)), sigma_e_prior_batch[:,None].repeat([1,self.n_choices]))
obs = [e_obs]
for i in range(self.n_choices):
for j in range(i+1,self.n... | Python | 1 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, api
class UoM(models.Model):
_inherit = "uom.uom"
fiscal_country_codes = fields.Char(compute="_compute_fiscal_country_codes")
@api.depends_context("allowed_company_ids")
... | Python | 1 |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
12478
import pandas as pd
file_path = r"On_Time_Reporting.csv"
df = pd.read_csv(file_path)
# In[2]:
df
# In[5]:
# Specify the columns to keep
columns_to_keep = [
'Year', 'Month', 'DayofMonth', 'DayOfWeek',
'OriginAirportID', 'DestAirportID', 'DestAirpor... | Python | 1 |
rk.parametrize("klass", [Series, DatetimeIndex])
def test_vectorized_offset_addition(self, klass):
s = klass(
[
Timestamp("2000-01-15 00:15:00", tz="US/Central"),
Timestamp("2000-02-15", tz="US/Central"),
],
name="a",
)
with... | Python | 1 |
e[assignment]
else:
# Handle empty dict input
storage_options = None
pylf = PyLazyFrame.new_from_csv(
source,
sources,
separator=separator,
has_header=has_header,
ignore_errors=ignore_errors,
skip_rows=skip_rows,
n_rows=n_rows,
cac... | Python | 1 |
g = &pk.params.g;
let p = &pk.params.p;
let q = &pk.params.q();
let h = &pk.h;
// perform quadratic residue check: m^q mod p == 1
// to ensure DDH is given
assert!(m.modpow(q, p) == BigUint::one());
// a = g^r
let a = g.modpow(r, p);
// b = h^r ... | Rust | 0 |
_bytes: self.key_bytes - other.key_bytes,
value_bytes: self.value_bytes - other.value_bytes,
reused_keys_bytes: self.reused_keys_bytes - other.reused_keys_bytes,
}
}
}
impl std::ops::Sub for StorageBackendStats {
type Output = Self;
fn sub(self, other: Self) -> Self::Output... | Rust | 0 |
width_max = ctxt.read_u16be()?;
let min_left_side_bearing = ctxt.read_i16be()?;
let min_right_side_bearing = ctxt.read_i16be()?;
let x_max_extent = ctxt.read_i16be()?;
let caret_slope_rise = ctxt.read_i16be()?;
let caret_slope_run = ctxt.read_i16be()?;
let caret_offset = ... | Rust | 0 |
from flask import Flask, jsonify, request
app = Flask(__name__)
# dicionario para registros
pontuacoes = [
{
'id': 1,
'nome': "renata",
'tempo': 50,
'pontuacao': 900
},
{
'id': 2,
'nome': "marcelo",
'tempo': 50,
'pontuacao': 900
},
... | Python | 1 |
model.
print("MODEL SUMMARY",model.summary())
logbook().record_model_json(model.to_json())
# Finally, we configure and compile our agent. You can use every built-in Keras optimizer and
# even the metrics!
memory = SequentialMemory(limit=50000, window_length=1) # see https://stackoverflow.com/questions/47140642/what-d... | Python | 1 |
ySelectorAll('[id*="botCaptcha"], [class*="botdetect"]').length,
captcha_scripts: detection_scripts
};
// 숨겨진 필드들
const hidden_fields = {};
document.querySelectorAll('input[type="hidden"]').forEach(input => {
... | Python | 1 |
Self::Sha3 => write!(f, "SHA-3"),
#[cfg(feature = "blake3")]
Self::Blake3 => write!(f, "BLAKE3"),
}
}
}
impl Default for Hash {
fn default() -> Self {
#[cfg(feature = "blake3")]
return Self::Blake3;
#[cfg(all(not(feature = "blake3"), feature = "sha3"))]
return Self::Sha3;
#[cfg(all(not(feature = "... | Rust | 0 |
BurrowRavagerDownCancel = 2341,
BurrowUpRavager = 2342,
PurificationNovaPurificationNova = 2344,
EffectPurificationNova = 2346,
ImpaleImpale = 2348,
LockOnLockOn = 2350,
LockOnAirLockOnAir = 2352,
CancelLockOn = 2354,
CorruptionBombCorruptionBomb = 2356,
CorruptionBombCancel = 2357,
EffectTacticalJump = 235... | Rust | 0 |
e_created', 'N/A')}")
# print(f"Last Activity Date: {details.get('last_activity_date', 'N/A')}")
# print(f"View Count: {details.get('view_count', 'N/A')}")
# print(f"Detailed Tags: {', '.join(details.get('detailed_tags', []))}")
# print(f"Question Text:\n{details.get('question_text', 'N/A')}\n")
# ... | Python | 1 |
variants<'b, I>(&self, variants: I) -> Result<()>
where
I: IntoIterator<Item = RpVariantRef<'b>>,
{
let mut it = variants.into_iter().peekable();
if it.peek().is_none() {
return Ok(());
}
for variant in it {
let id = variant.name.join("_");
... | Rust | 0 |
frame_system::mocking::MockBlock<Test>;
frame_support::construct_runtime!(
pub enum Test where
Block = Block,
NodeBlock = Block,
UncheckedExtrinsic = UncheckedExtrinsic,
{
System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T... | Rust | 0 |
}
}
#[inline]
pub fn set_broken_link(&mut self, val: ::std::os::raw::c_uint) {
self._bitfield_1 &= !(1usize as u8);
self._bitfield_1 |= ((val as u32 as u8) << 0u32) & (1usize as u8);
}
#[inline]
pub fn closed_entry(&self) -> ::std::os::raw::c_uint {
unsafe {
... | Rust | 0 |
::formats::adj::Adj;
use ssbh_lib::formats::meshex::MeshEx;
use ssbh_lib::{Ssbh, SsbhFile};
use std::env;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::Instant;
fn write_json<T: Sized + Serialize>(output_path: &Path, object: T) {
let json = serde_json::to_string_pretty(&object).unwrap();
... | Rust | 0 |
encoder.write(&bitmap.width.to_le_bytes()).ok()?;
encoder.write(&bitmap.height.to_le_bytes()).ok()?;
encoder.write(&bitmap.srgba).ok()?;
}
Some(())
}
}
/// Helper function.
pub fn clone_into_array<A, T>(slice: &[T]) -> A
where
A: Default + AsMut<[T]>,
T: Clone,
{
... | Rust | 0 |
2
},
/* AND H */ 0xA4 => {
debug_system!("AND H\n", cpu.debug_mode);
let d8 = cpu.registers.r_h;
arithmetic::and(cpu, d8);
2
},
/* AND L */ 0xA5 => {
debug_system!("AND L\n", cpu.debug_mode);
let d8 = cpu.register... | Rust | 0 |
Mutex<Address>,
pub throw_thunk: Mutex<Address>,
pub threads: Threads,
pub safepoint: Safepoint,
}
impl<'ast> VM<'ast> {
pub fn new(args: Args, ast: &'ast ast::Ast) -> Box<VM<'ast>> {
let empty_class_id: ClassId = 0.into();
let empty_class_def_id: ClassDefId = 0.into();
let emp... | Rust | 0 |
fn fizzbuzz(&self) {
print_fizzbuzz(*self);
}
}
impl FizzBuzz for i64 {
fn fizzbuzz(&self) {
print_fizzbuzz(*self as i32);
}
}
fn main() {
(20 as i32).fizzbuzz();
(20 as i64).fizzbuzz();
}
use crate::api;
use crate::api::baca_api::BacaApi;
use crate::command::prompt::{Input, Passwo... | Rust | 0 |
api_port=llm_api_port,
types="rag" if (similarity_retrieval_task or keyword_retrieval_task) else "general",
search_results_types=search_results_types,
)
)
if USE_RAGAS:
logging.info("Using RAGAS evaluation")
ragas_evaluation_task... | Python | 1 |
, Debug)]
pub enum State {
/// The connection has not yet been established.
Connecting,
/// The WebSocket connection is established and communication is possible.
Open,
/// The connection is going through the closing handshake, or the close() method has been
/// invoked.
Closing,
/// The... | Rust | 0 |
import logging
from mitmproxy import hooks
class Recorder:
call_log = []
def __init__(self, name="recorder"):
self.name = name
def __getattr__(self, attr):
if attr in hooks.all_hooks and attr != "add_log":
def prox(*args, **kwargs):
lg = (self.name, attr, ar... | Python | 1 |
_parser(mcu, svd)
dev = svd_parser.get_device()
if group:
flt = lambda p: p.group_name == peripheral_name
else:
flt = lambda p: p.name == peripheral_name
return peripheral_name, filter(flt, dev.peripherals), dev
def generate(name, peripherals, dev):
peripherals = list(peripherals)
... | Python | 1 |
on, and 1 is the current visual information.
"""
# observation = {"history_depth":np.array(self.episode_buffer["depth"][1:-1:2]), "history_action":np.array(self.action_buffer), "current_depth":np.array(self.episode_buffer["depth"][-1])}
return np.array(self.episode_buffer["depth"][-1])#observat... | Python | 1 |
raction.shading_normal;
}
for material in object.get_materials() {
material.compute_scattering_functions(&mut surface_interaction);
}
let light_irradiance = uniform_sample_light(scene, &surface_interaction);
l += contribution.component_mul(&light_irradiance);
... | Rust | 0 |
#-*- coding: UTF-8 -*-
# 调用必需库
from imutils.video import VideoStream
from imutils.video import FPS
from imutils.object_detection import non_max_suppression
import numpy as np
import argparse
import imutils
import time
import cv2
def decode_predictions(scores, geometry):
# 获取score的行数和列数
# 初始化外边框列表和置信度列表
(numRows, n... | Python | 1 |
import jieba
import re
import numpy as np
from pyltp import SentenceSplitter
from torchtext import data
from torchtext.vocab import Vectors
import torch
import pandas as pd
def tokenizer(text): # create a tokenizer function
regex = re.compile(r'[^\u4e00-\u9fa5aA-Za-z0-9]')
text = regex.sub(' ', text)
ret... | Python | 1 |
Option<Int32>,
#[min_version = 8]
pub batch_index_error_message: Option<NullableString>,
}
impl ProduceResponse0 {
fn get_first_error(&self) -> Option<ApiError> {
None
}
}
pub mod value;
pub mod chunk;
<reponame>rivy-fix/dprint
use crate::utils::to_absolute_glob;
use std::borrow::Cow;
use std:... | Rust | 0 |
t self, item: &T) -> Result<BytesMut, Self::Error> {
bincode::serialize(item).map(Into::into)
}
}
// Copyright (c) 2021, BlockProject 3D
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions a... | Rust | 0 |
)
X = ([[0, 0], [1, 1]] * 5 + [[3, 3], [4, 4]] * 5 +
[[0, 4], [1, 3]] * 5 + [[3, 1], [4, 0]] * 5)
labels = [0] * 10 + [1] * 10 + [2] * 10 + [3] * 10
pytest.approx(davies_bouldin_score(X, labels), 2 * np.sqrt(0.5) / 3)
# Ensure divide by zero warning is not raised in general case
with pytes... | Python | 1 |
# Python program to demonstrate using the input() and print() functions. The
# program should:
# a. Prompt the user to input two values, a and b.
# b. Display the result of applying the + operator to a and b without any type casting
# (showing string concatenation behavior).
# c. Prompt the user to input two values, a ... | Python | 1 |
let shmem_provider = StdShMemProvider::new().unwrap();
let mut broker = match LlmpConnection::on_port(shmem_provider.clone(), 1337).unwrap() {
IsClient { client: _ } => panic!("Could not bind to port as broker"),
IsBroker { broker } => broker,
};
// Add the firs... | Rust | 0 |
k::new(Ipv6Addr::new(0x2001, 0x0db8, 0x4000, 0, 0, 0, 0, 0), 34).unwrap()
);
assert_eq!(
subnets.next().unwrap(),
Ipv6Network::new(Ipv6Addr::new(0x2001, 0x0db8, 0x8000, 0, 0, 0, 0, 0), 34).unwrap()
);
assert_eq!(
subnets.next().unwrap(),
Ip... | Rust | 0 |
("foo"), "666F6F");
assert_eq!(encode("foob"), "666F6F62");
assert_eq!(encode("fooba"), "666F6F6261");
assert_eq!(encode("foobar"), "666F6F626172");
assert_eq!(encode_lowercase(""), "".to_lowercase());
assert_eq!(encode_lowercase("f"), "66".to_lowercase());
assert_eq!(encode_lowercase("fo"), "6... | Rust | 0 |
e = None,
) -> float:
"""Measure transcription accuracy for a given language."""
language = args.language if language is None else language
index, mean_accuracy = 0, 0
with os.scandir(os.path.join(args.data_dir, language)) as entries:
for entry in entries:
if not entry.is_file() or ... | Python | 1 |
or i in range(len(columns)):
# columns[i].append(values[i])
# return columns
def load_as_recarr(self, filename, fields=None, formatmarker='# format:'):
"""Warning: if there's missing value, it will be filled with default value.
See: https://docs.scipy.org/doc/numpy/user/basi... | Python | 1 |
ey.startswith("images/")}
writer.write_images(step, train_info_img)
curr_dir = os.path.join(visdir, "step_%d" % step)
tf.io.gfile.MakeDirs(curr_dir)
for k, out in train_info_img.items():
out_fpath = os.path.join(curr_dir, "%s.png" % (k[len("train/"):]))
image_vis_utils.save_images(out, out_fpath)
# ... | Python | 1 |
#########################
##### PARTIE IMPORT #####
#########################
#########################
# IMPORT DES LIBRAIRIES #
#########################
import streamlit as st
##############################
# IMPORT DES FICHIERS PYTHON #
##############################
from modeles import preparation_modele as pm... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.