text string | label_name string | labels int64 |
|---|---|---|
::<Context>(), 8 * 4 * 6 + 512);
impl Context {
pub(super) fn kernel(entry: VirtAddr, pml4: PhysFrame, rsp: VirtAddr) -> Self {
Self::new(
entry,
pml4,
rsp,
gdt::kernel_code_selector(),
gdt::kernel_data_selector(),
)
}
pub(super) f... | Rust | 0 |
PA => 1,
VEC3_EVR::AON_RTC_CH2 => 0,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> VEC3_EVR {
match value {
31 => VEC3_EVR::ADC_IRQ,
30 => VEC3_EVR::MCU_EV,
29 => VEC3_EVR::ACLK_REF,
28 => VE... | Rust | 0 |
#! /usr/bin/env python2
# -*- coding: utf-8 -*-
# Please note that this example may not work on all GPUs (eg. intel chipsets)
# because of a bug in the drivers. See the corresponding SFML issue:
# https://github.com/LaurentGomila/SFML/issues/101
import sfml as sf
def main():
window = sf.RenderWindow(sf.VideoMod... | Python | 1 |
{
x: -self.x,
y: -self.y,
z: -self.z,
r: self.r,
g: self.g,
b: self.b,
}
}
}
impl cmp::PartialEq for Vec3 {
fn eq(&self, rhs: &Vec3) -> bool {
if self.x != rhs.x {
return false;
}
if self.y != ... | Rust | 0 |
# Mobile Verification Toolkit (MVT)
# Copyright (c) 2021-2023 The MVT Authors.
# Use of this software is governed by the MVT License 1.1 that can be found at
# https://license.mvt.re/1.1/
from .artifact import AndroidArtifact
class DumpsysPlatformCompatArtifact(AndroidArtifact):
"""
Parser for uninstalled ... | Python | 1 |
import traceback
from time import sleep
FAILED = []
SUCCESS = []
def test_kivy():
import kivy
import kivy.event
import kivy.core.window
import kivy.uix.widget # noqa: F401
def test_audiostream():
from audiostream import get_output
from audiostream.sources.wave import SineSource
stream ... | Python | 1 |
(size - 10) * dy).x,
y: (loc.bottom_left + f64::from(size - 10) * dx - 3.0 * dy).y,
};
debug!("ORIG EST {:?}, NEW EST {:?}", orig_estimate, est_alignment);
let mut delta = est_alignment - orig_estimate;
debug!("DELTA {:?}", delta);
delta = delta / f64::from((size - 10) * (size - 10));
... | Rust | 0 |
e_name_node)?;
NameClass::classify(sema, &name)?.defined(sema.db)
}
<reponame>tokera-com/ate
use ate::chain::ChainKey;
use serde::*;
use std::fmt;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct InstanceHello {
pub chain: ChainKey,
pub access_token: String,
}
impl fmt::Display
for InstanceH... | Rust | 0 |
,// EVEX_Vcvtw2ph_ymm_k1z_ymmm256b16
0x462A_007D,// EVEX_Vcvtw2ph_zmm_k1z_zmmm512b16_er
0x440A_005E,// EVEX_Vdivph_xmm_k1z_xmm_xmmm128b16
0x450A_005E,// EVEX_Vdivph_ymm_k1z_ymm_ymmm256b16
0x460A_005E,// EVEX_Vdivph_zmm_k1z_zmm_zmmm512b16_er
0x422A_005E,// EVEX_Vdivsh_xmm_k1z_xmm_xmmm16_er
0x443C_0056,// EVEX_Vfcm... | Rust | 0 |
"""Enables dynamic setting of underlying Keras module.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
_KERAS_BACKEND = None
_KERAS_UTILS = None
def set_keras_submodules(backend, utils):
# Deprecated, will be removed in the future.
global _KERA... | Python | 1 |
et new_user_count = get_all_users(&conn).len();
assert_eq!(response.status(), Status::Ok);
assert_eq!(new_user_count, user_count + 1);
assert!(response.body().is_some());
})
}
#[test]
fn test_register_is_not_successful_with_existing_email() {
run_test!(|client, conn, _jwt| {
let... | Rust | 0 |
(album)
count += 1
return albums
def extract_artists(self):
artists = []
count = 0
for j in self.params_bs4objs:
if j[0].get("qtype") == 2:
bsobj = j[1]
artist_tables = bsobj.select(".tdata td")
for i in... | Python | 1 |
# Copyright 2025 The kauldron Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | Python | 1 |
taType = 8;
pub const AVPacketSideDataType_AV_PKT_DATA_FALLBACK_TRACK: AVPacketSideDataType = 9;
pub const AVPacketSideDataType_AV_PKT_DATA_CPB_PROPERTIES: AVPacketSideDataType = 10;
pub const AVPacketSideDataType_AV_PKT_DATA_SKIP_SAMPLES: AVPacketSideDataType = 11;
pub const AVPacketSideDataType_AV_PKT_DATA_JP_DUALMON... | Rust | 0 |
let source_id = SourceId::crates_io(&config).unwrap();
let git = false;
let directory = Some(format!("{}/", output_path.to_str().unwrap()));
let opts = cargo_clone::CloneOpts::new(&crates, &source_id, directory.as_deref(), git);
cargo_clone::clone(&opts, &config).unwrap();
assert!(output_pat... | Rust | 0 |
ectural constraint"""
constraint_lower = constraint.lower()
content_lower = content.lower()
# Example constraint checks (can be expanded)
if "ui components must not directly access database" in constraint_lower:
if ("component" in file_path.lower() and
... | Python | 1 |
os.write_uint64(1, v)?;
}
if let Some(v) = self.endTxId {
os.write_uint64(2, v)?;
}
if let Some(v) = self.isInProgress {
os.write_bool(3, v)?;
}
os.write_unknown_fields(self.get_unknown_fields())?;
::std::result::Result::Ok(())
... | Rust | 0 |
[One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Zero])));
}
it "should show error when non digit on input" {
display.input("abc");
expect!(display.output()).to(be_err());
}
}
<filename>src/ostimer/evtimerh.rs<gh_stars>1-10
#[doc = "Reader of register EVTIMERH"]
pub type R = crate::R... | Rust | 0 |
");
struct OctopusGrid {
octopi: [Octopus; 100],
}
impl OctopusGrid {
fn octopus(&self, row: usize, col: usize) -> Option<&Octopus> {
if row >= 10 || col >= 10 {
return None;
}
Some(&self.octopi[(row * 10) + col])
}
fn octopus_mut(&mut self, row: usize, col: usize... | Rust | 0 |
tCPUMask(mask)?;
return Ok(0);
}
// SchedGetaffinity implements linux syscall sched_getaffinity(2).
pub fn SysSchedGetaffinity(task: &mut Task, args: &SyscallArguments) -> Result<i64> {
let tid = args.arg0 as i32;
let size = args.arg1 as usize;
let maskAddr = args.arg2 as u64;
// This limitation i... | Rust | 0 |
import pandas as pd
df = pd.DataFrame({'a': ['abcde', 'fghij', 'klmno'],
'b': [123, 456, 789]})
print(df)
# a b
# 0 abcde 123
# 1 fghij 456
# 2 klmno 789
print(df.dtypes)
# a object
# b int64
# dtype: object
print(df['a'].str[:2])
# 0 ab
# 1 fg
# 2 kl
# Name: a, dt... | Python | 1 |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
v=[]
for i in lists:
x=i
while ... | Python | 1 |
mf_u_ref, U_ref)
norm_H1 = gf.compute_H1_semi_norm(mf_u_ref, U_ref, mim_ref);
norm_H1 = np.sqrt(pow(norm_L2, 2)+ pow(norm_H1, 2))
err_H1 = gf.compute_H1_semi_dist(mf_u_ref, Ui, mim_ref,
m... | Python | 1 |
# Copyright (c) Alibaba, Inc. and its affiliates.
import os
from pathlib import Path
MODELSCOPE_URL_SCHEME = 'http://'
DEFAULT_MODELSCOPE_DOMAIN = 'www.modelscope.cn'
DEFAULT_MODELSCOPE_DATA_ENDPOINT = MODELSCOPE_URL_SCHEME + DEFAULT_MODELSCOPE_DOMAIN
MODELSCOPE_PARALLEL_DOWNLOAD_THRESHOLD_MB = int(os.environ.get('MOD... | Python | 1 |
'''
Webots simulator support for Crazyflie Python client
Copyright (C) 2023 Simon D. Levy
This program 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 2
of the License, or (at your option) any lat... | Python | 1 |
out += "\n" + i
await ctx.send(out)
list_command = {
"play":list_play,
"p":list_play,
"create":list_create_list,
"c":list_create_list
}
#####################################################################################################################################
#function
d... | Python | 1 |
the `engine.io` `Packet` types.
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum PacketId {
Open = 0,
Close = 1,
Ping = 2,
Pong = 3,
Message = 4,
Upgrade = 5,
Noop = 6,
}
/// A `Packet` sent via the `engine.io` protocol.
#[derive(Debug, Clone)]
pub struct Packet {
pub packet_id: Pa... | Rust | 0 |
}
#[rocket::get("/alive")]
pub fn get_health_check() {}
#[derive(Debug, Clone, Copy, Deserialize)]
pub struct MarginRequest {
pub price: Price,
pub quantity: Usd,
pub leverage: Leverage,
#[serde(with = "::bdk::bitcoin::util::amount::serde::as_btc")]
pub opening_fee: Amount,
}
/// Represents the... | Rust | 0 |
let b = b_ones.iter().cloned().collect::<BVector>();
a &= b;
let res = a.ones().collect::<Vec<usize>>();
assert!(res == a_and_b, "{:?}", res);
}
#[test]
fn bitor_assign_shorter() {
let a_ones: Vec<usize> = vec![2, 3, 7, 19, 31, 32, 37, 41, 43, 47, 71, 73, 101];
let... | Rust | 0 |
#!/usr/bin/env python
"""Test that Graph is implemented properly"""
import sys
from os.path import join
from os.path import dirname
from os.path import abspath
from AlgsSedgewickWayne.Graph import Graph
from AlgsSedgewickWayne.testcode.InputArgs import cli_get_fin
TEST_DIR = dirname(abspath(__file__))
def test_0():... | Python | 1 |
EvoPose(cfg)
print('{:.2f}M / {:.2f}G'.format(model.count_params() / 1e6, get_flops(model) / 1e9 / 2))
# search space size:
# default_genotype = np.array(genotype_from_blocks_args(DEFAULT_BLOCKS_ARGS))
# s = 2**default_genotype.shape[0] * 4 ** default_genotype.shape[0] # kernel and repeats
# for ... | Python | 1 |
tion[1], text_position[2])
blf.size(font_id, 20.0)
blf.color(font_id, 0.9, 0.9, 0.9, 1.0)
blf.draw(font_id, info["text"])
def location_3d_to_region_2d(self, coord: Iterable, context: bpy.types.Context) -> Union[Vector, None]:
"""Convert from 3D space to 2D sc... | Python | 1 |
M: Message<Result = ()> + Send + 'static,
S: Handler<M>,
{
notify(&self.tx, message, None).await
}
/// Sends a message to the actor without waiting for the result, but only for a limited time.
pub async fn notify_timeout<M>(&self, timeout: Duration, message: M) -> Result<()>
where
M: Message<... | Rust | 0 |
rt port=\"{3}\" protocol=\"tcp\" to-port=\"{4}\" to-addr=\"{5}\"' --permanent".format(
operation,
info['Family'],
info['S_Address'],
info['S_Port'],
info['T_Port'],
... | Python | 1 |
config, &crypto_components);
let sig_shares = sign_threshold_for_each(
&n_random_nodes_in(&config.receivers().get(), num_of_shares_to_combine),
&message(),
dkg_id,
&crypto_components,
);
let combination_result = crypto_for(
random_node_in(&config.receivers().get()),
... | Rust | 0 |
_parameters, expected):
self.camelyon_data_download(file_url)
dataset = PatchWSIDataset(**input_parameters)
samples = dataset[0]
for i in range(len(samples)):
self.assertTupleEqual(samples[i]["label"].shape, expected[i]["label"].shape)
self.assertTupleEqual(sample... | Python | 1 |
_check_out(true)
.build(manager)?;
Ok(Self::new(pool, logger))
}
/// Mark a given ingest invocation as decommissioned.
fn decommission_ingest_invocation_impl(
&self,
conn: &PgConnection,
ingest_invocation_id: &IngestInvocationId,
) -> Result<(), Error> {
... | Rust | 0 |
Vector<(T, u64)> {
fn gen_range(&self, rng: &mut impl Rng) -> Range<usize> {
let mut u = rng.gen_range(0..self.0.len());
let mut v = rng.gen_range(0..1 + self.0.len());
if u > v {
swap(&mut u, &mut v);
}
u..v
}
}
// -- init
impl<G: Help<Len> + Help<Value<T>>... | Rust | 0 |
self.log("正在编译: {}".format(' '.join(compile_command)))
process = subprocess.Popen(compile_command, stderr=subprocess.PIPE)
_, stderr_bytes = process.communicate()
if process.returncode != 0:
self.log("!!! 编译错误 !!!")
self.log(stderr_bytes.decode('utf-8'))
... | Python | 1 |
S r SSKrSSKJr SSKJr SSKJ r S/r
\ " S5 \ " S5 \R " S S
9SS j5 5 5 rg)
"Functions related to graph covers. Nhopcroft_karp_matchingmin_edge_covernot_implemented_forr directed
multigraphbipar... | Python | 1 |
# -*- coding: utf-8 -*-
import json
import time
import requests
import sys
try:
from urllib.parse import urlparse
except:
# noinspection PyUnresolvedReferences
from urlparse import urlparse
import hmac
import hashlib
class Secret:
ot_key = ''
ot_secret = ''
def gen_nonce():
return str(int(t... | Python | 1 |
f score > b["score"]:
b["score"] = score
if t == "surface" and (b["best_surface"] is None):
b["best_surface"] = e
if t == "atom":
b["best_atom"] = e
order = sorted(buckets.items(), key=lambda kv: kv[1]["score"], reverse=True)[:max(1,topk_groups)]
lines = []
... | Python | 1 |
_components)
X transformed in the new space.
"""
X = self._validate_data(X)
if X.shape[0] == X.shape[1] and self.dissimilarity != "precomputed":
warnings.warn(
"The MDS API has changed. ``fit`` now constructs an"
" dissimilarity matrix from... | Python | 1 |
ed_at IS NULL
// LIMIT $2
// "#;
//
// let mut query_result = sqlx::query(query_str)
// .bind(public_key)
// .bind(limit)
// .fetch(db);
//
// tokio::spawn(async move {
// loop {
// match query_result.try_next().await {
// Ok(Some(row)) => {
//... | Rust | 0 |
import numpy as np
from scipy.stats import t
from statsmodels.tsa.stattools import acf
def diebold_mariano_util(e1, e2, h):
"""
Diebold-Mariano test for predictive accuracy.
Parameters:
e1 (np.array): Forecast errors from model 1.
e2 (np.array): Forecast errors from model 2.
... | Python | 1 |
enum EventFilter {
Container(String),
Event(String),
Image(String),
Label(String),
Type(EventFilterType),
Volume(String),
Network(String),
Daemon(String),
}
#[derive(Default)]
/// Builder interface for [`EventOpts`](EventOpts).
pub struct EventsOptsBuilder {
params: HashMap<&'stati... | Rust | 0 |
else:
zfs.create()
result['diff'] = {'before': {'state': 'absent'}, 'after': {'state': state}}
elif state == 'absent':
if zfs.exists():
zfs.destroy()
result['diff'] = {'before': {'state': 'present'}, 'after': {'state': state}}
else:
re... | Python | 1 |
xts[idx]
texts = exportTresureFromMPD(mpd, fontTable)
if texts:
etcLists[filepath.stem] = { 'treasure' : texts }
texts = exportDoorFromMPD(mpd, fontTable)
if texts:
etcLists[filepath.stem] = { 'door' : texts }
if out_path:
with... | Python | 1 |
r)?;
for (short_channel_id, pending_forwards) in channel_state.forward_htlcs.iter() {
short_channel_id.write(writer)?;
(pending_forwards.len() as u64).write(writer)?;
for forward in pending_forwards {
forward.write(writer)?;
}
}
(channel_state.claimable_htlcs.len() as u64).write(writer)?;
for (... | Rust | 0 |
pub const UART_UCR2_WS: u32 = (1 << 5);
pub const UART_UCR2_IRTS: u32 = (1 << 14);
pub const UART_UCR2_STPB: u32 = (1 << 6);
pub const UART_UCR2_RXEN: u32 = (1 << 1);
pub const UART_UCR2_TXEN: u32 = (1 << 2);
pub const UART_USR2_ADET: u32 = (1 << 15);
pub const UART_USR2_IDLE: u32 = (1 << 12);
pub const UART_USR2_IRIN... | Rust | 0 |
b_a中 (之所以为LongTensor类型,是为了方便后面torch.gather的使用),b_a为32行1列
b_r = torch.FloatTensor(b_memory[:, N_STATES+1:N_STATES+2])
# 将32个r抽出,转为32-bit floating point形式,并存储到b_s中,b_r为32行1列
b_s_ = torch.FloatTensor(b_memory[:, -N_STATES:])
# 将32个s_抽出,转为32-bit floating point形式,并存储到b_s中,b_s_为32行4列
... | Python | 1 |
= BitSet::singleton(Field::A5)
+ BitSet::singleton(Field::B6)
+ BitSet::singleton(Field::C7)
+ BitSet::singleton(Field::E8);
assert_eq!(a5b6c7e8, a5b6c7e8.into_iter().collect());
}
// const e5: Field = Field::E5;
use super::Field::E5 as e5;
// use super::Fie... | Rust | 0 |
self) -> u16 {
match self.congestion_threshold {
// Default to a threshold of 3/4 of the max background threads
None => (self.max_background as u32 * 3 / 4) as u16,
Some(value) => min(value, self.max_background),
}
}
#[cfg(feature = "abi-7-28")]
fn max_pa... | Rust | 0 |
(max(ref_kpt[0]-ref_size, 0)), int(max(ref_kpt[1]-ref_size, 0)), int(min(ref_kpt[0]+ref_size, w)) , int(min(ref_kpt[1]+ref_size, h))
head_pic = Image.fromarray(res_image[y1:y2, x1:x2, :]).resize((384,384)).filter(ImageFilter.GaussianBlur(radius=15))
x1,y1,x2,y2 = res_new_hand_bbox
x... | Python | 1 |
' => {
should_stop = true;
break;
}
'e' => '\x1b',
'f' => '\x0c',
'n' => '\n',
'r' => '\r',
't' => '\t',
'v' => '\x0b',
... | Rust | 0 |
import sys
import logging
import os
from datetime import datetime
# Создаем директорию для логов, если она не существует
log_dir = "log"
log_subdir = f"{sys.argv[0][:-3]}_log"
log_path = os.path.join(log_dir, log_subdir)
os.makedirs(log_path, exist_ok=True)
# Настройка логирования
log_file = os.path.join(log_path, f"... | Python | 1 |
self.estimated_pose.position.y + noise_pos,
self.estimated_pose.position.z
),
Vector3(
self.estimated_pose.orientation.x,
self.estimated_pose.orientation.y,
self.estimated_pose.orientation.z + noise_ang... | Python | 1 |
単位元を `e` とするとき、 `pred(e)` が成り立つ。
///
/// # Examples
/// ```
/// use nekolib::ds::VecSegtree;
/// use nekolib::traits::{Fold, FoldBisect};
/// use nekolib::utils::OpAdd;
///
/// let vs: VecSegtree<OpAdd<i32>> = vec![2, 4, 1, 3, 5].into();
///
/// assert_eq!(vs.fold_bisect(1, |&x| ... | Rust | 0 |
num_shared_buffers: o.num_shared_buf,
buf_cache_size: o.buf_cache_size,
max_srq_depth: o.max_srq_depth,
no_srq: o.no_srq,
c2h_success: o.ch2_success,
dif_insert_or_strip: o.dif_insert_or_strip,
sock_priority: o.sock_priority,
... | Rust | 0 |
# Functional test that hotplugs a CPU and checks it on a Linux guest
#
# Copyright (c) 2021 Red Hat, Inc.
#
# Author:
# Cleber Rosa <crosa@redhat.com>
#
# This work is licensed under the terms of the GNU GPL, version 2 or
# later. See the COPYING file in the top-level directory.
from avocado_qemu import LinuxTest
... | Python | 1 |
,
success: false,
error: Some(String::from("Unable to find event")),
}
} else {
ReservationTxResultRequest {
wallet_address: None,
assigned_on: None,
tx: tx.txhash.clone(),
token_id: None,
success: false,
... | Rust | 0 |
seen: Storage,
/// The set of items that we have seen, but have yet to traverse.
queue: Queue,
/// The predicate that determines which edges this traversal will follow.
predicate: Predicate,
/// The item we are currently traversing.
currently_traversing: Option<ItemId>,
}
impl<'ctx, Sto... | Rust | 0 |
unwrap(),
vec![],
)),
);
// should fail, but VM executed successfully, need investigate, but out of API scope
test_transaction_vm_status(context, txn, true, "Executed successfully").await
}
#[tokio::test]
async fn test_get_txn_execute_failed_by_invalid_script_function_address() {
l... | Rust | 0 |
#!/usr/bin/env python
import sys, os, json
from pathlib import Path
# Repo-root import shim so `import forge3d` works when run from repo
REPO_ROOT = Path(__file__).resolve().parents[2]
if str(REPO_ROOT) not in sys.path:
sys.path.insert(0, str(REPO_ROOT))
def main():
out_json = None
args = sys.argv[1:]
... | Python | 1 |
# Test attention patterns
print("\nTesting different sequence lengths...")
for length in [32, 48, 64, 96]:
test_input = torch.randint(
0, config.vocab_size, (2, length), device=device
)
logits, loss = model(input_ids=test_i... | Python | 1 |
se if token == "do" {
TokenType::Do
} else if token == "for" {
TokenType::For
} else if token == "continue" {
TokenType::Continue
} else if token == "break" {
TokenType::Break
} else if token == "sizeof" {
TokenType::Sizeof
... | Rust | 0 |
invalid epoch.
#[fail(display = "`HoneyBadger` received a message with an invalid epoch.")]
UnexpectedHbMessageEpoch,
/// `HoneyBadger` could not deserialize bytes (i.e. a serialized Batch) from a given proposer
/// into a vector of transactions.
#[fail(
display = "`HoneyBadger` could not de... | Rust | 0 |
:mocking::MockBlock<Runtime>;
construct_runtime!(
pub enum Runtime where
Block = Block,
NodeBlock = Block,
UncheckedExtrinsic = UncheckedExtrinsic
{
System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
NFTModule: nft::{Pallet, Call, Event<T>},
BNFT: bholdus_suppo... | Rust | 0 |
import re
from .utils import validator
md5_regex = re.compile(
r"^[0-9a-f]{32}$",
re.IGNORECASE
)
sha1_regex = re.compile(
r"^[0-9a-f]{40}$",
re.IGNORECASE
)
sha224_regex = re.compile(
r"^[0-9a-f]{56}$",
re.IGNORECASE
)
sha256_regex = re.compile(
r"^[0-9a-f]{64}$",
re.IGNORECASE
)
sha5... | Python | 1 |
<'ast>>,
import_map: HashMap<(PathBuf, String), (PathBuf, String)>,
mode: Mode,
}
struct ZLoc {
var: Loc,
accesses: Vec<ZAccess>,
}
enum ZAccess {
Member(String),
Idx(T),
}
fn loc_store(struct_: T, loc: &[ZAccess], val: T) -> Result<T, String> {
match loc.first() {
None => Ok(val)... | Rust | 0 |
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
fig_size = 5
fix_axes = True
show_frames = False
start = 0
length = 1000
mark_origin = True
mark_horizon = False
source = "trajectory.txt"
with open(source) as data:
lines = data.readlines()
point_hist = []
for lin... | Python | 1 |
espData, sNonce=nonce, timestamp=timestamp)
if ret != 0:
return "Error in message encryption"
return sEncryptMsg
else:
await queue.put({"FromUserName": FromUserName, "content_recived": content_recived, "AgentID": AgentID})
logging.info("任务+1")
... | Python | 1 |
from io import StringIO
import pytest
from pandas import read_sas
import pandas._testing as tm
class TestSas:
def test_sas_buffer_format(self):
# see gh-14947
b = StringIO("")
msg = (
"If this is a buffer object rather than a string "
"name, you must specify a fo... | Python | 1 |
) = (STATUS_WRAPPER_HEIGHT / 2.0, STATUS_WRAPPER_WIDTH);
// Check whether chip state is currently in stopped mode or active (running)
let is_unit_stopped = config.chip_state == &ChipState::Stopped;
// Check whether power is currently on AC or battery
// Notice: the telemetry library re... | Rust | 0 |
import boto3
import streamlit as st
import json
SERVICE_NAME=st.secrets['SERVICE_NAME']
REGION_NAME=st.secrets['REGION_NAME']
bedrock = boto3.client(
service_name=SERVICE_NAME,
region_name=REGION_NAME,
endpoint_url=f'https://{SERVICE_NAME}.{REGION_NAME}.amazonaws.com',
aws_access_key_id=st.secrets["ACCESS_KEY"],
... | Python | 1 |
+ 1)..path.len()].to_string();
path.clone()[..idx].to_string()
},
};
let mut http_request = SignedRequest::new(
"POST",
"s3",
&Region::from_str(&std::env::var("AWS_REGION").unwrap_or(String::from("us-east-1")))
.unwrap_or(Region::UsEast1),
&path,... | Rust | 0 |
': ',', '<': '?', '.': '।',
'>': 'श्र', '/': 'र', '?': 'रु', '=': '.'
}
def get_special_rules(self) -> List[FontRule]:
"""
Get special conversion rules that require context or patterns.
Returns:
List of special font rules
"""
rule... | Python | 1 |
T, S, F>
where
T: DeserializeOwned + Serialize,
S: Stream,
F: StreamFactory<S> + Clone,
{
}
impl<T, S, F> Builder<ByteStream<T, S, F>> for StreamBuilder<T, S, F>
where
T: DeserializeOwned + Serialize,
S: Stream,
F: StreamFactory<S> + Clone,
{
fn build(self) -> ByteStream<T, S, F> {
... | Rust | 0 |
rs="EPSG:4326"
)
assert_geoseries_equal(expected, g["geometry"])
assert_series_equal(g["address"], pd.Series(locations, name="address"))
def test_reverse(locations, points):
from geopy.geocoders import Photon
for provider in ["photon", Photon]:
with mock.patch("geopy.geocoders... | Python | 1 |
t: VerticalLine,
t_distribution: FilledCurve,
);
fn line_comparison(
&mut self,
path: PathBuf,
title: &str,
unit: &str,
value_type: ValueType,
axis_scale: AxisScale,
lines: &[(Option<&String>, LineCurve)],
);
fn violin(
&m... | Rust | 0 |
opcode {
/* NOP */ 0x00 => {
debug_system!("NOP\n", cpu.debug_mode);
1
},
/* STOP */ 0x10 => {
debug_system!("STOP\n", cpu.debug_mode);
cpu.fetch_operand(memory);
cpu.stopped = true;
1
},
/* HALT */ 0x76 => ... | Rust | 0 |
r", &self.header)
.field("command", &format_args!("0x{:04X}", self.command))
.field("param16", &format_args!("0x{:04X}", self.param16))
.field(
"param32",
&format_args!("0x{:08X} ({})", self.param32, self.param32),
)
.finish()
... | Rust | 0 |
+ a
~ ~ ~
"
no_references: true, r"
a := ¦1
a := a + c + a
"
}
<filename>src/vs/compiler.rs
pub use super::super::compiler::*;
use super::super::cache::Cache;
use super::postprocess;
use super::super::utils::filter;
use super::super::io::memstream::MemStream;
use super::sup... | Rust | 0 |
equested " + str(nbytes) + " bytes.")
if readonly and preexisting != nbytes:
raise SharedMemoryReadError("{} exists, but the allocation size ({} bytes) does not match the request ({} bytes).".format(
shmloc, preexisting, nbytes
))
if (nbytes - preexisting) > available:
overallocated = nbytes - p... | Python | 1 |
import argparse
import pyfiglet
from model.regression import LinearRegression
from model.preprocess import CustomStandardScaler
from model.layer import Dense
import numpy as np
def main():
parser = argparse.ArgumentParser(description="Prediction Program")
parser.add_argument("--model", type=str, required=True... | Python | 1 |
try_from(method) {
Ok(method) => method,
Err(_) => panic!("illegal method"),
};
self.config.allow_methods.insert(method);
self
}
/// Add an allow origin.
#[must_use]
pub fn allow_origin<T>(mut self, origin: T) -> Self
where
HeaderValue: TryFro... | Rust | 0 |
": &user_refresh_token,
"org_access_token": &org_access_token,
"org_refresh_token": &org_refresh_token,
"registry_contract_address": ®istry_contract_address,
"org_id": &create_organization_body.id,
"org_name": &create_organization_body.name,
"app_access_token": &app_ac... | Rust | 0 |
).unwrap();
let rclass = unsafe { interp.with_ffi_boundary(|mrb| spec.rclass().resolve(mrb)) }.unwrap();
assert!(rclass.is_none());
}
#[test]
fn rclass_for_undef_nested_module() {
let mut interp = interpreter();
let scope = Spec::new(&mut interp, "Kernel", qed::const_cstr_fr... | Rust | 0 |
# -*- coding: utf-8 -*-
import sys
from operator import add
from pyspark import SparkConf,SparkContext
def distance(loc1, loc2):
import math
lat1, lng1, lat2, lng2 = loc1[0]/180*math.pi, loc1[1]/180*math.pi, loc2[0]/180*math.pi, loc2[1]/180*math.pi
R, C = 6400, min(math.sin(lat1)*math.sin(lat2)*math.cos(lng1-lng2... | Python | 1 |
self.inner().n_targets as u32
}
pub fn target_names(&self) -> Vec<&[u8]> {
let names = unsafe {
slice::from_raw_parts(self.inner().target_name, self.target_count() as usize)
};
names
.iter()
.map(|name| unsafe { ffi::CStr::from_ptr(*name).to_b... | Rust | 0 |
fn is_16_byte(&self) -> bool {
*self == F1DS_A::_16_BYTE
}
#[doc = "Checks if the value of the field is `_20_BYTE`"]
#[inline(always)]
pub fn is_20_byte(&self) -> bool {
*self == F1DS_A::_20_BYTE
}
#[doc = "Checks if the value of the field is `_24_BYTE`"]
#[inline(always)]
... | Rust | 0 |
# Copyright 2019-2020 Stanislav Pidhorskyi
#
# 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 |
"""
Technology Watch Service - Application Layer
Hexagonal Architecture DDD
"""
import logging
from typing import List, Optional
from ...domain.entities.post import Post
from ...domain.value_objects.date_range import DateRange
logger = logging.getLogger(__name__)
class TechWatchService:
"""Main service orchestr... | Python | 1 |
8333, 44.5783348, 835.0),
City::new(576, "Armenia", "Byurakan", 40.3413889, 44.2736130, 1462.0),
City::new(577, "Armenia", "Tsovagyugh", 40.6330556, 44.9522209, 1981.0),
City::new(578, "Armenia", "Gandzak", 40.3147222, 45.1113892, 1985.0),
City::new(579, "Armenia", "Arshaluys", 40.1688889, 44.2141685, 872.0),
City... | Rust | 0 |
is_empty() {
self.path_idx = 0;
Move::Stop
} else {
// path is non-empty
let new_head = &self.path[0];
self.path_idx = 1;
direction(cur_head, new_head)
}
} ... | Rust | 0 |
from .common import InfoExtractor
from ..utils import ExtractorError, str_or_none, traverse_obj, unified_strdate
from ..compat import compat_str
class IchinanaLiveIE(InfoExtractor):
IE_NAME = '17live'
_VALID_URL = r'https?://(?:www\.)?17\.live/(?:[^/]+/)*(?:live|profile/r)/(?P<id>\d+)'
_TESTS = [{
... | Python | 1 |
mut han = 0;
// 門前自摸
if info.hand.is_menzen() && info.tsumo {
yaku.insert(Yaku::Tsumo);
han += 1;
}
// 立直/ダブルリーチ
if info.riichi {
yaku.insert(Yaku::Riichi);
han += 1;
} else if info.doubleriichi {
yaku.insert(Yaku::Doubleriichi);
han ... | Rust | 0 |
d_id = to_global_id('ProfileField', profile_field.id)
configurable_field_id = to_global_id('TextField', profile_field.configurable_field.id)
text_field2_id = to_global_id('TextField', text_field2.id)
data = [
# create custom field
{
u"configurableFieldId": text_field2_id,
... | Python | 1 |
},
TextureView(TextureViewId),
TextureArrayView(Vec<TextureViewId>),
Sampler(SamplerId),
}
impl RenderResourceBinding {
pub fn get_texture_view(&self) -> Option<TextureViewId> {
if let RenderResourceBinding::TextureView(texture) = self {
Some(*texture)
} else {
... | Rust | 0 |
t will download all house data. Use --id house_id to download specific house data.
The --task_data argument is optional and will download task data and model files.
''',
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('-o', '--out_dir', required=True, help='directory in wh... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.