text string | label_name string | labels int64 |
|---|---|---|
s.frames)
assert_equal(times, ana.results.times)
assert_equal(timeseries, ana.results.timeseries)
def mass_xyz(atomgroup1, atomgroup2, masses):
return atomgroup1.positions * masses
def test_AnalysisFromFunction_args_content(u, client_AnalysisFromFunction):
protein = u.select_atoms("protein")... | Python | 1 |
j][0]
y = step_gene.inner_edges[2*j+1][1]
y_op = step_gene.inner_edges[2*j+1][0]
# print(j, x, x_op, y, y_op)
# c.edge(inner_node_names[x], inner_node_names[2+j], label=x_op)
# c.edge(inner_node_names[y], inner_node_names[2+j], label=y_op)
... | Python | 1 |
import numpy as np
import matplotlib.pyplot as plt
# 1) 분포 배열 로드
flying = np.load('./mean_disparity_distribution_flyingthing.npy')
kitti = np.load('./mean_disparity_distribution_kitti.npy')
# 2) 길이 맞추기 (둘 중 짧은 길이 기준)
common_len = min(len(flying), len(kitti))
flying = flying[:common_len]
kitti = kitti[:common_len]
d... | Python | 1 |
from skorch import NeuralNetClassifier
from skorch.dataset import ValidSplit
from torch import nn
from torch import optim
from tsai.models.XceptionTimePlus import XceptionTimePlus
def xceptiontime_v5(device="cpu", c_in=20, class_weights=None):
net = NeuralNetClassifier(module=XceptionTimePlus, module__c_in=c_in, ... | Python | 1 |
on `f` with the
* element's value.
*/
pure fn riter<T>(v: &[T], f: fn(T)) {
riteri(v, |_i, v| f(v))
}
/**
* Iterates over a vector's elements and indexes in reverse
*
* Iterates over vector `v` and, for each element, calls function `f` with the
* element's value and index.
*/
pure fn riteri<T>(v: &[T], f: f... | Rust | 0 |
($wrapper:tt) => {
impl<E: EngineBLS> Clone for $wrapper<E> {
fn clone(&self) -> Self { $wrapper(self.0) }
}
impl<E: EngineBLS> Copy for $wrapper<E> { }
impl<E: EngineBLS> PartialEq<Self> for $wrapper<E> {
fn eq(&self, other: &Self) -> bool {
self.0.eq(&other.0)
}
}
impl <E: EngineBLS> Eq for $... | Rust | 0 |
logging.error(f"Executing one-time update task failed: {str(e)}")
return False
def main():
main_pid = 'logs/task.pid'
if os.path.exists(main_pid):
os.system("kill -9 $(cat {}) &> /dev/null".format(main_pid))
pid = os.fork()
if pid:
sys.exit(0)
os.setsid()
_pi... | Python | 1 |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... | Python | 1 |
ing.info(f"{column} - MAE: {mae}, MSE: {mse}, R²: {r2}")
r2_scores[column] = r2
# 绘制评估指标图
plt.figure(figsize=(6, 6))
plt.scatter(y_val_column.cpu().numpy(), y_test_pred, edgecolors=(0, 0, 0))
plt.plot([min(y_val_column.cpu().numpy()), max(y_val_column.cpu().numpy())],
[min(y_val_column... | Python | 1 |
,
spectral_penalty=0,
):
hessian_pytree = jax.hessian(jpc.pc_energy_fn, argnums=1)(
params,
activities,
y,
x=x,
param_type=param_type,
activity_decay=activity_decay,
weight_decay=weight_decay,
spectral_penalty=spectral_penalty,
)
H = un... | Python | 1 |
from collections import deque
delta = [[0, 1], [0, -1], [1, 0], [-1, 0]]
def bfs(i, j):
q = deque()
union = []
q.append((i, j))
union.append((i, j)) # 연합만들기
while q:
x, y = q.popleft()
for dx, dy in delta:
nx, ny = x+dx, y+dy
if 0 <= nx < N and 0 <= ny < N ... | Python | 1 |
(b_and_d[0], b_and_d[1])
} else {
(b_and_d[1], b_and_d[0])
};
assert!(scrambled_to_real.insert(b, 'b').is_none());
assert!(scrambled_to_real.insert(d, 'd').is_none());
// g is the segment that appears in 3 that is otherwise unaccounted for
let g = three
.chars()
.filte... | Rust | 0 |
from .models import HeatShelter
from rest_framework import serializers
class HeatShelterSerializer(serializers.ModelSerializer):
class Meta:
model = HeatShelter
fields = '__all__'
| Python | 1 |
) / 1000), '%Y-%m-%d %H:%M:%S.%f')[:-3]
key_str = "~" + novelId + "$" + chapterId + key_time_str + "-0o4MQlyrz2pQPRMLN2/TYAVBDkYN6FwTown1V1AAQJBANDww8VC6nqRM+teVqNNbzPbxzQLJUjgNzJ6FdX4OXhSDGQrYN62czDtUTfTXVOzZuDjJq7h+E17hd7ue/yQezsXuPPTsPKflgWOKCGhlKowdTNFABBdmq39hAkB1fhd/VSB/1G7zb/iCzoC84m2QsDVrfgLQSC3jGdeiLgJ... | Python | 1 |
edict, 0)
num_hits = (y_true == y_predict).float().sum()
acc = num_hits / y_true.shape[0]
# print()
if print_perform and mode != 'backdoor' and mode != 'widen' and mode != 'pruned':
print(classification_report(y_true.cpu(), y_predict.cpu(), target_names=data_loader.dataset.classes, digits=4))
... | Python | 1 |
_INTEGRAL_GAIN: f64 = 3.;
const FLOW_CONTROL_FORCE_GAIN: f64 = 200000.;
const MAX_DAMPING_CONSTANT_FOR_SLOW_DAMPING: f64 = 800000.;
fn a320_aileron_actuator(bounded_linear_length: &impl BoundedLinearLength) -> LinearActuator {
let randomized_damping = random_from_range(
Self::MAX_DAMPI... | Rust | 0 |
json::from_str(&msg2.get(0).unwrap()).unwrap();
let s0: State = serde_json::from_str(msg2[1].as_ref()).unwrap();
let pay_token = handle_error_result!(mpc::activate_merchant(
&mut db as &mut dyn StateDatabase,
channel_token.clone(),
&s0,
&mut merch_state
... | Rust | 0 |
>;
#[doc = "Reserved"]
pub mod a1_pd_src_mask_n;
#[doc = "A1_WU_SRC_MASK_N register accessor: an alias for `Reg<A1_WU_SRC_MASK_N_SPEC>`"]
pub type A1_WU_SRC_MASK_N = crate::Reg<a1_wu_src_mask_n::A1_WU_SRC_MASK_N_SPEC>;
#[doc = "Control masking of wake-up event triggers for the A1 domain"]
pub mod a1_wu_src_mask_n;
#[do... | Rust | 0 |
ding)
self.verticalLayout_9.addItem(spacerItem7)
self.dong_btn = QtWidgets.QPushButton(Form)
self.dong_btn.setMinimumSize(QtCore.QSize(90, 40))
self.dong_btn.setMaximumSize(QtCore.QSize(93, 40))
self.dong_btn.setStyleSheet("#dong_btn {\n"
" background-color: white;\n"
" col... | Python | 1 |
els=1):
interval = (2 * nsig + 1.) / (kernlen)
x = np.linspace(-nsig - interval / 2., nsig + interval / 2., kernlen + 1)
kern1d = np.diff(st.norm.cdf(x))
kernel_raw = np.sqrt(np.outer(kern1d, kern1d))
kernel = kernel_raw / kernel_raw.sum()
out_filter = np.array(kernel, dtype=np.float32)
out_... | Python | 1 |
return self.vector_retriever.retrieve(query_bundle)
def _expand_context_via_graph(self, entry_nodes: List[NodeWithScore]) -> Set[str]:
"""
通过知识图谱扩展上下文节点
从入口点节点开始,在知识图谱中进行广度优先遍历,
收集指定深度内的所有相关节点ID。
Args:
entry_nodes (List[NodeWithS... | Python | 1 |
, // A0
1 => &&peripherals.gpio_port[33], // A1
2 => &&peripherals.gpio_port[11], // A2
3 => &&peripherals.gpio_port[29], // A3
5 => &&peripherals.gpio_port[31] // A5
),
)
.finalize(components::gpio_component_buf!(apollo3::gpio::GpioPin));
// Cre... | Rust | 0 |
t"]
# st4
assert st4.parameters["num"].ref.component == dag3 and \
st4.parameters["num"].ref.name == list(dag3.parameters.keys())[0]
# st5
assert st5.inputs["data"].ref.component == dag2 and \
st5.inputs["data"].ref.name == list(dag2.outputs.keys())[0]
... | Python | 1 |
# [ doc = "12-bit transfer" ]
_12_BIT_TRANSFER,
# [ doc = "13-bit transfer" ]
_13_BIT_TRANSFER,
# [ doc = "14-bit transfer" ]
_14_BIT_TRANSFER,
# [ doc = "15-bit transfer" ]
_15_BIT_TRANSFER,
# [ doc = "16-bit transfer" ]
_16_BIT_TRANSFER,
}
... | Rust | 0 |
_1, fk_x_2], references: [id, y], onUpdate: NoAction, map: "yfk")
x_x_yToy x[] @relation("x_yToy")
}
"#]];
expected.assert_eq(&api.introspect_dml().await?);
Ok(())
}
#[test_connector(tags(Mssql))]
async fn multiple_foreign_key_constraints_are_taken_always_in_the_same_order(a... | Rust | 0 |
#!/usr/bin/env python
import wx
import images
class ToolbarFrame(wx.Frame):
def __init__(self, parent, id):
wx.Frame.__init__(self, parent, id, 'Toolbars',
size=(300, 200))
panel = wx.Panel(self)
panel.SetBackgroundColour('White')
statusBar = self.CreateStatusBar()... | Python | 1 |
f32,
winy : f32,
winz : f32,
modelview_matrix : &Mat4,
projection_matrix : &Mat4,
viewport_matrix : &[i32]
) -> Option<Vec3>
{
let mut fin = projection_matrix.multiply(modelview... | Rust | 0 |
RANGE)))
self.play(MoveAlongPath(d1, l1), rate_func=linear)
"""
def __init__(
self,
mobject: Mobject,
path: VMobject,
suspend_mobject_updating: bool | None = False,
**kwargs,
) -> None:
self.path = path
super().__init__(
mo... | Python | 1 |
scancodes
// the track_* functions track the keyup/keydowns to modify keys with shift, hold, and chord state
let kc: Vec<char, 4> = match kbd.get_map() {
KeyMap::Braille => {
kbd.track_chord(keyups, keydowns)
},
... | Rust | 0 |
:sync::Arc;
#[derive(Debug)]
pub struct CheckerTexture {
pub coeff: FloatTy,
pub even: Arc<dyn Texture>,
pub odd: Arc<dyn Texture>,
}
impl CheckerTexture {
pub fn new(even: Arc<dyn Texture>, odd: Arc<dyn Texture>, coeff: FloatTy) -> Self {
CheckerTexture { even, odd, coeff }
}
}
impl Text... | Rust | 0 |
="8"
"#,
)
.unwrap();
assert_eq!(
Linux {
distro: "centos".to_string(),
version: Some("8".to_string()),
version_name: None,
},
os_release
);
}
}
<reponame>nils-we97/rust_road_router-fork
// Metric de... | Rust | 0 |
import os
from typing import Any
import torch
from trainer.logging.tensorboard_logger import TensorboardLogger
from trainer.trainer_utils import is_clearml_available
from trainer.utils.distributed import rank_zero_only
if is_clearml_available():
from clearml import Task # pylint: disable=import-error
else:
... | Python | 1 |
Batu Rakit'},
'609669':{'en': 'Batu Rakit'},
'609679':{'en': 'Jerteh'},
'609680':{'en': 'Kuala Brang'},
'609681':{'en': 'Kuala Brang'},
'609682':{'en': 'Kuala Brang'},
'6096830':{'en': 'Kuala Brang'},
'609684':{'en': 'Bukit Bading'},
'609685':{'en': 'Kuala Brang'},
'609686':{'en': 'Kuala Brang'},
'609687':{'e... | Python | 1 |
ake};
#[cfg(feature = "debug")]
use std::any::{type_name, TypeId};
use std::cell::UnsafeCell;
use std::collections::BTreeMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
/// Task token
type Token = usize;
#[cfg(feature = "debug")]
#[derive(Clone, Debug)]
pub struct ... | Rust | 0 |
//! Lit test failed with:
//! failed to find check string: USAGE:
//! ```
use derive_builder::Builder;
use std::process::{Command, Output};
use std::str::from_utf8;
#[derive(Builder)]
pub struct LitTester {
#[builder(setter(into))]
cmd: String,
#[builder(default = "vec![]")]
args: Vec<String>,
#... | Rust | 0 |
#We will implement the RSI strategy here
import yfinance as yf
import matplotlib.pyplot as plt
import datetime as dt
import pandas as pd
tickers = {
"HDFCBANK": "HDFCBANK.NS"}
#WE WILL ONLY LOOK FOR HDFC NOW AND COMPARE OTHER STOCKS LATER
df = pd.read_csv("HDFCBANK.csv")
close = df['Close']
def rsi(close, peri... | Python | 1 |
* Asana
*
* This is the interface for interacting with the [Asana Platform](https://developers.asana.com). Our API reference is generated from our [OpenAPI spec] (https://raw.githubusercontent.com/Asana/developer-docs/master/defs/asana_oas.yaml).
*
* The version of the OpenAPI document: 1.0
*
* Generated by: http... | Rust | 0 |
let Some(count) = people_now_present {
status.state.open = Some(count > 0);
if count == 1 {
status.state.message = Some(format!("{} person here right now", count));
} else if count > 1 {
status.state.message = Some(format!("{} people here right now", c... | Rust | 0 |
Point) -> s1::S1Angle {
// Note that atan2(0, 0) is defined to be zero.
return s1::S1Angle::from_radians(p.y.atan2(p.x));
}
/// Return the latitude of this point.
pub fn lat(&self) -> s1::S1Angle {
return s1::S1Angle::from_radians(self.coords[0]);
}
/// Return the longitude ... | Rust | 0 |
ER,
AMERICAN_LAGER,
CREAM_ALE,
AMERICAN_WHEAT_BEER,
INTERNATIONAL_PALE_LAGER,
INTERNATIONAL_AMBER_LAGER,
INTERNATIONAL_DARK_LAGER,
CZECH_PALE_LAGER,
CZECH_PREMIUM_PALE_LAGER,
CZECH_AMBER_LAGER,
CZECH_DARK_LAGER,
MUNICH_HELLES,
FESTBIER,
HELLES_BOCK,
GERMAN_LEICHTB... | Rust | 0 |
from locust import HttpUser, task, between
import random
from datetime import datetime
class DeviceMeasureUser(HttpUser):
host = "http://localhost:8000"
wait_time = between(0.5, 1.5)
def on_start(self):
self.device_id = random.randint(1, 10)
@task(3)
def post_measure(self):
# Ими... | Python | 1 |
}
pub fn connect(&mut self, a: &Uuid, b: &Uuid) {
let edge = Edge::new(a.clone(), b.clone());
if self.edges.iter().find(|&e| e == &edge).is_none() {
self.edges.push(edge);
}
}
pub fn siblings(&self, node: &Uuid) -> Vec<&Uuid> {
self.edges.iter().filter_map(... | Rust | 0 |
_key: &[u8], // the key being merged
/// old_value: Option<&[u8]>, // the previous value, if one existed
/// merged_bytes: &[u8] // the new bytes being merged in
/// ) -> Option<Vec<u8>> { // set the new value, return None to delete
/// let mut ret = old_value
//... | Rust | 0 |
t Vec<Scanner>) {
let scanners_len = scanners.len();
let mut scanners_to_do: HashSet<_> = (0..scanners_len).collect();
scanners[0].abs_beacons = Some(scanners[0].rel_beacons.clone());
scanners[0].abs_position = Some(Position::new("0,0,0"));
while scanners_to_do.len() > 0 {
for known_idx in... | Rust | 0 |
o_path(12, 4).unwrap(), vec![2, 1, 2]);
assert_eq!(from_node_num_to_path(8, 4).unwrap(), vec![1, 2, 2]);
}
// TODO: Test to and from conversion of path and node number using randoms
#[test]
fn test_node_successors_7() {
let T = 7;
let l = calculate_l(T).unwrap();
let su... | Rust | 0 |
st AFE4490_PROG10 : [u16;5] = [ 0x0310,0x0300,0x0307,0x03FF,0x0600 ]; // Программировать регистр по адресу 10
pub const AFE4490_PROG11 : [u16;5] = [ 0x0311,0x0300,0x0308,0x0304,0x0600 ]; // Программировать регистр по адресу 11
pub const AFE4490_PROG12 : [u16;5] = [ 0x0312,0x... | Rust | 0 |
#temperature is part of the state and is maybe overriden in set_state()
temperature = 300 * kelvin
self.set_torsion_metaDbias(temperature)
self.set_atmforce()
#add barostat
pressure=1*bar
self.set_barostat(temperature,pressure,0)
#hack to store... | Python | 1 |
self.log_directory = directory
self.dir_label.config(text=f"Selected Directory: {self.log_directory}")
self.load_button.config(state=tk.DISABLED) # Disables button after loading
else:
messagebox.showwarning("No Directory", "No directory has been selected. Please select a... | Python | 1 |
h self.handle.poll_lock() {
Async::Ready(mut l) => l.flush(),
Async::NotReady => Err(io::ErrorKind::WouldBlock.into()),
}
}
}
<filename>src/music_constants.rs<gh_stars>0
#![allow(dead_code)]
pub const IONIAN: [i32;7] = [UNISON, MAJ_2, MAJ_3, P_4, P_5, MAJ_6, MAJ_7];
pub const DORIAN:... | Rust | 0 |
##########################################################################
#
# Copyright (c) 2017, John Haddon. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of so... | Python | 1 |
self.emit_with_stack(&[0x48, 0x89, 0x85], &right);
self.call_builtin_alloc(STR_PROTOTYPE);
// mov r11,[rbp+{}]
self.emit_with_stack(&[0x4C, 0x8B, 0x9D], &right);
// mov r10,[rbp+{}]
self.emit_with_stack(&[0x4C, 0x8B, 0x95], &left);
self.free_stack(right);
self.fr... | Rust | 0 |
ered)
.and_then(|use_id| analysis_host.get_def(use_id))
.and_then(|def| analysis_host.id(&def.span))
.map(|def_id| {
uses.entry(lowered.file)
.or_insert_with(|| HashSet::new())
.insert(def_id)
... | Rust | 0 |
import logging
from django.core.management.base import BaseCommand
from biostar.forum import markdown
logger = logging.getLogger('engine')
test = """
<b>foo</b>
1 > 0
1 > 0
"""
test2 = """
<b> foo </b>
1 > 0
<script> bar() </script>
1 > 0
<b> bar </b>
<script> bar() </script>
"""
test3... | Python | 1 |
e".into()),
},
Named {
name: "last".into(),
value: Format::TypeName("Name".into()),
},
]),
},
);
assert_eq!(
registry.get("Person").unwrap(),
&ContainerFormat::Enum(variants)
);
}
mod... | Rust | 0 |
class Node(object):
def __init__(self, value, next=None):
self.value = value
self.next = next
def delete_node(head_p, delete_p):
"""
题目一:O(1)时间内删除链表节点
"""
if head_p is None or delete_p is None:
return
# 只有一个节点
if head_p == delete_p and delete_p.next is None:
... | Python | 1 |
import logging
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.constants import ParseMode
from telegram.ext import (ApplicationBuilder,
CommandHandler,
ContextTypes,
MessageHandler,
... | Python | 1 |
impl<K, V, S> MapExt<K, V, S> for HashMap<K, V, S>
where K: Eq + Hash + Clone,
S: BuildHasher + Default {
fn get_or(&mut self, key: K, or: V) -> &V {
if self.get(&key).is_some() { // TODO contains_key is currently unavailable on redox.
self.get(&key).unwrap()
} else {
... | Rust | 0 |
derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Encounter {
// No ongoing encounter.
None,
// Ongoing unknown encounter.
Unknown,
// Ongoing encounter with known boss.
Boss(Boss),
}
/// Current column sorted by.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Sorting {
... | Rust | 0 |
erSize>, AeadError>;
/// Decrypt a buffer in place given the private key, and given the footer
/// also
///
/// Meant to mirror aead::decrypt_in_place_detached
///
/// NOTE: Meant to run in constant-time even if the mac-check fails.
///
/// Returns
/// `Ok(true)` if decryption succe... | Rust | 0 |
rs(df):
df = dropna(df)
# 볼린저 밴드
indicator_bb = ta.volatility.BollingerBands(close=df['close'], window=20, window_dev=2)
df['bb_bbm'] = indicator_bb.bollinger_mavg()
df['bb_bbh'] = indicator_bb.bollinger_hband()
df['bb_bbl'] = indicator_bb.bollinger_lband()
# RSI
df['rsi'] = ta.mome... | Python | 1 |
Track) # processTrackWithRep(theTrack,rep,True)
fitStatus = theTrack.getFitStatus()
if self.Debug: print("Fit result: converged chi2 Ndf",fitStatus.isFitConverged(),fitStatus.getChi2(),fitStatus.getNdf())
if not fitStatus.isFitConverged():
theTrack.Delete()
return -1
if self.Debug:
... | Python | 1 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | Python | 1 |
tings::ColoredHelp)
.arg(
Arg::with_name("verbose")
.short("v")
.long("verbose")
.help("Show each time tick on stdout"),
)
.arg(
Arg::with_name("starttime")
.required(true)
.value_name("STARTT... | Rust | 0 |
that something went wrong.
decl_error! {
pub enum Error for Module<T: Trait> {
/// Tweet not found.
TweetNotFound,
/// Text too long.
TweetTooLong,
/// Run out of tweet id.
NoAvailableTweetId,
}
}
pub const MAX_TEXT_LEN: u64 = 140;
decl_module! {
pub struct Module<T: Trait> for enum Call where origin: ... | Rust | 0 |
_dict = {} # type: Dict[str, Union[str, List[str]]]
with PreserveAptCfg(_get_apt_config) as apt_cfg:
for cfg_name in cfg_names:
cfg_value = apt_cfg.get(cfg_name)
if not str(cfg_value):
cfg_value = apt_cfg.value_list(cfg_name) or None
apt_cfg_dict[cfg_n... | Python | 1 |
"""
Classifies: CHEBI:17984 acyl-CoA
"""
from rdkit import Chem
from rdkit.Chem import AllChem
def is_acyl_CoA(smiles: str):
"""
Determines if a molecule is an acyl-CoA based on its SMILES string.
An acyl-CoA is a thioester formed from the condensation of a carboxylic acid and coenzyme A.
Args:
... | Python | 1 |
ch value:
case str():
print(f"Got a string: {value}")
case int():
print(f"Got an integer: {value}")
case list() | tuple():
print(f"Got a sequence: {value}")
case User(name=name, age=age):
print(f"Got a user: {name}, {age} years old")
... | Python | 1 |
]
/// },
/// {"id": "Schedule",
/// "name": "Schedule",
/// "fields":
/// [
/// {"key": "startDateTime",
/// "stringValue": "2012-09-25T17:00:00"},
/// {"key": "type",
/// "stringValue": "Schedule"},
/// {"key": "period",
/// "stringValue": "1 hour"},
/// {"key": "endDateTime",
/// "stringValue": "2012-09-25T18:00:00"... | Rust | 0 |
sync::mpsc::TryRecvError;
use std::thread;
use std::thread::JoinHandle;
use aoc_2019_2::{read_memory_from_file, ComputationResult, IntComputer};
use permutohedron::LexicalPermutation;
use aoc_2019_7::{ChannelReader, ChannelWriter};
fn main() {
solve_day_7_2()
}
fn solve_day_7_1() {
let result = aoc_2019_7::... | Rust | 0 |
str> {
Transport::get_addr_from_arg(host_addr)
.and_then(|host_addr|
Transport::get_addr_from_arg(to_addr)
.and_then(|to_addr|
UdpSocket::bind(host_addr)
.and_then(|sock| Ok(Transport { socket: sock, to_addr: to_addr }))
... | Rust | 0 |
1 - self._childbar_offset
cols.append((1, bar))
cols.append((rspace_width, void))
else:
cols.append((self._indent, void))
# add the original widget for this line
cols.appe... | Python | 1 |
s = ""'Start with empty string' ' and lint docstring safely'
s = "Do not"' start with empty string' ' and lint docstring safely'
| Python | 1 |
#[serde(alias = "BRL")]
BrazilianReal,
#[serde(alias = "BSD")]
BahamianDollar,
#[serde(alias = "BTN")]
BhutaneseNgultrum,
#[serde(alias = "BWP")]
BotswanaPula,
#[serde(alias = "BYN")]
BelarusianRuble,
#[serde(alias = "BZD")]
BelizeDollar,
#[serde(alias = "CAD")]
Ca... | Rust | 0 |
ptr: Some(test_store::BLOCKS[1].clone()),
handler: None,
deterministic: true,
};
// Fails the base subgraph at block 1 (and advances the pointer).
test_store::transact_errors(
&store,
&deployment,
test_store::BLOCKS[1].clone(),
... | Rust | 0 |
}
<filename>src/adc14/adc14hi1.rs
#[doc = "Reader of register ADC14HI1"]
pub type R = crate::R<u32, super::ADC14HI1>;
#[doc = "Writer for register ADC14HI1"]
pub type W = crate::W<u32, super::ADC14HI1>;
#[doc = "Register ADC14HI1 `reset()`'s with value 0x3fff"]
impl crate::ResetValue for super::ADC14HI1 {
type Typ... | Rust | 0 |
"""Tests for the Abode cover device."""
from unittest.mock import patch
from homeassistant.components.abode import ATTR_DEVICE_ID
from homeassistant.components.cover import DOMAIN as COVER_DOMAIN
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_FRIENDLY_NAME,
SERVICE_CLOSE_COVER,
SERVICE_OPEN_COV... | Python | 1 |
rn ious
def calculate_dice(confusion_matrix):
dices = []
for index in range(confusion_matrix.shape[0]):
true_positives = confusion_matrix[index, index]
false_positives = confusion_matrix[:, index].sum() - true_positives
false_negatives = confusion_matrix[index, :].sum() - true_positive... | Python | 1 |
{x: self.x + other.x, y: self.y + other.y, z: self.z + other.z}
}
}
impl Sub<Point> for Point {
type Output = Point;
fn sub(self, other: Point) -> Point {
Point {x: self.x - other.x, y: self.y - other.y, z: self.z - other.z}
}
}
impl Mul<f64> for Point {
type Output = Point;
fn mul(self, other: f6... | Rust | 0 |
powers = (0u32..10).map(|n| n.pow(4)).collect::<Vec<u32>>();
assert!(is_curious(&fourth_powers, 1634));
assert!(is_curious(&fourth_powers, 8208));
assert!(is_curious(&fourth_powers, 9474));
}
<filename>examples/dw1000_only_rx.rs<gh_stars>0
//! Waits to receive data and signals status via LEDs
#![no_main]
#... | Rust | 0 |
,
QueryMsg::Players { lottery_id } => to_binary(&query_all_players(deps, lottery_id)?)?,
_ => to_binary(&())?,
};
Ok(response)
}
fn query_config(deps: Deps) -> StdResult<ConfigResponse> {
let state = read_state(deps.storage)?;
Ok(state)
}
fn query_winner_rank(deps: Deps, lottery_id: u64... | Rust | 0 |
&local: &Local, context: PlaceContext, _: Location) {
// Because we do not call `super_place` above, `visit_local` is only called for locals that
// do not appear as part of a `Place` in the MIR. This handles cases like the implicit use
// of the return place in a `Return` terminator or the in... | Rust | 0 |
d(anno_gen_sc, 2),
round(knlg_exp_sc, 2),
round(case_gen_sc, 2),
round(code_gen_sc, 2),
round(code_cor_sc, 2),
round(final_score, 2)
])
# 使用 tabulate 生成 Markdown 表格
headers = [
"Model Name",
"Annotation Gen Score",
"Kno... | Python | 1 |
rame_depth(self, image_array, stream):
image_array = np.array(image_array)
# if float, convert to uint8
# TODO: this is a hack, need to fix it
if image_array.dtype == np.float32:
image_array = (image_array * 255).astype(np.uint8)
# if 3 dim, convert to 2 dim
i... | Python | 1 |
Tests...")
print("=" * 60)
try:
# Setup
test_instance.setup_method()
# Run tests
await test_instance.test_secure_python_execution()
await test_instance.test_security_violation_detection()
await test_instance.test_resource_limits()
await test... | Python | 1 |
"SOHOO",
"SPDW",
"SPEM",
"SPIB",
"SPLB",
"SPLG",
"SPLPpT",
"SPSB",
"SPSM",
"SPTL",
"SPTM",
"SPTS",
"BERN",
"BRGL",
"CORpA.CL",
"DEMS",
"GOP",
"IBO",
"KIOrw",
"RIVr",
"TAXR",
"AIEQ",
"CATC",
"LOGO",
"MMIN",
"MMIT",
"OCSI",
"OCSL",
"OCSLL",
"OSLE",
"GGZrw",
... | Rust | 0 |
/ one; keep in mind that changing the Resource will destabilize the simulation
if physics.mechanical_world.timestep() != time_step.0 {
warn!(
"TimeStep and mechanical_world.timestep() differ, changing worlds timestep from {} to: {:?}",
physics.mechanic... | Rust | 0 |
),
),
(
"snippet",
modelcluster.fields.ParentalKey(
to="utils.MenuSnippet", related_name="links"
),
),
],
options={
"abstract": ... | Python | 1 |
+ "&"
if(apiEnrichmentRequestDTO.method.method=="GET"):
#url = "http://" + ses["service"] + "." + environment + "." + st.secrets["api_domain"] + ses["method"] + "?" + queryString
url = apiEnrichmentRequestDTO.url + "?" + queryString
r = getApi(url)
... | Python | 1 |
"""Testing formula 5.33 of EN 1992-1-1:2004."""
import pytest
from blueprints.codes.eurocode.en_1992_1_1_2004.chapter_5_structural_analysis.formula_5_33 import Form5Dot33NominalSecondOrderMoment
from blueprints.validations import LessOrEqualToZeroError, NegativeValueError
class TestForm5Dot33NominalSecondOrderMomen... | Python | 1 |
import socket
import struct
import numpy as np
import sys
import os
import yaml
import pygame
import pytz
import datetime
import csv
script_dir = os.path.dirname(__file__)
parent_dir = os.path.dirname(script_dir)
sys.path.append(parent_dir)
from SoftActorCritic.SAC import SAC
train_log_Forward = rf"{script_... | Python | 1 |
await state.update_data(images="")
list_images.clear()
btns = ["Закончить формирование заявки"]
await message.answer(
"Приложите документ и нажмите на кнопку: Закончить формирование заявки",
reply_markup=reply.get_callback_btns(btns=btns),
)
await sta... | Python | 1 |
_state.plaintext_val, value.plaintext_val);
assert_eq!(got_state.version, value.version);
} else {
panic!("Failed to retrieve history node state");
}
}
async fn test_batch_get_items<Ns: Storage>(storage: &Ns) {
let mut rand_users: Vec<String> = vec![];
for _ in 0..20 {
rand_user... | Rust | 0 |
# 面试题13 机器人的运动范围
'''
判断位数之和有两种方法:
1.转化为字符串
2.通过循环,例如a=101,每次对a进行%10,循环判断条件是a!=0
https://www.cnblogs.com/54Leo/p/6133270.html
https://github.com/Jack-Lee-Hiter/AlgorithmsByPython/blob/master/Target%20Offer/%E6%9C%BA%E5%99%A8%E4%BA%BA%E7%9A%84%E8%BF%90%E5%8A%A8%E8%8C%83%E5%9B%B4.py
和面试题12一样使用回溯法,进行迭代,套路很相... | Python | 1 |
engerType;
use crate::message::MessageHubUtil;
use crate::service::test::Payload;
use crate::service::MessageHub;
use crate::tests::scaffold::workload::Workload;
use assert_matches::assert_matches;
use rand::Rng;
#[test]
fn test_id_generation() {
let mut generator = IdGenerator... | Rust | 0 |
')
args = parser.parse_args()
if args.curriculum == 'baseline':
curriculum_steps = gen_curriculum_baseline(args.max_digits)
elif args.curriculum == 'naive':
curriculum_steps = gen_curriculum_naive(args.max_digits)
elif args.curriculum == 'mixed':
curriculum_steps = gen_curriculu... | Python | 1 |
import requests
import json
def prompt_propcess(text):
num = ['1st', '2nd', '3rd']
prompt_text = ''
c = 0
s = ''
for ch in text:
if ch == '|':
# prompt_text += 'The ' + (num[c] if c <= 2 else str(c) + 'th') + ' diagnosis is {' + s + '}. '
if c == 0:
... | Python | 1 |
#!/usr/bin/env python3
"""Download flags of countries (with error handling).
asyncio async/await version
"""
# tag::FLAGS2_ASYNCIO_TOP[]
import asyncio
from collections import Counter
from http import HTTPStatus
from pathlib import Path
import httpx
import tqdm # type: ignore
from flags2_common import main, Downl... | Python | 1 |
def test_full_loop_with_noise(self):
scheduler_class = self.scheduler_classes[0]
scheduler_config = self.get_scheduler_config()
scheduler = scheduler_class(**scheduler_config)
scheduler.set_timesteps(self.num_inference_steps)
model = self.dummy_model()
sample = self.dummy_sample_deter * schedule... | Python | 1 |
classes] and types as instances of those type classes. For
//! example, the trait [`InputConfig`] acts as a [type-level enum] of the
//! available input configurations, and the types [`Floating`], [`PullDown`],
//! [`PullUp`] and [`BusKeep`] are its type-level variants.
//!
//! When applied as a trait bound, a type-le... | Rust | 0 |
import numpy as np
def get_sample(batch_size=128, in_bits=10, out_bits=8, max_size=20, min_size=1):
# in order to be a generator, we start with an endless loop:
while True:
# generate samples with random length.
# there a two flags, one for the beginning of the sequence
# (only second... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.