text string | label_name string | labels int64 |
|---|---|---|
/// True when a PTRACE_EXIT_EVENT has been observed in the wait_status
/// for this task.
pub(in super::super) seen_ptrace_exit_event: Cell<bool>,
/// A counter for the number of stops for which the stop may have been caused
/// by PTRACE_INTERRUPT. See description in do_waitpid
pub(in super::s... | Rust | 0 |
.unwrap_or(true));
(&mut next_vreg, candidate)
};
if let Some(param) = try_fill_baldrdash_reg(call_conv, param) {
assert!(intreg);
ret.push(param);
} else if let Some(reg) = candidate {
ret.push(ABIArg::Reg(reg.to_real_reg(), param.valu... | Rust | 0 |
K = Pminus / (Pminus + self.R)
pred_disp_fused = pred_disp_warp + K * (
pred_disp - pred_disp_warp
) # weighted sum
outliers = (pred_disp_warp - pred_disp).abs() > 1
pred_disp_fused[pred_disp_warp <= 0.0] = pred_disp[
pred_disp_war... | Python | 1 |
osen_minor_class_samples_to_oversample = minor_set[quantity_same_class_neighbours >= self.k1]
weights = quantity_same_class_neighbours[quantity_same_class_neighbours >= self.k1] / self.k2
weights_sum = np.sum(weights)
if weights_sum != 0:
weights /= np.sum(weights)
elif len... | Python | 1 |
and is kind of 1/x^2 falling
bl += step(falloff,depthDifference)*normDiff*(1.0-smoothstep(falloff,strength,depthDifference));
}
// output the result
float ao = 1.0 - base*bl/16;
gl_FragColor.rgb = color * ao;
gl_FragColor.a = 1.0;
}
"""
window = app.Window(width=800, height=800, color=(1,1,1,1))... | Python | 1 |
rustc. Rather than calling rustc
/// directly, we'll use an `Executor`, giving clients an opportunity to intercept
/// the build calls.
pub trait Executor: Send + Sync + 'static {
/// Called after a rustc process invocation is prepared up-front for a given
/// unit of work (may still be modified for runtime-kn... | Rust | 0 |
log| api::Log {
user_agent: log.user_agent,
response_time: log.response_time,
timestamp: DateTime::from_utc(log.timestamp, Utc),
})
.collect();
Ok(HttpResponse::Ok().json(api::logs::get::Response(logs)))
}
/// `GET /csv`のハンドラ
pub fn handle_get_csv(
server: S... | Rust | 0 |
}
fn main() {
env_logger::init();
match cli::cli() {
Err(e) => {
eprintln!("Invalid command line: {}", e);
::std::process::exit(1);
}
Ok(cli::CommandSpec::Net(cmd)) => {
net::main(&cmd);
}
Ok(cli::CommandSpec::File(cmd)) => file_main(&c... | Rust | 0 |
from internal crate details. */
fn produce_license(&self) -> LicenseData {
let licenses_str = self
.crate_catalog_entry
.package()
.license
.as_ref()
.map_or("", String::as_str);
license::get_license_from_str(licenses_str)
}
/** Generates the set of dependencies for the con... | Rust | 0 |
�간: 4 ms
* 해결 날짜: 2020년 10월 4일
*/
use std::cmp;
macro_rules! get_line {
( $( $t: ty ),+ ) => {
{
let mut line = String::new();
std::io::stdin().read_line(&mut line).unwrap();
let mut iter = line.split_whitespace();
( $( iter.next().unwrap().parse:... | Rust | 0 |
import torch
from itertools import product
from collections import defaultdict
from data_utils import load_data
def filtered_gene():
gene_matrix, gene_names, adjacency_matrix, connection_matrix = load_data(threshold=0.8)
mask = ~(gene_matrix == 1).all(dim=0) # True = 保留, False = 全1列
filtered_gene_mat... | Python | 1 |
::result::Result<serde_json::Value, srpc::json_rpc::Error>> + Send>> {
Box::pin(self.call(context, fn_name, args))
}
}
};
TokenStream::from(q)
}
use protocol_derive::{Decode, Encode};
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 6425)]
pub struct Gam... | Rust | 0 |
not be performed (e.g. because a target
/// tile is occupied), the function returns `None`.
///
fn move_elements(
&mut self,
moving_field: &mut MovingField,
static_field: &StaticField,
transform_pos: impl Fn([util::Position; 2]) -> Option<[util::Position; 2]>,
transf... | Rust | 0 |
import logging
import pandas as pd
from typing import Optional
from modules.config import CONFIG # CONFIG centralisé
import scoring_utils
# ---------------- CONFIG ----------------
SOURCE_WEIGHTS = CONFIG["SOURCE_WEIGHTS"]
scoring_utils.set_config(CONFIG)
# ---------------- LOGGING ----------------
logging.basicConf... | Python | 1 |
nce the Epoch, 1970-01-01 00:00:00 (UTC).
/// Only overwrites *unix_time on success.
pub fn get_current_time(&self) -> Result<u64> {
let mut status = ptr::null_mut();
unsafe {
let tm = ll::rocks_env_get_current_time(self.raw, &mut status);
Error::from_ll(status).map(|()| ... | Rust | 0 |
HeatmapMSMUHead):
"""Heads for multi-stage multi-unit heads.
TopDownMSMUHead has been renamed into TopdownHeatmapMSMUHead, check
https://github.com/open-mmlab/mmpose/pull/656 for details.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
warnings.warn(
... | Python | 1 |
v;
use std::fs::File;
use std::io::{copy, BufRead, BufReader, Error, Read, Seek};
use std::os::unix::prelude::CommandExt;
use std::process::Command;
mod build {
include!(concat!(env!("OUT_DIR"), "/built.rs"));
}
#[cfg(test)]
mod tests {
use indoc::indoc;
use std::io::{BufRead, Cursor};
fn buf<T>(cont... | Rust | 0 |
),
ApiTypeDelegate::SyncReturnVecU8 => "SyncReturn<Vec<u8>>".to_string(),
ApiTypeDelegate::StringList => "Vec<String>".to_owned(),
ApiTypeDelegate::ZeroCopyBufferVecPrimitive(_) => {
format!("ZeroCopyBuffer<{}>", self.get_delegate().rust_api_type())
}
... | Rust | 0 |
fn day5_part1_tests() {
let inputs = [
"input/day5-part1-test0.txt",
"input/day5-part1-test1.txt",
];
let outputs = [
vec![1002, 4, 3, 4, 99],
vec![1101, 100, -1, 4, 99],
];
assert_eq!(inputs.len(), outputs.len());
for (input, output) in inputs.into_iter().zip(out... | Rust | 0 |
# https://github.com/videolan/vlc/blob/3.0.16/include/vlc_interface.h#L152
SUPPORTED_AUDIO_EXT = frozenset(
(
"3ga",
"669",
"a52",
"aac",
"ac3",
"adt",
"adts",
"aif",
"aifc",
"aiff",
"amb",
"amr",
"aob",
... | Python | 1 |
NDSHAKE_FAILED_AUTH,
e => panic!("unknown event {}", e),
}
}
}
<gh_stars>1-10
use outbound_redis::*;
use redis::Commands;
pub use outbound_redis::add_to_linker;
use spin_engine::{
host_component::{HostComponent, HostComponentsStateHandle},
RuntimeContext,
};
use wit_bindgen_wasmtime::wa... | Rust | 0 |
# Imports
import os
import torch
from ultralytics import YOLO
def main():
# Check if CUDA (GPU support) is available
training_device = 'cuda:0' if torch.cuda.is_available() else 'cpu'
print("Using device:", training_device)
# Load a pretrained model
# Model Options:
'''
yolov8n.pt # Nano De... | Python | 1 |
ot_key_name_offset..].split('\\'); // key path can be shorter and match
let mut filter_iterator = self.key_path.iter();
let mut filter_path_segment = filter_iterator.next();
for key_path_segment in key_path_iterator {
match filter_path_segment {
Some(fps) => match fp... | Rust | 0 |
# ------------------------------------------------------------------
# Copyright (c) 2020 PyInstaller Development Team.
#
# This file is distributed under the terms of the GNU General Public
# License (version 2.0 or later).
#
# The full license is available in LICENSE, distributed with
# this software.
#
# SPDX-Licens... | Python | 1 |
self.var = var
def __call__(self, sample):
image_in, patch_mid, image_gt, patch_gt \
= sample['image_in'], sample['patch_mid'], sample['image_gt'], sample['patch_gt']
image_in_gs = Grayscale()(image_in)
image_gt_gs = Grayscale()(image_gt)
image_in_gs.fill_(image_in_g... | Python | 1 |
.org/licenses/LICENSE-2.0>)
//! * MIT license ([LICENSE-MIT](LICENSE-MIT) or
//! <https://opensource.org/licenses/MIT>)
//!
//! at your option.
#![cfg_attr(not(feature = "std"), no_std)]
mod decode_chunk;
mod encode_chunk;
mod error;
mod smallbytebuf;
#[cfg(test)]
mod tests;
pub use decode_chunk::{decode_chunk, D... | Rust | 0 |
tack, d)
del stack
if args.stat == True:
print("\n STAT: Data upload took: " +
graphic_nompi_lib.humanize_time(MPI.Wtime() - t0_trans))
med = None
t0_trans = MPI.Wtime()
## gather results and save
for n in range(nprocs - 1):
chunk = comm.recv(source=n + 1)
... | Python | 1 |
rest:tt)*) => {{
let out: $crate::GenericArray<$T, _> = $crate::arr![$($rest)*];
out
}};
($first:expr $(, $rest:expr)* $(,)*) => {
$crate::sequence::Lengthen::prepend($crate::arr![$($rest),*], $first)
};
($(,)*) => {
$crate::GenericArray::new()
};
}
<reponame>PhilipDa... | Rust | 0 |
#!/usr/bin/env python3
"""
Receive data from MuseLSL stream
Run this AFTER starting: muselsl stream
"""
import time
import sys
print("MUSELSL RECEIVER")
print("=" * 40)
try:
from pylsl import StreamInlet, resolve_byprop
except ImportError:
print("✗ PyLSL not installed")
print("Run: pip3 install pylsl")
... | Python | 1 |
Context;
use vrp_core::models::problem::ProblemObjective;
use vrp_core::prelude::*;
use vrp_core::rosomaxa::evolution::*;
use vrp_core::rosomaxa::{get_default_population, get_default_selection_size};
use vrp_core::solver::*;
use vrp_core::utils::*;
const FORMAT_ARG_NAME: &str = "FORMAT";
const PROBLEM_ARG_NAME: &str =... | Rust | 0 |
s {
#[clap(short, long, default_value = "default.forming")]
input: String,
#[clap(short, long, default_value = "src")]
dir: String,
#[clap(short, long, default_value = "default.forming")]
// auto crate a basic
generate: String,
}
fn main() {
let opts: Opts = Opts::parse();
let con... | Rust | 0 |
&[&str]) -> VmResult<()> {
unsafe { self.suspend_vm_unescaped(vms.iter().map(escape_pwsh)) }
}
/// Suspends VMs.
///
/// For more information, See [Suspend-VM](https://docs.microsoft.com/en-us/powershell/module/hyper-v/suspend-vm).
///
/// # Safety
///
/// This function doesn't ... | Rust | 0 |
# -*- coding: utf-8 -*-
"""
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
"Li... | Python | 1 |
#########################################################################
#
# Date: Jun 2002 Authors: Daniel Stoffler, Michel Sanner
#
# stoffler@scripps.edu
# sanner@scripps.edu
#
# Copyright: Daniel Stoffler, Michel Sanner, and TSRI
#
#########################################################################
i... | Python | 1 |
device_address(address)?;
let mut payload: [u8; $addr_bytes + $page_size] = [0; $addr_bytes + $page_size];
AS::fill_address(address, &mut payload);
// only available since Rust 1.31: #[allow(clippy::range_plus_one)]
payload[$addr_bytes..$addr_bytes + data.... | Rust | 0 |
if !passport.contains_key(&mandatory_field.to_string()) {
return 0;
}
}
if !check_values {
return 1;
}
// Part 2 only
// byr
let byr: i32 = passport.get("byr").unwrap().parse().unwrap();
if !(1920..=2002).contains(&byr) {
return 0;
}
// iyr
l... | Rust | 0 |
RSYNC)),
"remount" => Some((false, MsFlags::MS_REMOUNT)),
"mand" => Some((false, MsFlags::MS_MANDLOCK)),
"nomand" => Some((true, MsFlags::MS_MANDLOCK)),
"atime" => Some((true, MsFlags::MS_NOATIME)),
"noatime" => Some((false, MsFlags::MS_NOATIME)),
... | Rust | 0 |
#!/usr/bin/python3
"""
python_version_check.py
Validate that the version file matches the CHANGELOG.
"""
import glob
import json
import logging
import os
import re
import sys
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
if __name__ == '__main__':
warning_color = '\033[91m'
e... | Python | 1 |
import logging
import sys
import logging.config
def create_logger(logger_name, terminal_level=logging.INFO):
""" Create a logger.
Args:
logger_name: str, name of the logger
terminal_level: int, logging level in the terminal
"""
logging.config.dictConfig(
{"version": 1, "disable... | Python | 1 |
Announcement {
let G = &ED25519_BASEPOINT_TABLE;
announce_secret * G
}
fn gen_announce_secret<Rng: CryptoRng + RngCore>(
&self,
_witness: &Self::Witness,
rng: &mut Rng,
) -> Self::AnnounceSecret {
Scalar::random(rng)
}
fn sample_response<Rng: CryptoR... | Rust | 0 |
(equation_name: str) -> list:
"""Get the free variables (non-x) from an equation."""
pattern = (
r"\b(?!x\b|X\b" # Exclude 'x' and 'X'
r"|sec\b|sin\b|cos\b|log\b|tan\b|csc\b|cot\b" # Exclude trig func.
r"|arcsin\b|arccos\b|arctan\b" # Exclude arctrig func.
r"|arccot\b|arcsec\b... | Python | 1 |
.
NotForcing,
/// Force a new era, then reset to `NotForcing` as soon as it is done.
ForceNew,
/// Avoid a new era indefinitely.
ForceNone,
/// Force a new era at the end of all sessions indefinitely.
ForceAlways,
}
impl Default for Forcing {
fn default() -> Self {
Forcing::NotForcing
}
}
// A value placed... | Rust | 0 |
tion<Rect>;
fn get_screen_point(&mut self, browser: CefRc<Browser>, view_point: (i32, i32)) -> Option<(i32, i32)> { None }
fn get_screen_info(&mut self, browser: CefRc<Browser>) -> Option<ScreenInfo> { None }
fn on_popup_show(&mut self, browser: CefRc<Browser>) {}
fn on_popup_hide(&mut self, browser: Ce... | Rust | 0 |
timeout_ms", ValType::Number(0, i32::MAX)),
Config::new("enable_idempotence", ValType::Boolean),
Config::new(
"fetch_message_max_bytes",
// The range of values comes from `fetch.message.max.bytes` in
// https://github.com/edenhill/librdkafka/blob/m... | Rust | 0 |
ype Response = Response;
type Error = hyper::Error;
// The future representing the eventual Response your call will
// resolve to. This can change to whatever Future you need.
type Future = Box<future::Future<Item = Self::Response, Error = Self::Error>>;
// Req is a mutable reference because we nee... | Rust | 0 |
min_row=2, min_col=1, max_col=1):
for cell in row:
cell.alignment = Alignment(wrap_text=True)
# Optionally, autofit column widths
for column_cells in ws.columns:
length = max(len(str(cell.value)) if cell.value else 0 for cell in column_cells)
ws.column_dimensions[column_cell... | Python | 1 |
as_int64: i64,
pub as_double: f64,
pub as_string: *mut raw::c_char,
pub as_send_port: DartNativeSendPort,
pub as_capability: DartNativeCapability,
pub as_array: DartNativeArray,
pub as_typed_data: DartNativeTypedData,
_bindgen_union_align: [u64; 5usize],
}
#[repr(C)]
#[derive(Debug, Copy, ... | Rust | 0 |
dimensions': _TYPE_SIZE_ARRAY,
}
INTERFACE_SYMBOL = 'archi_context_opencl_work_vector_interface'
DATA_TYPE = _TYPE_OPENCL_WORK_VECTOR
INIT_PARAMETERS_CLASS = InitParameters
GETTER_SLOT_TYPES = {
'num_dimensions': {0: _TYPE_UINT32},
'dimension': {1: _TYPE_SIZE}... | Python | 1 |
Debug"))]
pub fn SetupVerifyInfFileA(infname: ::windows_sys::core::PCSTR, altplatforminfo: *const SP_ALTPLATFORM_INFO_V2, infsignerinfo: *mut SP_INF_SIGNER_INFO_V2_A) -> super::super::Foundation::BOOL;
#[doc = "*Required features: `\"Win32_Devices_DeviceAndDriverInstallation\"`, `\"Win32_Foundation\"`, `\"Win32... | Rust | 0 |
n = int(input())
k = int(input())
start = 1
end = n**2
answer = 0
while start <= end:
mid = (start + end) // 2
temp = 0
for i in range(1, n + 1):
temp += min(mid // i, n)
if temp >= k:
answer = mid
end = mid - 1
else:
start = mid + 1
print(answer)
| Python | 1 |
on
let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
assert_eq!(node_txn.len(), 7);
assert_eq!(node_txn[0], node_txn[5]);
assert_eq!(node_txn[1], node_txn[6]);
check_spends!(node_txn[0], commitment_txn[0].clone());
assert_eq!(node_txn[0].input.len(), 1);
check_spends!(node_txn[1], co... | Rust | 0 |
)
return
try:
log_info("[reddit_interface] Importing core_initializer...")
from core.core_initializer import core_initializer
log_info("[reddit_interface] Initializing Reddit interface...")
reddit_interface = RedditInterface()
if reddit_interface.reddit is None:
... | Python | 1 |
,
f_shwith200: [
0.85, 0.82, 0.78, 0.78, 0.66, 0.67, 0.68, 0.75, 0.73, 0.82, 0.88, 0.85,
],
f_shwith300: [
0.8, 0.75, 0.71, 0.67, 0.57, 0.49, 0.57, 0.63, 0.64, 0.72, 0.8, 0.73,
],
f_shwith500: [
0.64, 0.54, 0.54, 0.43, 0.27, 0.13, 0.19, 0.35, 0... | Rust | 0 |
from __future__ import annotations
from dataclasses import FrozenInstanceError, dataclass
from dataclasses import fields as dataclass_fields
@dataclass
class FrozenAfterInitDataclass:
"""A mixin for dataclasses that disallows changing fields after init.
Fields can be set once and not again. This is an alter... | Python | 1 |
Stream),
Unix(UnixStream),
}
impl Stream {
pub(crate) fn try_read(&self, buf: &mut [u8]) -> io::Result<usize> {
match self {
Stream::Tcp(value) => value.try_read(buf),
Stream::Unix(value) => value.try_read(buf),
}
}
pub(crate) async fn readable(&self) -> io::Result<()> {
match self {
... | Rust | 0 |
f let Some(x) = self.option(DHCP_MESSAGE_TYPE) {
if x.len() != 1 {
Err(CaptivePortalError::DhcpError("Invalid length for DHCP MessageType"))
} else {
MessageType::from(x[0])
}
} else {
Err(CaptivePortalError::DhcpError("Packet does ... | Rust | 0 |
"""
Dynamic projections dask
========================
Using dask array operations, one can dynamically take arbitrary slices
and computations of a source dask array and display the results in napari.
When the computation takes one or more parameters, one can tie a UI to
them using magicgui.
.. tags:: visualization-ad... | Python | 1 |
, operations::ClientBuilder};
#[cfg(feature = "package-2019-01-01-preview")]
pub mod package_2019_01_01_preview;
#[cfg(all(feature = "package-2019-01-01-preview", not(feature = "no-default-tag")))]
pub use package_2019_01_01_preview::{models, operations, operations::Client, operations::ClientBuilder};
#[cfg(feature = "... | Rust | 0 |
_base_ = './gfl_r50_fpn_mstrain_2x_coco.py'
model = dict(
pretrained='torchvision://resnet101',
backbone=dict(
type='ResNet',
depth=101,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', requires_grad=True),
norm_eval=True,
... | Python | 1 |
e_precision_score, det_curve, precision_recall_curve, roc_curve]
)
@pytest.mark.parametrize(
"classes", [(False, True), (0, 1), (0.0, 1.0), ("zero", "one")]
)
def test_ranking_metric_pos_label_types(metric, classes):
"""Check that the metric works with different types of `pos_label`.
We can expect `pos_lab... | Python | 1 |
, composer: &mut StandardComposer<F, P>) -> Result<(), Error> {
let hasher_gadget = HG::from_native(composer, self.hasher.clone());
let smt = SparseMerkleTree::<F, HG::Native, N>::new_sequential(
self.leaves,
&self.hasher,
self.empty_leaf,
)
.unwrap();
let path = smt.generate_membership_proo... | Rust | 0 |
import heapq
def a_star():
# Define the initial state of the problem
coins = [26, 32, 14, 36, 14, 8, 9, 3, 8, 18, 7, 23, 6, 20, 34, 8, 37, 19, 15, 6, 2, 13, 37, 7, 31, 2, 7, 4, 17, 9, 4, 22, 7, 16, 33, 14, 11, 30, 36, 14, 34, 37, 36, 37, 32, 38, 15, 17, 19, 14]
taxes = {17: 16, 4: 2, 15: 2, 8: 1, 19: 5, 9... | Python | 1 |
nst wchar_t,
_EndPtr: *mut *mut wchar_t,
_Radix: ::std::os::raw::c_int,
_Locale: _locale_t,
) -> ::std::os::raw::c_longlong;
}
extern "C" {
pub fn wcstoul(
_String: *const wchar_t,
_EndPtr: *mut *mut wchar_t,
_Radix: ::std::os::raw::c_int,
) -> ::std::os::raw:... | Rust | 0 |
from django.conf import settings
from django.db import models
from django_sharding_library.fields import BigAutoField
def _get_primary_shards():
"""
Returns the names of databases which make up the shards and have no primary.
"""
return sorted(
filter(
lambda db: not settings.DATA... | Python | 1 |
_g {
use super::*;
pub fn get() -> protocol::StructG {
protocol::StructG {
field_a: struct_a::get(),
field_b: struct_b::get(),
}
}
pub fn equal(strct: protocol::StructG) -> bool {
get() == strct
}
}
pub mod struct_j {
use super::*;
pub fn get()... | Rust | 0 |
t.raises(ValueError, match="dimensions"):
diagram_type(invalid_data)
def test_gh_21286():
generators = np.array([[0, 0], [0, 1.1], [1, 0], [1, 1]])
tri = qhull.Delaunay(generators)
# verify absence of segfault reported in ticket:
with pytest.raises(IndexError):
tri.find_simplex(1)
... | Python | 1 |
#!/usr/bin/env python
from __future__ import print_function
import cmor
import numpy
def main():
cmor.setup(inpath='/git/cmip5-cmor-tables/Tables',
netcdf_file_action=cmor.CMOR_REPLACE_3)
cmor.dataset('pre-industrial control', 'ukmo', 'HadCM3', 'noleap',
institute_id='ukmo',
... | Python | 1 |
from rdkit import Chem
from rdkit.Chem import AllChem
from rdkit import RDLogger
RDLogger.DisableLog('rdApp.*')
def smiles_to_3d_conformer(smiles_string):
"""
将单个 SMILES 字符串转换为 RDKit 的 3D 分子对象。
参数:
smiles_string (str): 输入的 SMILES 字符串。
返回:
rdkit.Chem.Mol: 带有 3D 构象的 RDKit 分子对象,如果失败则返回 N... | Python | 1 |
= min(max_train_samples, len(train_dataset))
trainer.log_metrics("train", metrics)
trainer.save_metrics("train", metrics)
trainer.save_state()
# Evaluation
results = {}
max_length = (
training_args.generation_max_length
if training_args.generation_max_length is not... | Python | 1 |
import os, subprocess
def confirm(message, default = False):
message += " [Y/n]" if default else " [y/N]"
response = ""
while response not in ("y", "n"):
response = input(message).strip().lower()
if response == "":
return default
return response == "y"
def backup_code(no_co... | Python | 1 |
import ipaddress
from django.conf import settings
from django.core.exceptions import DisallowedHost, MiddlewareNotUsed
from django.http.request import split_domain_port, validate_host
ORIG_ALLOWED_HOSTS = []
class AllowCIDRMiddleware:
def __init__(self, get_response, *args, **kwargs):
self.get_response ... | Python | 1 |
MemoryResourceNotification\0")) ) } )
}
pub fn GetSystemFileCacheSize() -> Option<unsafe fn(
lpMinimumFileCacheSize: PSIZE_T,
lpMaximumFileCacheSize: PSIZE_T,
lpFlags: PDWORD,
) -> BOOL> {
Some( unsafe { std::mem::transmute( get_k32_fn(obfstr::obfstr!("GetSystemFileCacheSize\0")) ) } )
}
pub fn SetSystemFi... | Rust | 0 |
import os
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
from urllib.parse import unquote
import boto3
import psycopg2
from dotenv import load_dotenv
load_dotenv()
# 환경 변수 설정
AWS_ACCESS_KEY = unquote(os.environ.get('AWS_ACCESS_KEY')) # AWS 액세스 키 로드
AWS_SECRET_KEY = unquote(os.environ.get('AWS_... | Python | 1 |
& ( * ( 0 as * const bgfx_platform_data ) ) . backBufferDS as
* const _ as usize } , 32usize , concat ! (
"Alignment of field: " , stringify ! ( bgfx_platform_data ) ,
"::" , stringify ! ( backBufferDS ) ));
assert_eq! (unsafe {
& ( * ( 0 as * c... | Rust | 0 |
DETAIL_INFO = {
"id": 3,
"name": "АО Рога и копыта",
"responsible_user_id": 504141,
"group_id": 0,
"created_by": 504141,
"updated_by": 504141,
"created_at": 1582117331,
"updated_at": 1586361223,
"closest_task_at": None,
"custom_fields_values": [
{
"field_id": ... | Python | 1 |
g.norm(pos_end - obj_center_mass)
p.disconnect(physicsClientId=conn_id)
return distance
def vhacd(
filename,
vhacd_path,
resolution=1000,
concavity=0.001,
planeDownsampling=4,
convexhullDownsampling=4,
alpha=0.05,
beta=0.0,
maxhulls=1024,
pca=0,
mode=0,
maxNumVe... | Python | 1 |
=> format!("string (\"{}\")", value),
json::Value::Array(_) => "array".into(),
json::Value::Object(_) => "structure".into(),
};
JsonValueErrorType::TypeError {
expected: expected.into(),
actual: actual_string,
}
}
}
use crate::error::GSError;... | Rust | 0 |
ng_move)
.last()
.unwrap();
winning_board_data.final_draw * winning_board_data.empty_cells
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_winning() {
use Cell::*;
let mut board = Board([
[Empty(14), Empty(21), Empty(17), Empty(24), Empty(4)],
... | Rust | 0 |
enderscript/Test.rs
#pragma version(1)
#pragma rs java_package_name(cn.louispeng.imagefilter.renderscript)
int *intArrayPointer;
static void print(float3 f3) {
rsDebug("f3 = ", f3);
}
static float3 init() {
float3 f3 = {0.1f, 0.2f, 0.3f};
return f3;
}
void test() {
{
float3 f3 = init();
f3 *= 2.... | Rust | 0 |
# -*- coding: utf-8 -*-
#
# RERO ILS
# Copyright (C) 2024 RERO
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that... | Python | 1 |
#!/usr/bin/env python3
import subprocess
import argparse
import re
WORKING_DIR = "/tmp/" #TODO convert to global path and generated dirname
FFUF_KEYWORD = "FUZZ"
FFUF_PATH = "ffuf" #TODO make this a command line argument or move to a config file
ANSI_ESCAPES_RE = re.compile(r"\x1b\[[0-9;]*[a-zA-Z]|\r")
def main():
... | Python | 1 |
ts for each segment in the RLE data.
Raises
------
ValueError
If there are more than 15 segments or if the header is not 64 bytes
long.
References
----------
DICOM Standard, Part 5, :dcm:`Annex G<part05/chapter_G.html>`
"""
if len(header) != 64:
raise ValueError... | Python | 1 |
BIND_HEADER.to_vec();
append_section_header(&mut bytecode, SYMB_MAGIC_NUM, 9);
let str_1: [u8; 5] = [0x49, 0x42, 0x49, 0x53, 0]; // "IBIS"
bytecode.extend_from_slice(&[1, 0, 0, 0]);
bytecode.extend_from_slice(&str_1);
let primary_node_inst = [0x30, 0x01, 0x01, 0, 0, 0, 0x05, 0... | Rust | 0 |
() {
let input = include_str!("../input/input.txt");
let measurements = ParsedInput(
input
.lines()
.map(|line| line.parse::<i32>().unwrap())
.collect_vec(),
);
part1(&measurements);
part2(&measurements);
}
//! Loans pallet benchmarking.
#![cfg_attr(no... | Rust | 0 |
'yue-Hans': '纽西兰', 'yue-Hant': '紐西蘭', 'zgh': 'ⵏⵢⵓⵣⵉⵍⴰⵏⴷⴰ', 'zh': '新西兰', 'zh-Hans': '新西兰', 'zh-Hant': '紐西蘭', 'zu': 'i-New Zealand'},
'Nagm': {'bs': 'nag mundari pismo', 'bs-Cyrl': 'наг мундари писмо', 'bs-Latn': 'nag mundari pismo', 'en': 'Nag Mundari', 'et': 'Nagi mundari', 'eu': 'nag mundariera', 'ff-Adlm': '𞤐𞤢�... | Python | 1 |
import numpy as np
import vae
from pyga import Individual, blended, gaussian
class ShapeOrig(Individual):
_crossover_method = staticmethod(blended)
_mutate_method = staticmethod(gaussian)
target_shape = None
def __init__(self, genes):
super().__init__(genes)
@classmethod
def set_t... | Python | 1 |
"""
========================
Expected Degree Sequence
========================
Random graph from given degree sequence.
"""
import networkx as nx
# make a random graph of 500 nodes with expected degrees of 50
n = 500 # n nodes
p = 0.1
w = [p * n for i in range(n)] # w = p*n for all nodes
G = nx.expected_degree_gra... | Python | 1 |
/// `VPSHUFLW ymm1 {k1}{z}, ymm2/m256, imm8`
///
/// `EVEX.256.F2.0F.WIG 70 /r ib`
///
/// `AVX512VL and AVX512BW`
///
/// `16/32/64-bit`
EVEX_Vpshuflw_ymm_k1z_ymmm256_imm8,
/// `VPSHUFLW zmm1 {k1}{z}, zmm2/m512, imm8`
///
/// `EVEX.512.F2.0F.WIG 70 /r ib`
///
/// `AVX512BW`
///
/// `16/32/64-bit`
EVEX... | Rust | 0 |
L_0`"]
#[inline(always)]
pub fn is_captiopisel_0(&self) -> bool {
*self == CAPTIOPISEL1_A::CAPTIOPISEL_0
}
#[doc = "Checks if the value of the field is `CAPTIOPISEL_1`"]
#[inline(always)]
pub fn is_captiopisel_1(&self) -> bool {
*self == CAPTIOPISEL1_A::CAPTIOPISEL_1
}
#[... | Rust | 0 |
lf.epsilon*self.ep_decay**i_episode
policy = self.__epislon_greedy_policy(policy_epsilon, self.nA)
step = 0
# Initialize S
state = self.env.reset()
# Repeat (for each step of episode)
while(True):
# Choose ... | Python | 1 |
import pandas as pd
import numpy as np
from scipy.spatial.distance import directed_hausdorff
import matplotlib.pyplot as plt
import geopandas as gpd
from shapely.geometry import LineString, Point
# 读取轨迹数据
matched_traj_df = pd.read_csv('matched_traj.csv')
# 读取需要匹配的轨迹数据
sim_task_df = pd.read_csv('../data/sim_task.csv')... | Python | 1 |
resp: &Response,
) -> Result<RenderStatus> {
let description = &resp.as_current()?.weather[0].description;
let description = if let Some(d) = description {
d
} else {
return Ok(RenderStatus::Empty);
};
if let Some(ref style) = self.style {
... | Rust | 0 |
SCREEN: NcFlags_u64 =
ffi::NCOPTION_NO_ALTERNATE_SCREEN as NcFlags_u64;
/// [`NcFlags_u64`] flag to avoid trying to clear any preexisting bitmaps.
///
/// Note that they might still get cleared even if this is set, and they might
/// not get cleared even if this is not set.
pub const NCOPTI... | Rust | 0 |
r_shaved == number_of_yaks,
);
});
}
<reponame>trembel/ambiq-apollo3p-pac<filename>src/gpio/cfge.rs<gh_stars>0
#[doc = "Reader of register CFGE"]
pub type R = crate::R<u32, super::CFGE>;
#[doc = "Writer for register CFGE"]
pub type W = crate::W<u32, super::CFGE>;
#[doc = "Register CFGE `reset()`'s with valu... | Rust | 0 |
uí
]
# Comparación de indicadores corporales
for indicador, inicial, final, clasificador in indicadores_corporales:
mejora = calcular_mejora(inicial, final)
clasificacion_inicial = clasificador(inicial) if inicial is not None else "No disponible"
clasificacio... | Python | 1 |
self, _: &T) -> Self {
*self
}
}
impl<T> ExtractParam<errors::respond::EmitHeaders, T> for ClientRescue {
#[inline]
fn extract_param(&self, _: &T) -> errors::respond::EmitHeaders {
// Always emit informational headers on responses to an application.
errors::respond::EmitHeaders(self... | Rust | 0 |
tion = torch.sum(query_to_surface * closest_vertex_normals, dim=-1)
signed_distance_to_human = same_direction.sign() * distance_to_human # (B, O)
# find signed distance to object from human
# signed_distance_to_object = torch.zeros([pairwise_distance.shape[0], pairwise_distance.shape[2]]).float().cu... | Python | 1 |
os = "android", target_os = "linux"))]
mod epoll;
#[cfg(any(target_os = "android", target_os = "linux"))]
pub use self::epoll::Selector;
#[cfg(any(target_os = "freebsd", target_os = "macos",
target_os = "netbsd", target_os = "openbsd"))]
mod kqueue;
#[cfg(any(target_os = "freebsd", target_os = "macos",
... | Rust | 0 |
0x3 0x1c 0x7f 0x15 0x4 0xff ' # Control characters
'&>/dev/null;%s' % command)
def command(self, command, raw=False, timeout_ms=None):
"""Run the given command and return the output."""
return ''.join(self.streaming_command(command, raw, timeout_ms))
def streaming_command(self, command, raw=... | Python | 1 |
import torch
import torch.nn as nn
import torch.optim as optim
from sklearn.neighbors import NearestNeighbors
import numpy as np
# Define LSTM Model
class LSTMModel(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, output_size):
super(LSTMModel, self).__init__()
self.hidden_size =... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.