text string | label_name string | labels int64 |
|---|---|---|
0020: {'type': 'model',
'name': 'copy of middle',
'comment': '',
'parentEntId': 10008,
'pos': Point3(5.71999979019, 0.0, 0.0),
'hpr': Vec3(0.0, 0.0, 0.0),
'scale': Vec3(0.954999983311, 1.0, 1.0),
'collisionsOnly': 0,
'flattenType': 'light',
... | Python | 1 |
from bytes
pub fn create_font(font_name: &str, size: i32) -> FontPallet {
let font = FontPallet::cache(ASCII_CHARS, size);
let mut map = FONT_CACHE.lock().expect("lock failed");
map.insert(font_name.to_string(), font.clone());
font
}
/// manually cache characters
pub f... | Rust | 0 |
singular(split.1))
}
#[cfg(feature = "heavyweight")]
/// Determines if a `&str` is `ClassCase` `bool`
///
/// ```
/// use inflector::cases::classcase::is_class_case;
/// let mock_string: &str = "Foo";
/// let asserted_bool: bool = is_class_case(mock_string);
/// assert!(asserted_bool == true);
///
/// ... | Rust | 0 |
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()?;
forward_to_logging(process.stdout.take().unwrap(), "task-manager", "stdout");
forward_to_logging(process.stderr.take().unwrap(), "task-manager", "stderr");
Ok(Self { process })
... | Rust | 0 |
}
}
<reponame>allansrc/fuchsia
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use std::collections::HashMap;
use sdk_metadata::{CcPrebuiltLibrary, JsonObject, TargetArchitecture};
use crate::app::... | Rust | 0 |
`table_scans` > other nodes - having table scan means not detected cube scan
/// - `non_detected_cube_scans` > other nodes - minimize cube scans without members
/// - `filters` > `filter_members` - optimize for push down of filters
/// - `filter_members` > `cube_members` - optimize for `inDateRange` filter push down t... | Rust | 0 |
"No such channel {:?}/{}", channel, complementary),
}
}
fn get_max_duty(&self) -> u16 {
self.car.read().car().bits() as u16
}
}
};
}
macro_rules! timer_idle_reg_ext {
($timerX:ident, ($($channel:ident: $iso:ident $(/ $ison:ident)? ;)+... | Rust | 0 |
UnexpectedListenerFd(fd) => {
write!(f, "Unexpected value for the socket listener fd: {}", fd)
}
UnshareNewNs(ref err) => {
write!(f, "Failed to unshare into new mount namespace: {}", err)
}
UnsetCloexec(ref err) => write!(
... | Rust | 0 |
and
* we need them to be 0-based for the calculation to work.
* Then we apply the direction which is always +1 or -1.
*
* We then use the remainder part of Euclidean division of
* potential page over total number of pages, in order to
* wrap the page number ar... | Rust | 0 |
# This file was generated by 'versioneer.py' (0.23) from
# revision-control system data, or from the parent directory name of an
# unpacked source archive. Distribution tarballs contain a pre-generated copy
# of this file.
import json
version_json = '''
{
"date": "2025-04-10T11:38:49-0700",
"dirty": false,
"error... | Python | 1 |
lowest resolution image in <tt>\\ref VX_DF_IMAGE_U8</tt> or <tt>\\ref VX_DF_IMAGE_S16</tt> format necessary to reconstruct the input image from the pyramid. The output image format should be same as input image format."]
#[doc = " \\ingroup group_vision_function_laplacian_pyramid"]
#[doc = " \\see group_pyramid... | Rust | 0 |
from agents.baseline_agent import BaselineAgent
from agents.domain_expert_agent import DomainExpertAgent
from agents.self_recitation_agent import SelfRecitationAgent
from agents.chain_of_thought_agent import ChainOfThoughtAgent
from agents.composite_agent import CompositeAgent
class AgentFactory:
def __init__(self... | Python | 1 |
ivate = suspended.to(active)
overdraft = active.to(overdrawn)
resolve_overdraft = overdrawn.to(active)
close_account = closed.from_.any(cond="can_close_account")
can_close_account: bool = True
# Actions performed during transitions
def on_close_... | Python | 1 |
}
else if val > 5000.0
{
5000.0
}
else
{
val
};
let count = (self.output_rate * tc2sec_delay(val) / 64.0) as u32;
self.volenv_data[VoiceEnvelope::Delay as usize].count = count;
self.volenv_data[VoiceEnvelope::Delay as usize].c... | Rust | 0 |
, AccountIdOf<T>, HospitalOf<T>>;
/// Get HospitalId by Country-Region, City
/// (CountryRegionCode, CityCode) => Vec<AccountId>
#[pallet::storage]
#[pallet::getter(fn hospitals_by_country_region_city)]
pub type HospitalsByCountryRegionCity<T> =
StorageDoubleMap<_, Blake2_128Co... | Rust | 0 |
usize,
}
impl<'parent, R: Read> ChildXmlBuffer<'parent, R> {
/// Advance the child buffer without marking an event as "used"
pub fn skip(&mut self) {
debug_assert!(
self.cursor < self.buffer.len(),
".skip() only should be called after .peek()"
);
self.cursor +=... | Rust | 0 |
s, np.zeros((n_centroids, image.shape[3]))],
axis=-1), dtype=dtype)
# Scaling of ratio in the same way as in the SLIC paper so the
# values have the same meaning
step = max(steps)
ratio = 1.0 / compactness
image = np.ascontiguousarray(image * ratio, dtype=dtype)
if update_centroids:
... | Python | 1 |
}).unwrap();
assert_eq!(got_result, want_result)
}
}<gh_stars>0
use std::path::PathBuf;
use anyhow::Result;
pub use clap::ArgMatches;
pub use config::Config as OroConfig;
use config::{ConfigError, Environment, File};
use directories::ProjectDirs;
pub use oro_config_derive::*;
pub trait OroCon... | Rust | 0 |
name)?);
let input = class!(AVCaptureDeviceInput);
let null: *const i32 = std::ptr::null();
let input: *mut Object =
unsafe { msg_send![input, deviceInputWithDevice: *device error: null] };
unsafe { msg_send![session, addInput: input] }
let av_capture_class = class!... | Rust | 0 |
from typing import TYPE_CHECKING, List
from systemrdl.rdltypes import OnReadType
from .bases import NextStateConditional
if TYPE_CHECKING:
from systemrdl.node import FieldNode
class _OnRead(NextStateConditional):
onreadtype = None # type: OnReadType
def is_match(self, field: 'FieldNode') -> bool:
... | Python | 1 |
xtbox, imagebox] + btn_list,
queue=False
)
textbox.submit(
add_text,
[state, textbox, imagebox, image_process_mode],
[state, chatbot, textbox, imagebox] + btn_list,
queue=False
).then(
http_bot,
[state, model_se... | Python | 1 |
vec.extend_from_slice(&((a * i16::MAX as f32).round() as i16).to_le_bytes());
}
vec
});
// Write file out
let mut w = std::io::BufWriter::new(std::fs::File::create("sinenaive.wav")?);
diysynth::MinimalWaveHeader::write_wave_file_u8(
&mut w,
&data,
... | Rust | 0 |
# Code generated by Lark OpenAPI.
from typing import Any, Optional, Union, Dict, List, Set, IO, Callable, Type
from lark_oapi.core.construct import init
class DlpExecuteEvidence(object):
_types = {
"keyword_hits": List[str],
"regular_hits": List[str],
"sensitive_hits": List[str],
}
... | Python | 1 |
# Instagram Follower Bot
import time
import random
from selenium import webdriver
import config
# Note: expects Google Chrome and the appropriate ChromeDriver to be properly installed on the system
# https://chromedriver.chromium.org/downloads
# name of the account to get the followers from
SOURCE_ACCOUNT = "chefs... | Python | 1 |
dChatJoin_t>())).m_steamIDClanChat as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(GameConnectedChatJoin_t),
"::",
stringify!(m_steamIDClanChat)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<GameConnectedChatJoin_t>())).m_steamIDUser as *const _ as usize
},
... | Rust | 0 |
Ok(p);
}
}
}
<filename>src/connectivity/bluetooth/profiles/bt-a2dp/src/stream_controller.rs
// Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
anyhow::Error,
bt_a2dp::permits::{Per... | Rust | 0 |
use super::*;
use fuchsia_async as fasync;
use lazy_static::lazy_static;
lazy_static! {
static ref TEST_STATE: State = State::SingleEnrollment {
auth_mechanism_id: String::from("test_id"),
data: vec![1, 2, 3],
};
}
... | Rust | 0 |
# coding: utf-8
# flake8: noqa
"""
Properties
All HubSpot objects store data in default and custom properties. These endpoints provide access to read and modify object properties in HubSpot. # noqa: E501
The version of the OpenAPI document: v3
Generated by: https://openapi-generator.tech
"""
from ... | Python | 1 |
="Rendering", unit="frame",
bar_format="{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}]")
for i, pose in enumerate(camera_poses):
# Calculate time progress
t = i / (len(camera_poses) - 1) if len(camera_poses) > 1 else 0.0
... | Python | 1 |
pub output_item_num: Vec<u32>,
}
}
rsz_struct! {
#[rsz("snow.data.WeaponProcessUserData")]
#[derive(Debug, Serialize)]
pub struct WeaponProcessUserData {
pub param: Vec<WeaponProcessUserDataParam>,
}
}
rsz_struct! {
#[rsz("snow.data.WeaponProductUserData.Param")]
#[derive(Debug, Se... | Rust | 0 |
if let Some(token)=self.tokens.get(if self.tokens.len()>=n{self.tokens.len()-n}else{0}){
token.kind.clone()
}else{
TokenKind::EOF
}
}
pub fn get_prev(&self)->TokenKind{
self.prev.clone()
}
}
<filename>src/test/run-pass/for-loop-while/for-loop-li... | Rust | 0 |
};
Ok((gas_cost, memory_cost))
}
#[derive(Clone)]
struct Inner<'config> {
memory_cost: usize,
used_gas: usize,
refunded_gas: isize,
config: &'config Config,
}
impl<'config> Inner<'config> {
fn memory_cost(
&self,
memory: MemoryCost,
) -> Result<usize, ExitError> {
let from = memory.offset;
let len =... | Rust | 0 |
ub fn into_parts(self) -> (S, Bytes) {
(self.stream, self.read_leftover)
}
}
impl<S> AsyncRead for HttpsProxyStream<S>
where
S: AsyncRead,
{
#[inline]
fn poll_read(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
buf: &mut tokio::io::ReadBuf<'_>,
) -... | Rust | 0 |
__tablename__ = "scenario"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str_100] = mapped_column()
specializations: Mapped[list[Specialization]] = relationship(
secondary=scenario_specializations,
back_populates="scenarios",
cascade="all, delete",
pass... | Python | 1 |
# -*- coding: utf-8 -*-
"""
DreamentoConverter: This file is meant to convert several 'raw' .hyp ZMax recordings
into the corresponding .edf files.
=== Inputs ===
1. path_to_HDRecorder: path to HDRecorder.exe (specify the folder name only, e.g., C:/Program Files (x86)/Hypnodyne/ZMax)
2. filenames: path to the files to... | Python | 1 |
_preview_like" in i['node'].keys() else ''
item = {'postURL': url, 'isVideo': video, 'date_posted': date_posted_human,
'timestamp': date_posted_timestamp, 'likeCount': like_count, 'commentCount': comment_count,
'image_url': image_url,
'videoURL': v... | Python | 1 |
ngeonly is True and emitatstartup is True,
# we should see a return when the beacon is run.
config = [
{"services": {"salt-master": {"emitatstartup": True, "onchangeonly": True}}}
]
ret = service_beacon.validate(config)
assert ret == (True, "Valid beacon configurati... | Python | 1 |
32_accessor(
"currency_awarded",
CollectDailyDefenderBonusResponse::get_currency_awarded,
));
fields.push(::protobuf::reflect::accessor::make_singular_i32_accessor(
"defenders_count",
CollectDailyDefenderBonu... | Rust | 0 |
release: conflicts_with[debug] --release "Build a release version")
(@arg debug: conflicts_with[release] --debug "Build a debug version")
)
(@subcommand clippy =>
(about: "Runs clippy")
(@arg release: conflicts_with[debug] --release "Build a release version")
... | Rust | 0 |
100-1000
use super::components::Layout;
use super::state::*;
use derive_more::{Deref, DerefMut};
use rill_engine::tracers::tracer::Tracer;
use rill_protocol::flow::core::FlowMode;
use rill_protocol::io::provider::Path;
#[derive(Debug, Deref, DerefMut, Clone)]
pub struct LayoutsTracer {
tracer: Tracer<LayoutsState>... | Rust | 0 |
FUNC_LOCAL_STATE_SANDBOX_CALL: ScHname = ScHname(0x7bd22c53);
pub const HFUNC_POST_INCREMENT: ScHname = ScHname(0x81c772f5);
pub const HFUNC_REPEAT_MANY: ScHname = ScHname(0x4ff450d3);
pub const HFUNC_WHEN_MUST_INCREMENT: ScHname = ScHname(0xb4c3e7a6);
pub const HVIEW_GET_COUNTER: ScHname = ScHname(0xb423e607);
<repona... | Rust | 0 |
from django.shortcuts import render
# Create your views here.
def index(request, *args, **kwargs):
return render(request, 'frontend/index.html') | Python | 1 |
{
let this = self.eval_context_ref();
// Step 1: cut off the fractional part of `f`. The result of this is
// guaranteed to be precisely representable in IEEE floats.
let f = f.round_to_integral(Round::TowardZero).value;
// Step 2: Cast the truncated float to the target integer... | Rust | 0 |
',
b'I', b'0', b'I', b'1', b'I', b'2', b'I', b'3', b'I', b'4', b'I', b'5', b'I', b'6', b'I', b'7',
b'I', b'8', b'I', b'9', b'I', b'A', b'I', b'B', b'I', b'C', b'I', b'D', b'I', b'E', b'I', b'F',
b'I', b'G', b'I', b'H', b'I', b'I', b'I', b'J', b'I', b'K', b'I', b'L', b'I', b'M', b'I', b'N',
b'I', b'O', b... | Rust | 0 |
for w, h in all_sizes:
for i, j in itertools.product(range(sfeat), repeat=2):
cx, cy = (j + 0.5) / fk[idx], (i + 0.5) / fk[idx]
dboxes.append((cx, cy, w, h))
return torch.tensor(
dboxes,
dtype=model_dtype,
device=device
).clamp(0, 1)
dbox... | Python | 1 |
let mut curr = args;
for arg_type in method.parameters.iter() {
let arg = match arg_type.as_str() {
"B" => JavaType::Byte((*args).b),
"C" => JavaType::Char((*args).c),
"D" => JavaType::Double((*args).d),
"F" => JavaType::Float((*args).f),
"I" => ... | Rust | 0 |
db_mem_decute)
db_all_rate = 100 - db_top_decute
if db_all_rate >= 60:
db_rate_color = 'green'
db_rate_level = 'success'
elif db_all_rate >= 20 and db_all_rate < 60:
db_rate_color = 'yellow'
db_rate_level = 'warning'
else:
db_ra... | Python | 1 |
__BindgenBitfieldUnit<[u8; 4usize], u32> =
Default::default();
__bindgen_bitfield_unit.set(0usize, 1u8, {
let relative: u32 = unsafe { ::std::mem::transmute(relative) };
relative as u64
});
__bindgen_bitfield_unit.set(1usize, 1u8, {
let search: u3... | Rust | 0 |
self
.timeout
.spawn(Duration::from_secs(self.props.delay_secs), self.callback_done.clone());
self.count_down = self.props.delay_secs;
self.timeout_job.replace(Box::new(handle));
}
{
let... | Rust | 0 |
True:
idx = lower_text.find(pat, start)
if idx == -1:
break
matches.append(Match(pattern=pattern_map[pat], start=idx, end=idx + len(pat)))
start = idx + 1
matches.sort(key=lambda m: (m.start, m.end))
unmatched: Optional[list[... | Python | 1 |
import time
import tkinter as tk
from tkinter import *
from datetime import datetime
from win10toast import ToastNotifier
import winsound
#creating a winodw
window = Tk()
window.geometry('600x600')#giving size
window.title('PALVI')#giving title
Label(window, text="Countdown Clock and Timer", font=('Calibri 15')).pack(... | Python | 1 |
self.y() * m.data[1][1] + m.data[1][2];
Self::new(x, y)
}
/// Creates this from a "x y" string. E.g. "4.3 17.29"
fn parse(text: &str) -> Result<Self> {
let mut words = text.split(" ").skip_empty_string();
let x = f64::from_str(words.next().ok_or(ErrorKind::ParseError)?)?;
l... | Rust | 0 |
'''To test filter products by price high to low functionality'''
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
import time
import sys
sys.path.insert(0, 'C:\\Users\\HD\\SwagLabs_testing\\utility')
from webdriver_setup import initialize_driver
def test_filter_products_pr... | Python | 1 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试601127股票名称获取问题的专用测试程序
这个程序专门用于诊断和解决601127股票名称显示为"股票601127"而非实际名称的问题。
"""
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from datetime import datetime
import traceback
def test_stock_name_mapping():
"""测试股票名称映射字典"""
print(... | Python | 1 |
from dataclasses import dataclass
from mypy.nodes import CallExpr, RefExpr, StrExpr
from refurb.checks.common import normalize_os_path, stringify
from refurb.error import Error
@dataclass
class ErrorInfo(Error):
"""
The Path() constructor defaults to the current directory, so don't pass the
current dire... | Python | 1 |
initial
/// subsequences. It's called with each queue until it returns `true`.
///
/// This destructively removes the initial subsequences of `queue_one` and
/// `queue_two`.
///
/// For example, given `(A B C | D E)` and `(1 2 | 3 4 5)` (with `|` denoting
/// the boundary of the initial subsequence), this would return... | Rust | 0 |
my_dic1={'Ten':10,'Twenty':20,'Thirty':30}
my_dic2={'Thirty':30,'Fourty':40,'Fifty':50}
my_dic1.update(my_dic2)
print(my_dic1) | Python | 1 |
from ultralytics import YOLOv10
import cv2
import math
import random
import time
# Function to read words from file
def read_words_from_file(file_path):
with open(file_path, 'r') as file:
words = file.read().splitlines()
return words
# Function to choose a new target word
def choose_new_target():
... | Python | 1 |
data['marketing']['branding_strategy'] else "N/A"
html += f"""
<div class="section">
<h2>Marketing</h2>
<p><strong>Marketing Channels:</strong> {', '.join(data['marketing']['channels'])}</p>
<p><strong>Branding Strategy:</strong> {branding_strategy}</p>
</div>
... | Python | 1 |
ef<Mux> = siv.find_name("Mux").unwrap();
let id = mux.focus();
mux.remove_id(id).unwrap();
}
use anyhow::Result;
use std::fs;
use std::path::Path;
fn parse_line(line: &str) -> usize {
line.parse::<usize>().expect("Failed to parse")
}
fn count_depth_increase(window: usize, content: &str) -> usize {
let... | Rust | 0 |
return np.array(self.bin, dtype=np.uint32)
@property
def rtp_words(self)->List[int]:
""" From the rtp array pack them into 32bit words """
rtp_words = [self.num_rtp_words]
for i in range(0, len(self.rtp), 2):
rtp_word = self.rtp[i] | (self.rtp[i+1] << 16)
cty... | Python | 1 |
# Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source,
# Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
# SPDX - License - Identifier: GPL - 3.0 +
impo... | Python | 1 |
let mut img = tmp_out_img.lock().unwrap();
for j in 0..chunk_h {
for i in 0..chunk_w {
let c = chunk[(j * chunk_w + i) as usize];
self.add_to_pixel(
&c,
... | Rust | 0 |
is_true = True
NegQueryGraph.append(q_g)
# 在y上的实体约束
two_hop_entity_constrains_y = from_id_path_get_3hop_po_oName_y(query_e, topicEntityID,
... | Python | 1 |
import os
# import tarfile
from PIL import Image
# import urllib.request
import torch
from torch.utils.data import Dataset
from torchvision import transforms
import imgaug.augmenters as iaa
import glob
from datasets.perlin import rand_perlin_2d_np
import numpy as np
import cv2
import random
CLASS_NAMES = [
'bottle'... | Python | 1 |
from collections import deque
# Define the matrix map of the city
city_map = [
['x', 6, 19, 13, 'x', 16, 11, 6, 14, 15, 7, 'x', 'x', 'x'],
['x', 6, 16, 15, 'x', 19, 16, 18, 'x', 8, 10, 'x', 'x', 'x'],
['x', 5, 10, 14, 2, 'x', 'x', 'x', 11, 'x', 11, 'x', 'x', 'x'],
[6, 13, 15, 10, 'x', 'x', 'x', 'x', 1... | Python | 1 |
_ => panic!("First block in this Song isn't a Verse"),
}
}
fn get_verse(song: &Song, block_num: usize) -> &Verse {
match &song.blocks[block_num] {
Block::Verse(verse) => verse,
b => panic!("Unexpected block type: {:?}", b),
}
}
#[test]
fn songs_spl... | Rust | 0 |
input by space
pub fn split_tags(input: &str) -> Vec<String> {
input
.split(' ')
.map(|word| word.trim().to_string())
.collect::<Vec<String>>()
}
/// Converts an array of bytes to a string
pub fn u8_to_str(input: &[u8]) -> color_eyre::Result<String> {
Ok(str::from_utf8(input)?.to_owned... | Rust | 0 |
eep_copy_result is not complex_data
assert manual_deep_copy_result[STUDENTS][FIRST] is not complex_data[STUDENTS][FIRST]
assert manual_deep_copy_result[STUDENTS][FIRST][SCORES] is not complex_data[STUDENTS][FIRST][SCORES]
print("✅ 수동 깊은 복사 성공 (교육용, 실제로는 copy.deepcopy 권장)\n")
print("4. 성능 비교 (참고용)")
... | Python | 1 |
el=BFLFluxDepthImageRequest,
response_model=BFLFluxProGenerateResponse,
),
request=BFLFluxDepthImageRequest(
prompt=prompt,
prompt_upsampling=prompt_upsampling,
steps=steps,
guidance=guidance,
seed=se... | Python | 1 |
{
let sub = _mm512_sub_pd(a, b).as_f64x8();
let zero = _mm512_setzero_pd().as_f64x8();
transmute(simd_select_bitmask(k, sub, zero))
}
/// Multiply the low signed 32-bit integers from each packed 64-bit element in a and b, and store the signed 64-bit results in dst.
///
/// [Intel's documentation](https://... | Rust | 0 |
",
"darkred" => "DarkRed",
"lightskyblue" => "LightSkyBlue",
"slateblue" => "SlateBlue",
"orange" => "Orange",
"chartreuse" => "Chartreuse",
"maroon" => "Maroon",
"peru" => "Peru",
"mediumturquoise" => "MediumTurquoise",
"aquamarine" => "Aquamarine",
"lightcoral" => "LightCoral",
"thistle" => "Thi... | Rust | 0 |
()?;
let result = le_f32().parse(buffer);
match result {
Ok((val, _)) => {
return Ok(val);
}
Err(_) => {
return Err(Error::new(ErrorKind::Other, "Unexpected Parse"));
}
}
}
}
#[cfg(test)]
mod tests {
use sup... | Rust | 0 |
"""
Core models and abstract base classes for the fuel_route_optimizer project.
"""
from django.db import models
from django.utils import timezone
class TimestampedModel(models.Model):
"""
Abstract base model with created and modified timestamps.
"""
created_at = models.DateTimeField(auto_now_add=True... | Python | 1 |
from keys import api_key, api_secret
from alpaca.data.live import StockDataStream
wss_client = StockDataStream(api_key, api_secret)
# async handler
async def quote_data_handler(data):
print(data)
wss_client.subscribe_quotes(quote_data_handler, "AAPL")
wss_client.run() | Python | 1 |
") {
let mut data = Vec::new();
if let Ok(_) = file.read_to_end(&mut data) {
Some(data)
} else {
None
}
} else {
None
}
};
let second_cache = if let Some(data) = data {
// This is unsafe because ... | Rust | 0 |
;
if let Some(i) = idx_iter.next() {
//println!("sum: {}", sum);
let high = 100 - sum;
d[i] = if high > 0 { rng.gen_range(0, high) } else { 0 };
sum += d[i];
}
}
}
if let Some(i) = idx_iter.next() {
d[i] = 10... | Rust | 0 |
#!/usr/bin/env python3
"""
Unit tests for PaperlessClient class functionality.
"""
import asyncio
import os
import sys
from unittest.mock import AsyncMock, Mock, patch, MagicMock
# Add src directory to path for imports
sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(__file__)), "src"))
# Mock externa... | Python | 1 |
endida = db.session.execute(text(query)).fetchone()
query = """ SELECT
nombre_producto nombre, cantidad_inv merma, (SUM( cantidad_inv ) * SUM(costoproducto)) costo
FROM inventario
INNER JOIN producto on id_producto = producto_inv
WHERE tipo_inv = 2 and tipostock_inv in ( 2, 4 )
GROUP BY n... | Python | 1 |
def tiled_encode(self, x: torch.FloatTensor, return_dict: bool=True
) ->AutoencoderKLOutput:
"""Encode a batch of images using a tiled encoder.
Args:
When this option is enabled, the VAE will split the input tensor into tiles to compute encoding in several
steps. This is useful to keep ... | Python | 1 |
ry!(File::open(filename));
try!(file.read_to_string(&mut content));
content
};
load_theme(&content)
}
/// Loads a theme string and sets it as active.
pub fn load_theme(content: &str) -> Result<Theme, Error> {
let table = toml::de::from_str(content)?;
let mut theme = Theme::default();
... | Rust | 0 |
@staticmethod
def estimate_pose_angle(a, b, c):
"""
Calculate the pose angle for object.
Args:
a (float) : The value of pose point a
b (float): The value of pose point b
c (float): The value o pose point c
Returns:
angle (degree): Degree valu... | Python | 1 |
test]
fn query_deserialize() {
let json = r#"{"query": "foo {size:30} bar {season:4} baz {show}"}"#;
let expected =
"{size:30} {season:4} {show} foo bar baz".parse().unwrap();
#[derive(Deserialize)]
struct Test {
query: Query,
}
let got: Test ... | Rust | 0 |
y[t * hop_length]``.
- If `False`, then frame ``t`` begins at ``y[t * hop_length]``
pad_mode : string
If ``center=True``, the padding mode to use at the edges of the signal.
By default, STFT uses reflection padding.
power : float > 0 [scalar]
Exponent for the magnitude melspec... | Python | 1 |
# prompt: https://adventofcode.com/2017/day/3
import math
from ...base import BaseSolution, InputTypes
class Solution(BaseSolution):
_year = 2017
_day = 3
@property
def input_type(self):
return InputTypes.INTEGER
def part_1(self):
side = math.ceil(
math.sqrt(self.in... | Python | 1 |
the address
/// pointed-to by `output`. Use `ergo_lib_ergo_tree_bytes_len` to determine the length of the
/// byte array.
#[no_mangle]
pub unsafe extern "C" fn ergo_lib_ergo_tree_to_bytes(
ergo_tree_ptr: ConstErgoTreePtr,
output: *mut u8,
) -> ErrorPtr {
let res = ergo_tree_to_bytes(ergo_tree_ptr, output);... | Rust | 0 |
pping(
StandardQueryParameters, 'f__xgafv', '$.xgafv')
encoding.AddCustomJsonEnumMapping(
StandardQueryParameters.FXgafvValueValuesEnum, '_1', '1')
encoding.AddCustomJsonEnumMapping(
StandardQueryParameters.FXgafvValueValuesEnum, '_2', '2')
encoding.AddCustomJsonFieldMapping(
CloudkmsProjectsLocationsEk... | Python | 1 |
}
impl Dangerous for Builder {
fn set_root_certificates<C: Into<Vec<Certificate>>>(builder: &mut Self, certificates: C) {
builder.root_certificates = certificates.into();
}
fn root_certificates(builder: &Self) -> &[Certificate] {
&builder.root_certificates
}
}
#[cfg(test)]
mod test {
use std::task::Poll;
... | Rust | 0 |
orage, sname, pname):
payload = PayloadBuilder().SELECT(["id", "enabled"]).WHERE(['schedule_name', '=', sname]).payload()
result = await storage.query_tbl_with_payload('schedules', payload)
if result['count'] == 0:
raise ValueError('{} service does not exist.'.format(sname))
plugins = PluginDisc... | Python | 1 |
#!/usrbin/python
#encoding:utf-8
'''
Author: wangxu
Email: wangxu@oneniceapp.com
任务更新
'''
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import logging
import tornado.web
import json
import os
CURRENTPATH = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(CURRENTPATH, '../../'))
f... | Python | 1 |
#Exercício 1:
#Peça ao usuário para inserir um número e manipule a exceção caso ele insira algo que não seja um número inteiro.
def teste1 ():
try:
numero = int(input('insira um numero: '))
print (numero)
except:
print('houve um erro!')
#Exercício 2:
#Peça ao usuário para inserir doi... | Python | 1 |
Identifier: Apache-2.0
mod contract_call;
mod node_api_types;
pub mod pubsub;
pub use contract_call::*;
use jsonrpc_core_client::RpcChannel;
pub use node_api_types::*;
use scs::SCSCodec;
use serde::Deserialize;
use serde::Serialize;
use serde_helpers::{deserialize_binary, deserialize_u64, serialize_binary, serialize_u... | Rust | 0 |
ault()
.with_node_limit(usize::MAX)
.with_hook(move |r| {
let size = r.egraph.total_number_of_nodes();
if size > node_limit {
Err(format!("Node limit: {}", size))
} else {
Ok(())
}
... | Rust | 0 |
let mut notification = Notification::new();
notification
.appname(APPNAME)
.summary(SUMMARY)
.body(&body)
.icon(ICON)
.hint(NotificationHint::Category(String::from(HINT_CATEGORY)))
.hint(NotificationHint::Transie... | Rust | 0 |
of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or d... | Rust | 0 |
ache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
mod _common;
use _common::{validate, SEED}... | Rust | 0 |
) {
let me_date_opt = date_time_offset(me_date_tuple, me_time_tuple, me_offset);
let other_date_opt = date_time_offset(other_date_tuple, other_time_tuple, other_offset);
if let Some((me_date, other_date)) = me_date_opt.zip(other_date_opt) {
return Some(me_date.cmp(&other_date));
}
}
None
}
pu... | Rust | 0 |
just add 0 to indexes, i.e. indexes.push(0) etc. to build the BIP32 path
//! let mut indexes: Vec<u32> = Vec::new();
//! // main net
//! let net: u32 = 0x0488B21Eu32;
//! let xpub = ehsm.get_bitcoin_pub(session, &indexes, net).expect("Failed to get btc pub");
//! ```
//!
//! ## Signing a hash with the private key at t... | Rust | 0 |
# Import necessary classes from the siliconcompiler framework and the LambdaPDK.
from siliconcompiler import ASIC
from lambdapdk.interposer import Interposer_3ML_0400
from lambdapdk.interposer.libs.bumps import BumpLibrary
from siliconcompiler.flows import interposerflow
from siliconcompiler.flows import drcflow
##... | Python | 1 |
[
[x - sx / 2, y - sy / 2, z - sz / 2],
[x + sx / 2, y - sy / 2, z - sz / 2],
[x + sx / 2, y + sy / 2, z - sz / 2],
[x - sx / 2, y + sy / 2, z - sz / 2],
[x - sx / 2, y - sy / 2, z + sz / 2],
[x + sx / 2, y - sy / 2, z + sz / 2],
[x... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.