text string | label_name string | labels int64 |
|---|---|---|
ber of elements up front too
let typeDefinedArray: [i32; 5] = [1, 2, 3, 4, 5];
println!("{} is the last element in this array", typeDefinedArray[4]);
}
fn do_functions(){
////////////////
//3.3 FUNCTIONS!
////////////////
println!("\n--FUNCTIONS--");
another_function(5, 6);
}
//Rust uses ... | Rust | 0 |
for Wtf8Buf {
type Target = Wtf8;
fn deref(&self) -> &Wtf8 {
unsafe { transmute(&*self.bytes) }
}
}
/// Format the string with double quotes,
/// and surrogates as `\u` followed by four hexadecimal digits.
/// Example: `"a\u{D800}"` for a string with code points [U+0061, U+D800]
impl fmt::Debug f... | Rust | 0 |
from . import glvars
from .TetColors import TetColors
# ----------------------
# UTIL. FUNCTIONS
# ----------------------
# def cli_logout():
# global nom_utilisateur, solde_gp, id_perso
# nom_utilisateur = solde_gp = id_perso = None
def load_server_config():
import os
f = open(os.path.join('server... | Python | 1 |
her) {
let mut random_vec = gen_random_f64_vec(NUMBER);
b.iter(|| {
for _ in 0..ITERS {
let _ =sample(&mut random_vec, 0xBad53eed);
}
});
}
#[bench]
fn test_sample_plain(b: &mut Bencher) {
let mut random_vec = gen_random_f64_vec(NUMBER);
b.iter(|| {
for _ in 0..I... | Rust | 0 |
gen_ssa::common::TypeKind::Double,
TypeKind::X86_FP80 => rustc_codegen_ssa::common::TypeKind::X86_FP80,
TypeKind::FP128 => rustc_codegen_ssa::common::TypeKind::FP128,
TypeKind::PPC_FP128 => rustc_codegen_ssa::common::TypeKind::PPC_FP128,
TypeKind::Label => rustc_codegen_s... | Rust | 0 |
erial,
InterruptEnableFlag::Joypad => InterruptFlag::Joypad,
}
}
}
/// This mask represent the various interrupts that the program can enable.
#[derive(Debug, Clone, Copy, PartialEq, IntoPrimitive, IntoEnumIterator)]
#[repr(u8)]
pub enum InterruptEnableFlag {
VerticalBlanking = 0b00000001,
... | Rust | 0 |
= Regex::new(pattern).expect("Failed to create Regex pattern!");
stats
.into_iter()
.filter(|s| re.is_match(&s.name).unwrap())
.collect()
}
fn print(opt: &Opt, to_print: &[impl Tabled + Serialize]) {
if opt.json {
debug!("Printing as json");
println!("{}", serde_json::t... | Rust | 0 |
//! A library for reading and writing Blizzard's proprietary MoPaQ archive format.
//!
//! Currently, `ceres-mpq` only supports reading and writing Version 1 MoPaQ
//! archives, as this is the only version of the format still actively encountered
//! in the wild, used by Warcraft III custom maps.
//!
//! For this reas... | Rust | 0 |
ub struct COMP_SPEC;
impl crate::RegisterSpec for COMP_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [comp::R](R) reader structure"]
impl crate::Readable for COMP_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [comp::W](W) writer structure"]
impl crate::Writable for COMP_SPEC {
t... | Rust | 0 |
# tests/accounting/test_signalpnl_standardization.py
import pytest
import numpy as np
from endersgame.accounting.stdsignalpnl import StdSignalPnl
def test_initialization_defaults():
pnl = StdSignalPnl()
assert pnl.signal_var.get_mean() == 0.0, "Initial signal mean should be 0.0"
assert pnl.signal_var.get... | Python | 1 |
BR = bindings::vea_bitrate_mode_VBR,
CBR = bindings::vea_bitrate_mode_CBR,
}
/// Represents a bitrate for the VEA.
#[derive(Debug, Clone, Copy)]
pub struct Bitrate {
pub mode: BitrateMode,
pub target: u32,
pub peak: u32,
}
impl Bitrate {
pub fn to_raw_bitrate(&self) -> bindings::vea_bitrate_t {
... | Rust | 0 |
// The layout of value, based on its Rust type.
pub layout: TyLayout<'tcx>,
}
impl<'tcx> fmt::Debug for OperandRef<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "OperandRef({:?} @ {:?})", self.val, self.layout)
}
}
impl<'a, 'tcx> OperandRef<'tcx> {
pub fn new_z... | Rust | 0 |
!',
'Do it!':'Скажите "ДА"!',
'Please, restart Kodi now!':'Теперь перезагрузите Коди, пожалуйста!',
'./ (Root folder)':'./ (Корневой каталог)',
'Opening torrent file':'Открытие torrent-файла',
'New player to Torrenter v2 - pyrrent2http! Advantages of Torrent2H... | Python | 1 |
tes and dashes to
# typographically correct entities.
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}
# If false, no module ... | Python | 1 |
tern which will later be usable for fuzzy search.
/// A pattern should be reused
pub fn from(pat: &str) -> Self {
let chars = pat
.chars()
.map(secular::lower_lay_char)
.collect::<Vec<char>>()
.into_boxed_slice();
let max_nb_holes = match chars.len... | Rust | 0 |
='Use dropout at inference time')
group.add_argument('--retain-dropout-modules', default=None, nargs='+', type=str,
help='if set, only retain dropout for the specified modules; '
'if not set, then dropout will be retained for all modules')
# special decoding f... | Python | 1 |
ithub/workflows/self-scheduled.yml@refs/heads/main"
if os.environ.get("CI_WORKFLOW_REF") == target_workflow:
# Get the last previously completed CI's failure tables
artifact_names = ["prev_ci_results"]
output_dir = os.path.join(os.getcwd(), "previous_reports")
os.makedirs(output_dir,... | Python | 1 |
sum_acc += acc
loss = sum_loss / (batch_idx + 1)
acc = sum_acc / (batch_idx * bs + mb_len)
pbar.set_postfix(loss='{:.4f}, acc={:.4f}'.format(loss, acc))
predicted = torch.concat([predicted, output], dim=0)
labels = torch.concat([labels, target], dim=0)
... | Python | 1 |
# -----------------------------------------------------------------------------
# Python & OpenGL for Scientific Visualization
# www.labri.fr/perso/nrougier/python+opengl
# Copyright (c) 2017, Nicolas P. Rougier
# Distributed under the 2-Clause BSD License.
# ------------------------------------------------------------... | Python | 1 |
string"
},
"VerificationMessageTemplate": {
"DefaultEmailOption": "string",
"EmailMessage": "string",
"EmailMessageByLink": "string",
"EmailSubject": "string",
"EmailSubjectByLink": "string",
"SmsMessage"... | Rust | 0 |
ation_file")]
TranslationFile(PassportElementErrorTranslationFile),
#[serde(rename = "translation_files")]
TranslationFiles(PassportElementErrorTranslationFiles),
#[serde(rename = "unspecified")]
Unspecified(PassportElementErrorUnspecified),
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialE... | Rust | 0 |
"""Greet Agent CrewAI Flow"""
import json
from typing import Any, Dict, cast
from crewai.flow.flow import Flow, start, router, listen
from litellm import completion
from copilotkit.crewai import copilotkit_exit, copilotkit_stream
EXTRACT_NAME_TOOL = {
"type": "function",
"function": {
"name": "Extract... | Python | 1 |
($a0: expr, $a1: expr, $a2: expr, $is_signed: expr) => {
[cap_u8!($a0, $is_signed), $a1, cap_u8!($a2, $is_signed)]
};
}
<filename>src/gdb_expression_parsing/ast.rs
use super::lexer::Span;
use json::{object, JsonValue};
pub const ANON_KEY: &'static str = "*anon*";
pub const EMPTY_SPAN: Span = (0, 0);
p... | Rust | 0 |
exposes the `VirtualNode` struct and methods that power our
//! virtual dom.
// TODO: A few of these dependencies (including js_sys) are used to power events.. yet events
// only work on wasm32 targets. So we should start sprinkling some
//
// #[cfg(target_arch = "wasm32")]
// #[cfg(not(target_arch = "wasm32"))]
//
/... | Rust | 0 |
0..=10.0));
root.add({
let mut container = Container::vbox();
container.add(Button::labelled("One", 12));
container.add(Button::labelled("Two", 12));
container.add({
let mut nested = Container::new(BorderLayout::new());
let mut nested_button = Button::labelled("Nested button", 12);
nested_butt... | Rust | 0 |
class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
ans = []
def dfs(root: Optional[TreeNode], path: List[str]) -> None:
if not root:
return
if not root.left and not root.right:
ans.append(''.join(path) + str(root.val))
return
path.appe... | Python | 1 |
n=int(input("Nhap kích thước danh sách"))
list=[]
def nhap(list,n):
for i in range(n):
print("Nhập phần tử thứ",i)
list.append(int(input()))
return list
def kiem_tra(list,n):
ktra=0
for i in list:
if x==i:
ktra=1
return ktra
print(f"Mảng vừa nhập là: {n... | Python | 1 |
from typing import Annotated
from fastapi import Depends, status, Request, HTTPException
from app.schemas.user import User
from app.utils.jwt_token_provider import jwt_provider
def get_token(request: Request) -> str:
"""
헤더의 Authorization에서 Bearer 토큰을 추출합니다.
:param request: Request
:return: jwt acces... | Python | 1 |
ING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION W... | Rust | 0 |
ver_fixes(self):
'''
These fixes ensure that the <meta> tag for the cover has a content
of 'cover' and the corresponding manifest item of 'cover' is first item.
'''
root = self.container.opf
from calibre.customize.ui import plugin_for_output_format
oeb_output = pl... | Python | 1 |
Sets bit at position `i` in `data`
/// # Panics
/// panics if `i >= data.len() / 8`
#[inline]
pub fn set_bit(data: &mut [u8], i: usize, value: bool) {
data[i / 8] = set(data[i / 8], i % 8, value);
}
/// Sets bit at position `i` in `data` without doing bound checks
/// # Safety
/// caller must ensure that `i < data... | Rust | 0 |
if self.print_prune_params:
print_prune_params(model)
ori_flops = flops(model, input_spec) / 1000
logger.info("FLOPs before pruning: {}GFLOPs".format(ori_flops))
if self.criterion == 'fpgm':
pruner = paddleslim.dygraph.FPGMFilterPruner(model, input_spec)
... | Python | 1 |
# Copyright 2021 HPC-AI Technology Inc.
#
# 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 i... | Python | 1 |
ErrorKind::NotFound => ConfigError::NotFound,
_ => ConfigError::ReadingFile(format!("Reading configuration file: {}", e)),
})
.and_then(|file_content| {
toml::from_slice::<Config>(&file_content).map_err(|e| {
ConfigError::ReadingFile(format!("P... | Rust | 0 |
RENDER = False
dat_folder = os.path.dirname(__file__)
experiment = BlenderExperiment(Nb_frames=2) # We want Time 0 and Time 1 -> 2 frames (WARNING : BLENDER frames = rendering time, OBJECT frame = orientation in the scene)
experiment.set_default_background()
# Reading the mesh and adding it to the experiment
print("A... | Python | 1 |
)
stats["dex_breakdown"][dex_id] = {
"pools": len(pools),
"reserve_usd": stats["total_reserve_usd"]
}
else:
# Get stats for all target DEXes
for target_dex in self.target_dexes:
p... | Python | 1 |
=> self.r_pc = value,
9 => self.r_cond = value,
_ => panic!("Inxed out of bound. "),
}
}
pub fn get(&self, index: u16) -> u16 {
match index {
0 => self.r_00,
1 => self.r_01,
2 => self.r_02,
3 => self.r_03,
4 => ... | Rust | 0 |
= " @brief Event pool descriptor"]
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct _ze_event_pool_desc_t {
#[doc = "< [in] type of this structure"]
pub stype: ze_structure_type_t,
#[doc = "< [in][optional] pointer to extension-specific structure"]
pub pNext: *const ::std::os::raw::c_void,
#[doc ... | Rust | 0 |
: TokenRead>(parser: &mut Parser<T>) -> Result<Self> {
Ok(ListElement {
element_type: track!(parser.parse())?,
non_empty: track!(parser.parse())?,
})
}
}
impl PositionRange for ListElement {
fn start_position(&self) -> Position {
self.element_type.start_position()... | Rust | 0 |
_modal('CANCEL', 'RIGHTMOUSE', 'ANY', any=True)
kmi = km.keymap_items.new_modal('CONFIRM', 'RET', 'PRESS', any=True)
kmi = km.keymap_items.new_modal('CONFIRM', 'NUMPAD_ENTER', 'PRESS')
kmi = km.keymap_items.new_modal('SELECT', 'LEFTMOUSE', 'PRESS')
kmi = km.keymap_items.new_modal('DESELECT', 'MIDDLEMOUSE', 'PRESS')
kmi... | Python | 1 |
const IOCTL_STORAGE_POWER_ACTIVE: DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0722,
METHOD_BUFFERED, FILE_ANY_ACCESS);
pub const IOCTL_STORAGE_POWER_IDLE: DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0723,
METHOD_BUFFERED, FILE_ANY_ACCESS);
pub const IOCTL_STORAGE_EVENT_NOTIFICATION: DWORD = CTL_CODE!(IOCTL_STORAGE_BASE... | Rust | 0 |
from ..Qt import QtGui
from .. import functions as fn
from .PlotDataItem import PlotDataItem
from .PlotCurveItem import PlotCurveItem
__all__ = ['FillBetweenItem']
class FillBetweenItem(QtGui.QGraphicsPathItem):
"""
GraphicsItem filling the space between two PlotDataItems.
"""
def __init__(self, curve... | Python | 1 |
writer.prefix("MasterUsername");
if let Some(var_175) = &input.master_username {
scope_174.string(var_175);
}
#[allow(unused_mut)]
let mut scope_176 = writer.prefix("MasterUserPassword");
if let Some(var_177) = &input.master_user_password {
scope_176.string(var_177);
}
#[all... | Rust | 0 |
#[test_case("-42", CypherValue::from(-42) ; "int: negative")]
#[test_case("0.0", CypherValue::from(0.0) ; "float: zero v1")]
#[test_case("0.", CypherValue::from(0.0) ; "float: zero v2")]
#[test_case(".0", CypherValue::from(0.0) ; "float: zero v3")... | Rust | 0 |
.append_pair("code", access_code.as_ref());
let req = Request::get(url.to_string()).body(Nothing)?;
let opts = FetchOptions {
cache: Some(Cache::NoCache),
..Default::default()
};
FetchService::fetch_with_options(
req,
opts,
... | Rust | 0 |
scores_mask = (target_sum > 0) & (other_sum < 0)
else:
scores_mask = (target_sum < 0) & (other_sum > 0)
# Create a 2D numpy array of scores for each pair of candidate features
scores = (
tf.cast(scores_mask, tf_dtype) * (-target_sum * other_sum) * zero_diagona... | Python | 1 |
"""Unit tests for the route injection plugin model."""
import unittest
import bottle
from routes.plugins import InjectionPlugin
class RouteInjectionPluginTest(unittest.TestCase):
"""Unit tests for the route injection plugin."""
def tearDown(self):
"""Override to remove the plugins."""
bott... | Python | 1 |
import os
import json
import unittest
import jc.parsers.sysctl
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
class MyTests(unittest.TestCase):
# input
with open(os.path.join(THIS_DIR, os.pardir, 'tests/fixtures/centos-7.7/sysctl-a.out'), 'r', encoding='utf-8') as f:
centos_7_7_sysctl = f.rea... | Python | 1 |
#!/usr/bin/env python3
"""
Test script for verifying Sapphire authentication using oasis-sapphire-py.
This script tests basic connectivity and authentication with the Sapphire network.
"""
import os
import logging
from web3 import Web3
import time
from sapphire_wrapper import create_sapphire_web3
# Configure logging... | Python | 1 |
(&listener, 1).expect("listen");
let local_addr = rustix::net::getsockname(&listener)?;
let sender = rustix::net::socket(AddressFamily::INET, SocketType::STREAM, Protocol::default())?;
rustix::net::connect_any(&sender, &local_addr).expect("connect");
let request = b"Hello, World!!!";
let n = rustix... | Rust | 0 |
up clk: Spi45(Variant) d2ccip1 "SPI4/5"],
Spi5 [group clk: Spi45],
Usart1 [group clk: Usart16(Variant) d2ccip2 "USART1/6"],
Usart6 [group clk: Usart16]
];
#[cfg(feature = "rm0455")]
APB2, "" => [
Dfsdm1 [kernel clk: Dfsdm1 cdccip1 "DFSDM1"],
Sai1 [kernel clk: Sai1(V... | Rust | 0 |
0.05 -0.3 ]]
When ``s=[2, 4]``, shape of the transform will be ``(2, 4)``
>>> with jnp.printoptions(precision=2, suppress=True):
... print(jax.scipy.fft.idctn(x, s=[2, 4]))
[[ 0.1 0.18 0.07 -0.16]
[ 0.2 0.06 -0.03 -0.01]]
``jax.scipy.fft.idctn`` can be used to reconstruct ``x`` from t... | Python | 1 |
and persisting policies set by clients.
#[async_trait]
pub trait PolicyHandler {
/// Called when a policy client makes a request on the policy API this handler controls.
async fn handle_policy_request(&mut self, request: Request) -> Response;
/// Called when a setting request is intercepted for the setting... | Rust | 0 |
from .utils import _MetaCls
from typing import TypeVar, Any
from .types_syntactic import AtomicType
from .types_semantic import SemanticType
from .types_tecto import TNone, TAny, TectoType
BuiltInTypeSubclass = TypeVar('BuiltInTypeSubclass', bound="BuiltInType")
class _BuiltInType(AtomicType, SemanticType, metacla... | Python | 1 |
MockThing::private_deserialize_context();
ctx.expect()
.withf(|st: &Result<SurrogateThing, ()>|
st.as_ref().unwrap().x == 42
).once()
.returning(|_| MockThing::default());
let json = "{\"x\":42}";
let _thing: MockThing = serde_json::from_str(json).unwrap();
}
<filena... | Rust | 0 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome to Car Rental System</title>
<style>
body {
background-color: #282828;
color: white;
font-family: Georgia, seri... | Python | 1 |
h controller's name will be a property of this object.
The value of each property of the returned value is an object with the following properties:
``analog``:
holds a dictionary with analog port names as keys and numpy array of samples as values.
``digital``:
holds a... | Python | 1 |
pub radius: f32,
/// Number of sections in cylinder between hemispheres.
pub rings: usize,
/// Height of the middle cylinder on the y axis, excluding the hemispheres.
pub depth: f32,
/// Number of latitudes, distributed by inclination. Must be even.
pub latitudes: usize,
/// Number of l... | Rust | 0 |
.5), texcoord: vec2(0.0, 1.0) },
Vertex { pos: vec3(-0.5, -0.5, 0.5), texcoord: vec2(0.0, 0.0) },
Vertex { pos: vec3(-0.5, 0.5, 0.5), texcoord: vec2(1.0, 0.0) },
Vertex { pos: vec3(-0.5, 0.5, -0.5), texcoord: vec2(1.0, 1.0) },
Vertex { pos: vec3(-0.5, -0.5, -0.5), texcoord: vec2(0.0, 1.0) },
Vertex { pos... | Rust | 0 |
tring("/lorem/ipsum/").is_some());
///
/// let matcher = route!("/{*}/dolor/sit");
/// assert!(matcher.match_route_string("/lorem/ipsum/dolor/sit").is_some());
/// assert!(matcher.match_route_string("/lorem/dolor/sit").is_some());
/// assert!(matcher.match_route_string("/dolor/sit").is_none());
/// ```
///
/// #### Mat... | Rust | 0 |
rrow::Cow, io, iter, pin::Pin};
use unsigned_varint::codec;
/// Implementation of the `ConnectionUpgrade` for the Gossipsub protocol.
#[derive(Debug, Clone)]
pub struct ProtocolConfig {
protocol_id: Cow<'static, [u8]>,
max_transmit_size: usize,
}
impl Default for ProtocolConfig {
fn default() -> Self {
... | Rust | 0 |
__ == "__main__":
path_manager: TrainingDataPathManager = TrainingDataPathManager("path_manager")
tag_type: str = "Funny"
transform_type: str = "Realistic3High"
model_type: str = "Default"
model_num: str = "50.4"
existing_model_num: str = "0"
... | Python | 1 |
Caller must keep the returned guard alive.
pub fn set_global_logger(async_drain: bool, chan_size: Option<usize>) -> GlobalLoggerGuard {
set_global_logger_with_level(async_drain, chan_size, FilterLevel::Info)
}
/// Creates and sets the global logger with the given filter level.
pub fn set_global_logger_with_level(... | Rust | 0 |
test]
fn test_shared_inc_metric() {
let metric = Arc::new(SharedIncMetric::default());
// We're going to create a number of threads that will attempt to increase this metric
// in parallel. If everything goes fine we still can't be sure the synchronization works,
// but if something... | Rust | 0 |
uted (switched) from <NAME>'s original VEF file...not entirely sure
/// why, yet.
pub fn get_vertices(&self) -> Vec<Vector4<f32>> {
match *self {
Polychoron::Cell8 => vec![
Vector4::new(-0.5, -0.5, -0.5, -0.5),
Vector4::new(-0.5, -0.5, -0.5, 0.5),
... | Rust | 0 |
eq date --days 10",
result: None,
},
Example {
description: "print the previous 10 days in YYYY-MM-DD format with newline separator",
example: "seq date --days 10 -r",
result: None,
},
Example {
... | Rust | 0 |
one, Copy, PartialEq, Eq)]
pub enum Profile {
BerlinSuburbanRailway,
BerlinUrbanRailway,
BerlinRapidTransit,
BerlinMetro,
BerlinWithoutRailway,
Berlin,
BerlinBrandenburgWithoutRailway,
BerlinBrandenburg,
}
impl Profile {
pub(crate) fn filter<'a>(self, agencies: impl Iterator<Item = ... | Rust | 0 |
, 2, 4], [10, 11, 12, 14]");
}
}
<reponame>DKerp/fut-compat
use std::net::{
SocketAddr,
SocketAddrV4,
SocketAddrV6,
IpAddr,
};
use std::str::FromStr;
use std::path::Path;
use async_trait::async_trait;
/// Contains the compatibility objects for the [`tokio`](https://docs.rs/tokio) runtime.
#[cfg(... | Rust | 0 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2018-01-19 09:03
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('order', '0015_create_disable_repeat_order_check_switch'),
]
operations = [
migrations.RemoveField(
model_name=... | Python | 1 |
"""make news.slug unique and not nullable
Revision ID: 95639507ec8b
Revises: e21cfb702854
Create Date: 2018-08-09 00:35:39.510051
"""
# revision identifiers, used by Alembic.
revision = '95639507ec8b'
down_revision = 'e21cfb702854'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as s... | Python | 1 |
) == 1:
server = Server(None, event.group_id).server
school = args[0]
if len(args) == 2:
if args[0] != "全服":
server = Server(args[0], event.group_id).server
else:
server = "全服"
school = args[1]
school = School(school).name
if school is None:
... | Python | 1 |
engine/api/v1.23/">Docker Remote API</a> and the <code>--cpu-shares</code> option to
/// <a href="https://docs.docker.com/engine/reference/run/">docker run</a>. Each vCPU is equivalent to 1,024 CPU shares. For EC2
/// resources, you must specify at least one vCPU. This is required but can be specified in severa... | Rust | 0 |
+ 1e-10 # 防止除以零
extracted_features = masked_features.sum(dim=(1, 2)) / total_area
exo_funcparts_mask.append(mask_tensor)
exo_funcparts.append(extracted_features.unsqueeze(0)) # 添加特征至列表
# ----------circle----------#
... | Python | 1 |
import random
from api import GameService
def main():
svc = GameService()
print("Game app! (client)")
print()
print()
print("TOP SCORES")
for s in svc.top_scores():
print("{} scored {}".format(s.get('player').get('name'), s.get('score')))
print()
game_id = svc.create_game().... | Python | 1 |
y(rho2[cv2_ix])[patch_idxs2]
for ring in range(num_rings):
scale = scales[ring]
members = np.where((patch_rho2 >= scales[ring]) & (patch_rho2 < scales[ring + 1]))
if len(members[0]) == 0:
comp_rings2_25[ring] = 0.0
comp_rings2_50[ring] = 0.0
... | Python | 1 |
#!/usr/bin/python
# Python AES Crypter
# Author: SLAE-935
#
# Usage: python Enctypt.py 16bytesKey
# Ex: python Encrypt.py AABBCCDDAABBCCDD
import base64, re
from Crypto.Cipher import AES
from Crypto import Random
def encrypt(key):
shellcode = "\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x89\x... | Python | 1 |
}
// reconnect the controller to see
// the real partition pop up after unlocking
device.reconnect_controller(st).fix(info!())?;
}
}
let handle = find_boot_partition(st)?;
let dp = st
.boot_services()
.handle_protocol::<DevicePath>(handle)
... | Rust | 0 |
(rename = "s390")]
S390,
#[serde(rename = "s390x")]
S390x,
#[serde(rename = "sparc")]
Sparc,
#[serde(rename = "sparc64")]
Sparc64,
#[serde(rename = "mips")]
Mips,
#[serde(rename = "mips-le")]
MipsLe,
#[serde(rename = "mips64")]
Mips64,
#[serde(rename = "mips64-le"... | Rust | 0 |
import random
import numpy as np
import os
from PIL import Image
import json
import jax
import jax.numpy as jnp
import equinox as eqx
def seed_all(seed):
"""
provide the seed for reproducibility
"""
random.seed(seed)
os.environ["PYTHONHASHSEED"] = str(seed)
np.random.seed(seed)
return jax... | Python | 1 |
non-representable data, then recursively serialize their input without
//needing to repeat those checks.
struct Unchecked<T>(T);
impl<'a> Serialize for Unchecked<&'a Val> {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
match *self.0 {
Val::Nil => s.serialize_unit_variant("Val", 0... | Rust | 0 |
ices last 60s before they go from fresh to stale
const FRESH_TIMESPAN: u64 = 60;
/// ## Description
/// Exposes all the execute functions available in the contract.
///
/// ## Params
/// - **deps** is an object of type [`DepsMut`].
///
/// - **env** is an object of type [`Env`].
///
/// - **info** is an object of type... | Rust | 0 |
req: AggTradesRequest<S>,
) -> Result<Vec<AggTradesRecord>, A::ErrorCode>
where
S: AsRef<str>,
{
self.client.get(A::agg_trades(), req).await
}
pub async fn klines<S>(&self, req: KlinesRequest<S>) -> Result<Vec<KlinesRecord>, A::ErrorCode>
where
S: AsRef<str>,
{
... | Rust | 0 |
_deltas();
parameter_manager.zero_all_state_derivatives();
}
fn info(&self){
println!("optimizer_name: {}", self.name);
println!("learning_rate: {}", self.learning_rate);
println!("momemtum: {}", self.momemtum);
println!("decay: {}", self.decay);
println!("nesterov: {}... | Rust | 0 |
_stars>0
#[macro_use]
extern crate kaspa_miner;
use clap::{ArgMatches, FromArgMatches};
use kaspa_miner::{Plugin, Worker, WorkerSpec};
use log::{info, LevelFilter};
use opencl3::device::{Device, CL_DEVICE_TYPE_ALL};
use opencl3::platform::{get_platforms, Platform};
use opencl3::types::cl_device_id;
use std::error::Err... | Rust | 0 |
self
}
fn _verification_level(&mut self, verification_level: VerificationLevel) {
let num = from_number(verification_level.num());
self.0.insert("verification_level", num);
}
/// Modifies the notifications that are sent by discord to the configured system channel.
///
/// ``... | Rust | 0 |
Predicted relevance score
"""
model = load_model(model_path, config)
# Calculate direct cosine similarity between embeddings
# This shows what the similarity would be without the trained model
raw_similarity = np.dot(sample_website_embedding, sample_prompt_embedding)
print(f"Raw cosine simi... | Python | 1 |
n_now()
# Allow time for API calls to complete
await asyncio.sleep(5)
logger.info("One-time summary generation completed (DUMMY MODE)")
async def main() -> None:
"""
Main application entry point for dummy mode.
"""
try:
# Initialize components
components = await ini... | Python | 1 |
ScalarClass for f32 {
fn getClass()->mxClassID{
return mxClassID::mxSINGLE_CLASS;
}
}
impl MexScalarClass for f64 {
fn getClass()->mxClassID{
return mxClassID::mxDOUBLE_CLASS;
}
}
impl MexScalarClass for i32 {
fn getClass()->mxClassID{
... | Rust | 0 |
medium += 1
severity = '<span style="background-color: #f1c40f;"><strong>MEDIUM</strong></span>'
elif severity == "HIGH":
high += 1
severity = '<span style="background-color: #f8cac6;"><strong>HIGH</strong></span>'
elif severity == "LOW":
... | Python | 1 |
import os
def clearScreen():
os.system('clear')
def addBid (bidsDictionary):
name = ""
bid = 0
while len(name) == 0:
name = input("What's your name?\n")
while bid <= 0:
bid = input("Input your bid now\n$ ")
try:
bid = int(bid)
except ValueError:
... | Python | 1 |
fig_wait = px.histogram(
x=wait_times,
title='Distribution of Waiting Times',
labels={'x': 'Waiting Time (minutes)', 'y': 'Frequency'},
nbins=30
)
st.plotly_chart(fig_wait, use_container_width=True)
# Add explanatory no... | Python | 1 |
"""The lag/bond oper-status always follows the carrier"""
def lower(iplink):
"""Return a dictionary of the status of a lag member"""
port = {
"lag": iplink['master'],
}
info = iplink['linkinfo']['info_slave_data']
if info:
# active or backup link
port['state'] = info['stat... | Python | 1 |
$($name::$v => <$other>::$v),*
}
}
}
};
}
keyboard_enum! {
KeyInput as glutin::event::VirtualKeyCode {
Key1,
Key2,
Key3,
Key4,
Key5,
Key6,
Key7,
Key8,
Key9,
Key0,
A,
... | Rust | 0 |
.
#[test]
fn file_logging() {
setup_log_config();
let log_file_name = unwrap!(PathBuf::from_str("AppClient.log"));
let file_name = unwrap!(CString::new(unwrap!(log_file_name
.clone()
.into_os_string()
.into_string())));
unsafe {
u... | Rust | 0 |
def find_empty_cell(sudoku):
for row in range(9):
for column in range(9):
if sudoku[row][column] == 0:
return row, column
return None, None
def validity(sudoku, guess, row, column):
row_vals = sudoku[row]
if guess in row_vals:
return False
c... | Python | 1 |
lightlike_normal(&mut self, cmd: PlightlikeingCmd<S>) {
self.normals.push_back(cmd);
}
fn take_conf_change(&mut self) -> Option<PlightlikeingCmd<S>> {
// conf change will not be affected when changing between follower and leader,
// so there is no need to check term.
self.conf_c... | Rust | 0 |
each provider"]
#[doc = " Whenever this struct is updated, please also update the MakeKey function in onnxruntime/core/framework/execution_provider.cc"]
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub enum OrtMemType {
OrtMemTypeCPUInput = -2,
OrtMemTypeCPUOutput = -1,
OrtMemTypeDefault = 0,
}
#[rep... | Rust | 0 |
Quad::PI * Quad::ONE;
id_num:
Quad::PI,
Quad::ONE * Quad::PI;
num_small:
qd!("3.1415926535897932384626433832795028841971693993751058209749445923069e-60"),
Quad::PI * qd!("1e-60");
small_num:
qd!("3.1415926535897932384626433... | Rust | 0 |
v-testcases<filename>cases/src/vmsop_vv_cases.rs
use core::{arch::asm, convert::TryInto};
use eint::{Eint, E256};
use rvv_asm::rvv_asm;
use rvv_testcases::{
intrinsic::vmsop_vv,
misc::{avl_iterator, set_bit_in_slice},
runner::{run_vmsop_vv, WideningCategory},
};
fn expected_eq(lhs: &[u8], rhs: &[u8], resul... | Rust | 0 |
class BankersAlgorithm:
"""
实现银行家算法的类。
属性:
- allocation:当前资源分配情况
- max_need:每个进程的最大资源需求
- available:系统中可用的资源
- need:每个进程还需要的资源
- safe_sequence:安全序列
"""
def __init__(self, allocation, max_need, available):
"""
构造函数。
参数:
- allocation:当前资源分配情况
... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.