text string | label_name string | labels int64 |
|---|---|---|
y schema.
If strict, extra keys cause an exception during coercion.
@param schema: A dict mapping keys to schemas that the values of those
keys must match.
"""
def __init__(self, schema, optional=None, strict=True):
if optional is None:
optional = []
self.optional =... | Python | 1 |
riant::Data`.
fn set_data(&mut self, data: TreeData) {
self.node = NodeVariant::Data(data);
}
}
impl Node<TreeBranch, TreeLeaf, TreeData> for TreeNode {
#[inline]
fn new(node_variant: NodeVariant<TreeBranch, TreeLeaf, TreeData>) -> Self {
Self::new(node_variant)
}
#[inline]
... | Rust | 0 |
US = 44,
/// Rename2
// #[cfg(feature = "abi-7-23")]
FUSE_RENAME2 = 45,
/// Find next data or hole after the specified offset
// #[cfg(feature = "abi-7-24")]
FUSE_LSEEK = 46,
/// Copy a range of data from an opened file to another
// #[cfg(feature = "abi-7-28")]
FUSE_COPY_FILE_RANGE ... | Rust | 0 |
0)
ChrSetDirection(0x00FE, 270, 400)
Sleep(1000)
ChrSetDirection(0x00FE, 90, 400)
Sleep(1000)
ChrWalkTo(0x00FE, -3260, 250, 32560, 2000, 0x00)
ChrWalkTo(0x00FE, -1940, 0, 33880, 2000, 0x00)
ChrWalkTo(0x00FE, -1940, 0, 40100, 2000, 0x00)
ChrWalkTo(0x00FE, -3100, 0, 41680, 2000, 0x00)
... | Python | 1 |
def suma(*numeros):
resultado = 0
for numero in numeros:
resultado += numero
print(resultado)
suma(2, 5, 7)
suma(3, 8)
suma(2, 8, 7, 45, 32)
| Python | 1 |
"da", "no"
]
# Language setting
self.current_lang = tk.StringVar(value="zh-Hans")
# 加载配置
self.load_config()
if "language" in self.config:
self.current_lang.set(self.config["language"])
set_language(self.current_lang.get())
... | Python | 1 |
_RESR {
match value {
i => PWR_TRIM_USB_PM_RESR::_Reserved(i),
}
}
}
#[doc = "Possible values of the field `pwr_trim_usb_dm_res`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PWR_TRIM_USB_DM_RESR {
#[doc = r" Reserved"]
_Reserved(u8),
}
impl PWR_TRIM_USB_DM_RESR {
#[doc... | Rust | 0 |
"""Create devil fruit table
Revision ID: 4e51cc7af9aa
Revises: a21bad468b4c
Create Date: 2025-09-15 17:33:36.183389
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '4e51cc7af9aa'
down_revision: Union[str, Sequence[str], ... | Python | 1 |
import os
from dotenv import load_dotenv
load_dotenv()
class Telegram:
API_ID = int(os.environ.get('API_ID', '27938510'))
API_HASH = os.environ.get('048361ef8db1239fab7d895b8d3fb473')
BOT_TOKEN = os.environ.get('8361736643:AAETqhR8vrGOlapU3uJA_qz9tbmc8i4GmUY')
AUTH_USER_ID = int(os.environ.get('718364... | Python | 1 |
float()
pos_y = pos_y.to(tensor.device).float()
sin_inp_x = pos_x.unsqueeze(-1) @ self.inv_freq.unsqueeze(0)
sin_inp_y = pos_y.unsqueeze(-1) @ self.inv_freq.unsqueeze(0)
emb_x = torch.cat((sin_inp_x.sin(), sin_inp_x.cos()), dim=-1).unsqueeze(0)
emb_y = torch.cat... | Python | 1 |
::saturating_from_rational(2, 100), // 0.02
base_rate: Rate::saturating_from_rational(2, 100), // 2%
kink_rate: Rate::saturating_from_rational(10, 100), // 10%
full_rate: Rate::saturating_from_rational(32, 100), // 32%
kink_utilization: Ratio::from_percent(80), ... | Rust | 0 |
The data sent for a post request should follow next object.
Here is an example request data that updates the ``course_grading``
```json
{
"graders": [
{
"type": "Homework",
"min_count": 1,
"drop_coun... | Python | 1 |
from django.contrib import admin
from blog.models import Post
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display=['title','slug','author','publish','status']
list_filter=['status','created','publish','author']
search_fields=['title','body']
prepopulated_fields={'slug':('title',)}
... | Python | 1 |
intln!("");
}
fn print_factors_str(num_str: &str) {
let num = match u64::parse_bytes(num_str.as_bytes(), 10) {
Some(x) => x,
None => { crash!(1, "{} not a number", num_str); }
};
print_factors(num);
}
#[allow(dead_code)]
fn main() { uumain(os::args()); }
pub fn uumain(args: Vec<String>) ... | Rust | 0 |
hite', command=lambda: self.show('*')).place(x=270,
y=125)
Button(width=11, height=4, text='=', relief='flat', bg='white', command=self.solve).place(x=270, y=350)
Button(width=11, height=4, text... | Python | 1 |
user_agent
match field_map.get(44) {
Some(val) => {
if val != &"" {
log.add_field(
"http.request.user_agent",
SiemField::Text(Cow::Owned(val.to_string())),
);
}
}
None => {}
};
//xff
m... | Rust | 0 |
prod_quality_assurance_status=row["qa_status"],
prod_cate_no=cate_no,
prod_cost_price=row["cost_price"],
prod_retail_price=row["retail_price"],
prod_sell_zone=row["sell_zone"],
prod_outer_quantity=row["outer_quantity"... | Python | 1 |
import json
import logging
import os
from collections import defaultdict
from pathlib import Path
from huggingface_hub import HfApi
import diffusers
PATH_TO_REPO = Path(__file__).parent.parent.resolve()
ALWAYS_TEST_PIPELINE_MODULES = [
"controlnet",
"stable_diffusion",
"stable_diffusion_2",
"stable_... | Python | 1 |
0, predict_example, label_list,
max_seq_length, tokenizer)
prediction = predict_fn({
"input_ids": [feature.input_ids],
"input_mask": [feature.input_mask],
"segment_ids": [feature.segment_ids],
"label_ids": [feature.label_i... | Python | 1 |
#!/usr/bin/env python
# CiderPress: Machine-learning based density functional theory calculations
# Copyright (C) 2024 The President and Fellows of Harvard College
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free S... | Python | 1 |
from django import forms
class CSVUploadForm(forms.Form):
csv_file = forms.FileField()
| Python | 1 |
cli::get().get_matches();
let verbose = app_matches.is_present("verbose");
let cfg = try!(set_globals(verbose));
// On windows, put the process and its children in a job object
// so they are all killed together.
//
// We don't do this for self-uninstall and upgrade because
// it interfere... | Rust | 0 |
: &[u8]) -> Result<Vec<u8>, TinkError> {
let key = new_cha_cha20_poly1305_key();
let mut sk = Vec::new();
key.encode(&mut sk)
.map_err(|e| wrap_err("ChaCha20Poly1305KeyManager: failed to encode new key", e))?;
Ok(sk)
}
fn type_url(&self) -> &'static str {
CHA... | Rust | 0 |
import requests
import asyncio
url = "https://www.hngbwlxy.gov.cn/api/Page/CourseList"
headers = {
'Connection': 'close',
'sec-ch-ua': '";Not A Brand";v="99", "Chromium";v="88"',
'Accept': 'application/json, text/plain, */*',
'sec-ch-ua-mobile': '?0',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; W... | Python | 1 |
;
println!("Answer 1,2: {:?}", solve(&input));
}
<reponame>plorefice/aoc21-rs
use itertools::Itertools;
pub fn parse_input(input: &str) -> Vec<&str> {
input.lines().collect()
}
pub fn part_1(input: &[&str]) -> u32 {
input.iter().fold(0, |points, &line| match compile(line) {
Err(ch) => points + ill... | Rust | 0 |
ListArrayReader::<i64>::new(
Box::new(item_array_reader),
ArrowType::LargeList(Box::new(Field::new("item", ArrowType::Int32, true))),
ArrowType::Int32,
1,
1,
0,
1,
);
let next_batch = list_array_reader.next_batch(1024)... | Rust | 0 |
(inputs["sentence1"], inputs["sentence2"])]
elif target_lang == 'bg':
input = [prompt_prefix['bg'] + '\n' + "Изречение 1: " + s1 + "\nИзречение 2: " + s2 + '\nОтговор: \"' for s1, s2 in zip(inputs["sentence1"], inputs["sentence2"])]
elif target_lang == 'sv':
input = [prompt_prefix['sv'] + '\n' +... | Python | 1 |
oc[0]
st.sidebar.markdown(f"- Dernière humidité : `{latest['value']:.2f} %`")
if latest['value'] < threshold:
publish.single(topic, payload="ON", hostname=MQTT_BROKER_IP)
st.sidebar.success(f"✅ Arroseur `{sensor_id}` activé automatiquement")
... | Python | 1 |
'𒂭', '𝙋', '𐹢', 'ᮧ', '𝓏', '𝓋', '𔓇', '⺾', '𝒿', '🭖', '♮',
'👠', '𖩐', '䷲', '𒑓', '𝢞', '嬾', '\u{fe00}', '\u{1b6f}', 'ꓹ', 'ﻁ',
'𘥈', '拾', 'ꑣ', '𐨠', 'ݙ', 'Ი', '⡁', '⭊', '𝓩', '𘥪', '𘥄', 'ꏎ',
'ⓧ', '𑝀', '𖾜', '𐞕', '𒄱', 'ⓛ', '𒑄', 'ሗ', 'ꔀ', '🃱', 'ᚔ', 'ᚪ',
'ﯻ', '𘩩', '👇', '\u{11041}', 'ꠤ', '𛆦'... | Rust | 0 |
Span::call_site(),
"Only `u8`, `u16`, `u32`, `u64` and `u128` are supported for serde_repr."
)?,
};
if is_overflowed {
error(Span::call_site(), "serialize_repr cannot be smaller than bitset.")?;
}
}
Ok(())
... | Rust | 0 |
may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES... | Rust | 0 |
"""
ckwg +31
Copyright 2016 by Kitware, Inc.
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 source code must retain the above copyright notice,
this list of conditions and the ... | Python | 1 |
y_src_element_trampoline::<Self, F> as usize)), Box_::into_raw(f))
}
}
fn connect_property_target_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(self.as_ptr() as *mut _, b"notify::target\0".as_ptr() as... | Rust | 0 |
<HeroComponent />
<div class="section">
<CatalogueComponent />
</div>
</>
},
Ap... | Rust | 0 |
ion_ids = compute_position_id_with_mask(rm_attention_mask)
rm_inputs = {'input_ids': rm_input_ids, 'attention_mask': rm_attention_mask, 'position_ids': rm_position_ids}
return DataProto.from_dict(rm_inputs)
@register(dispatch_mode=Dispatch.DP_COMPUTE_PROTO)
def compute_rm_score(self, data: Da... | Python | 1 |
, LevelFilter},
fmt::format,
prelude::*,
registry::LookupSpan,
reload, Layer,
};
const ENV_LOG_LEVEL: &str = "LINKERD2_PROXY_LOG";
const ENV_LOG_FORMAT: &str = "LINKERD2_PROXY_LOG_FORMAT";
const ENV_ACCESS_LOG: &str = "LINKERD2_PROXY_ACCESS_LOG";
const DEFAULT_LOG_LEVEL: &str = "warn,linkerd=info";
co... | Rust | 0 |
rip())
elif lbw_item.strip() != '':
lbw = lbw_item
if a is None:
a = 1.0
if b is None:
b = 1.0
if lora is not None and lora not in added:
result.append((lora, a, b, lbw, lbw_a, lbw_b))
added.add... | Python | 1 |
from rest_framework import serializers
from .models import Route
from fare.serializers import FareSerializer
from stop.serializers import StopSerializer
class RouteSerializer(serializers.ModelSerializer):
fare = FareSerializer(many=True, read_only=True)
stops = StopSerializer(many=True, read_only=True)
... | Python | 1 |
x = "input"
print(len(x))
#substring
print("substring 1 =", x[2:])
print("substring 1 =", x[1:3])
print("substring 1 =", x[-3:])
print("substring 1 =", x[-3:-1])
#contains
print("contains", ("put" in x))
| Python | 1 |
import torch
def KMeans(x, device=torch.device, K=10, Niters=10, verbose=False):
N, D = x.shape # Number of samples, dimension of the ambient space
# K-means loop:
# - x is the point cloud,
# - cl is the vector of class labels
# - c is the cloud of cluster centroids
# start = time.time()
... | Python | 1 |
category
and category.parent_id != 0
and category.parent_id not in category_ids
):
category_ids.add(category.parent_id)
blog_in.category_ids = list(category_ids)
new_blog = await blog_controller.create(obj_in=blog_in.create_dict())
if not new_blog:
... | Python | 1 |
0,
precision,
scale,
nobits: NoBits::N64,
}),
SqlType::Ipv4 => Value::Ipv4([0_u8; 4]),
SqlType::Ipv6 => Value::Ipv6([0_u8; 16]),
SqlType::Uuid => Value::Uuid([0_u8; 16]),
SqlType::Enum8(values) => Value::Enum8(v... | Rust | 0 |
/// An error indicating that a provided name is invalid.
#[derive(Debug, PartialEq)]
pub struct KeyNameInvalidError{
name: String,
}
impl KeyNameInvalidError {
pub fn new(name: String) -> Self {
KeyNameInvalidError { name }
}
/// Returns the name that is invalid.
pub fn name(&self) -> &str ... | Rust | 0 |
=> write!(f, "[{}:{}]", self.begin, end_v),
None => write!(f, "[{}:]", self.begin)
}
}
}
pub fn slice_input(slice: Slice, input: &mut dyn BufRead, output: &mut dyn Write) -> io::Result<()> {
enum PrintMode { Buf, Overflow };
let mut mode = PrintMode::Overflow;
let mut buf_size: us... | Rust | 0 |
f} segundos".center(columns))
print(f" - Tentativas: {data['attempts']}".center(columns))
print(f" - Respostas corretas: {data['correct_answers']}".center(columns))
input("\nPressione Enter para voltar ao menu.")
else:
print("\nNenhum... | Python | 1 |
.starts_with("attempt to access a file outside of lib_dir"));
assert!(compiler
.compile_in_game_file(&in_game_path, None)
.unwrap_err()
.to_string()
.starts_with("attempt to access a file outside of lib_dir"));
}
}
}
// Copyright (... | Rust | 0 |
ullscreen.set_position_x(1.0 - 0.32);
btn_fullscreen.set_position_y(1.1 /*50.0 / 480.0*/);
btn_fullscreen.set_event_on_released(self.events.clone(), LandingPageEvent::Fullscreen);
let btn_fullscreen_text = UiText::new();
btn_fullscreen_text.set_text(String::from("Fullscreen"));
btn_fullscreen_text.s... | Rust | 0 |
{
_unused: [u8; 0],
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct OCISvcCtx {
_unused: [u8; 0],
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct OCIStmt {
_unused: [u8; 0],
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct OCIBind {
_unused: [u8; 0],
}
#[repr(C)]
#[derive(Debug, Copy,... | Rust | 0 |
2., 2.])
.at(1),
Err(ModelError::IncorrectParameterCount { .. })
),
"Derivative for invalid function must fail with correct error"
);
// check an out of bounds index for the derivative
assert!(
matches!(
model_with_bad_function.eval_deriv(&tv... | Rust | 0 |
programming_dictionary={
"Bug":"Its a bug dude",
"Function":"Its a function buddy",
}
# here bug is a key , inside it the value is present i.e key value pair
#here each key can have only 1 value, if we have multiple values then we need to use lists.
#print(programming_dictionary["Function"])
#adding new items ... | Python | 1 |
// The task was scheduled, drain it explicitly.
task.shutdown();
}
None => {
list.shutdown();
}
};
match s1.recv() {
Some(task) => task.shutdown(),
None => {}
}
assert_err!(th.... | Rust | 0 |
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.ensemble import RandomForestClassifier #引入随机森林分类模块
X ,Y= [],[] #读取数据
fr = open("D:\\knn.txt")
for line in fr.readlines():
line = line.strip().split()
X.append([int(line[0]),int(line[1])])
Y.append(int(line[-1])) #... | Python | 1 |
'7.4.1': False
},
'choices': [
'disable',
'enable'
],
'type': 'str'
},
'uuid': {
'required': False,
'revision': {
... | Python | 1 |
from unittest.mock import patch
import pytest
from pydantic import Field
from enrichmcp import EnrichMCP, EnrichModel, Relationship
@pytest.mark.asyncio
async def test_tool_description_prefixes() -> None:
app = EnrichMCP("My API", instructions="desc")
with patch.object(app.mcp, "tool", wraps=app.mcp.tool) ... | Python | 1 |
_angle],
dim=-1).reshape(num_prior, num_gt, 2, 2)
offset = points - ctr
offset = torch.matmul(rot_matrix, offset[..., None])
offset = offset.squeeze(-1)
w, h = wh[..., 0], wh[..., 1]
offset_x, offset_y = offset[..., 0], offset[..., 1]
left ... | Python | 1 |
n=int(input('enter number of sub:'))
t=0
for i in range(1,n+1):
m=int(input('enter marks of subject '+str(i)+":"))
t=t+m
print('Total of marks:',t)
a=t/n
print('avg. marks :',round(a,2))
| Python | 1 |
from typing import Any, TYPE_CHECKING
if TYPE_CHECKING:
from client import BSClient
try:
from models.parse_error import ParseException
except ImportError:
class ParseException(Exception):
"""Custom exception for parsing errors."""
pass
from .brawler_info import BrawlerInfo
class MatchTea... | Python | 1 |
rom<LFXT1S_A> for u8 {
#[inline(always)]
fn from(variant: LFXT1S_A) -> Self {
variant as _
}
}
#[doc = "Field `LFXT1S` reader - Mode 0 for LFXT1 (XTS = 0)"]
pub struct LFXT1S_R(crate::FieldReader<u8, LFXT1S_A>);
impl LFXT1S_R {
pub(crate) fn new(bits: u8) -> Self {
LFXT1S_R(crate::FieldR... | Rust | 0 |
"car:window",
"car:wheel",
"cat:head",
"cat:leg",
"cat:ear",
"cat:eye",
"cat:paw",
"cat:neck",
"cat:nose",
"cat:tail",
"cat:torso",
"cow:head",
"cow:leg",
"cow:ear",
"cow:eye",
"cow:neck",
"cow:horn",
"cow:muzzle",
"cow:tail",
"cow:torso",
... | Python | 1 |
# Copyright (c) 2017-present, Facebook, Inc.
#
# 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... | Python | 1 |
# Monkey patch for qfluentwidgets.components.widgets.tool_tip.ToolTip because of bug in qfluentwidgets
# This patch sets window flags correctly to Qt.ToolTip
# Needed for wayland linux sessions only. Shows a box around the tooltip in macOS and Windows
from loguru import logger
from utils.check_flatpak_sandbox import ... | Python | 1 |
06 - eUSCI_Bx Baud Rate Control Word Register"]
#[inline(always)]
pub fn ucb1brw_mut(&self) -> &mut UCB1BRW {
unsafe { &mut *(((self as *const Self) as *mut u8).add(6usize) as *mut UCB1BRW) }
}
#[doc = "0x08 - UCB1STATW_SPI"]
#[inline(always)]
pub fn ucb1statw_spi(&self) -> &UCB1S... | Rust | 0 |
# Skip displaying config with no matched snapshot to be deleted.
continue
config_abs_path = pathlib.Path(mapping.config.config_file).resolve()
print(f"Config: {str(config_abs_path)} (source={mapping.config.source})")
print(f"Snaps at: {mapping.config.dest_prefix}...")
for sn... | Python | 1 |
optimizer.zero_grad()
losses = []
for image_idx in range(len(inputs)):
image = inputs[image_idx].unsqueeze(0)
image_name = image_names[image_idx]
for _ in range(self.T):
logits, labels = self.forward(image)
loss = self.loss_fu... | Python | 1 |
"""
衛星位置轉換為 gNodeB 參數服務
整合 Skyfield 軌道計算,將衛星 ECEF/ENU 坐標轉換為 UERANSIM gNodeB 配置參數
實現真實衛星軌道與 5G 網路模擬的橋接
"""
import asyncio
import math
import logging
import json
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Tuple, Any
import structlog
import aiohttp
import redis.asyncio as redis
fro... | Python | 1 |
): str,
vol.Optional(
"decode_html",
default=self.config_entry.options.get("decode_html", False),
): bool,
vol.Optional(
"notes_affichees",
default=self.c... | Python | 1 |
توانید وضعیت تونل را از منوی اصلی بررسی کنید یا تونل جدیدی ایجاد کنید!"),
parse_mode="MarkdownV2"
)
await state.finish()
await bot.send_message(
chat_id=message.chat.id,
text=escape_md("🏠 به منوی اصلی بازگشتید! لطفاً یک گزینه را انتخاب کنید."),
reply_markup=get_main_menu_key... | Python | 1 |
#!/usr/bin/env python
# multimodal_retrieval.py
import os
import gradio as gr
import yaml
from pipelines import PipelineRegistry
def main():
# 确保配置文件路径正确
retrieval_config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
"config/pipeline_config.yaml")
query_ana... | Python | 1 |
def calculate_price(num_people, is_xingdaohu_qingdao=False, is_xinxijiang_menghuanzhilv = False):
# 定义单个景点的票价
xingdaohu_qingdao_price = 35
xinxijiang_menghuanzhilv_price = 35
# 定义组合票价
combo_price = 70
# 判断逻辑
if is_xingdaohu_qingdao:
# 如果只问星岛湖晴岛
total_price = num_people * xi... | Python | 1 |
rules! impl_to_extra_primitive_for_int {
($ty:ty) => {
impl ToExtraPrimitive for $ty {
fn to_u128(&self) -> Option<u128> {
#[cfg(extprim_has_stable_i128)] {
ToPrimitive::to_u128(self).map(u128::from_built_in)
}
#[cfg(not(extprim... | Rust | 0 |
"""
Expand the template, preserving expansions for missing variables.
May raise ExpansionFailed if a composite value is passed to a variable with a prefix modifier.
"""
expanded = [expansion.partial(kwargs) for expansion in self.expansions]
return URITemplate(''.join(expa... | Python | 1 |
from fasthtml.common import Button
def button(label, color="default", hx_get=None, hx_post=None, hx_swap=None, hx_target=None, extra={}):
styles = {
"default": "text-white bg-blue-600 hover:bg-blue-700 focus:ring-blue-800",
"alternative": "text-gray-400 bg-gray-800 border border-gray-600 hover:tex... | Python | 1 |
"""
Microsoft Archive parser
Author: Victor Stinner
Creation date: 2007-03-04
"""
from hachoir.parser import Parser
from hachoir.field import FieldSet, String, UInt32, SubFile
from hachoir.core.endian import LITTLE_ENDIAN
from hachoir.core.text_handler import textHandler, filesizeHandler, hexadecimal
MAX_NB_FILE = 1... | Python | 1 |
) = split_results[thread_id].next().unwrap();
print!("\t({}, {}; {})", start, end, end as isize - start as isize);
}
println!();
}
for _ in 0..SUB_SPLIT {
let mut temp = vec![];
for thread_id in 0..thread_count {
temp.push(split_results[thread_id].next().... | Rust | 0 |
|| (sec_fraction != 0) {
if sec_fraction == 0 {
write!(f, "{}{}", arc_sec, ARC_SECOND_SIGN)
} else {
let arc_sec = f64::from(arc_sec)
+ f64::from(sec_fraction) / f64::from(Self::$arc_... | Rust | 0 |
while fraction != fraction.floor()
&& (fraction.round() as $t) >= <$t>::MIN / 2
&& (fraction.round() as $t) <= <$t>::MAX / 2
&& (!exponent.is_negative() || ((-exponent) as u32) < MAX_EXPONENT_MODULUS)
{
f... | Rust | 0 |
const _).collect::<Vec<_>>());
//
// (Self(nodes), insert_position)
// }
//
// /// Returns the raw insert position (as if no deletes ever happened) of the requested item. The
// /// returned range always starts with the requested order and the end is the maximum range.
// fn order_to_raw(&self, ... | Rust | 0 |
D Course.credit = %s;", (dept_id,selected_week,selected_credit,))
else: #week/cerdit/time
cursor.execute("SELECT DISTINCT * FROM Course JOIN CourseTime ON Course.course_id = CourseTime.course_id WHERE Course.department_id = %s AND CourseTime.week_day = %s... | Python | 1 |
d by a tracer or debugger
# to get information from traced functions.
# These have to be defined.
run_sympy: Callable = run_fast
run_mpmath: Callable = run_fast
# If you want to test without using Mathics3 debugger module:
# import os
# if os.environ.get("MATHICS3_SYMPY_TRACE", None) is not None:
# hook_entry_fn ... | Python | 1 |
Reserved)?;
details.owner = owner.clone();
Self::deposit_event(Event::OwnerChanged(id, owner));
Ok(())
})
}
/// Change the Issuer, Admin and Freezer of an asset.
///
/// Origin must be Signed and the sender should be the Owner of the asset `id`.
///
/// - `id`: The identifier of the asset... | Rust | 0 |
ub fn crocksdb_compactionjobinfo_total_output_bytes(
arg1: *const rocksdb_CompactionJobInfo,
) -> u64;
}
extern "C" {
pub fn crocksdb_compactionjobinfo_num_input_files(
info: *const rocksdb_CompactionJobInfo,
) -> usize;
}
extern "C" {
pub fn crocksdb_compactionjobinfo_num_input_files_at... | Rust | 0 |
# Test class for testing the boot process of a Linux kernel
#
# This work is licensed under the terms of the GNU GPL, version 2 or
# later. See the COPYING file in the top-level directory.
import hashlib
import urllib.request
from .cmd import wait_for_console_pattern, exec_command_and_wait_for_pattern
from .testcase... | Python | 1 |
ratio = {learning_rate}\n'
f'Number of neurons = {2}\n'
f'SSE error cut off = {sse_threshold}')
plt.plot(range(len(errors)), errors, color='b')
plt.xscale('log')
plt.yscale('log')
plt.xlabel('Number of iterations (log scale)')
plt.ylabel('Sum of squared errors (log scale)')
plt.tight_layout()
plt.... | Python | 1 |
(default_factory=list)
class RequestInvokeEncrypt(BaseModel):
"""
Request to encryption
"""
opt: Literal["encrypt", "decrypt", "clear"]
namespace: Literal["endpoint"]
identity: str
data: dict = Field(default_factory=dict)
config: list[BasicProviderConfig] = Field(default_factory=list)... | Python | 1 |
##########
#
# File: loginServer.py
# Author: pgOnline
# Date: January 2017
# Notes: A simple login server program
# Version 1 - Only deals with login process
#
##########
# A function to check login details
def checkLogin():
# Set a flag to see if the username was found
userFound = Fals... | Python | 1 |
cktzn+A9owN/C3kYg+AGEYN/Cpw1j+A9owN/C
cAAAw+AiWkN/C67nq+A9owN/C99Tt+A0isN/C
ctIb3+A99TN/Cx1jy+AGEYN/ChrH1+A99TN/C
lDXP6+A99TN/C
lDXP6+AAAAAAC
ljX62+AAAAAAC
ljX62+AXPKM/C
cJbnv+ApbSM/CqGv0+AXPKM/CMdTy+AgVOM/C
ccSMo+AFueM/CGZ7s+A8naM/Cnvfq+AFueM/C
c0isd+ANepL/CqGvk+AFueM/CdTih+AXPK... | Rust | 0 |
gain_ctrl4_gc_tbb(&self) -> GAIN_CTRL4_GC_TBB_R {
GAIN_CTRL4_GC_TBB_R::new((self.bits & 0x1f) as u8)
}
}
impl W {
#[doc = "Bits 30:31"]
#[inline(always)]
pub fn gain_ctrl5_gc_tbb_boost(&mut self) -> GAIN_CTRL5_GC_TBB_BOOST_W {
GAIN_CTRL5_GC_TBB_BOOST_W { w: self }
}
#[doc = "Bits... | Rust | 0 |
t());
let block1_b = insert_header(&backend, 1, block0, None, [1; 32].into());
let block1_c = insert_header(&backend, 1, block0, None, [2; 32].into());
assert_eq!(backend.blockchain().leaves().unwrap(), vec![block1_a, block1_b, block1_c]);
let block2_a = insert_header(&backend, 2, block1_a, None, Default::def... | Rust | 0 |
+ Seek>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
(|| -> Result<_, DeserializeError> {
let len = raw.array()?;
let ret = Self::deserialize_as_embedded_group(raw, len);
match len {
cbor_event::Len::Len(_) => /* TODO: check finite len somew... | Rust | 0 |
ging_mode(ina260::Averaging::AVG16)
.map_err(drop)
.unwrap();
// Endless loop
loop {
led.set_low().ok();
// Clear screen contents
disp.clear();
// Read voltage current and power
let... | Rust | 0 |
parse::{parse_non_empty_number_to_string, parse_optional_number_to_string},
units::{convert_cv_to_v, convert_sub_ppm_to_ppm, ConvertMode},
};
use crate::{APP_CONTEXT, APP_I18N};
type FieldWidgetIds = (
WidgetId,
WidgetId,
WidgetId,
WidgetId,
WidgetId,
WidgetId,
WidgetId,
);
type T... | Rust | 0 |
hermal_solver_settings"]["linear_solver_settings"])
self.mechanical_linear_solver = linear_solver_factory.ConstructSolver(self.settings["mechanical_solver_settings"]["linear_solver_settings"])
print("Construction of DamUPThermoMechanicSolver finished")
def AddVariables(self):
super(DamUPT... | Python | 1 |
import warnings
from typing import Callable
import numpy as np
import pytest
from numpy.testing import assert_array_equal
from dem_stitcher.geoid import get_geoid_path, read_geoid, remove_geoid
from dem_stitcher.rio_tools import reproject_arr_to_match_profile
"""We will test 'geoid_18' over US because we include th... | Python | 1 |
import argparse
import random
random.seed(1)
parser = argparse.ArgumentParser()
parser.add_argument("--cutoff-sim-low", default=0.7, type=float, help='cutoff for sim')
parser.add_argument("--cutoff-sim-high", default=1.0, type=float, help='cutoff for sim')
parser.add_argument("--cutoff-ovl", default=0.5, type=float,... | Python | 1 |
store(Arc::new(state));
self.notify.notify_waiters();
}
fn establish_connection(&'static self, current: &Arc<ConnectionState>) {
let prev = self
.state
.compare_and_swap(current, Arc::new(ConnectionState::Connecting));
if Arc::ptr_eq(&prev, current) {
match &*CLIENT {
Ok(clie... | Rust | 0 |
import pandas as pd
label = pd.read_csv('/data2/whr/czl/TwiBot22-baselines/datasets/vendor-purchased-2019/label.csv')
main_user = pd.read_csv('./user_feature.csv')
user = main_user.loc[0:len(main_user)-1]
user_list = list(user['user_id'])
del_list = []
bool_label = []
for i,r in label.iterrows():
if r[1] == 'hu... | Python | 1 |
CRIPTOR::TYPE::Page
+ STAGE1_PAGE_DESCRIPTOR::VALID::True
+ (*attribute_fields).into(),
);
Self { value: val.get() }
}
}
/// Convert the kernel's generic memory attributes to HW-specific attributes of the MMU.
impl convert::From<AttributeFields>
for tock_registe... | Rust | 0 |
"""
Configuration settings for CryptoGap+
"""
import os
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
# Exchange API keys
BINANCE_API_KEY = os.getenv("BINANCE_API_KEY", "")
BINANCE_API_SECRET = os.getenv("BINANCE_API_SECRET", "")
KRAKEN_API_KEY = os.getenv("KRAKEN_API_KEY", ... | Python | 1 |
v as u!($size))?;
Ok(())
}
} };
}
macro_rules! imul_high_low_src {
( $size:expr, $high:ident, $low:ident, $src:ident ) => { paste::item! {
fn [<imul_ $high _ $low _ $src>](exec: &mut exec::Exec) -> Result<(), EmuException> {
let src1h = exec.[<get_ $high>]()? as i!($siz... | Rust | 0 |
].memaddrs[MemIdx(0)];
let mem = &mut store.mems[a];
let c = T::assert_val_type(stack.pop_val());
let i = I32::assert_val_type(stack.pop_val());
// NB: Explicitly use u64 to make calculations correct under 32 bit systems
let ea = (i as u64) + (memarg.offset as u64);
if ... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.