text string | label_name string | labels int64 |
|---|---|---|
pub fn run_forever(callback: impl FnMut(Event) + 'static) -> Result<(), Error> {
let key_hook_id = unsafe {
SetWindowsHookExW(
WH_KEYBOARD_LL,
Some(wh_keyboard_callback),
ptr::null_mut(),
0,
)
};
if key_... | Rust | 0 |
import math
import mymodule
import requests
import random
from typing import Tuple, List, Dict
print(math.sqrt(25)) # Output: 5.0
print("added two numbers")
print(mymodule.add(5, 3)) # Output: 8
# like we have third party library reqests, numpy, pandas etc.
response = requests.get("https://www.asharib.xyz/api/prof... | Python | 1 |
], seed: u32) -> u128 {
let mut h: [u32; 4] = [seed; 4];
let mut k = [0u32; 4];
let len: u32 = (data.len() as u32) * 4 * 4; // Length of data, in bytes
for block in data {
k[0] = getblock32(block, 0);
k[1] = getblock32(block, 1);
k[2] = getblock32(block, 2);
k[3] = getbl... | Rust | 0 |
jobs = get_jobs(args.pbs_user)
jobnames = [jobs[x]['Job_Name'] for x in jobs]
source_dir = args.source_dir[idb]
for ijob in to_compute:
if str(ijob) not in jobnames:
data_collected = popu.collect_data(ijob, workdir=source_dir + os.sep + str(... | Python | 1 |
if not arg:
raise gdb.GdbError('Please provide pointer to struct device')
dev = gdb.parse_and_eval(arg)
if dev.type != device_type.get_type().pointer():
raise gdb.GdbError('Please provide pointer to struct device')
_show_device(dev, level=0, recursive=True)
class LxD... | Python | 1 |
self.bot.is_online else self.settings["timeout_offline"],
self.settings["timeout_reason"],
disable_warnings=self.settings["disable_warnings"],
)
return False
return True
def enable(self, bot: Optional[Bot]) -> None:
HandlerManager.add_handl... | Python | 1 |
Y OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
use crate::{chain_storage::ChainStorageError, validation::ValidationError};
use tari_comms::{
connectivit... | Rust | 0 |
from flask import Flask, jsonify, request
from flask_cors import CORS
import cv2
import numpy as np
from keras.models import model_from_json
app = Flask(__name__)
CORS(app)
# Load model architecture from JSON
with open('./model.json', 'r') as json_file:
loaded_model_json = json_file.read()
# Load model architectu... | Python | 1 |
from Crypto.Cipher import AES
from base64 import *
key = "1234567812345678"
def add_padding(str1, key):
modulo = len(str1) % len(key)
print("length before: " + str(len(str1)))
i = 0
while i < (modulo-2):
str1 += "\x00"
i += 1
str1 += ("0" + str(modulo))
print("length after: ... | Python | 1 |
master/include/swift/Reflection/Records.h
impl FieldDescriptorKind {
$(
$(#[$kind_meta])+
pub const $kind: Self = Self($value);
)+
$(
$(#[$is_kind_meta])+
#[inline]
pub const fn $is_kind(&self) -... | Rust | 0 |
put: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = parse_macro_input!(input as DeriveInput);
match derive_num_variants_impl(input) {
Ok(token_stream) => proc_macro::TokenStream::from(token_stream),
Err(err) => proc_macro::TokenStream::from(err.to_compile_error()),
}
}
fn... | Rust | 0 |
sp.unwrap();
assert_eq!(resp.status.as_u16(), 404);
assert_eq!(resp.body, "");
}
#[actix_rt::test]
async fn test_post() {
let mut app = test::init_service(App::new().service(post_user)).await;
let user = User { name: "Filip".to_string() };
let resp = post_json(&mut ... | Rust | 0 |
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.metrics import accuracy_score
gb_model = GradientBoostingClassifier(n_estimators=100, learning_rate=0.1, random_state=42)
gb_model.fit(x_train, y_train)
gb_pred = gb_model.predict(x_test)
gb_accuracy = accuracy_score(y_test, gb_pred)
print("Gradient ... | Python | 1 |
from tkinter import *
from PIL import Image, ImageTk
root = Tk()
root.title("Stock Market Analysis")
root.geometry("1550x1000")
root.minsize(200, 100)
root.configure(background="#001F3F")
# Show login page function
def show_login_page():
root.destroy()
import LoginPage
# Show register page function
def s... | Python | 1 |
'Version'])
self.assertEqual(api_response, True)
def test_replace_route_interface(self):
self.set_http_response(status_code=200)
api_response = self.service_connection.replace_route(
'rtb-g8ff4ea2', '0.0.0.0/0', interface_id='eni-1a2b3c4d')
self.assert_request_parameter... | Python | 1 |
}
}
// Bit 7 - LCD Display Enable (0=Off, 1=On)
pub fn is_on(&self) -> bool {
self.lcdc & 0b1000_0000 == 0b1000_0000
}
// Bit 6 - Window Tile Map Display Select (0=9800-9BFF, 1=9C00-9FFF)
fn window_tile_map_display_select(&self) -> RangeInclusive<usize> {
if ... | Rust | 0 |
};
fs::write(cargo, content.to_string()).await?;
}
/// Adds programs to Cargo.toml as a dev dependencies to be able to be used in tests
#[throws]
async fn add_program_dev_deps(&self, root: &Path, cargo_toml_path: &Path) {
let programs = self.get_programs(root).await?;
if !progra... | Rust | 0 |
ufReader::new(file);
let mut line = String::new();
if let Ok(_nbytes) = reader.read_line(&mut line) {
version = scan!(line, char::is_whitespace, u8).0;
}
if version != VERSION {
panic!(
"Invalid scores version. Please delete the scores file {}.",
&scores_file
);
}
line.clear();
... | Rust | 0 |
fragment.find_token(token)
}
}
impl<'a, T, X> FindSubstring<&'a str> for LocatedSpan<T, X>
where
T: FindSubstring<&'a str>,
{
#[inline]
fn find_substring(&self, substr: &'a str) -> Option<usize> {
self.fragment.find_substring(substr)
}
}
impl<R: FromStr, T, X> ParseTo<R> for LocatedSpan<T,... | Rust | 0 |
pv = 1000 # Present value
r = 0.04 # Interest rate
fv = pv * 2 # Future value (double the present value)
n = 0 # Initialize the number of periods (years)
# Calculate the number of years using the compound interest formula
while pv < fv:
pv *= (1 + r) # Calculate the future value after one year
n +... | Python | 1 |
eta,
'rmse': rmse,
'mae': mae
})
results_df = pd.DataFrame(results)
import os
os.chdir(__file__)
os.chdir('visuals/hyperparameters')
plt.figure(figsize=(8, 5))
plt.plot(results_df['beta'], results_df['rmse'], marker='o', linestyle='-')
plt.title("RMSE vs... | Python | 1 |
ram)
if self.gauge_lora_info is not None:
running_lora_adapters = \
",".join(iteration_stats.running_lora_adapters.keys())
waiting_lora_adapters = \
",".join(iteration_stats.waiting_lora_adapters.keys())
lora_info_labels = {
se... | Python | 1 |
"""
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
class Solution:
def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
# https://leetcode.c... | Python | 1 |
from enum import Enum
class RequestType(Enum):
# 定义一些深度学习请求类型
IMAGE_RECOGNITION = 1 # 图像识别
OBJECT_DETECTION = 2 # 目标检测
SEMANTIC_SEGMENTATION = 3 # 语义分割
INSTANCE_SEGMENTATION = 4 # 实例分割
TEXT_RECOGNITION = 5 # 文本识别
FACE_DETECTION = 6 # 人脸检测
IMAGE_GENERATION = 7 # 图像生成
@classm... | Python | 1 |
style
#[derive(ToString, EnumString, Serialize, Deserialize, Debug)]
pub enum StyleType {
/// Lager beer
Lager,
/// Ale beer
Ale,
/// Mead
Mead,
/// Wheat beer
Wheat,
/// Mixed style
Mixed,
/// Cider
Cider,
}
impl Default for StyleType {
fn default() -> StyleType {
... | Rust | 0 |
(param_as_slice);
let new_len = header_len as usize + param_len;
self.packet.set_header_length(((new_len - 8) / 8) as u8);
}
}
/// The HIP header values for the CLOSE_ACK packet:
///
/// Header:
/// - Packet Type = 19
/// - SRC HIT = Sender's HIT
/// - DST HIT = Recipient'... | Rust | 0 |
from station.view import View
class SplashView(View):
def __init__(self) -> None:
View.__init__(self)
| Python | 1 |
s(outputs, soft_y, params['class_num'])
loss_value = loss.item()
loss.backward()
optimizer.step()
# print statistics
running_loss = running_loss + loss.item()
if (it % valid_gap == valid_gap - 1):
train_avg_loss = running_loss / valid_gap
valid_lo... | Python | 1 |
mples
def __getitem__(self, idx):
results = copy.deepcopy(self.dataset[idx])
for (transform, transform_type) in zip(self.pipeline,
self.pipeline_types):
if self._skip_type_keys is not None and \
transform_type in self._s... | Python | 1 |
integer(0), Value::integer(0)));
/// ~~~
///
pub fn safe_gcd_lcm(self_: &i64, other: &i64) -> (Value, Value) {
(safe_gcd(self_, other), safe_lcm(self_, other))
}
<reponame>NadyaNayme/Dorothy<filename>src/modules/csv.rs
extern crate csv;
use chrono::{DateTime, Local};
use serde::Serialize;
use std::error::Error;
us... | Rust | 0 |
from animals.pets import Pets
class Hamster(Pets):
def __init__(self, animals_name, pets_name, animal_name, animal_command, animal_birth):
super().__init__(animals_name, pets_name)
self.animal_name = animal_name
self.animal_command = animal_command
self.animal_birth = animal_birth | Python | 1 |
/// Defines a module.
DefModule(Var, T::Symbol, IRProc<T>),
/// Defines a class.
DefClass(Var, T::Symbol, Option<Var>, IRProc<T>),
/// Defines a method.
// TODO: params?
DefMethod(T::Symbol, IRProc<T>),
/// Defines a singleton class.
DefSingletonClass(Var, IRProc<T>),
/// Defines a ... | Rust | 0 |
from click.testing import CliRunner
from odrive_can.cli import cli
def test_cli():
runner = CliRunner()
result = runner.invoke(cli, ["--help"])
assert result.exit_code == 0
assert "Usage: cli [OPTIONS]" in result.output
assert "Options:" in result.output
assert "--help Show this message and e... | Python | 1 |
#!/usr/bin/env python3
def main():
infile = open('./return_codes.h','r')
outfile = open('./return_codes_map.h', 'w')
outfile.write('/*\n')
outfile.write('Copyright 2020, 2022 Hewlett Packard Enterprise Development LP\n\n')
outfile.write('This file was auto-generated by return_codes_map_maker.py. Do ... | Python | 1 |
]
pub struct Box3f {
pub min: glm::Vec3,
pub max: glm::Vec3,
}
impl Bound3<f32> for Box3f {
fn from_slice(slice: &[f32; 6]) -> Self {
Box3f {
min: glm::Vec3::new(slice[0], slice[1], slice[2]),
max: glm::Vec3::new(slice[3], slice[4], slice[5]),
}
}
fn as_slic... | Rust | 0 |
rint!(concat!("ninja explain: ", $fmt, "\n"), $($arg)*)
});
}
/// Log a fatal message and exit.
#[macro_export]
macro_rules! fatal {
($fmt:expr) =>
({
eprint!(concat!("ninja fatal: ", $fmt, "\n"));
$crate::utils::exit();
});
($fmt:expr, $($arg:tt)*) =>
({... | Rust | 0 |
slice_unchecked(slice: &[u8]) -> Self {
let slice = slice.as_ptr() as *const Self::Array;
Self::from_byte_array(*slice)
}
}
impl<T: crate::FromByteArray> FromByteSlice for T {}
<filename>src/main.rs
extern crate libc;
use std::ptr;
use std::ffi::{CString};
use libc::{c_int, c_uchar, c_char, uint8_... | Rust | 0 |
dint(1, 100) % 4
phone_images[k] = np.rot90(phone_images[k], random_rotate)
dslr_images[k] = np.rot90(dslr_images[k], random_rotate)
random_flip = np.random.randint(1, 100) % 2
if random_flip == 1:
phone_images[k] = np.flipud(phone_images[k])
... | Python | 1 |
"""Between."""
# standard
from datetime import datetime
from typing import TypeVar, Union
# local
from ._extremes import AbsMax, AbsMin
from .utils import validator
PossibleValueTypes = TypeVar("PossibleValueTypes", int, float, str, datetime, None)
@validator
def between(
value: PossibleValueTypes,
/,
... | Python | 1 |
m ArenaLayer {
Player,
World,
Laser,
}
#[derive(Debug)]
pub struct Arena {
pub asteroid_spawn_timer: Timer,
}
pub fn setup_arena(
commands: Commands,
mut runstate: ResMut<RunState>,
asset_server: Res<AssetServer>,
) {
runstate.arena = Some(Arena {
asteroid_spawn_timer: Timer::fr... | Rust | 0 |
normalization * (1.0 - inv_erf * tan_theta_i);
if abs(value) < 1e-5 {
break;
}
// Update bisection intervals.
if value > 0.0 {
c = b;
} else {
a = b;
}
b -= value / derivative;
}
// Now convert back into a slope val... | Rust | 0 |
self.embeddings = embeddings.AsyncEmbeddingsWithStreamingResponse(client.embeddings)
self.files = files.AsyncFilesWithStreamingResponse(client.files)
self.images = images.AsyncImagesWithStreamingResponse(client.images)
self.audio = audio.AsyncAudioWithStreamingResponse(client.audio)
sel... | Python | 1 |
// 0..10 -> Font DICT index 2
// 10..17 -> Font DICT index 1
// 17..33 -> Font DICT index 0
let ranges: Vec<Range<u16, u8>> = vec![
Range {
first: 0,
n_left: 2,
},
Range {
first: 10,
n_left: 1,
... | Rust | 0 |
apply_admin_chrome(back_page=back_page or "app.py", icon_only=icon_only)
except Exception:
pass
# 로그아웃 버튼은 헤더에 통합 (사이드바 제거로 인해)
# 실제 로그아웃 기능은 header.py에서 처리
def render_management_content() -> None:
"""관리 탭 내용 렌더링 - 중복 호출 방지를 위해 비활성화"""
# render_admin_indexing_panel()은 app.py... | Python | 1 |
w many publisher are publishing the topic which this subscription subscribes to.
///
/// # Examples
///
/// ```
/// # use anyhow::Result;
/// # use rclrust::qos::QoSProfile;
/// # use rclrust_msg::std_msgs::msg::Int32;
/// #
/// # #[tokio::main]
/// # async fn main() -> Result<()... | Rust | 0 |
"""Update postgresql trigger to use clock_timestamp function
NOTE: This migration will not be applied on SQLIte.
Revision ID: a91ea1d97111
Revises: f070559879f1
Create Date: 2025-06-09 12:21:53.427419
"""
from alembic import op
from galaxy.model.migrations.util import _is_sqlite
# revision identifiers, used by Al... | Python | 1 |
s:
/// - The `WebDriverCommands` trait contains all of the methods you would
/// typically call in order to interact with the browser.
/// - The `GenericWebDriver` struct implements the `WebDriverCommands` trait
/// for a generic HTTP client.
/// - The `WebDriver` struct is the `GenericWebDriver` implemented for a
... | Rust | 0 |
from .utils import *
class MasterScale(BetaDistribution):
def __init__(self, current_rank_rate: list, target_level: int, samples: int = 1e6):
"""
初始化
:param current_rank_rate: 目前评级分布,即目前每一个评级的占比
:param target_level: 目标细分评级等级数
:param samples: 随机数模拟 Beta 分布样本数
"""
... | Python | 1 |
for bar, color in zip(bars2, [colors[1]]*len(bars2)):
height = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2,
height * 1.01,
f'{height:.1f}',
ha='center', va='bottom', rotation=45,
fontsize=10, color=color)
for bar, ... | Python | 1 |
# Copyright (c) OpenMMLab. All rights reserved.
import mmcv
from mmcv.utils import print_log
from ..utils import get_root_logger
from .builder import DATASETS
from .custom import CustomDataset
@DATASETS.register_module()
class iSAIDDataset(CustomDataset):
""" iSAID: A Large-scale Dataset for Instance Segmentati... | Python | 1 |
use tempfile::TempDir;
use veracruz_utils::platform::icecap::message::{Header, Request, Response};
const VERACRUZ_ICECAP_QEMU_BIN_DEFAULT: &'static [&'static str] = &["qemu-system-aarch64"];
const VERACRUZ_ICECAP_QEMU_FLAGS_DEFAULT: &'static [&'static str] = &[
"-machine",
"virt,virtualization=on,gic-version=... | Rust | 0 |
not select wm events: {}", e);
}
let supported = [
instance.atoms.net_client_list,
instance.atoms.net_supporting_wm_check,
];
let cookie = xcb.xcb_change_property_checked(
c.c,
ffi::XCB_PROP_MODE_REPLACE as _,
c.screen.root,
... | Rust | 0 |
StorageProcessor<'_>,
tokens: &TokenDBCache,
pending_ops: Vec<OngoingDeposit>,
confirmations_for_eth_event: u64,
) -> Result<DepositingAccountBalances, Error> {
let mut balances = HashMap::new();
for op in pending_ops {
let token_symbol = if *op.token_id == 0 {
"ETH".to_string(... | Rust | 0 |
import re
from dataclasses import dataclass
from typing import Union
from mflux.ui.defaults import DIMENSION_STEP_PIXELS
@dataclass
class ScaleFactor:
value: Union[int, float]
def __post_init__(self):
"""Validate that the scale factor is positive"""
if self.value <= 0:
raise Valu... | Python | 1 |
azure_core::headers::add_optional_header2(&self.expiry_seconds, request)?;
#[derive(Serialize, Deserialize)]
struct RequestBody<'x> {
id: &'x str,
#[serde(rename = "permissionMode")]
permission_mode: &'x str,
resource: &'x str,
}
let requ... | Rust | 0 |
,
"agent_name": {"required": False},
"agent_cpf": {"required": False},
"agent_office": {"required": False},
"agent_phone": {"required": False},
"is_active": {"required": False},
}
read_only_fields = ["id"]
class PasswordSetSerializer(serializ... | Python | 1 |
"[AmapTools] 周边搜索成功: {location}, 结果数量: {len(result_pois)}"
)
return json.dumps(result, ensure_ascii=False, indent=2)
except KeyError as e:
error_msg = f"缺少必需参数: {e}"
logger.error(f"[AmapTools] {error_msg}")
return json.dumps({"success": False, "message": error_msg}, ensure_a... | Python | 1 |
node_color="blue",
alpha=0.3,
)
nx.draw_networkx_edges(
self.G, pos, edge_color="r", arrows=True, arrowsize=30, arrowstyle="-|>"
)
nx.draw_networkx_labels(self.G, pos)
nx.draw_networkx_edge_labels(
self.G,
pos,
... | Python | 1 |
s256Test {
key: [0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,],
pt: [0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,],
ct: [0xdb,0xae,0x34,0x17,0x4... | Rust | 0 |
# Copyright 2025 DeepMind Technologies Limited. 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 required by ... | Python | 1 |
import time
import openai
import openai.error
from common.log import logger
from common.token_bucket import TokenBucket
from config import conf
# OPENAI提供的画图接口
class OpenAIImage(object):
def __init__(self):
openai.api_key = conf().get("open_ai_api_key")
if conf().get("rate_limit_dalle"):
... | Python | 1 |
std::fmt::Formatter<'_>) -> std::fmt::Result {
for i in 0..N {
writeln!(f, "{} {} {} {}", self.from[i].0, self.from[i].1, self.to[i].0, self.to[i].1)?;
}
Ok(())
}
}
pub fn parse_input(f: &str) -> Input {
let f = proconio::source::once::OnceSource::from(f);
input! {
from f,
a: [(i32, i32, i32, i32); N]
... | Rust | 0 |
let md5_checksum = Md5Checksum::from(<[u8; 16]>::from(hasher.finalize()));
let reference_sequence = ReferenceSequence::builder()
.set_name(name)
.set_length(len)
.set_md5_checksum(md5_checksum)
.build()?;
builder = builder.add_reference_sequence(r... | Rust | 0 |
client_hpr,
ip_inclusions,
maxmind_inclusions,
Some(exclusions),
),
);
tokio::spawn(http_proxy);
}
Ok(())
}
pub fn sockaddr_from_uri(uri: &str) -> Result<SocketAddr, String> {
let uri: Uri = uri
.parse()
.map_err(... | Rust | 0 |
super) fn new(values: Vec<HzdataValue>) -> Self {
HzdataValueSeqAccess { values }
}
}
impl<'de> de::SeqAccess<'de> for HzdataValueSeqAccess {
type Error = Error<'de>;
fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
where
T: de::DeserializeSeed<'de>,... | Rust | 0 |
from django.shortcuts import render
from django.core import serializers
from django.http import HttpResponse
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.conf import settings
import json
import datetime
from registrar.models import Student
from regist... | Python | 1 |
pub extern "efiapi" fn efi_main(_image_handle: efi::EFIHandle, system_table: &mut efi::EFISystemTable) -> efi::EFIStatus {
use core::fmt::Write;
system_table.con_out.clear_screen();
write!(system_table.con_out, "Hello, Tachibana World\n").unwrap();
loop {}
}
#[panic_handler]
fn panic(_panic: &PanicInf... | Rust | 0 |
from django.shortcuts import render, redirect, get_object_or_404
from .models import Feeling, Comment
def index(request):
if request.method == 'POST':
if 'feeling' in request.POST:
feeling_text = request.POST.get('feeling')
if feeling_text:
Feeling.objects.create(tex... | Python | 1 |
import pytest
from rasa.shared.nlu.training_data.message import Message
from rasa.nlu.tokenizers.whitespace_tokenizer import WhitespaceTokenizer
from rasa.engine.storage.resource import Resource
from rasa.engine.storage.local_model_storage import LocalModelStorage
from rasa.engine.graph import ExecutionContext
from r... | Python | 1 |
import streamlit as st
import pandas as pd
from sqlalchemy import create_engine
# Load connection string from Config.py
from Config import connection_string
# Set page configuration (must be first Streamlit command)
st.set_page_config(page_title="Liane's Library", layout="centered")
# Create and cache the engine onc... | Python | 1 |
// id self.id;
///
/// // Define the resource "type"
/// kind "posts";
///
/// // Define attributes with a comma seperated list of field names.
/// attrs body, title;
///
/// // Define relationships with a comma seperated list of field names.
/// has_one author;
/// has_many comments;
//... | Rust | 0 |
particle_velocities[i][1] * (-1 if j == 1 else 1),
particle_velocities[i][2] * (-1 if j == 2 else 1)
)
draw_particle(particles[i])
pygame.display.flip()
frame_count += 1
elapsed_time = int(time.time() - start_time)
percentage_comp... | Python | 1 |
2,
arg3: *mut usize,
) -> ::libc::c_int;
}
extern "C" {
pub fn pcre2_substring_nametable_scan_16(
arg1: *const pcre2_code_16,
arg2: PCRE2_SPTR16,
arg3: *mut PCRE2_SPTR16,
arg4: *mut PCRE2_SPTR16,
) -> ::libc::c_int;
}
extern "C" {
pub fn pcre2_substring_number_fro... | Rust | 0 |
64 = s_inf + (s_sup - s_inf) / 2.;
let s_to_delta = |s: f64| if delta > delta_thr {
case_a(epsilon, s)
} else {
case_b(epsilon, s)
};
loop {
let delta_prime = s_to_delta(s_mid);
let diff = delta_prime - delta;
if (diff.abs() <= tol) && (diff <= 0.) { break }
... | Rust | 0 |
to drop this requirement (tuples give move errors if no clone)
{
type PairMinor = (Key, Val) ;
type ViewMinor = iter::Once< Self::PairMinor >;
fn view_minor<'b: 'a>( &'b self, index: Key ) -> Self::ViewMinor
{
iter::once( ( index, self.scalar.clone() ) )
}
}
// OracleMinorAscend
... | Rust | 0 |
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
from . import PrepareStage
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("cura")
def getMetaData():
return {
"stage": {
"name": i18n_catalog.i18nc("@item:inmenu", "Prepare"),
... | Python | 1 |
members;
#[allow(deprecated)]
pub use members::{AllowAll, DenyAll, Filter};
pub use members::{
AsContains, ChangeMembers, Contains, ContainsLengthBound, Everything, InitializeMembers,
IsInVec, Nothing, SortedMembers,
};
mod validation;
pub use validation::{
DisabledValidators, EstimateNextNewSession, EstimateNextS... | Rust | 0 |
, 0);
dcache_flush(curaddr,0x4);
//smmu_writereg(MC_SMMU_PTC_FLUSH_1, (curaddr >> 32) as u32);
//smmu_writereg(MC_SMMU_PTC_FLUSH, ((curaddr & 0xFFFFFFF0) | 1) as u32);
//smmu_readreg(0x70019010);
if ((tblval & 0x10000000) != 0) // page table
{
//prin... | Rust | 0 |
def find_circumcenter(x1, y1, x2, y2, x3, y3):
mid_ab = ((x1 + x2) / 2, (y1 + y2) / 2)
mid_bc = ((x2 + x3) / 2, (y2 + y3) / 2)
slope_ab = (y2 - y1) / (x2 - x1) if x2 != x1 else None
slope_bc = (y3 - y2) / (x3 - x2) if x3 != x2 else None
perp_slope_ab = -1 / slope_ab if slope_ab is not None els... | Python | 1 |
::static_type(),
]);
/* Init TreeView */
let tree_view = init_view(&list_store);
tree_view.set_model(Some(&list_store));
/* Init ScrolledWindow */
let scrolled_window = ScrolledWindow::new(None, None);
scrolled_window.add(&tree_view);
window.add(&scrolled_window);
/* Events */
... | Rust | 0 |
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl core::convert::From<crate::W<ISOURCE_SPEC>> for W {
fn from(writer: crate::W<ISOURCE_SPEC>) -> S... | Rust | 0 |
zontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.gcf().subplots_adjust(bottom=0.25)
def save_confusion_matrix(cnf_matrix, base_dir, model):
plt.figure()
plot_confusion_matr... | Python | 1 |
assert_eq!(part1_bit(input.as_slice()), 2724524);
}
#[test]
fn verify_part2() {
let input = include_str!("../input/2021/day3.txt");
assert_eq!(part2(parse_input(input).as_slice()), 2775870);
}
#[test]
fn part1_provided_example() {
let result = part1(&parse_input(
... | Rust | 0 |
# flake8: noqa: E501
from . import utils
import functools
import lazyllm
add_chinese_doc = functools.partial(utils.add_chinese_doc, module=lazyllm.flow)
add_english_doc = functools.partial(utils.add_english_doc, module=lazyllm.flow)
add_example = functools.partial(utils.add_example, module=lazyllm.flow)
add_chinese_d... | Python | 1 |
get("name").and_then(|v| v.as_str()) == Some(&bin_name))
{
bins.push(Value::Table(Map::from_iter([
("name".into(), Value::String(bin_name)),
(
"path".into(),
Value::String(format!("src/{}.rs", base_yd_path(year, day))),
),
])))
... | Rust | 0 |
::os::raw::c_int, rho: SEXP) -> SEXP;
}
extern "C" {
pub fn R_MakeExternalPtr(p: *mut ::std::os::raw::c_void, tag: SEXP, prot: SEXP) -> SEXP;
}
extern "C" {
pub fn R_ExternalPtrAddr(s: SEXP) -> *mut ::std::os::raw::c_void;
}
extern "C" {
pub fn R_ExternalPtrTag(s: SEXP) -> SEXP;
}
extern "C" {
pub fn R_... | Rust | 0 |
# widgets/multiline_entry_row.py
#
# Copyright 2025 Christophe Gueret
#
# 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 Software Foundation, either version 3 of the License, or
# (at your option) any later version.
... | Python | 1 |
container.set_inner_html(&format!(
"Converting `{}` ({:.2}kB) to SVG...",
url,
buffer.length() as f64 / 1000.0,
));
request_animation_frame(move || {
request_animation_frame(move || {
... | Rust | 0 |
gmap in Series form but with wrong axis
msg = "'gmap' is a Series but underlying data for operations is a DataFrame"
gmap = Series([1, 2], index=["X", "Y"])
with pytest.raises(ValueError, match=msg):
styler_blank.background_gradient(gmap=gmap, axis=None)._compute()
@pytest.mark.parametrize("cmap"... | Python | 1 |
import os
import sys
import subprocess
from rich.console import Console
console = Console()
def create_python_workspace(path, version):
venv_path = os.path.join(path, ".venv")
console.print(f"[yellow]Creating virtual environment with Python {version}...[/]")
try:
if sys.platform == "win32":
... | Python | 1 |
y: 1000,
width: 9,
height: 34,
};
const BACKGROUND: Rectangle<u16> = Rectangle {
x: 9,
y: 1000,
width: 1,
height: 34,
};
const RIGHT: Rectangle<u16> = Rectangle {
x: 18,
y: 1000,
width: 9,
height: 34,
};
const HEIGHT_SCALE: f32 = 1.0;
impl sheet_button::Renderer for Rende... | Rust | 0 |
str = ".cache/spotify-player";
const APP_CONFIG_FILE: &str = "app.toml";
const THEME_CONFIG_FILE: &str = "theme.toml";
const KEYMAP_CONFIG_FILE: &str = "keymap.toml";
use anyhow::{anyhow, Result};
use config_parser2::*;
use serde::Deserialize;
use std::path::{Path, PathBuf};
pub use keymap::*;
pub use theme::*;
#[de... | Rust | 0 |
"""Constants for the color_extractor component."""
ATTR_PATH = "color_extract_path"
ATTR_URL = "color_extract_url"
DOMAIN = "color_extractor"
DEFAULT_NAME = "Color extractor"
SERVICE_TURN_ON = "turn_on"
| Python | 1 |
sString> {
use std::os::unix::ffi::OsStringExt;
let mut name_vec = vec![0; 16];
unsafe {
crate::raw_prctl(
libc::PR_GET_NAME,
name_vec.as_ptr() as libc::c_ulong,
0,
0,
0,
)?;
}
name_vec.truncate(name_vec.iter().position(|x... | Rust | 0 |
-> u64 {
self.metric(ProtocolMetricsKind::SlowPath)
}
pub fn fast_paths_reads(&self) -> u64 {
self.metric(ProtocolMetricsKind::FastPathReads)
}
pub fn slow_paths_reads(&self) -> u64 {
self.metric(ProtocolMetricsKind::SlowPathReads)
}
pub fn stable(&self) -> u64 {
... | Rust | 0 |
id(10)
a = 10
id(a)
id(2)
id(a+2)
id(12)
b = a+2
id(b)
a = b
id(a)
#########################
id([1,2,3])
c = [1,2,3]
id(c)
d = c
id(d)
# list is mutable
c.append(4)
c
id(c)
id(d)
d
x = [1,2,3]
y = [1,2,3]
id(x)
id(y)
# value difference
x == y
# identity or address difference
x is y
############################
x = [... | Python | 1 |
"""The onkyo component."""
| Python | 1 |
ex = Lex::from_stack(morph, StackSource::from(shaped));
result.push(Parsed::new(lex, score));
}
}
<reponame>thomcc/thin_str<filename>src/lib.rs
#![no_std]
#![allow(clippy::partialeq_ne_impl)]
//! [`ThinStr`] is the slimmer sibling of `Box<str>` and `String`. It's a single
//! pointer, and stores it's lengt... | Rust | 0 |
buf * clust_mb_args; does not work.
*/
#[no_mangle]
pub static mut clust_mb_args: clust_args = clust_args {
parent_mbuf: 0 as *mut mbuf,
};
/* **************** Functions taken from user_mbuf.h *************/
unsafe extern "C" fn mbuf_constructor_dup(
mut m: *mut mbuf,
mut pkthdr: libc::c_int,
mut type_... | Rust | 0 |
_fn)),
DefOrUse::Def,
outline.loc,
));
on_params(&data.params, KLocalVarParent::ExternFn(extern_fn), sites);
}
for (const_enum, outline) in mod_outline.const_enums.enumerate() {
sites.push((
SymbolOccurrence::ModLocal(KModSymbol::ConstEnum(const_enum... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.