text string | label_name string | labels int64 |
|---|---|---|
// threads means number of fuse service threads
let threads: u32 = cmd_arguments
.value_of("threads")
.map(|n| n.parse().unwrap_or(1))
.unwrap_or(1);
let rlimit_nofile_default = get_default_rlimit_nofile()?;
let rlimit_nofile: rlim = cmd_arguments
.value_of("rlimit-nofil... | Rust | 0 |
emrate results using string concatenation
return (
r.get("job_name", "")
+ r.get("engine_module", "")
+ r.get("key", "")
+ f"{r.get('workers', ''):05}"
+ f"{r.get('job_number', ''):06}"
)
results_sorted = sorted(result_list, key=memrate_ke... | Python | 1 |
inline]
fn deref(&self) -> &Self::Target {
// SAFETY: ReadGuards are only created when no WriteGuard
// are held so the data can't be modified while a ReadGuard is held
// so it is safe to get a reference to the data for the lifetime of
// the guard.
unsafe { &*self.rwlock.da... | Rust | 0 |
return {"exito" : True,
"num_videos" : 1,
"mensaje" : u"URL obtenido correctamente",
"videos":[{
"url_video" : [url.replace("&mp4:","mp4/")],
"url_img" : img if img is not None else None,
... | Python | 1 |
let op = Expression::build(&mut ctx, op).unwrap();
let got = op.eval(&mut ctx, &[]).unwrap();
let exp = Datum::I64(exp);
assert_eq!(got, exp);
}
}
#[test]
fn test_sqrt() {
let tests = vec![
(Datum::F64(64f64), Datum::F64(8f64)),
... | Rust | 0 |
import math as m
from scipy.stats import t as student
# Student's test statistics function:
def statistic_test_student(μ1, μ2, σ1, σ2, n1, n2):
Sp = m.sqrt(((n1 - 1) * σ1 ** 2 + (n2 - 1) * σ2 ** 2) / (n1 + n2 - 2))
t = (μ1 - μ2) / (Sp * m.sqrt(1 / n1 + 1 / n2))
return t
a = 0.05 # Level of significance
μ1 = ... | Python | 1 |
es W \times H \times C$.
#
# ### 1.4.1. Các thuộc tính của tensor
#
# Một tensor được đặc trưng bởi kích thước các chiều, số lượng chiều, định dạng dữ liệu của tensor.
#
# ::::{tabbed} pytorch
# :::{code-block} python
# A = torch.tensor([[[1, 2, 3],
# [3, 2, 1]],
# [[2, 1, 2],
#... | Python | 1 |
pub fn porta(self) -> &'a mut W {
self.variant(EXTIPSEL3_A::PORTA)
}
#[doc = "Port B pin 3 selected for external interrupt 3"]
#[inline(always)]
pub fn portb(self) -> &'a mut W {
self.variant(EXTIPSEL3_A::PORTB)
}
#[doc = "Port C pin 3 selected for external interrupt 3"]
... | Rust | 0 |
from typing import Optional
import pytest
from d3rlpy.algos.qlearning.crr import CRRConfig
from d3rlpy.models import (
MeanQFunctionFactory,
QFunctionFactory,
QRQFunctionFactory,
)
from d3rlpy.types import Shape
from ...models.torch.model_test import DummyEncoderFactory
from ...testing_utils import creat... | Python | 1 |
(_) => hlspoffset::generate,
LdSpHl => ldsphl::generate,
BitHalf { cmd: _, op: _ } => bithalf::generate,
Control(_) => control::generate,
Jump {
target: _,
condition: _,
} => jump::generate,
Call {
ta... | Rust | 0 |
} else {
None
}
})
}
/// Returns the location of the toplevel, if it exists.
pub fn location(&self, toplevel: &Kind<R>) -> Option<(i32, i32)> {
self.windows
.iter()
.find(|w| w.toplevel.equals(toplevel))
.map(|w| w.... | Rust | 0 |
pe=", ".join([get_short_name(cls, data_graph) for cls in o_classes]),
expected_type=", ".join([get_short_name(cls, data_graph) for cls in allowed_range_classes]),
)
)
return violations
def validate_property_type(data_graph: Graph, ont_graph: Graph) -> set[Violation... | Python | 1 |
not covered
match_false!(NonEmptyEnum5::V1);
//~^ ERROR `V1`, `V2`, `V3` and 2 more not covered
}
<gh_stars>1-10
lazy_static! {
// See this chart: http://www.calmar.ws/vim/256-xterm-24bit-rgb-color-chart.html
static ref COLORS: Vec<i32> = vec![
0x080808, 0x121212, 0x1c1c1c, 0x262626, 0x303030, 0x3a3a3a... | Rust | 0 |
"""
Reddit module
"""
import logging
from datetime import datetime
import praw
from .source import Source
class Reddit(Source):
"""
Builds articles from a series of Reddit API queries.
"""
def run(self):
# List of articles created
articles = []
# Reddit API connection
... | Python | 1 |
quest(AbstractModel):
"""DescribeDailyMediaPlayStat请求参数结构体
"""
def __init__(self):
r"""
:param _FileId: 媒体文件 ID 。
:type FileId: str
:param _StartDate: 起始日期,使用 [ISO 日期格式](https://cloud.tencent.com/document/product/266/11732#I)。该参数仅日期部分有效。
:type StartDate: str
... | Python | 1 |
# Example of a Class with Attributes and Methods
# Class definition
class Book:
def __init__(self, title, author, pages):
# Attributes
self.title = title
self.author = author
self.pages = pages
self.is_open = False
# Method to display book information
def display_in... | Python | 1 |
'cpu').numpy())
elif mode == 'test':
loss_epoch.append(loss.detach().to('cpu').item())
aoe_mean_epoch.append(aoe_mean.item())
foe_mean_epoch.append(foe_mean.item())
aoe_std_epoch.append(aoe_std.item())
foe_std_epoch.append(foe_s... | Python | 1 |
unwrap();
let mut order_book = OrderBook::default();
let mut trades = Trades::default();
let orders = match Order::from_file("orders.json") {
Ok(orders) => orders,
Err(e) => panic!("Couldn't read order.json - {}", e),
};
for new_order in orders {
if new_order.is_new() {
... | Rust | 0 |
#[cfg(target_os="linux")]
use std::ffi::OsString;
// use std::process;
fn main() {
// option_to_native();
chrome_native_config();
firefox_native_config();
// let instream = io::stdin();
// let mut input = String::new();
// loop{
// match instream.read_line(&mut input) {
// ... | Rust | 0 |
_, cause } => assert_eq!(cause.downcast::<Error>().unwrap().kind(), ErrorKind::ConnectionRefused),
_ => assert!(false)
}
// Err on pagination loading
let load_function = |_event_id: &str, _token: &str, page: u8| {
match page {
0 => Ok(AttendeesResponse {... | Rust | 0 |
"""
We would like to ignore a list of subreddits that would be sources of very bad
data. So that we don't have to do extensive, subjective research to make the
decision of which subreddits are bad, we exclude only the very worst:
subreddits that have been banned by the Reddit admins. Comments from these
subreddits that... | Python | 1 |
A, nodelabel = utils.to_adjacency_matrix(G)
x = self._lapsgn_core(A)
Q = self._score(A, None, x)
self.nodelabel = nodelabel
self.c_ = np.zeros(A.shape[0]).astype(int)
self.x_ = x.astype(int)
self.Q_ = np.sum(Q)
self.qs_ = Q
def _score(self, A, c, x):
... | Python | 1 |
.0 as i64
}
fn max_t<'a, T>(v: ArrayViewD<'a, T>, _last: bool) -> T
where
T: Copy + Datum + num_traits::Bounded + ::std::cmp::PartialOrd,
{
v.fold(T::min_value(), |acc, &v| if acc > v { acc } else { v })
}
fn min_t<'a, T>(v: ArrayViewD<'a, T>, _last: bool) -> T
where
T: Copy + Datum + num_traits:... | Rust | 0 |
"""
ECCV Caption
Copyright (c) 2022-present NAVER Corp.
MIT license
"""
import csv
def get_flag(ann, strict_pos, dump_negative):
posflag = ann == 1 if strict_pos else ann in {1, 2}
flag = posflag if not dump_negative else not posflag
return flag
def get_human_verified_data(human_verified_annotation_path... | Python | 1 |
),
),
)
.into(),
);
}
if !self.is_being_added {
//add "add" button
row_children.push(
Button::new(
&mut self.add_button,
... | Rust | 0 |
e_tx.send(msg).await?;
match rep_rx.await {
Ok(response) =>
{
match response {
Response::ContractDetails(contracts) => Ok(contracts),
_ => Err(Box::new(ResponseError{}))
}
},
Err(error) => Er... | Rust | 0 |
.field("public", &self.1)
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::repr::{ToPublicBytes, ToSecretBytes};
#[test]
fn expand_keypair() {
let seed = b"000000000000000000000000Trustee1";
let test_sk = &hex!("303030303030303030303030303030... | Rust | 0 |
group_name
data["start_date"] = payslip["start_date"]
data["end_date"] = payslip["end_date"]
data["status"] = "draft"
data["contract_wage"] = payslip["contract_wage"]
data["basic_pay"] = payslip["basic_pay"]
data["gross_pay... | Python | 1 |
_dec_str(&s).map_err(|e| {
config_error::FileError {
err: format!("Minimum fee string ill-formed: {}", e),
}
.build()
})?,
None => U256::zero(),
};
let num_buffer_epochs: usize = env_cli_config
.num... | Rust | 0 |
# підключення необхідних бібліотек
import cv2
sources = {'video1': "C:/Users/User/PycharmProjects/oop/video/bunnies.mp4", 'video2': "web"}
def main():
# метод зчитування даних з відеофайлу (стор. 142 - 145)
cap = cv2.VideoCapture(sources.get('video1'))
# Перевірка готовності веб-камери
while cap.isOp... | Python | 1 |
InvalidTransaction::Call.into()
}
}
}
impl<T: Config> pallet_treasury::SpendFunds<T> for Pallet<T> {
fn spend_funds(
budget_remaining: &mut BalanceOf<T>,
imbalance: &mut PositiveImbalanceOf<T>,
_total_weight: &mut Weight,
... | Rust | 0 |
x0002, 60)
def _loc_283(): pass
label('loc_283')
If(
(
(Expr.TestScenaFlags, ScenaFlag(0x0050, 7, 0x287)),
Expr.Return,
),
'loc_298',
)
OP_71(0x0000, 0x0004)
OP_71(0x0001, 0x0004)
OP_64(0x00, 0x0001)
def _loc_298(): pass
label('lo... | Python | 1 |
64 <= 1.0 &&
self.config.line_width / self.config.height * self.config.resolution_y as f64 <= 1.0 {
if self.config.pixel_in_image(x as i32, y as i32) {
image_buffer.put_pixel(x as u32, y as u32, image::Rgb(*color));
}
} else {
... | Rust | 0 |
let ciphertext_buf = &mut [0; 1024]; // Can't use PLAINTEXT.len() here.
let ciphertext = aead
.encrypt(1, AAD, PLAINTEXT, ciphertext_buf)
.expect("encrypt should work");
let expected_ciphertext: &[u8] = &[
0x5f, 0x01, 0xc4, 0xc2, 0xa2, 0x30, 0x3d, 0x29, 0x7e, 0x3c, 0x51, 0x9b, 0xf6, 0... | Rust | 0 |
, 0);
assert_eq!(gate.wire_first_input(0, 2), 2);
assert_eq!(gate.wire_second_input(0, 0), 3);
assert_eq!(gate.wire_second_input(0, 2), 5);
assert_eq!(gate.wire_first_output(0, 0), 6);
assert_eq!(gate.wire_second_output(0, 2), 11);
assert_eq!(gate.wire_switch_bool(0), 12)... | Rust | 0 |
# Практика
# Задача 1. Вода
# Одна бутылка воды «КлирВотер» от производителя «ВодЗавод» в разных магазинах стоит по-разному.
#
# Напишите программу, которая три раза вызывает функцию about_water, передаёт
# в неё один аргумент — цену на воду и выводит на экран название воды, производителя и цену.
# Пример:
#
# Название... | Python | 1 |
represent a constant (as in representable in
/// the constants table).
pub fn is_valid_for_constant(&self) -> bool {
use SignatureToken::*;
match self {
Bool | U8 | U64 | U128 | Address => true,
Vector(inner) => inner.is_valid_for_constant(),
Signer
... | Rust | 0 |
}
server
.client_timeout(opt.client_timeout.unwrap_or(std::u64::MAX))
.client_shutdown(opt.client_shutdown.unwrap_or(std::u64::MAX))
.max_connections(std::usize::MAX)
.max_connection_rate(std::usize::MAX)
.keep_alive(actix_http::KeepAlive::Timeout(5))
.run()
... | Rust | 0 |
one(),
field2.clone(),
field3.clone()
],
extension: vec![],
nested_type: vec![],
enum_type: vec![
EnumDescriptorProto {
name: Some("ContentTypeHint".to_string()),
value: vec![
EnumValueDescriptorProto {
name: Some("DEFAU... | Rust | 0 |
"""
https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html#multi-value-headers
When an ALB is configured to send multi-value headers, the headers are sent as a list of values under the key in the multiValueHeaders object.
"""
MOCK_LAMBDA_ALB_MULTI_VALUE_HEADER_EVENT = {
"request... | Python | 1 |
= (end_sequence[index - 1] + end_sequence[index]) % 10;
}
}
end_sequence
.iter()
.take(8)
.map(|&b| ((b + 48) as u8) as char)
.collect()
}
#[test]
pub fn tests_part1() {
assert_eq!(part1("80871224585914546619083218645595"), "24176176");
assert_eq!(part1(include... | Rust | 0 |
hes")]
async fn get_crashes(db_pool: web::Data<SqlitePool>) -> impl Responder {
match Crash::get_all_crashes(db_pool.get_ref()).await {
Ok(crashes) => HttpResponse::Ok().json(crashes),
Err(err) => {
error!("Error fetching crashes: {}", err);
HttpResponse::InternalServerError(... | Rust | 0 |
r not.
// pub fn repeat() -> BoxedFilter<(String, )> {
// warp::get()
// .and(path!("repeat" / String))
// .and(warp::path::end())
// .boxed()
// }
// Is this was the reason of all this problem?
// https://github.com/seanmonstar/warp/pull/359
// Use .. at the end when you want to make prefi... | Rust | 0 |
from pydantic import BaseModel, PositiveInt
from .enums import LaftelTagTypes
__all__ = ("LaftelTag",)
class LaftelTag(BaseModel):
"""라프텔에 사용되는 태그를 나타냅니다."""
id: PositiveInt
is_show: bool
name: str
type: LaftelTagTypes | Python | 1 |
rs to all queries. If a single answer cannot be determined, return -1.0.
* Note: The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.
*
* Example 1:
*
* Input: equations = [["a","b"],["b","c"]], values = [2.0,3.0], queries ... | Rust | 0 |
import os
import sys
import types
# Ensure project root is on sys.path
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
if ROOT not in sys.path:
sys.path.insert(0, ROOT)
SRC = os.path.join(ROOT, 'src')
if os.path.isdir(SRC) and SRC not in sys.path:
sys.path.insert(0, SRC)
class _DummyGI... | Python | 1 |
<dyn Fn(BoxFuture<()>) + Send + Sync>,
dataset: String,
#[derivative(Debug = "ignore")]
executor: FutureExecutor,
trace_config: Option<opentelemetry::sdk::trace::Config>,
transmission_options: libhoney::transmission::Options,
#[derivative(Debug = "ignore")]
on_span_start: Option<Arc<dyn Fn(&... | Rust | 0 |
ame))
self.assertTrue(id(var1) == id(var2))
self.assertTrue(net1_name in var1.name)
self.assertTrue(net1_scope in var1.name)
self.assertTrue(net2_name in var2.name)
self.assertTrue(net2_scope in var2.name)
var = net1[2][0]
op = tf.assign(var,
... | Python | 1 |
#
# This file is licensed under the Affero General Public License (AGPL) version 3.
#
# Copyright 2014-2016 OpenMarket Ltd
# Copyright (C) 2023 New Vector, Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Fre... | Python | 1 |
"""
Run:
python zipsrc.py
This will create a file `source.zip` which you can upload to Coursys (courses.cs.sfu.ca) as your submission.
To customize the files used by default, run:
python zipsrc.py -h
"""
import sys, os, optparse, shutil
if __name__ == '__main__':
optparser = optparse.OptionParser()
... | Python | 1 |
1, cond1), (slater2, cond2), (func0(z0), True))
# We couldn't find an expression without hypergeometric functions.
# TODO it would be helpful to give conditions under which the integral
# is known to diverge.
r = Piecewise((slater1, cond1), (slater2, cond2), (func0(z0), True))
if r.has(hyper) ... | Python | 1 |
#!/usr/bin/env python
# coding: utf-8
# In[2]:
import numpy as np
from data_prep import features, targets, features_test, targets_test
def sigmoid(x):
"""
Calculate sigmoid
"""
return 1 / (1 + np.exp(-np.array(x, dtype=float)))
def sigmoid_prime(x):
return sigmoid(x) * (1 - sigmoid(x))
# TODO:... | Python | 1 |
from machine import sleep, SoftI2C, Pin, Timer
from utime import ticks_diff, ticks_us
from max30102 import MAX30102, MAX30105_PULSE_AMP_MEDIUM
from hrcalc import calc_hr_and_spo2
BEATS = 0 # 存储心率
FINGER_FLAG = False # 默认表示未检测到手指
SPO2 = 0 # 存储血氧
TEMPERATURE = 0 # 存储温度
# ------------ 添加新代码 -----------
HREAT_LIST = ... | Python | 1 |
"""Add stage two MITS team fields
Revision ID: 4036e1fdb9ee
Revises: 26bc228319d2
Create Date: 2020-04-14 22:59:59.346742
"""
# revision identifiers, used by Alembic.
revision = '4036e1fdb9ee'
down_revision = '26bc228319d2'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
tr... | Python | 1 |
new(255, 128, 0), *bmp.color(2, 3));
}
}
<filename>src/storage/conformance/src/io1_request_logger_factory.rs
// Copyright 2020 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 {
crate::directory_request_logger:... | Rust | 0 |
# -*- coding: utf-8 -*- #
# Copyright 2022 Google LLC. All Rights Reserved.
#
# 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 requir... | Python | 1 |
: iter_expr.hir_id,
past_while_let: false,
var_used_after_while_let: false,
};
if let Some(enclosing_block) = get_enclosing_block(cx, def_id) {
walk_block(&mut visitor, enclosing_block);
}
visitor.var_used_after_while_let
}
fn is_nested(cx: &LateContext<'_>, match_expr: &Expr<'_... | Rust | 0 |
sway workspaces
#[derive(Debug, Parser)]
#[clap(name = "swayws", version)]
struct SwayWs {
/// Use verbose output
#[clap(short, parse(from_occurrences))]
verbose: u8,
#[clap(subcommand)]
cmd: Command,
}
#[derive(Debug, Subcommand)]
enum Command {
/// Focus a workspace
Focus {
/// ... | Rust | 0 |
import pandas as pd
from sklearn.preprocessing import MultiLabelBinarizer
# --- Load datasets ---
df = pd.read_csv("dataset.csv")
desc = pd.read_csv("symptom_Description.csv")
prec = pd.read_csv("symptom_precaution.csv")
sev = pd.read_csv("Symptom-severity.csv")
# Fill NaN with empty strings
df = df.fillna("")
# ---... | Python | 1 |
exec(input: *const u8, output: *mut u8, buflen: u64) -> i64;
}
pub fn mesapy_from_buffer(_helper: &mut WorkerHelper, input: WorkerInput) -> Result<String> {
let payload = match input.payload {
Some(value) => value,
None => return Err(Error::from(ErrorKind::MissingValue)),
};
let mut py_scr... | Rust | 0 |
import django_filters
from articles.models import Article
class ArticleFilter(django_filters.FilterSet):
tag = django_filters.CharFilter(method="tag_filter")
author = django_filters.CharFilter(method="author_filter")
favorited = django_filters.CharFilter(
field_name="favorites",
method="f... | Python | 1 |
s_name, value));
self
}
pub fn dom_ref(mut self, behavior: &Behavior<Option<web_sys::Element>>) -> Self {
self.dom_ref = Some(behavior.clone());
self
}
pub fn style(mut self, style_name: &'static str, value: StyleStream) -> Self {
self.styles.push((style_name, value));
... | Rust | 0 |
class Human:
default_name = "Ramil"
default_age = 0
def __init__(self,name: str = default_name, age: int = default_age):
self.default_name = name
self.default_age = age
self.__money = 0
self.__house = None
def info(self):
print(self.name, self.age, self.__money,... | Python | 1 |
from pipelines.training_pipeline import train_pipeline
from zenml.client import Client
if __name__ == '__main__':
# Run the pipeline
print("CLient URI: ", Client().active_stack.experiment_tracker.get_tracking_uri())
path = r"C:\Users\okore\OneDrive\Desktop\MACHINE_LEARNING\Anomaly_Detection\data\Train.txt... | Python | 1 |
# flake8: noqa
# There's no way to ignore "F401 '...' imported but unused" warnings in this
# module, but to preserve other warnings. So, don't check this module at all.
# Copyright 2020 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use thi... | Python | 1 |
(
(Expr.PushValueByIndex, 0x3),
Expr.Return,
),
(0x00000001, 'loc_2CA'),
(-1, 'loc_2CD'),
)
def _loc_2CA(): pass
label('loc_2CA')
OP_B4(0x00)
Return()
def _loc_2CD(): pass
label('loc_2CD')
EventBegin(0x00)
OP_66(0x0001)
... | Python | 1 |
"""Update file table path
Revision ID: c29facfe716b
Revises: c69f45358db4
Create Date: 2024-10-20 17:02:35.241684
"""
from alembic import op
import sqlalchemy as sa
import json
from sqlalchemy.sql import table, column
from sqlalchemy import String, Text, JSON, and_
revision = "c29facfe716b"
down_revision = "c69f45... | Python | 1 |
rtswith('http'):
t = 'https://' + t
targets.append(t.rstrip('/'))
for target_base in targets:
try:
tester.run_on_target(target_base, args.path)
except KeyboardInterrupt:
print("[*] Interrupted by user")
break
except Exception as e:
... | Python | 1 |
_spiptrcntl2::W](bb_spiptrcntl2::W) writer structure"]
impl crate::Writable for BB_SPIPTRCNTL2 {}
#[doc = "Third control register for the radio interface SPI pointers"]
pub mod bb_spiptrcntl2;
#[doc = "Advertising channel map register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generi... | Rust | 0 |
b fn mul_high_u16(self, other: m128i) -> m128i {
m128i(unsafe { _mm_mulhi_epu16(self.0, other.0) })
}
/// lanewise u16x8 subtraction with saturation
#[inline(always)]
pub fn saturating_sub_u16(self, other: m128i) -> m128i {
m128i(unsafe { _mm_subs_epu16(self.0, other.0) })
}
/// lanewise u64x2 mul... | Rust | 0 |
.lock().unwrap().clone(),
);
}
window.surface().damage_buffer(0, 0, dimensions.0 as i32, dimensions.1 as i32);
window.surface().commit();
}
event_queue.dispatch().unwrap();
}
}
fn redraw(
pool: &mut Mem... | Rust | 0 |
от сложности
difficulty = settings.get('difficulty', 'medium')
if difficulty == 'easy':
ball_lifetime = 4.0
elif difficulty == 'hard':
ball_lifetime = 2.0
else:
ball_lifetime = 3.0
global BALL_LIFETIME
BALL_LIFETIME = ball_lifetime
def start_round():
nonloca... | Python | 1 |
riter::new(File::create(o)?);
trec::write_all(file, list)?;
}
None => {
trec::write_all(std::io::stdout(), list)?;
}
}
}
}
}
Ok(())
}
<gh_stars>0
use std::thread;
use ... | Rust | 0 |
er = match value_ty {
ParsedType::Boolean(_) => {
quote! {
let converted_bool_vector: Vec<u8> = arg.into_iter().map(|v| *v as u8).collect::<_>();
let ptr = converted_bool_vector.as_ptr();
let len = converted_bool_vector.len();
marine_r... | Rust | 0 |
import streamlit as st
import matplotlib.pyplot as plt
import numpy as np
from math import sin, sqrt
import matplotlib
def first_func(x):
return x ** 2
def second_func(x):
return x ** 3
def two_func():
x = np.linspace(0, 100, 1000)
first_y = [first_func(i) for i in x]
second_y = [second_func(i) f... | Python | 1 |
oveField(
model_name='webhook',
name='content_types',
),
migrations.RemoveField(
model_name='webhook',
name='enabled',
),
migrations.RemoveField(
model_name='webhook',
name='type_create',
),
migration... | Python | 1 |
nk+1}. path={doc_info['file_path']} dist={dist:.4f}")
# 5. Build a context from the retrieved doc summaries
# You can refine how you combine them—here we simply concat with newlines.
context = "\n\n".join([doc["summary"] for doc, _dist in retrieved_docs])
# 6. Load your generative model (fine-tuned s... | Python | 1 |
None;
}
if self._anchor_cache.a1_g1.is_some() {
self._anchor_cache.a1_g1 = None;
}
}
pub fn set_source(&mut self, index: usize, new_source: &str) {
if self._items[index].source != new_source {
self.dispose_caches();
self._items[index].set_sou... | Rust | 0 |
re content into buffer, and reduce the read times
if let Some(ref mut file) = self.file {
let read = file.read(&mut buffer)?;
self.counter += 1; // Read times + 1
if read > 0 {
// TO fix!
// println!("DD {} {} {:?}", size, read, &buffer[0..rea... | Rust | 0 |
where T:PartialOrd+Copy {
RankedSet{ ascending:asc, v:s.v.to_vec(), i:rank(s,asc) }
}
/// From Ordered - the index will be trivial
pub fn from_ordered(s: &OrderedSet<T>, asc: bool) -> Self where T:PartialOrd+Copy {
RankedSet{ ascending:asc, v:s.v.to_vec(), i:trivindex(asc =... | Rust | 0 |
"""Ratios Helper Module"""
import pandas as pd
def map_period_data_to_daily_data(
period_data: pd.DataFrame, daily_dates: pd.PeriodIndex, quarterly: bool = False
):
"""
Maps period data to daily dates and fills missing values.
Args:
period_data (pandas.DataFrame): The period data to map to d... | Python | 1 |
.WindowsTerminal" in result.stdout
except subprocess.CalledProcessError:
return False
def download_file(url: str, dest_path: Path, description: str) -> bool:
"""Download a file with progress indication."""
try:
print(f" 📥 Downloading {description}...")
urllib.request.urlretrieve(... | Python | 1 |
turn Err(ErrorCode::WrongState.into());
}
let optifi_exchange = &ctx.accounts.optifi_exchange;
let margin_stress_account = &mut ctx.accounts.margin_stress_account;
let now = margin_stress_account.timestamp;
let iv = u_to_f_repr!(margin_stress_account.iv);
let spot_price = u_to_f_repr!(margin_s... | Rust | 0 |
import sqlite3, sys, os.path
# define Color
Green = '\033[32m'; Red = '\033[31m'; GreenBG = '\033[42;37m'; RedBG = '\033[41;37m'
Yellow = '\033[0;33m'; SkyBlue = '\033[0;36m'; Font = '\033[0m'
db_flag = os.path.exists('vps2021.db')
conn = sqlite3.connect('vps2021.db')
c = conn.cursor()
if db_flag == False :
c.exec... | Python | 1 |
_power_smoothed: epoch_qa_power_smooth,
}
}
fn make_fault_params_from_faulting_sectors(
rt: &MockRuntime,
state: &State,
fault_sector_infos: &[SectorOnChainInfo],
) -> DeclareFaultsParams {
let mut declaration_map: BTreeMap<(u64, u64), FaultDeclaration> = BTreeMap::new();
for sector in fault_se... | Rust | 0 |
rbose"), 1);
}
_ => panic!(),
}
}
#[test]
fn test_optflagmulti_long2() {
let args = vec!["--verbose".to_string(), "--verbose".to_string()];
match Options::new()
.optflagmulti("v", "verbose", "verbosity")
.parse(&args)
{
Ok(ref m) => {
assert_eq!(m.opt... | Rust | 0 |
the information of a specific contribution.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct CurrentContributorInfoResponse {
/// Latest penalty period of this contribution
pub n: u64,
/// Contribution to in this penalty period
pub value_contributed: Uint128,
}
/// ## D... | Rust | 0 |
<Input<MouseButton>>,
mut pressed_on_ent_events: EventWriter<PressedOnEntity>,
mouse_world_position: Res<MouseWorldPosition>,
q_pickable: Query<(Entity, &Transform, &RectFromTransform), With<Pickable>>,
) {
if mouse_button_input.just_pressed(MouseButton::Left)
|| mouse_button_input.just_pressed(... | Rust | 0 |
, &size, |b, &size| {
b.iter(|| {
deswizzle_surface(
size,
size,
1,
&source,
BlockDim::block_4x4(),
None,
black_box(16),
black_box(6... | Rust | 0 |
tch recv.recv() {
Ok(delta) => match delta {
Delta::Next(response) => {
let value = response.body().clone();
for v in value["responses"].as_array().unwrap().iter() {
match v["id"].as_str().unwrap().as_bytes()... | Rust | 0 |
ent_crashed(crash_message)
logger.error("Agent has crashed: %s", crash_message)
return f"Agent has crashed: {crash_message}"
_handle_fallback_response(e, fallback_handler, agent, msg_list)
continue
except FallbackTo... | Python | 1 |
dline(cmd)
if timeout != -1:
timeout *= self.timeout_multiplier
self.qemu.expect("# ", timeout=timeout)
# Remove double carriage return from qemu stdout so str.splitlines()
# works as expected.
output = self.qemu.before.replace("\r\r", "\r").splitlines()[1:]
... | Python | 1 |
rable_in = []
v1.created_at = v1.updated_at = datetime.datetime.utcnow()
vuln1 = VulnerableArtifact()
vuln1.created_at = vuln1.updated_at = v1.created_at
vuln1.namespace_name = v1.namespace_name
vuln1.name = python_pkg1_100.name
vuln1.vulnerability_id = v1.id
vuln1.parent = v1
vuln1.ver... | Python | 1 |
"""Constants for the Control4 Amplifier integration."""
from typing import Final
DOMAIN: Final = "control4_amplifier"
# SSDP Constants
ATTR_MANUFACTURER = "Control4"
ATTR_MODEL = "C4-8AMP1-B"
ATTR_ST = "c4:v1_8chanamp"
ATTR_MAC_ADDRESS = "mac_address"
# Config Constants
CONF_PORT = "port"
CONF_INPUTS = "inputs"
CONF... | Python | 1 |
_uint,
);
}
extern "C" {
pub fn rtcDetachGeometry(scene: RTCScene, geomID: ::std::os::raw::c_uint);
}
extern "C" {
pub fn rtcGetGeometry(scene: RTCScene, geomID: ::std::os::raw::c_uint) -> RTCGeometry;
}
extern "C" {
pub fn rtcCommitScene(scene: RTCScene);
}
extern "C" {
pub fn rtcJoinCommitScene(sc... | Rust | 0 |
s.push(Point::new(a_point.x(), a_point.y()));
}
}
}
points
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_line() {
let line = Line::from("1,5->3,7");
assert_eq!(Line::new(Point::new(1, 5), Point::new(3, 7)), line);
}
#[test]
fn test_line_... | Rust | 0 |
/ This file is generated by rust-protobuf 2.8.1. Do not edit
// @generated
// https://github.com/Manishearth/rust-clippy/issues/702
#![allow(unknown_lints)]
#![allow(clippy::all)]
#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(box_pointers)]
#![allow(dead_code)]
#![allow(missing_docs)]
#![allow(non_camel_case_types)]
... | Rust | 0 |
_csv(self, subnet_id, writer):
ipaddress_model = load_model("openwisp_ipam", "IpAddress")
subnet = load_model("openwisp_ipam", "Subnet").objects.get(pk=subnet_id)
writer.writerow([subnet.name])
writer.writerow([subnet.subnet])
writer.writerow([subnet.organization.slug] if subnet.... | Python | 1 |
from django.shortcuts import render
from rest_framework import generics
from .serializer import RoomSerializer
from .models import Room
# Create your views here.
class RoomView(generics.CreateAPIView):
queryset=Room.objects.all()
serializer_class=RoomSerializer
| Python | 1 |
0), 'Helvetica-Bold'),
('BOTTOMPADDING', (0,0), (-1,0), 8),
('BACKGROUND', (0,1), (-1,-1), colors.HexColor("#161a25")),
('TEXTCOLOR', (0,1), (-1,-1), colors.white),
('GRID', (0,0), (-1,-1), 0.25, colors.gray)
]))
elements += [table,... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.