text string | label_name string | labels int64 |
|---|---|---|
## Calcolo Area e Perimetro di figure geometriche
def AreaCerchio():
print("AREA CERCHIO:")
r= (float(input("inserisci il raggio: ")))
A= (r**2)*3.14
Area= (str(input("inserisci la formula dell'area: ")))
if Area == "(r**2)" or Area == "r**2*3.14":
print("La risposta è corretta.")
else:... | Python | 1 |
rminate();
let lm = LogMgr::new(conf.clone()).expect("Failed to create log mgr");
let starting_csn = lm.starting_csn();
assert_eq!(starting_csn, csn+6);
let latest_commit_csn = lm.latest_commit_csn();
assert_eq!(latest_commit_csn, csn+5);
let mut lr = lm.get_reader()... | Rust | 0 |
= failure_pb2.InjectRequest()
request.failure_unit = failure_unit.translate_to_rpc()
request.failure_type = failure_type.translate_to_rpc()
request.instance = instance
response = await self._stub.Inject(reques... | Python | 1 |
from __future__ import absolute_import
from __future__ import print_function
import pyverilog.vparser.ast as vast
from pyverilog.ast_code_generator.codegen import ASTCodeGenerator
def main():
# Define ports
a = vast.Ioport(vast.Input('A', width=vast.Width(vast.IntConst('7'), vast.IntConst('0'))))
x = vast.... | Python | 1 |
#!/usr/bin/env python3
"""
FastAPI Server Startup and Demo Launcher
This script starts the FastAPI server and runs the API demonstration.
"""
import asyncio
import subprocess
import sys
import time
import signal
import os
from pathlib import Path
def print_banner():
"""Print startup banner"""
banner = """
╔═... | Python | 1 |
for i in range(10):
print(i)
# prints 0 to 9
for i in range(10):
print(i+1)
# prints 0 to 10
for i in range(50, 100):
print(i)
# prints 50 to 99
for i in range(50, 100, 2):
print(i)
# prints even numbers from 50 to 98
for i in range(3):
chant = 'Bloody Mary'
print(chant)
# prints... | Python | 1 |
ize].copy_from_slice(&slice[self.pos as usize..(self.pos + amt) as usize]);
self.pos += amt;
Ok(amt as usize)
}
}
impl<T: AsRef<[u8]>> Seek for Cursor<T> {
fn seek(&mut self, pos: SeekFrom) -> Result<u64> {
match pos {
SeekFrom::Current(x) => {
if (self.pos a... | Rust | 0 |
param_replacement(
&self,
(_, expr): &(ast::ParamKind, ast::Expr),
) -> Option<&ReplVar> {
match &expr.2 {
ast::Expr_::Lvar(inner) => self.lookup_replacement(&inner.1.1).and_then(|repl| {
if repl.op == VarOp::Args {
... | Rust | 0 |
LError),
CannotSaveEmptyDocument,
CannotDeleteDocument(ffi::CBLError),
CannotCreateNewQuery(ffi::CBLError),
CannotFillDocumentFromJson(ffi::CBLError),
CannotCreateNewReplicator(ffi::CBLError),
CannotExecuteQuery(ffi::CBLError),
CannotCreateIndex(ffi::CBLError),
ErrorInBatch(ffi::CBLError... | Rust | 0 |
self.select_skill.extend(select_skill)
return
elif event.key == pg.K_UP:
sel_tree = (sel_tree + sl - 1) % sl
elif event.key == pg.K_DOWN:
sel_tree = (sel_tree + 1) % sl
elif even... | Python | 1 |
alt((
value(AuthMechanism::Login, tag_no_case("LOGIN")),
value(AuthMechanism::Plain, tag_no_case("PLAIN")),
value(AuthMechanism::CramMD5, tag_no_case("CRAM-MD5")),
value(AuthMechanism::CramSHA1, tag_no_case("CRAM-SHA1")),
value(AuthMechanism::DigestMD5, tag_no_case("DIGEST-M... | Rust | 0 |
x824C;
#[allow(dead_code, non_upper_case_globals)] pub const DEBUG_TYPE_MARKER: types::GLenum = 0x8268;
#[allow(dead_code, non_upper_case_globals)] pub const DEBUG_TYPE_MARKER_KHR: types::GLenum = 0x8268;
#[allow(dead_code, non_upper_case_globals)] pub const DEBUG_TYPE_OTHER: types::GLenum = 0x8251;
#[allow(dead_code, ... | Rust | 0 |
# Adapted for numpy/ma/cdms2 by convertcdms.py
import cdms2, MV2
# Let's start by creating data by hand, but you could achieve this via a script,
# reading data from a file, etc..
my_data=[
[1,2,3],
[4,5,6],
[7,8,9],
[10,11,12],
]
# It is really easy to convert this 2 dimensional list int... | Python | 1 |
"""Tests for schedule generation utilities."""
import re
from unittest.mock import patch
from cli_git.utils.schedule import describe_schedule, generate_random_biweekly_schedule
class TestGenerateRandomBiweeklySchedule:
"""Test random bi-weekly schedule generation."""
def test_generates_valid_cron_expressio... | Python | 1 |
ding
} else {
this.fut.poll_cancel(cx)
}
}
}
impl<F: CompletionFuture + Future> Future for Yield<F> {
type Output = <F as CompletionFuture>::Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
unsafe { C... | Rust | 0 |
s sent by the client or browser as the origin of the request. It is set through an `Origin` header. * **Access-Control-Allow-Methods**: This specifies the allowed options for requests from that domain. This will generally be all available methods. * **Access-Control-Expose-Headers**: This will contain the headers t... | Python | 1 |
/// assuming there are no constant-evaluation errors there.
#[inline]
pub fn discriminant_for_variant(
&self,
tcx: TyCtxt<'tcx>,
variant_index: VariantIdx,
) -> Discr<'tcx> {
assert!(self.is_enum());
let (val, offset) = self.discriminant_def_for_variant(variant_ind... | Rust | 0 |
import numpy as np
import pandas as pd
from babel.numbers import format_currency
def remove_decimal(S):
S = str(S)
S = S[:-3]
return S
def convert_df(df, cols):
# breakup the dataframe into cols and others
df1 = df[cols].copy(deep=True)
cols_other = df.columns.difference(cols)
df2 = df[col... | Python | 1 |
const FORMAT_CPP_MAP : &str = "cpp_map";
struct ZoneArea<'a>(&'a str);
const ZONE_AREAS : [ZoneArea; 12] = [
ZoneArea("africa"),
ZoneArea("antarctica"),
ZoneArea("asia"),
ZoneArea("australasia"),
ZoneArea("backward"), // These data for backward compatible
ZoneArea("backzone"), // The Zones ... | Rust | 0 |
cessed)
print("Mean IoU by Fold:")
print(mean_iou_by_fold)
print("Std IoU by Fold:")
print(std_iou_by_fold)
# Save mean and std IoU per fold to Excel in the same file
excel_dir = RESULTS_DIR / 'EXCEL'
excel_dir.mkdir(parents=True, exist_ok=True)
with pd.ExcelWriter(excel_dir / f'{experi... | Python | 1 |
*element;
if previous.data_ptr.add(previous.data_size) == current.data_ptr {
previous.data_size += current.data_size;
previous.next = next_free;
current.data_ptr = null_mut();
current.data_size = 0;
current.next = control.unused_blocks;
c... | Rust | 0 |
ct['map_geoms'] # {0: List[ped_crossing: LineString], 1: ...}
semantic_mask = self.get_semantic_mask(map_geoms)
input_dict['semantic_mask'] = semantic_mask # (num_class, canvas_size[1], canvas_size[0])
return input_dict
def __repr__(self):
repr_str = self.__class__.__name__
... | Python | 1 |
en(error_messages)}] ERRORS were generated when parsing the Atomic Red Team Repo.\n"
"Please raise an issue so that they can be fixed at https://github.com/redcanaryco/atomic-red-team/issues.\n"
"Note that this is only a warning and contentctl will ignore Atomics contained in these files... | Python | 1 |
ree::KdtreePointTrait;
//!
//!
//! // This can by any object or point with its associated metadata
//! #[derive(Copy, Clone, PartialEq)]
//! pub struct Point3WithId {
//! dims: [f64; 3],
//! pub id: i32,
//! }
//!
//!
//! impl KdtreePointTrait for Point3WithId {
//! #[inline]
//! fn dims(&self) -> &[f64... | Rust | 0 |
context: Context,
graphics: &mut G2d,
rect: &mut [u32; 4],
glyps: &mut Glyphs) {
let margin = 10;
let text_height = 20;
let block_height = 30;
let text_padding = 7;
let color = if self.selected {
[0.0, 1... | Rust | 0 |
new(7716, "Paraguay", "<NAME>", -25.5333333, -54.6166649, 201.0),
City::new(7717, "Paraguay", "<NAME>", -25.4166667, -56.4500008, 171.0),
City::new(7718, "Paraguay", "Concepcion", -23.4063889, -57.4344444, 44.0),
City::new(7719, "Paraguay", "Villarrica", -25.7500000, -56.4333344, 126.0),
City::new(7720, "Paraguay",... | Rust | 0 |
#!/usr/bin/env python3
"""
Route module for the API
"""
from os import getenv
from flask import Flask, jsonify, abort, request
from flask_cors import (CORS, cross_origin)
import os
from api.v1.auth.session_db_auth import SessionDBAuth
from api.v1.auth.session_exp_auth import SessionExpAuth
from api.v1.views import app... | Python | 1 |
polynomial(z - 0.5, ERF_IMPL_BN) / polynomial(z - 0.5, ERF_IMPL_BD),
0.3440242112,
)
} else if z < 1.25 {
(
polynomial(z - 0.75, ERF_IMPL_CN) / polynomial(z - 0.75, ERF_IMPL_CD),
0.419990927,
)
} else if z < 2.25 {
... | Rust | 0 |
=[text_input, language_input],
outputs=audio_output,
fn=tts_engine.generate_speech,
cache_examples=False,
)
generate_btn.click(
fn=tts_engine.generate_speech,
inputs=[text_input, language_input],
outputs=audio_output,
)
... | Python | 1 |
multiplier *= 0
return multiplier
def apply_damage(self, attacker, defender, attack):
"""
Applique les dégâts d'une attaque à un défenseur en tenant compte de l'efficacité du type, des statistiques et des effets spéciaux.
"""
if attack.use(): #... | Python | 1 |
StandalonePdfMac(bytes_reserved=2 * tok_size)
w.set_custom_trailer_entry(pdf_name('/AuthCode'), mac_dict)
prepared_br_digest: PreparedByteRangeDigest
cms_writer = mac_dict.fill(
w,
# here we intentionally take the handlers MD (more convenient
# to override in tests)
md_algor... | Python | 1 |
ate.attachments.append({
"name": uploaded_file.name,
"bytes": file_bytes,
"type": uploaded_file.type
})
# Display uploaded files
with st.sidebar:
st.markdown("**📁 ATTACHED FILES:**")
for file in st.session_stat... | Python | 1 |
(self)?;
let object = self.context.avm1.pop().coerce_to_object(self);
object.set(&name, value, self)?;
Ok(FrameControl::Continue)
}
fn action_set_property(&mut self) -> Result<FrameControl<'gc>, Error<'gc>> {
let value = self.context.avm1.pop();
let prop_index = self.c... | Rust | 0 |
#HERENCIA
#Superclase
class Animal:
def __init__(self, name:str):
self.name = name
def sound(self):
pass
#Subclases
class Dog(Animal):
def sound(self):
print("Guau!")
class Cat(Animal):
def sound(self):
print("Miau!")
def print_sound(animal:Animal):
an... | Python | 1 |
'
saved_model_path="./a2c_Breakout_30M_lr_5e-4_gamma_90.zip"
unzip_file_path="./a2c_Breakout_30M_lr_5e-4_gamma_90_unzipped"
'''
Environment variables
'''
# n_stack is the number of frames stacked together to form the input to the
# model.
n_stack=4
# n_envs is the number of environments that will be run in parallel
n_... | Python | 1 |
}
};
let ext_node_hash = Blake2bHash::new(&ext_node.to_bytes().unwrap());
let node_1: Trie<Bytes, Bytes> = {
let mut pointer_block = PointerBlock::new();
pointer_block[0] = Some(Pointer::LeafPointer(leaf_1_hash));
pointer_block[1] = Some(Pointer::NodePointer(ext_node_hash))... | Rust | 0 |
"""
集中度風險管理模組
此模組實現了投資組合的集中度風險控制。
"""
from typing import Dict
from src.core.logger import logger
class ConcentrationRiskManager:
"""
集中度風險管理器
管理投資組合的集中度風險。
"""
def __init__(self, max_position_percent: float = 0.2, max_positions: int = 20):
"""
初始化集中度風險管理器
Args:
... | Python | 1 |
"?",
"@", "A", "B", "C", "D", "E", "F", "G",
"H", "I", "J", "K", "L", "M", "N", "O",
"P", "Q", "R", "S", "T", "U", "V", "W",
"X", "Y", "Z", "[", "\\", "]", "^", "_",
"`", "a", "b", "... | Rust | 0 |
ndowTextW, IsWindow,
};
use std::sync::atomic::{AtomicIsize, Ordering};
fn create_capture_item_for_window(
interop: &IGraphicsCaptureItemInterop,
window_handle: HWND,
) -> Result<GraphicsCaptureItem> {
println!(
"creating capture item for {} IsWindow:{}",
window_handle,
unsafe { Is... | Rust | 0 |
self.toggle(EP_TX_RX_MASK, EP_RX_VALID | EP_TX_STALL, 0)
}
fn toggle_tx_out(&self) {
self.toggle(EP_TX_MASK, EP_TX_VALID, EP_STATUS_OUT)
}
fn toggle_out(&self) {
self.toggle(EP_TX_RX_MASK, EP_TX_RX_VALID, EP_STATUS_OUT)
}
fn toggle_0(&self) {
self.toggle(EP_TX... | Rust | 0 |
if c == '\n' || c == '\r' {
state = State::Separator;
word_start += 1;
}
else {
word_start += 1;
}
}
}
}
// Account for EOF
if let State::Word = state {
let... | Rust | 0 |
"""Factories for API management."""
import factory
from factory.django import DjangoModelFactory
from factory.fuzzy import FuzzyInteger, FuzzyText
from oauth2_provider.models import get_application_model
from openedx.core.djangoapps.site_configuration.tests.factories import SiteFactory
from openedx.core.djangoapps.a... | Python | 1 |
from django import forms
from django.contrib.admin.widgets import FilteredSelectMultiple
from django.contrib.postgres.fields import ArrayField
from django.db import models
from django.utils.timezone import now
class ChoiceArrayField(ArrayField):
def formfield(self, **kwargs):
defaults = {
"for... | Python | 1 |
ceDepthClipControlFeaturesEXT {
#[inline]
pub fn into_builder<'a>(self) -> PhysicalDeviceDepthClipControlFeaturesEXTBuilder<'a> {
PhysicalDeviceDepthClipControlFeaturesEXTBuilder(self, std::marker::PhantomData)
}
}
#[derive(Copy, Clone)]
#[doc = "[Vulkan Manual Page](https://www.khronos.org/registry... | Rust | 0 |
# Domine Apache Airflow. https://www.eia.ai/
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from datetime import datetime
dag = DAG('pool', description="pool",
schedule_interval=None,start_date=datetime(2023,3,5),
catchup=False)
task1 = BashOperator(task_id="tsk1",b... | Python | 1 |
import torch
import models.archs.SRResNet_arch as SRResNet_arch
import models.archs.discriminator_vgg_arch as SRGAN_arch
import models.archs.RRDBNet_arch as RRDBNet_arch
# import models.archs.EDVR_arch as EDVR_arch
import models.archs.AdaFMNet_arch as AdaFMNet_arch
import models.archs.CResMDNet_arch as CResMDNet_arch
... | Python | 1 |
"""LLM Types.
Maintain this file for backwards compat.
"""
from llama_index.legacy.core.llms.types import (
ChatMessage,
ChatResponse,
ChatResponseAsyncGen,
ChatResponseGen,
CompletionResponse,
CompletionResponseAsyncGen,
CompletionResponseGen,
LLMMetadata,
MessageRole,
)
__all__... | Python | 1 |
}
fn as_any(&self) -> &dyn (::std::any::Any) {
self as &dyn (::std::any::Any)
}
fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) {
self as &mut dyn (::std::any::Any)
}
fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> {
self
}
... | Rust | 0 |
import datetime
from flask import Flask
import flask_admin as admin
from flask_mongoengine import MongoEngine
from flask_admin.form import rules
from flask_admin.contrib.mongoengine import ModelView
# Create application
app = Flask(__name__)
# Create dummy secrey key so we can use sessions
app.config['SECRET_KEY'] ... | Python | 1 |
on = tokenize_kto
else:
raise ValueError("Unknow dataset type. Please choose one from ['sft', 'prompt', 'preference']")
for index, dataset in enumerate(list_dataset):
assert isinstance(dataset, dataset_dict.Dataset)
if len(dataset) == 0:
# Hack: Skip empty dataset. If datase... | Python | 1 |
fn from(function_name: FunctionName) -> Self {
function_name.0
}
}
impl From<String> for FunctionName {
fn from(s: String) -> Self {
Self(s)
}
}
impl From<&str> for FunctionName {
fn from(s: &str) -> Self {
Self::from(s.to_string())
}
}
impl AsRef<str> for FunctionName {
... | Rust | 0 |
t.append("*." + rootDoamin)
return domain_list
# 构造域名列表
def format_domains(self, domains):
if type(domains) != list:
return []
# 是否自动构造通配符
if self._auto_wildcard:
domains = self.auto_wildcard(domains)
wildcard = []
tmp_domains = []
... | Python | 1 |
saturating_add(T::DbWeight::get().writes(9 as Weight))
}
// Storage: BondedFinance BondOffers (r:1 w:1)
// Storage: System Account (r:1 w:1)
fn cancel() -> Weight {
(73_363_000 as Weight)
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
}
use ... | Rust | 0 |
for i in range(2,20+1):
prime = True
for j in range(2,i):
if (i%j == 0):
prime = False
break
if(prime):
print(f'{i} is a prime number') | Python | 1 |
ize,
) -> Result<(), ErrorKind> {
let mut res = Err(ErrorKind::GenericError);
_ykpiv_begin_transaction(state)?;
if _ykpiv_ensure_application_selected(state).is_ok() {
res = _ykpiv_change_pin(state, 0, current_pin, current_pin_len, new_pin, new_pin_len);
if res.is_ok() && !new_pin.is_null(... | Rust | 0 |
from PyObjCTools.TestSupport import *
from Foundation import *
try:
unicode
except NameError:
unicode = str
class TestNSNetServicesHelper (NSObject):
def netServiceBrowser_didFindDomain_moreComing_(self, a, b, c): pass
def netServiceBrowser_didFindService_moreComing_(self, a, b, c): pass
def netS... | Python | 1 |
).unwrap())).unwrap();
// If both versions are equal, we have no updates.
if current_versions == local_versions { APIResponseSchema::SuccessNoUpdate }
// In any other sisuation, there is an update (or I broke something).
else { APIRespons... | Rust | 0 |
# import torch
# flag = torch.cuda.is_available()
# if flag:
# print("CUDA可使用")
# else:
# print("CUDA不可用")
#
# ngpu= 1
# # Decide which device we want to run on
# device = torch.device("cuda:0" if (torch.cuda.is_available() and ngpu > 0) else "cpu")
# print("驱动为:",device)
# print("GPU型号: ",torch.cuda.get_device... | Python | 1 |
--save_normals",
default=False,
action="store_true",
help="load the estimated normal map and save as part of the PLY",
)
parser.add_argument(
"--stereo_folder",
type=str,
default="stereo",
help="folder in the dense workspace containing depth and normal ma... | Python | 1 |
mage(s).", message_type='finish')
return (torch.cat(ret_images, dim=0), torch.cat(ret_masks, dim=0))
# 在mask范围内随机生成指定数量的点
def poisson_disk_sampling(mask:Image, radius:float=32, num_points:int=16) -> list:
"""
使用泊松盘采样在掩码的白色区域内生成点,确保每个点之间至少为radius像素。
参数:
- mask: PIL.Image对象,将转换为numpy数组,二值化的掩码图像,... | Python | 1 |
riable-length integer.
dst.reserve(msg_size as usize + 5);
metrics::OUTGOING_TRAFFIC
.with_label_values(&[&PROTOCOL_LABEL])
.inc_by(msg_size as i64);
proto
.write_length_delimited_to_writer(&mut dst.writer())
.expect(
"there is no ... | Rust | 0 |
diction: {pred_path}")
continue
# Align with GT using least square
if "least_square" == alignment:
depth_pred, scale, shift = align_depth_least_square(
gt_arr=depth_raw,
pred_arr=depth_pred,
valid_mask_arr=valid_mask,
... | Python | 1 |
# Copyright (c) Facebook, Inc. and its affiliates.
from dataclasses import fields
from typing import Any, List
import torch
from detectron2.structures import Instances
def densepose_inference(densepose_predictor_output: Any, detections: List[Instances]):
"""
Splits DensePose predictor outputs into chunks, ea... | Python | 1 |
unwrap();
},
Err(_) => debug::info!("http fetch error from net"),
}
// let dot_price : u32 = Self::vec_to_u32(dot_price.data.priceUsd).unwrap();
debug::info!("dot_price = {:?}", dot_price_val);
// Here we are showcasing various techniques ... | Rust | 0 |
bold());
} else {
print!("{} ", value);
}
}
println!();
}
}
fn increase_energy(input: &mut Vec<i32>, x: usize, y: usize) -> &mut Vec<i32> {
if x >= 1 {
input[((x - 1) + y * 10)] += 1;
}
if x + 1 <= 9 {
input[((x + 1) + y * 10)] += ... | Rust | 0 |
former_paco(
patch_size=16, embed_dim=1024, depth=24, num_heads=16, mlp_ratio=4, qkv_bias=True,
norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)
return model
def vit_huge_patch14(**kwargs):
model = VisionTransformer_paco(
patch_size=14, embed_dim=1280, depth=32, num_heads=16, mlp_... | Python | 1 |
import argparse
import datetime
import os
import json
parser = argparse.ArgumentParser('JIZHI submit', add_help=False)
parser.add_argument('arch', default=None, type=str)
parser.add_argument('tag', default=None, type=str)
parser.add_argument('--config', default='/apdcephfs_cq2/share_1290939/xiaohanding/cnt/default_V10... | Python | 1 |
Box::new(|ctx| (self)(ctx).with(item))
}
}
impl<W: 'static, T, O, F> WidgetBuilderExtWithModified<T, O, F> for W
where
W: FnOnce(Ctx) -> Ctx,
T: Component,
O: UninitObserver,
for<'a> O::Observer: Observer<'a>,
F: for<'a> Fn(<O::Observer as Observ... | Rust | 0 |
value = float(value.split("^", 1)[1])
else:
value = int(value.split("^", 1)[1])
elif value.lower() == "true":
value = True
elif value.lower() == "false":
value = False
elif value.startswith(("{", "[", "("))... | Python | 1 |
help = '''
## 初次使用
欢迎进入网页控制台!
Admin账户可以通过左侧的选项进入不同的数据库直接修改,**首次登陆的Admin账户别忘了修改你的密码!**
普通账户可以通过左侧的选项进行绑定CK或者SK
未来还会加入更多功能!
## 丨我该如何获取Cookies?[#92](https://github.com/KimigaiiWuyi/GenshinUID/issues/92)
([@RemKeeper](https://github.com/RemKeeper))
```js
var cookie = document.cookie;
var Str_Num = cookie.indexOf('_MH... | Python | 1 |
# cook your dish here
x, y, z = map(int, input().split())
# Calculate points of the team
current_points = x + (y * 0.5)
# Remaining games
remaining_games = 4 - (x + y + z)
# Maximum possible points your team can obtain
max_possible_points = current_points + remaining_games
# Opponent's maximum points (assuming they... | Python | 1 |
});
while !(p.XOSC.status.read().stable().bit()) {}
}
// jump to usb
rp_hal::rom_data::reset_to_usb_boot(0, 0);
loop {}
}
<reponame>realSuffix/Rust-Full-Stack
use redis::{
Client as RedisClient,
Commands,
RedisResult,
ToRedisArgs, RedisWrite,
};
use crate::{
user:... | Rust | 0 |
{
let k = ki as f64;
1.0/(k*(k+x))
}).fold(0.0, |acc, elem| acc + elem)
}
fn main() {
let xlist = [0.0, 0.5, 1.0, f64::consts::SQRT_2, 10.0, 100.0, 300.0];
for &x in xlist.iter() {
println!("{:6.2} , {:16.12e}", x, psi(x));
}
}
fn main() {
match 10 {
<T as Trait>::... | Rust | 0 |
-> bool {
// From RFC1323:
// TCP determines if a data segment is "old" or "new" by testing
// whether its sequence number is within 2**31 bytes of the left edge
// of the window, and if it is not, discarding the data as "old". To
// insure that new data is never mistakenly consider... | Rust | 0 |
def plot_emergent_time(sequences):
fig = plt.figure(figsize=(18, 14))
ax = fig.add_subplot(111, projection='3d')
for i, seq in enumerate(sequences):
# Generate emergent time coordinates
t = generate_emergent_time(seq)
x, y, z = [], [], []
for layer, (val, time) ... | Python | 1 |
[0], t[1], t[2], t[3], t[4], t[5], t[6], t[7], t[8]);
let m00 = t11 * t22 - t12 * t21;
let m01 = t10 * t22 - t12 * t20;
let m02 = t10 * t21 - t11 * t20;
let det = t00 * m00 - t01 * m01 + t02 * m02;
if det.abs() < 1e-10 {
return None;
}
let m10 = t01 * t22 - t02 * t21;
let m11... | Rust | 0 |
from config import *
from file_processing import load_u_files, load_csv_files
from plotting import plot_velocity_data, plot_csv_data, plot_generated_wave, finalize_plot
import numpy as np
# Set figure size once here
plt.figure(figsize=(16, 9))
custom_colors = ["green", "#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#94... | Python | 1 |
l[[o, o + 3, o]]
- _27 * l[[o, o + 2, o]]
+ _270 * l[[o, o + 1, o]]
+ _270 * l[[o, o - 1, o]]
- _27 * l[[o, o - 2, o]]
+ _2 * l[[o, o - 3, o]]
... | Rust | 0 |
;
pub mod db_row;
pub mod db_schema;
pub mod db_table;
<reponame>MabezDev/rust-fscommon<gh_stars>0
#[cfg(not(feature = "std"))]
extern crate core;
#[cfg(not(feature = "std"))]
extern crate core_io;
#[macro_use]
extern crate log;
#[cfg(not(feature = "std"))]
use core_io as io;
#[cfg(feature = "std")]
use std as core... | Rust | 0 |
ay of parameters
max_its, # maximum number of iterations
lambda_sd, # hyper-parameter single-dish
lambda_r, # hyper-parameter regularization
positivity, # impose a positivity constaint
... | Python | 1 |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __author__ = 'liao gao xiang'
# 合并拼接字符串,如何你想将几个小的字符串合并为一个大的字符串
parts = ['Is', 'Chicago', 'Not', 'Chicago?']
print(''.join(parts), ' '.join(parts), ','.join(parts))
# 加号(+)操作符在作为一些复杂字符串格式化的替代方案的时候通常也工作的很好,比如:
a = 'Is Chicago'
b = 'Not Chicago'
print('{} {}'.format(a, b))
"... | Python | 1 |
"product_url": "https://amzn.in/d/07NHfVSW"
# },
# {
# "filename": "pr57.png",
# "product_name": "telephone",
# "product_url": "https://amzn.in/d/07NHfVSW"
# },
# {
# "filename": "pr58.png",
# "product_name": "Tissue_box",
# "product_url": "https://amzn.in/d/07NHfVSW"
# },
# {
# "filename": "pr5... | Python | 1 |
:NumberParseError(num, e) => {
format!("unable to parse the number \"{}\": {}", num, e)
}
config::ConfigError::NoOperationSpecified => format!("no operation was specified"),
config::ConfigError::UnknownServerKind(s) => format!("unknown server '{}', see --help", s),
config::Co... | Rust | 0 |
nfa.push_connections(a, b, 128..from[1]);
nfa.push_connections(b, e, ONWARDS);
// First and second exact
let a = nfa.push_state();
let b = nfa.push_state();
let e = nfa.push_state();
nfa.push_end(e);
nfa.push_connection(StateId::of(0),... | Rust | 0 |
ize) -> Option<Self::Item> {
assert!(n < 256);
let n = n as u16;
if self.start + n >= self.end {
return None
}
let start = self.start + n;
self.start += 1 + n;
Some(self.bits.get(start as u8))
}
fn size_hint(&self) -> (usize, Option<usize>) {
... | Rust | 0 |
ation to the leaderboard
LEADERBOARD
.lock()
.expect("leaderboard mutex already poisoned!")
.add(username, source_code, score);
Ok(Json(SimulationData { history: history, score: score }))
}
#[get("/leaderboard/<n>")]
fn get_leaderboard(n: usize) -> RequestResult<Vec<LeaderboardEntry>> ... | Rust | 0 |
import datetime
from unittest import mock
import autogpt_libs.auth.middleware
import fastapi
import fastapi.testclient
import prisma.enums
import prisma.models
import market.app
client = fastapi.testclient.TestClient(market.app.app)
async def override_auth_middleware(request: fastapi.Request):
return {"sub": "... | Python | 1 |
, PartialOrd, Clone, Debug)]
pub struct Total<T>(pub T);
impl<T> Total<T>
where
T: Clone,
{
pub fn unwrap(&self) -> T {
self.0.clone()
}
}
impl<T: PartialEq> Eq for Total<T> {}
impl<T: PartialOrd> Ord for Total<T> {
fn cmp(&self, other: &Total<T>) -> Ordering {
self.0.partial_cmp(&othe... | Rust | 0 |
min: Optional[float] = None
log_std_max: Optional[float] = None
tanh_squash_distribution: bool = True
@nn.compact
def __call__(self,
observations: jnp.ndarray,
temperature: float = 1.0,
training: bool = False) -> tfd.Distribution:
outputs = MLP... | Python | 1 |
-> ~str { "JMP xx".to_str() }
fn jmpi(&mut self) -> ~str { "JMP (xx)".to_str() }
// Procedure calls
// FIXME: Should disassemble the address!
fn jsr(&mut self) -> ~str { "JSR xx".to_str() }
fn rts(&mut self) -> ~str { "RTS".to_str() }
fn brk(... | Rust | 0 |
0.0);
let dist_to_focus:f64 = 10.0;
let aperture:f64 = 0.1;
let cam:Camera = Camera::new(lookfrom.clone(), lookat.clone(), vup.clone(), 20.0, AS_RATIO, aperture, dist_to_focus);
file.write(format!("P3\n{} {}\n255\n", I_WID, I_HIT).as_bytes());
let mut j:i32 = I_HIT - 1;
while j >= 0 {
... | Rust | 0 |
= &model.basefunctions[4];
assert_eq!(func.derivatives.len(), 1, "Incorrect number of derivatives");
assert_eq!(
(func.function)(&ts, ¶ms),
sinusoid_omega(&ts, omega2),
"Incorrect function value"
);
assert_eq!(
(func.derivatives.get(&3).unwrap())(&ts, ¶ms),
... | Rust | 0 |
= vec![];
/// rb1.serialize_into(&mut bytes).unwrap();
/// let rb2 = RoaringBitmap::deserialize_from_unvalidated(&bytes[..]).unwrap();
///
/// assert_eq!(rb1, rb2);
/// ```
pub fn deserialize_from_unvalidated<R: io::Read>(reader: R) -> io::Result<RoaringBitmap> {
RoaringBitmap::deserial... | Rust | 0 |
.66,0.68,3.15,1.76,4.24l1.42-1.42C8.45,15.1,8,14.11,8,13c0-2.21,1.79-4,4-4s4,1.79,4,4 c0,1.11-0.45,2.1-1.18,2.82l1.42,1.42C17.32,16.15,18,14.66,18,13C18,9.69,15.31,7,12,7z M12,3C6.48,3,2,7.48,2,13 c0,2.76,1.12,5.26,2.93,7.07l1.42-1.42C4.9,17.21,4,15.21,4,13c0-4.42,3.58-8,8-8c2.53,0,4.78,1.17,6.24,3h2.42 C18.93,5.01,15.... | Rust | 0 |
'lambda_A680')
def lambda_A680():
CameraMove(41850, 0, 30040, 3000)
ExitThread()
DispatchAsync(0x0101, 0x0001, lambda_A680)
@scena.Lambda('lambda_A698')
def lambda_A698():
ChrWalkTo(0x00FE, 40890, 0, 29970, 3000, 0x00)
ExitThread()
DispatchAsync(0x0024, 0x0001, l... | Python | 1 |
ert_eq!(get_name(&nfa,&dfa,make_state(4)),Some(&String::from("rule_2")));
}
// === The Benchmarks ===
#[bench]
fn bench_to_dfa_pattern_range(bencher:&mut Bencher) {
bencher.iter(|| Dfa::from(&nfa::tests::pattern_range().nfa))
}
#[bench]
fn bench_to_dfa_pattern_or(bencher:&mut Benc... | Rust | 0 |
import re
# Find all lower case characters alphabetically between "a" and "m":
txt = "The rain in Spain"
x = re.findall('[a-m]', txt)
print(x)
txt1 = "That will be 59 dollars"
# Find all digit characters:
x1 = re.findall('\d', txt1)
print(x1)
txt2 = "hello planet"
# Search for a sequence that starts with "he",... | Python | 1 |
# Python bytecode 2.7 (decompiled from Python 2.7)
# Embedded file name: scripts/common/auto_shoot_guns/auto_shoot_guns_common.py
PROJECTILE_INTERVAL = 0.2
BURST_ACTIVATION_MIN_TIMEOUT = 0.0
BURST_ACTIVATION_MAX_TIMEOUT = 1.0
BURST_DEACTIVATION_MIN_TIMEOUT = 0.0
BURST_DEACTIVATION_MAX_TIMEOUT = 1.0
BURST_VERIFYING_DELT... | Python | 1 |
# Russian localization
translations = {
"title": "Калькулятор Плюс",
"power_prompt": "ⁿ (введите степень)",
"settings_title": "Настройки",
"language_label": "Язык:",
"theme_label": "Тема:",
"save_btn": "Сохранить",
"error_division": "Деление на ноль!",
"error_input": "Некорректный ввод!"... | Python | 1 |
ibc_expected_response);
}
#[test]
fn test_send_sg721_fail_ibc_packet() {
let send_channel = CHANNEL_FROM_STARS_TO_OMNI;
let mut deps = setup(&[TEST_CHANNEL_0_DATA, TEST_CHANNEL_1_DATA]);
let contract_addr = "transfer-nft/abc/def";
let token_ids = vec!["1", "2", "3"];
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.