text string | label_name string | labels int64 |
|---|---|---|
"ru": {
"label": "Режим переключения",
"info": "Стратегия выбора блока для обновления для послойного BAdam.",
},
"zh": {
"label": "切换策略",
"info": "Layer-wise BAdam 优化器的块切换策略。",
},
},
"badam_switch_interval": {
"en": {
... | Python | 1 |
from flask import Flask, render_template
from flask_socketio import SocketIO, send
app = Flask(__name__)
app.config['SECRET'] = 'secret!123'
socketio = SocketIO(app, cors_allowed_origins = '*')
@app.route('/')
def index():
return render_template('index.html')
@socketio.on('message')
def handle_message(message):
... | Python | 1 |
_stars>1-10
use crate::{Symbol, State};
use crate::bottom_up::Configuration;
pub trait Language<F> {
// ...
}
pub trait ConfigurationIterator<'a, F: Symbol, Q: State> : Iterator<Item = Configuration<F, Q>> {
// ...
}
<reponame>ArturAralin/swc
use anyhow::Context;
use serde::{Deserialize, Serialize};
use swc_a... | Rust | 0 |
literal::hex!("50ad05ae44dca4fb1d5d2e7b3b40aed279b77427afba4d053a49a2f29282336a")),
// AccountId::from(hex_literal::hex!("6069afbaf2b6129e5edf876557e40dc357855ea69d84ad4139da8d47ec43ac56")),
// AccountId::from(hex_literal::hex!("<KEY>")),
// AccountId::from(hex_literal::hex!("8e5eb78b2dd8083b42fc2cb4370ca696ea... | Rust | 0 |
.process_manager.clone(),
self.db.clone(),
)
.create(None)
.spawn(&mut self.tasks);
disconnected.insert(addr);
}
}
impl<O> Actor<O>
where
O: xtra::Handler<oracle::GetAnnouncement>,
{
async fn handle_auto_rollover_impl(
&mut self,
ctx: &mut xtra::... | Rust | 0 |
;
let mut f_6: Option<CurvesApi> = None;
loop {
let field_ident = i_prot.read_field_begin()?;
if field_ident.field_type == TType::Stop {
break;
}
let field_id = field_id(&field_ident)?;
match field_id {
1 => {
let val = i_prot.read_string()?;
f_1... | Rust | 0 |
u32,
pub max_recursion_depth: u32,
pub max_shader_group_stride: u32,
pub shader_group_base_alignment: u32,
pub max_geometry_count: u64,
pub max_instance_count: u64,
pub max_primitive_count: u64,
pub max_descriptor_set_acceleration_structures: u32,
pub shader_group_handle_capture_replay_... | Rust | 0 |
fn draw(&self, vg: &Ctx)
{
let x = self.bounds.x();
let y = self.bounds.y();
let w = self.bounds.w();
let h = self.bounds.h();
let t = self.theta;
//f32 r0, r1, ax,ay, bx,by, cx,cy, aeps, r;
let hue = sin(t * 0.12);
vg.save();
/* vg.begin_path();
vg.rect(x,y,w,h);
vg.fill_color(rgba(255,0,0,... | Rust | 0 |
{ key } => {
let key = MilestoneIndex(u32::from_str(key).map_err(|_| RocksdbError::InvalidKey(key.clone()))?);
let value = Fetch::<MilestoneIndex, Vec<UnconfirmedMessage>>::fetch(&storage, &key).await?;
println!("Key: {:?}\nValue: {:?}\n", key, value);
}
... | Rust | 0 |
#!/usr/bin/env python3
# Software License Agreement (BSD License)
#
# Copyright (c) 2021, UFACTORY, Inc.
# All rights reserved.
#
# Author: Vinman <vinman.wen@ufactory.cc> <vinman.cub@gmail.com>
from launch import LaunchDescription
from launch.actions import IncludeLaunchDescription
from launch.launch_description_sour... | Python | 1 |
one, None, True],
"c": [False, True, True, False, True, True],
}
)
if not has_nulls:
ldf = ldf.select(pl.col("a"), pl.col("c"))
# To see the All/Any Horizontal nodes, we need a dataframe with
# more than 128 columns
if wide:
ldf = ldf.with_columns(pl.col("c").ali... | Python | 1 |
C in the"]
#[doc = " buffer object. Counted in elements."]
#[doc = " @param[in] ldc Leading dimension of matrix \\b C. It cannot be less"]
#[doc = " than \\b N when the \\b order parameter is set to"]
#[doc = " \\b clblasRowMajor,\\n ... | Rust | 0 |
import json
import os
import sys
from utils import dict_product, generate_configs, generate_shell_script, iwt
with open("../src/ILfD_base.json") as f:
BASE_CONFIG = json.load(f)
PARAMS = {
"game": ["window-open-v2"],
"mode": ["adv_ilfd"],
"out_dir": ["experiments/attack_sappo_convex_ilfd/window-open-... | Python | 1 |
, 0.0, 0.0);
let positive_tangent_pixel: Rgba<u8> = Rgba {
data: [255, 128, 128, 255],
};
assert_eq!(normal_to_pixel(straight_normal), straight_pixel);
assert_eq!(
normal_to_pixel(positive_tangent_normal),
positive_tangent_pixel
);
}
... | Rust | 0 |
# Write a Python function that takes a list of strings as input and returns a
# new list with the strings sorted in descending order of their lengths.
def sortbylength(strings):
sorted_strings = sorted(strings, key=len, reverse=True) # descending order sorting
return sorted_strings
stringlist = []
num_str... | Python | 1 |
#[doc = "Bit 9 - 9:9\\]
AUXIO25 pin level, read value corresponds to AUX_AIODIO3:GPIODIN bit 1."]
#[inline(always)]
pub fn auxio25(&self) -> AUXIO25_R {
AUXIO25_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 8 - 8:8\\]
AUXIO24 pin level, read value corresponds to AUX_AIODIO3:GPIODIN bit 0... | Rust | 0 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from typing import Dict
import pytest
from semantic_parsing_with_constrained_lm.src.semantic_parsing_with_constrained_lm.scfg.parser.macro import Macro, eval_expression, expand_macros
from semantic_parsing_with_constrained_lm.src.semantic_parsi... | Python | 1 |
import socket
from datetime import datetime
import sys
def main():
# Define a target
if len(sys.argv) == 2:
# Translate the hostname to IPv4
target = socket.gethostbyname(sys.argv[1])
else:
print("Invalid amount of argument")
print("Scanning Target: " + target)
print("Scan... | Python | 1 |
# train_rf.py
import os
import cv2
import numpy as np
import joblib
import shutil
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score
from sklearn.decomposition import PCA
from expression_classifier_rf i... | Python | 1 |
# -*- coding:utf8 -*- # 避免中文乱码
import xml.dom.minidom as Dom
from xml.dom import minidom
import random
import time
mass_set = 0.01 # 质量
chess_x = 7 # 棋盘格要检测部分的长
chess_y = 6 # 棋盘格要检测部分的宽
X = chess_x + 1 # 实际的长
Y = chess_y + 1 # 实际的宽
size = 0.025 # 一个正方形格子的大小 单位是米
z = 0.001
def write():
doc = Dom.Document()... | Python | 1 |
let cost = vec_vec_i32![[1, 10], [10, 1], [10, 1], [1, 10], [5, 1]];
let m = 5;
let n = 2;
let target = 3;
let res = 11;
assert_eq!(Solution::min_cost(houses, cost, m, n, target), res);
}
<gh_stars>0
mod input;
use std::collections::HashMap;
fn main() {
println!("{}", solve(&Grid::parse(inp... | Rust | 0 |
that wants lower-case option
#[cfg(stage0)]
use option = option::Option;
use result::{Result, Ok, Err};
use Path = path::Path;
use GenericPath = path::GenericPath;
use WindowsPath = path::WindowsPath;
use PosixPath = path::PosixPath;
use tuple::{TupleOps, ExtendedTupleOps};
use str::{StrSlice, UniqueStr};
use vec::... | Rust | 0 |
_, idx = next(skf.split(x, y))
else:
idx = range(len(y))
if return_idx:
return idx
x = x[idx, :]
y = y[idx]
return x, y
def _set_trained(self) -> None:
"""
Internal function used to set the buffer "trained" to true
"""
... | Python | 1 |
/v2/seedbox/add'
response = post(url, 'url=' + release.download[0] + '&async=true')
if response.success:
ui_print('[debridlink] adding uncached release: ' + release.title)
return True
except:
cont... | Python | 1 |
qtd_vendas = 1000
qtd_custo = 500
qtd_lucro = qtd_vendas - qtd_custo
print(qtd_lucro)
| Python | 1 |
_mut_Stream()) }.into_result().map(|r| unsafe { core::Ptr::<dyn crate::cudaoptflow::CUDA_NvidiaOpticalFlow_2_0>::opencv_from_extern(r) } )
}
/// Instantiate NVIDIA Optical Flow with ROI Feature
///
/// ## Parameters
/// * imageSize: Size of input image in pixels.
/// * roiData: Pointer to ROI data.
/// * perf... | Rust | 0 |
, b| b.1.cmp(a.1));
for v in vis_counts {
println_ignore_err!("{}: {}", v.0, v.1);
}
}
<filename>components/dada-ir/src/class.rs
use crate::{span::Span, token_tree::TokenTree, word::Word};
salsa::entity2! {
entity Class in crate::Jar {
#[id] name: Word,
name_span: Span,
fi... | Rust | 0 |
"""Copyright 2008 Orbitz WorldWide
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, software... | Python | 1 |
.expect("Something wrong with tauri_recent"),
&serde_json::to_value(&recent).expect("Unable to build final json (recent)"),
)
.expect(format!("Unable to write {:?}", tauri_recent).as_str());
}
<reponame>infinyon/fluvio
use fluvio_smartstream::{smartstream, SmartOpt, Record, RecordData, Result};
#[derive... | Rust | 0 |
#!/usr/bin/env python
'''This script sends a efetch request to NCBI, requesting a genbank-formatted data file
and creates a .gbk file if successful
retrieve.py NC_000913
should create NC_000913.gbk containing the annotated E. coli K12 reference genome '''
import os, sys
from Bio import Entrez
def downloadgbk(access... | Python | 1 |
from system_monitor import display_process_info
from deadlock_detection import detect_resource_contention
from deadlock_prevention import is_safe_state
from deadlock_recovery import resolve_deadlock
def main():
print("\n🔹 Step 1: System Monitoring")
display_process_info()
print("\n🔹 Step 2: Detecting De... | Python | 1 |
try("authLevel", auth_level)?;
}
if !self.methods.is_empty() {
map.serialize_entry("methods", &self.methods)?;
}
if let Some(route) = self.route.as_ref() {
map.serialize_entry("route", route)?;
}
if let Some(web_hook_type) = self.web_hook_type.as_r... | Rust | 0 |
usive 0 (first) element, exclusive 2 (third) element; so first and second elements
println!("Also use debug to print a slice {:?}", slice);
// tuple
let mytuple:(i32, f64, char, [i32; 5]) = (65, 65.0, 'r', myarr);
println!("A tuple indicated by (type, ...) with any type include arrays and tuples");
... | Rust | 0 |
r(user=self.user).update(is_primary=False)
super().save(*args, **kwargs)
class Transaction(TimeStampedModel):
class TransactionStatus(models.TextChoices):
PENDING = ("pending", _("Pending"))
COMPLETED = ("completed", _("Completed"))
FAILED = ("failed", _("Failed"))
class Trans... | Python | 1 |
line_end);
LDA.with_ptr(current_char);
STR;
// And increment line_end
LIA.with_data(1);
ADD;
LIB.with_ptr(line_end);
STR;
JMP.with_label(wait_loop);
// Set arguments to out and jump to it.
process_to... | Rust | 0 |
Debug print
if colorIndex == 0:
bpoints[indices['blue']].appendleft(fore_finger)
elif colorIndex == 1:
gpoints[indices['green']].appendleft(fore_finger)
elif colorIndex == 2:
rpoints[indices['red']].appendleft(fore_finger)
e... | Python | 1 |
}
}
pub struct FragmentShader {
fragment_shader: *mut ID3D11PixelShader,
}
impl FragmentShader {
pub fn new(renderer: &Renderer, fragment_file: &str) -> FragmentShader {
unsafe {
println!("Creating fragment shader {}", fragment_file);
let mut fs_buffer: Box<ID3DBlob> = Box... | Rust | 0 |
32::<BE>()?, read.read_f32::<BE>()?, read.read_f32::<BE>()?),
}),
_ => Ok(ScenePlacementData::Unknown(main_type, sub_type, data)),
}
}
}
#[derive(Clone, Debug)]
pub struct ScenePlacement {
pub model_name: String,
pub geom_name: String,
pub x_pos: f32,
pub y_pos: f32,... | Rust | 0 |
import os.path
from consts import kRepositoryRootDirectory, kResourcesDirectory
# ============================= Directory Consts =============================
kTestWorkingDirectory = os.path.join(kRepositoryRootDirectory, 'TestWorkingDirectory')
kTestResourcesDirectory = os.path.join(kResourcesDirectory, 'Test')
# ... | Python | 1 |
import os
import re
import matplotlib.pyplot as plt
def extract_retransmissions(file_path):
"""
Extract the number of retransmissions from an iperf3 output file.
"""
with open(file_path, 'r') as file:
content = file.read()
# Find the line that contains the retransmissions in the summary... | Python | 1 |
": "random_forest", "Accuracy": 0.95, "F1 Score": 0.00, "Precision": 0.00, "Recall": 0.00},
{"Model": "naive_bayes", "Accuracy": 0.86, "F1 Score": 0.20, "Precision": 0.14, "Recall": 0.34},
{"Model": "svm", "Accuracy": 0.95, "F1 Score": 0.00, "Precision": 0.00, "Recall": 0.00},
{"Mode... | Python | 1 |
_cache: env.get_cache(),
})
}
}
impl CanisterBuilder for AssetsBuilder {
fn supports(&self, info: &CanisterInfo) -> bool {
info.get_type() == "assets"
}
fn get_dependencies(
&self,
pool: &CanisterPool,
info: &CanisterInfo,
) -> DfxResult<Vec<Caniste... | Rust | 0 |
tializer='zeros')(x)
x = BatchNormalization()(x)
x = UpSampling2D(size=(2, 2))(x)
the_shape = K.int_shape(orig_1)
shape = (1, the_shape[1], the_shape[2], the_shape[3])
origReshaped = Reshape(shape)(orig_1)
xReshaped = Reshape(shape)(x)
together = Concatenate(axis=1)([origReshaped, xReshaped]... | Python | 1 |
n proposals
proposal_list = self.rpn_head.get_bboxes(
points, rpn_outs, img_metas, use_nms=proposal_cfg.use_nms)
feats_dict['proposal_list'] = proposal_list
else:
raise NotImplementedError
return self.roi_head.simple_test(
feats_dict, img_... | Python | 1 |
#!/usr/bin/python3i
"""
Docstyle for class Rectanle
"""
class Rectangle:
"""
class is Rectangle
"""
def __init__(self, width=0, height=0):
"""
__init__ is used for object initialization
Note:
self should not be included in the args
Args:
idth: wi... | Python | 1 |
from django.http import JsonResponse
from rest_framework import viewsets
from rest_framework.decorators import api_view, permission_classes
from rest_framework.generics import ListAPIView
from rest_framework.permissions import AllowAny
from rest_framework.views import APIView
from ...models import Job
from ..serialize... | Python | 1 |
for day in days {
writeln!(f, " {0} => day{0:02}::Problem {{}}.solve(day),", day)?;
}
writeln!(
f,
" d => println!(\"Day {{}} hasn't been solved yet :(\", d),
}}
}}"
)?;
Ok(())
}
fn gen_solutions(dir: &str, days: &[u32]) -> io::Result<()> {
for day in... | Rust | 0 |
_eq!(
Snapshot::load_with_crc64(&mut snapshot_mem.as_slice(), vm.clone()).unwrap_err(),
expected_err
);
}
#[allow(non_upper_case_globals)]
#[allow(non_camel_case_types)]
#[allow(non_snake_case)]
#[test]
fn test_kvm_bindings_struct() {
#[repr(C)]
#... | Rust | 0 |
from typing import List
def factorize(n: int) -> List[int]:
""" Return list of prime factors of given integer in the order from smallest to largest.
Each of the factors should be listed number of times corresponding to how many times it appeares in factorization.
Input number should be equal to the produc... | Python | 1 |
me", help="Object name (used with --project for reproducible UIDs)"
)
args = parser.parse_args()
if args.project and args.name:
# Generate reproducible UID based on project and object name
namespace_seed = f"project_{args.project}"
object_seed = f"object_{args.name}_{args.project}"... | Python | 1 |
import unittest
from pulsar.apps.wsgi import WsgiResponse
from pulsar.utils.lib import WsgiResponse as Wsgi
common = {
200: 'OK',
400: 'Bad Request',
404: 'Not Found',
500: 'Internal Server Error'
}
class TestWsgi(unittest.TestCase):
__benchmark__ = True
__number__ = 20000
def setUp(se... | Python | 1 |
= Service{name: ser.clone(), num: numb + 1};
}
else {
serde.services.push(Service{name: ser, num: 1})
}
let mut file = File::create(path).unwrap();
let serialized = serde_json::to_string(&serde).unwrap();
write!(&mut file, "{}", serialized).unwrap();
}
else if matches.is_present("display"){
if servl... | Rust | 0 |
_with_modifiers {
if key >= ' ' && key != '\x7f' {
Key::Character(insert_or_get_key_str(key.to_string()))
} else {
Key::Unidentified(NativeKeyCode::Gtk(scancode))
}
} else {
Key::Unidentified(NativeKeyCode::Gtk(scancode))
}
});
// make sure we have a valid key
if !... | Rust | 0 |
ot name"))?
.to_owned();
crate_root.push("src");
crate_root.push("lib.rs");
let mut visitor = UnstableVisitor::new(
crate_name,
crate_root,
Feature {
name: feature,
inherited: false,
},
);
visitor.visit()?;
Ok(())
}
#[derive(Debu... | Rust | 0 |
try:
job = session.query(AmlEventPool)\
.filter(AmlEventPool.id == id)\
.filter(AmlEventPool.job_id == job_id)\
.one()
job.updated_at = datetime.datetime.now()
for column in AmlEventPool._... | Python | 1 |
}
#[cfg(_XM_ARM_NEON_INTRINSICS_)]
{
unimplemented!()
}
#[cfg(_XM_SSE_INTRINSICS_)]
unsafe {
let vTemp: XMVECTOR = _mm_cmpge_ps(V1, V2);
return ((_mm_movemask_ps(vTemp) == 0x0f) != false);
}
// NOTE: The source contains a fallback that does not seem reachable
... | Rust | 0 |
size: i32,
}
impl Default for xcb_glx_select_buffer_request_t {
fn default() -> Self {
unsafe { std::mem::MaybeUninit::zeroed().assume_init() }
}
}
/// The cookie for the reply to a `Glx::RenderMode` request.
///
/// Pass this cookie to [`xcb_glx_render_mode_reply`] to retrieve the reply.
///
/// [`x... | Rust | 0 |
self) -> None:
pass
def testFindShortestPathAndVerify_test12_decomposed(self) -> None:
pass
def testFindShortestPathAndVerify_test11_decomposed(self) -> None:
pass
def testFindShortestPathAndVerify_test10_decomposed(self) -> None:
pass
def testFindShortestPathAndVerif... | Python | 1 |
yBufferBuilder::new()
.set_physical_size(width, height, Some(&mut physical_size))
.set_virtual_size(width, height, Some(&mut virtual_size))
.set_virtual_offset(0, 0, Some(&mut virtual_offset))
.set_buffer_depth(32, Some(&mut buffer_depth))
.set_pixel_order(0, Some(&mut pixel_orde... | Rust | 0 |
struct NeonF32Butterfly31<T> {
direction: FftDirection,
_phantom: std::marker::PhantomData<T>,
rotate: Rotate90F32,
twiddle1re: float32x4_t,
twiddle1im: float32x4_t,
twiddle2re: float32x4_t,
twiddle2im: float32x4_t,
twiddle3re: float32x4_t,
twiddle3im: float32x4_t,
twiddle4re: fl... | Rust | 0 |
OF_ROWS_PER_PATTERN;
for channel_number in 0..DEFAULT_NUMBER_OF_CHANNELS_PER_ROW as usize {
if row_number[channel_number] < lowest {
lowest = row_number[channel_number];
current_channel = channel_number;
}
}
if lowest >= truncate_pos {
break;
}
// println!("P {} C {} R {} P {:X}... | Rust | 0 |
from __future__ import unicode_literals
from frappe import _
def get_data():
return {
'fieldname': 'leave_policy',
'non_standard_fieldnames': {
'Employee Grade': 'default_leave_policy'
},
'transactions': [
{
'label': _('Employees'),
'items': ['Employee', 'Employee Grade']
},
{
'label'... | Python | 1 |
}
impl Card {
fn try_from_split(source: &str, split: usize) -> Option<Card> {
Some(Card {
rank: try_opt!(Rank::try_from(&source[..split])),
suit: try_opt!(Suit::try_from(&source[split..])),
})
}
fn try_from(source: &str) -> Option<Card> {
match source.len() ... | Rust | 0 |
import libtorrent as lt
import sys
import os
def create_private_torrent(file_or_dir_path, tracker_url, output_torrent_path):
"""
為指定的檔案或資料夾建立一個私有 .torrent 檔案。
"""
# --- 關鍵修正: 標準化路徑 ---
# 確保我們使用的是絕對路徑,這可以避免很多問題
target_path = os.path.abspath(file_or_dir_path)
if not os.path.exists(target_pat... | Python | 1 |
4, "dvr-esm"),
(2809, "corbaloc"),
(2882, "ndtp"),
(2914, "gamelobby"),
(2947, "gpsd"),
(2988, "afbackup"),
(3050, "gds_db"),
(3074, "xbox"),
(3130, "icpv2"),
(3148, "nm-game-admin"),
(3149, "nm-game-server"),
(3306, "mysql"),
(3326, "sftu"),
(3346, "trnsprntproxy"),
... | Rust | 0 |
import numpy as np
import pandas as pd
import sympy as sp
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import plotly.express as px
from scipy.optimize import minimize
v = 10 # initial velocity (m/s)
theta = np.radians(60) # angle in radians
x = 4 # vertical component (m)
g = 9.8 # accele... | Python | 1 |
{
($($t:ident)*) => ($(
//sh_impl_unsigned! { $t, u8 }
//sh_impl_unsigned! { $t, u16 }
//sh_impl_unsigned! { $t, u32 }
//sh_impl_unsigned! { $t, u64 }
//sh_impl_unsigned! { $t, u128 }
sh_impl_unsigned! { $t, usize }
//sh_impl_signed! { $t, i8 }
//sh_... | Rust | 0 |
from .campaign_base import CampaignBase
from module.map.map_base import CampaignMap
from module.map.map_grids import SelectedGrids, RoadGrids
from module.logger import logger
MAP = CampaignMap('ISP1')
MAP.shape = 'E5'
MAP.camera_data = ['C2']
MAP.camera_data_spawn_point = ['C2']
MAP.map_data = """
-- ++ ++ ++ --
... | Python | 1 |
error_nn_4dof = ik_4dof.verify_accuracy(target_4dof_ee_pos, pred_angles_nn_4dof)
print(
f"4-DOF NN Pred for {np.around(target_4dof_ee_pos, 1)}: angles={np.degrees(pred_angles_nn_4dof).round(1)} deg, error={error_nn_4dof:.3f} mm")
pred_angles_nr_4dof = ik_4dof.newton_r... | Python | 1 |
ate(self.pcz.data[word][sense_id]["cluster"]):
if cluster_word in wv.word2idx:
cw = cluster_word
else:
f = cluster_word.split(self.SEP_SENSE_POS)
if len(f) == 2 and f[0] in wv.word2idx:
... | Python | 1 |
se super::*;
const CORE_CLOCK: u32 = 84_000_000;
#[monotonic(binds = SysTick, default = true)]
type MyMono = DwtSystick<84_000_000>;
type IrProto = Nec;
type IrReceivePin = PA10<Input<Floating>>;
type IrReceiver = ConstReceiver<Nec, Event, PinInput<IrReceivePin>, CORE_CLOCK>;
#[shared]
... | Rust | 0 |
S, false)?
.visit_field::<flatbuffers::ForwardsUOffset<&str>>(
"prev_checkpoint_dir",
Self::VT_PREV_CHECKPOINT_DIR,
false,
)?
.visit_field::<flatbuffers::ForwardsUOffset<&str>>(
"new_checkpoint_dir",
Self... | Rust | 0 |
one());
return Poll::Pending;
}
}
let packet_option: Option<P> = ready!(Pin::new(&mut self.input_stream).poll_next(cx));
match packet_option {
None => {
for to_egressor in self.to_egressors.iter() {
... | Rust | 0 |
import streamlit as st
import data as data
st.set_page_config(layout="wide")
row1 = st.columns([1,10,1])
with row1[1]:
row1_sub = st.columns(6)
with row1_sub[0]:
st.title("MAJOR")
with row1_sub[1]:
st.header(data.df["ราคาปิด"][0] )
change = str(data.df["เปลี่ยนแปลง"][0]) + " (... | Python | 1 |
#!/usr/bin/env python3
"""
⚡ Satya Ultra-Fast API Showcase
=================================
Demonstrates the performance gains from using Satya's optimized APIs.
"""
from satya import BaseModel as SatyaModel
from pydantic import BaseModel as PydanticModel
import time
# Define models
class SatyaUser(SatyaModel):
... | Python | 1 |
days, 6) + calc(cache, num_days, 8);
cache.insert((num_days + 1, f), value);
value
} else {
1
}
}
use std::cell::RefCell;
use std::collections::HashMap;
use std::io::Error as IoError;
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync:... | Rust | 0 |
return super()._delete_index_sql(model, name, sql)
def _create_index_sql(
self,
model,
*,
fields=None,
name=None,
suffix="",
using="",
db_tablespace=None,
col_suffixes=(),
sql=None,
opclasses=(),
condition=None,
... | Python | 1 |
#!/usr/bin/env python3
import argparse, csv, json, os
from collections import defaultdict
def remove_prefix(text, prefix):
if text.startswith(prefix):
return text[len(prefix):]
return text
def remove_suffix(text, suffix):
if text.endswith(suffix):
return text[:-len(suffix)]
return tex... | Python | 1 |
pred_seq_prob = self.get_prob_of_token(
logit=logit, token_id=pred_seq, temperature=1.0
)
# set probability of unmasked tokens to infinity -> don't mask it again
pred_seq_prob = torch.where(
cur_mask, pred_seq_prob, torch.zeros_like(pred_seq_p... | Python | 1 |
destination address in msghdr",
);
return Err(err);
}
Some(d) => d,
};
Ok((
ret as usize,
sockaddr_to_std(&src_addr)?,
sockaddr_to_std(&dst_addr)?,
))
}
}
fn sockaddr_to_std(saddr: &libc::sockaddr_... | Rust | 0 |
import json
import os
import torch
from modules.agent.vits.models import SynthesizerTrn
from modules.agent.vits.vits import hps_ms, tts_fnD,save_as_wav
from modules.agent.vits import utils
class VITS:
"""
This class is used for the vits setup and inference.
这个类用于vits模型的配置以及推理。
"""
def __init__(self)... | Python | 1 |
f) -> u64 {
match self {
SplitReadTE::SM(sm_alignment) => sm_alignment.s,
SplitReadTE::MS(ms_alignment) => ms_alignment.s,
}
}
pub fn parse(cigar: String, pos: u64) -> Result<SplitReadTE> {
if regexes::SM_REGEX.is_match(&cigar[..]) {
... | Rust | 0 |
(Box::new(closure))).map_err(|err| match err {
Error::UiError(err) => match err {
SyncAllError::NoAccount => err!(NoAccount),
SyncAllError::ClientUpdateRequired => err!(UpdateRequired),
SyncAllError::CouldNotReachServer => err!(NetworkIssue),
},
Error::Unexpec... | Rust | 0 |
from setuptools import find_packages
from setuptools import setup
package_name = 'bno055'
setup(
name=package_name,
version='0.1.0',
# find sub-packages automatically in order to allow sub-modules, etc. to be imported:
# packages=[package_name],
packages=find_packages(exclude=['test']),
py_mod... | Python | 1 |
import logging
import os
import pandas as pd
import pytest
logger = logging.getLogger(__name__)
cow = bool(os.environ.get("LM_TEST_COPY_ON_WRITE", ""))
if cow:
try:
pd.options.mode.copy_on_write = cow
except AttributeError:
cow = False
if cow:
logger.critical("Copy on Write testing enable... | Python | 1 |
fn_args = $args;
$before
};
let mut $wrapped_res: $wrapped_body_ret = (|mut $before_block_res: &mut $before_block_ty| $wrapped_body)(&mut $before_block_res);
let _ = $after;
$wrapped_res
}
... | Rust | 0 |
_stars>0
use std::error::Error;
use std::fs;
use intcode::{Computer, ValueType};
const ORIGINAL_OUTPUT: ValueType = 19_690_720;
fn main() -> Result<(), Box<dyn Error>> {
let program = fs::read_to_string("input.txt")?;
let mut computer = Computer::new(program.trim())?;
computer.run_with_values(1, &[12, 2... | Rust | 0 |
x37, 3), // 0b0011
val16!(0x49, 3), // 0b0100
val16!(0x49, 3), // 0b0101
val16!(0x3b, 4), // 0b0110
val16!(0x15, 4), // 0b0111
val16!(0x7, 4), // 0b1000
val16!(0x11, 4), // 0b1001
val16!(0x5, 4), // 0b1010
val16!(0x3, 4), // 0b10... | Rust | 0 |
hurricane_server = HurricaneServerDriver()
hurricane_server.start_server(
params=["--webhook-url", "http://localhost:8074/webhook"],
env={"DJANGO_SETTINGS_MODULE": "tests.testapp.settings_hurricane_version"},
)
response = requests.get("http://localhost:8001/alive", t... | Python | 1 |
pub fn _bits(&self) -> u8 {
match *self {
PWM_CC_PWMDIVW::PWM_CC_PWMDIV_2 => 0,
PWM_CC_PWMDIVW::PWM_CC_PWMDIV_4 => 1,
PWM_CC_PWMDIVW::PWM_CC_PWMDIV_8 => 2,
PWM_CC_PWMDIVW::PWM_CC_PWMDIV_16 => 3,
PWM_CC_PWMDIVW::PWM_CC_PWMDIV_32 => 4,
P... | Rust | 0 |
import os, sys
# Add the parent directory to the sys.path
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import pytest
from hermes.core import transcribe
@pytest.mark.integration
def test_transcribe_local_file():
result = transcribe('tests/assets/input.mp4', provider='groq')
asse... | Python | 1 |
ame, window=7):
state_data = data[data['States'] == state_name]
fig = go.Figure()
fig.add_trace(go.Scatter(x=state_data['Date'], y=state_data['Confirmed'],
mode='lines+markers', name='Confirmed Cases'))
state_data['Confirmed_MA'] = state_data['Confirmed'].rolling(window=wind... | Python | 1 |
def array_count9(nums):
cnt = 0
for i in nums:
if i == 9:
cnt += 1
return cnt
| Python | 1 |
";
//!
//! let pjh = thread::spawn(move || {
//! println!("-> sending message: '{}'", smsg);
//!
//! let zero = [0 as u8];
//! let mut bytes = smsg.as_bytes().chain(&zero[..]);
//! loop {
//! match prod.read_from(&mut bytes, None) {
//! Ok(n) => {
//! if n == 0 {
//! ... | Rust | 0 |
f"Annealing completed in {total_time:.2f}s after {iteration} iterations. "
f"Final energy: {best_energy}"
)
return result
except Exception as e:
logger.error(f"Error during annealing: {str(e)}", exc_info=True)
raise
# Ex... | Python | 1 |
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, software
// distributed under the License ... | Rust | 0 |
from pathlib import Path
from typing import List, Optional, Tuple
import torch
from torch import Tensor
def _number_of_samples(routing_weights: List[Tensor]):
count = 0
for routing_weight in routing_weights:
count += routing_weight.size(0)
return count
class LayerWiseRoutingWeightSaver:
"""... | Python | 1 |
(),
new_data.variant.clone(),
new_data,
);
// the original function data is unchanged
data
}
fn name(&self) -> String {
"inconsistency_check_instrumenter".to_string()
}
}
<reponame>Logiase/stm32-rustup<filename>examples/rtic-blink.rs
#![no_main]
#![n... | Rust | 0 |
# -*- coding: utf-8 -*-
# Tested on Python 3.8.0
# This tool should be used with Legend of Galactic Heroes
# Ver Date Author
# v0.1 13.06.2020 Bartlomiej Duda
import os
import sys
import struct
def bd_logger(in_str):
import datetime
now = datetime.datetime.now()
print(now.strftime("%d-%... | Python | 1 |
VE Area) of the Intel® 64 and IA-32 Architectures Software Developer's Manual Volume 1 (Basic Architecture).
let offset = if self.is_extended_region_uncompacted()
{
sizing.uncompacted_byte_offset
}
else
{
const BaseOffset: usize = 576;
// "If XCOMP_BV[j] = 0 for every j, 2 ≤ j < i, locationI... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.