text string | label_name string | labels int64 |
|---|---|---|
Config` without `null` as `configs` to get the
/// number of matching configurations.
///
/// This will return a `BadParameter` error if `attrib_list` is not a valid
/// attributes list (if it does not terminate with `NONE`).
pub fn matching_config_count(display: Display, attrib_list: &[Int]) -> Result<usize, Error> {
... | Rust | 0 |
the results equations
// !!!return the running time
// !!!return on equation at a time
// !!!release
// !!!small
// !!! possible progress bar: https://medium.com/geekculture/rusting-javascript-with-webassembly-632405ba5a42
// !!! with 500 it pops up a "this page is slow" warning
// !!! add README.md etc
use wasm_bind... | Rust | 0 |
self._loop._add_writer(self._sock_fd, self._sendto_ready)
except OSError as exc:
self._protocol.error_received(exc)
return
except Exception as exc:
self._fatal_error(exc,
'Fatal write error on datagram transpor... | Python | 1 |
val / this.ext;
(1 << bits) - cmp::min(s + 1, 1 << bits)
}
#[no_mangle]
/**
Advance the decoder past the next symbol using the frequency information the
symbol was encoded with.
Exactly one call to ec_decode() must have been made so that all necessary
intermediate calculations are performed.
* `fl`: The cumulative... | Rust | 0 |
mic_load_store=\"128\"")
&& !target.contains("x86_64")
{
continue;
}
if m.contains("atomic_u64")
&& !target_cfg.contains(&"target_has_atomic_load_store=\"64\"")
{
continue;
}
if m.cont... | Rust | 0 |
import re
import os
import unittest
import codecs
from worker.runner import WorkerRunner
from worker.processor.klee_run import KleeRunProcessor
from worker.exceptions import KleeRunFailure
BASE_DIR = os.path.dirname(os.path.realpath(__file__))
FIXTURE_DIR = os.path.join(BASE_DIR, 'fixtures')
class TestWorkerRunner... | Python | 1 |
import pandas as pd
def clean_and_feature_engineer(df):
df = df.copy()
# Convert dates
df['booking_date'] = pd.to_datetime(df['booking_date'])
df['checkin_date'] = pd.to_datetime(df['checkin_date'])
df['checkout_date'] = pd.to_datetime(df['checkout_date'])
# Calculate features
df['stay_len... | Python | 1 |
Ok(())
}
pub fn serialize_structure_crate_model_distribution(
object: &mut aws_smithy_json::serialize::JsonObjectWriter,
input: &crate::model::Distribution,
) -> Result<(), aws_smithy_http::operation::SerializationError> {
if let Some(var_290) = &input.region {
object.key("region").string(var_290)... | Rust | 0 |
ew_args = ((args[i] if i >= 0 else None) for i in self.output_mask)
ret = self.grad(*new_args)
new_ret = []
for i, r in enumerate(ret):
j = self.input_mask[i]
if j < 0:
# -2 in input_mask represents it is stop_grad
assert r is None or j==-2... | Python | 1 |
assert response.voice == "alloy"
assert response.provider == "openai"
@pytest.mark.asyncio
async def test_agenerate_speech(tts_model):
"""Test asynchronous speech generation."""
response = await tts_model.agenerate_speech(
text="Hello world",
voice="nova"
)
# Verify async HTTP P... | Python | 1 |
fn get_chunks(&self) -> &Vec<u8>;
fn get_spawnarea(&self) -> Vec3D {
let size = self.get_size();
Vec3D::new(size.get_x() * 16, size.get_y() * 32, size.get_z() * 16)
}
fn get_spawnyaw(&self) -> u8 {
0
}
fn get_spawnpitch(&self) -> u8 {
255
}
fn get_b... | Rust | 0 |
}
#[test]
fn test_serde() {
assert_eq!(REPORT_BODY_SIZE, size_of::<sgx_report_body_t>());
let body = ReportBody::try_from(&REPORT_BODY_SRC).expect("Could not read report");
let serialized = serialize(&body).expect("Error serializing report");
let body2: ReportBody = deserialize... | Rust | 0 |
if c == None:
continue
barX += [(j, 1.0)]
barColors += [c]
if barX:
ax.broken_barh(barX, (startYear + (i / 12.0), 1.0 / 12.0),
facecolors = barColors)
else:
for i in range(maxUID + 1):
barX = []
barColors... | Python | 1 |
32,
#[serde(rename="Fee")]
pub fee: u64,
#[serde(rename="TransactionType")]
pub transaction_type: String,
#[serde(rename="Account")]
pub account: String,
#[serde(rename="Amount")]
pub amount: u64,
#[serde(rename="Method")]
pub method: i32,
#[serde(rename="Destination")]... | Rust | 0 |
s = (s & 0x3333_3333_3333_3333) + ((s >> 2) & 0x3333_3333_3333_3333);
s = ((s + (s >> 4)) & 0x0F0F_0F0F_0F0F_0F0F).wrapping_mul(L8);
let b = (i_le8(s, r.wrapping_mul(L8)) >> 7).wrapping_mul(L8)>> 53 & !7;
let l = r - ((s << 8).wrapping_shr(b as u32) & 0xFF);
s = (u_nz8((x.wrapping_shr(b as u32) & 0xFF)... | Rust | 0 |
import matplotlib.pyplot as plt
import pandas as pd
from io import StringIO
# Assuming 'your_file_path.csv' is the path to your CSV file
# file_path = 'your_file_path.csv'
file_path = r"C:\Code\IFC-extracted_elements_dataset\data_stats.csv"
# Read the CSV data into a pandas DataFrame
# df = pd.read_csv(file_path, en... | Python | 1 |
climb_speed = 0
burrow_speed = 40
hp_max = 94
hit_dice = '9d10 + 45'
condition_immunities = ''
damage_immunities = ''
damage_resistances = ''
damage_vulnerabilities = ''
spells = []
class Burrowshark(Monster):
"""
Elite warriors of the earth cult, burrowsharks are fierce ch... | Python | 1 |
# -----------------------------------------------------------------------------.
# MIT License
# Copyright (c) 2024 GPM-API developers
#
# This file is part of GPM-API.
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software")... | Python | 1 |
), mods: KeyMod::CtrlAlt despite the
/// shift key being pressed due to limitations in the terminal API
/// - KeyMod::AltCtrl and KeyCode::Char(0..=9) are not supported.
/// - KeyMod::CtrlShift and KeyCode::Char(0..=9) are not supported
/// - Any modifier keys and Backspace/Tab are not supported, save
/// KeyMod::Shift... | Rust | 0 |
bject>,
context: Option<Context<()>>,
}
impl From<RouterRequest> for crate::RouterRequest {
fn from(request: RouterRequest) -> Self {
let req = Request::new(crate::Request {
query: request.query,
operation_name: request.operation_name,
variables: request.variables.un... | Rust | 0 |
res)
}
pub fn add_schema(&mut self, node: Node<'a, '_>) -> Result<(), String> {
let schema = Schema::parse(node)?;
let ns = schema.target_namespace.as_ref().unwrap_or(&AnyUri(""));
self.types
.entry(ns.0)
.or_insert_with(GlobalTypesSet::default)
.add_... | Rust | 0 |
state.lock();
if window_state.modifiers_state != modifiers {
window_state.modifiers_state = modifiers;
// Drop lock
drop(window_state);
unsafe {
subclass_input.send_event(Event::WindowEvent {
window_id: RootWindowId(WindowId(window.0)),
event: ModifiersChanged(modifiers),
... | Rust | 0 |
from django.contrib import admin
from .models import Customer, Order, OrderItem, Cart, CartItem
@admin.register(Customer)
class CustomerAdmin(admin.ModelAdmin):
list_display = ('name', 'phone', 'email', 'city', 'created_at')
list_filter = ('city', 'created_at')
search_fields = ('name', 'phone', 'email', 'a... | Python | 1 |
# SNMP MIB module (RFC1298-MIB) expressed in pysnmp data model.
#
# This Python module is designed to be imported and executed by the
# pysnmp library.
#
# See https://www.pysnmp.com/pysnmp for further information.
#
# Notes
# -----
# ASN.1 source file:///Users/rob/MIBs/Standards/IETF/RFC1298-MIB.mib
# Produced by pysm... | Python | 1 |
er_center = []
for i in range(0, len(data[0])):
dummy_sum_num = 0.0
dummy_sum_dum = 0.0
for k in range(0, len(data)):
# 分子
dummy_sum_num += (U[k][j]) * data[k][i]
# 分母
dummy_sum_dum += (U[k][j] ** m)
# 第i列的聚类中心
current_cluster_center.append(dummy_sum_num/dummy_sum_dum)
# 第j... | Python | 1 |
import importlib
from IPython import embed
import os
import time
import yaml
import torch
from torch.nn import Parameter
from torch.nn.init import xavier_normal_
def import_class(module_and_class_name: str) -> type:
"""Import class from a module, e.g. 'model.TransE'"""
module_name, class_name = module_and_cla... | Python | 1 |
import cv2
import numpy as np
import pyassimp
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
from Webcam import Webcam
# Variables globales
window = 0
scene = None
width, height = 640, 480
webcam = None
aruco_dict = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_6X6_1000)
parameters = cv2... | Python | 1 |
me for the welcome message:")
if custom_text:
custom_welcome.set(custom_text)
welcome()
title=Label(root, text='Billing Software', bg=bg_color, fg='white',font=('times new rommon', 25, 'bold'), relief=GROOVE,bd=12)
title.pack(fill=X)
F1=LabelFrame(root,text='Customer Details', bg=bg_color, fg='g... | Python | 1 |
&js_raw.code, js_raw.args.len(), return_ty.clone() );
let return_signature = if let Some( ty ) = return_ty {
quote! { -> #ty }
} else {
quote! {}
};
let prototype_args = dummy_idents( js_raw.args.len() ).map( |name| quote! { #name: *const u8 } );
let call_args = dummy_idents( js_raw... | Rust | 0 |
d on the client or passed to this method.
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> WalletListResponse:
"""
Args:
extra_headers: ... | Python | 1 |
# Exercise 3 Solution
class Widget(anywidget.AnyWidget):
_esm = """
function chime({ duration, tone1, tone2 }) { // <---- NEW!
const c = new AudioContext();
const g = c.createGain();
const o = c.createOscillator();
g.connect(c.destination);
g.gain.value = 0.1;
g.gain.linearR... | Python | 1 |
from cassandra.cluster import Cluster
from cassandra.query import BatchStatement
import pandas as pd
import uuid
# Define Cassandra connection parameters
cassandra_host = '127.0.0.1'
cassandra_port = 9042
# Create a Cluster instance
cluster = Cluster([cassandra_host], port=cassandra_port)
# Connect to the Cassandra ... | Python | 1 |
, false);
// valid
check_regex!(T, "9606", true);
check_regex!(T, "731", true);
// invalid
check_regex!(T, "965X", false);
check_regex!(T, "965 ", false);
check_regex!(T, " 965", false);
check_regex!(T, "X965", false);
// extract
extract_... | Rust | 0 |
from .symbols import *
_symbol_to_id = {s: i for i, s in enumerate(symbols)}
def cleaned_text_to_sequence(cleaned_text, tones, language, symbol_to_id=None):
"""Converts a string of text to a sequence of IDs corresponding to the symbols in the text.
Args:
text: string to convert to a sequence
Retur... | Python | 1 |
import boto3
# Create the target group
def create_alb_target_group(applicationLoadBalancerArn, targetGroupName, targetGroupProtocol,
targetGroupPort, targetGroupVpcId, targetGroupHealthCheckProtocol,
targetGroupTargetType, ec2InstanceId):
alb_client = boto3.client('... | Python | 1 |
::null_mut(), ptr::null_mut()) {
0 => match avformat_find_stream_info(ps, ptr::null_mut()) {
r if r >= 0 => Ok(context::Input::wrap(ps)),
e => {
avformat_close_input(&mut ps);
Err(Error::from(e))
}
},
e => Err(Error::from(e)),
}
}
}
pub fn output<P: AsRef<Path>>(path: P) -> Result<co... | Rust | 0 |
pl InfoFlags1 {
pub(crate) const OP_INFO0_SHIFT: u32 = 0x0000_0000;
pub(crate) const OP_INFO0_MASK: u32 = 0x0000_000F;
pub(crate) const OP_INFO1_SHIFT: u32 = 0x0000_0004;
pub(crate) const OP_INFO1_MASK: u32 = 0x0000_0007;
pub(crate) const OP_INFO2_SHIFT: u32 = 0x0000_0007;
pub(crate) const OP_INFO2_MASK: u32 = 0x... | Rust | 0 |
"The specified project dir already exists. "
"To force overwriting it use '-f' or '--force'."
)
template_dir = str(Path(args.template_dir).resolve())
if not os.path.exists(template_dir):
raise TVMCException(f"Template directory {template_dir} does not exist!"... | Python | 1 |
# coding: utf-8
#
# Copyright 2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "lice... | Python | 1 |
pub fn MakeCurrent(hDc: types::HDC, newContext: types::HGLRC) -> types::BOOL;
#[link_name="wglRealizeLayerPalette"]
pub fn RealizeLayerPalette(hdc: types::HDC, iLayerPlane: __gl_imports::raw::c_int, bRealize: types::BOOL) -> types::BOOL;
#[link_name="wglSetLayerPaletteEntries"]
pub ... | Rust | 0 |
TriangleListAdjacency => D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST,
TriangleStrip => D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP,
TriangleStripAdjacency => D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP,
PatchList(num) => { assert!(num != 0);
D3D_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHL... | Rust | 0 |
="region",
axes=[time_axis, energy_axis],
)
npred_map.data[...] = 5
coords = npred_map.sample_coord(n_events=2, random_state=0)
assert len(coords["lon"]) == 2
assert_allclose(coords["lon"].data, [83.63, 83.63], rtol=1e-5)
assert_allclose(coords["lat"].data, [21.51, 21.51], rtol=1e-5)
... | Python | 1 |
file_access_mask;
use rand::{
distributions::{Distribution, Standard},
Rng,
};
pub const STRUCTURE_SIZE: &[u8; 2] = b"\x39\x00";
/// The SMB2 CREATE Request packet is sent by a client to request either
/// creation of or access to a file. In case of a named pipe or printer,
/// the server MUST create a new f... | Rust | 0 |
Program {
pub program_id: Pubkey,
pub process_instruction: ProcessInstructionWithContext,
}
impl std::fmt::Debug for BuiltinProgram {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
// These are just type aliases for work around of Debug-ing above pointers
type ErasedProces... | Rust | 0 |
let mut graph = NodeGraph::new(b1);
graph.insert(b2);
graph.insert(b3);
graph.insert_exit(b4);
// Analyze
let top = LivenessFact {
live: FnvHashSet::default(),
};
let mut analyzer = Analyzer::new_backward(top, trans, join);
let res = analyzer.solve(&graph);
// Compare
... | Rust | 0 |
f@h_ H S SK r S SK Jr SrSrSrSrSrSrS rS
r Sr
SrS
rSr
g) N)ADMIN_BOT_USERNAMEu4
**ʜᴇʟʟᴏ** {},
**<blockquote>ɪ'ᴍ ᴀᴅᴇᴘᴛ ᴀᴛ ᴇxᴛʀᴀᴄᴛɪɴɢ ᴏɴʟɪɴᴇ ᴄᴏᴜʀsᴇs ᴡɪᴛʜ ᴄᴜᴛᴛɪɴɢ-ᴇᴅɢᴇ ᴛᴇᴄʜɴᴏʟᴏɢʏ. ɪ'ᴠᴇ ᴍᴀɴᴀɢᴇᴅ ᴛᴏ ɢᴀᴛʜᴇʀ ʟɪɴᴋs ғᴏʀ ᴀʟᴍᴏsᴛ ᴀʟʟ ᴀᴠᴀɪʟᴀʙʟᴇ ᴄᴏᴜʀsᴇs, ᴍᴀᴋɪɴɢ ᴛʜᴇ ᴘʀᴏᴄᴇs... | Python | 1 |
# Copyright (c) 2010-2017 Samuel Abels
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, d... | Python | 1 |
ACCESS_DISABLE = 0,
#[doc = "1: DRAM1 access enabled"]
DRAM1_ACCESS_ENABLE = 1,
}
impl From<DRAM1_ACCESS_A> for bool {
#[inline(always)]
fn from(variant: DRAM1_ACCESS_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `DRAM1_ACCESS`"]
pub type DRAM1_ACCESS_R = crate::R<bool, DRAM1_... | Rust | 0 |
yclable` object.
#[doc(hidden)]
pub fn new(item: T) -> Self {
debug!("Creating a new ArcHandle.");
ArcHandle(Arc::new(RwLock::new(item)))
}
/// Locks this rwlock with shared read access, blocking the current thread until it can be acquired.
///
/// Refer to the [RwLock::read](ht... | Rust | 0 |
ons; // This will contain all the options for a target
impl Generator {
pub fn generate(&self, target_repo: &TargetRepository) -> PakResult<()> {
let project = Project::read()?;
let model = Model::new(project.model);
let target = target_repo.find(self.target_name.as_str())?;
let gen... | Rust | 0 |
1, y: 2 };
let b: Box<Trait<&'static str>> = Box::new(a);
b.f("Mary");
let c: &Trait<&'static str> = &a;
c.f("Joe");
}
/* automatically generated by rust-bindgen */
pub const ERROR_SUCCESS: u32 = 0;
pub const ERROR_FILE_NOT_FOUND: u32 = 2;
pub const ERROR_ACCESS_DENIED: u32 = 1;
pub const ERROR_INVALI... | Rust | 0 |
#[test]
fn test_parse_empty_uri() {
// extra spaces after the version
let mut buffer = RequestBuffer::new(http_token("GET HTTP/1.1"));
let method = buffer.next_token(SP);
assert_eq!(
http_token("GET"),
method.as_http_token(),
"{}",
... | Rust | 0 |
python main.py
| Python | 1 |
"""Common get info functions for static routing"""
# Python
import logging
# Genie
from genie.metaparser.util.exceptions import SchemaEmptyParserError
log = logging.getLogger(__name__)
def get_static_routing_routes(device, vrf, address_family):
"""Execute 'show ip static route vrf <vrf>' and retrieve the route... | Python | 1 |
def compress_pdf_content(pdf_content: bytes, compression_level: str) -> bytes:
"""
Compress PDF content based on the compression level.
"""
print(f"Compressing PDF content with level: {compression_level}")
import fitz
from io import BytesIO
doc = fitz.open(stream=pdf_content, filetype="pdf"... | Python | 1 |
# Copyright (c) 2024, Shanghai Iluvatar CoreX Semiconductor Co., Ltd.
# 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/license... | Python | 1 |
'IHD', 'HS', 'IS', 'Bcancer', 'Ccancer', 'Lcancer', 'DM1']:
excel_file = 'outputs/Raw/scenario_total_%s.xlsx' % ncd_name
xls = pd.ExcelFile(excel_file)
# Initialize an empty dictionary to store your arrays
res_total = {}
# Iterate through each sheet in the Excel file
for sheet_name in xls.shee... | Python | 1 |
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
# Test veri seti yolu
TEST_DATASET_PATH = "data/test"
IMG_SIZE = (224, 224)
BATCH_SIZE = 32
# Test veri hazırlığı
test_datagen = ImageDataGenerator(rescale=1.0/255)
test_generator = test_datagen.flow_from_directory(
TEST_... | Python | 1 |
sult;
use crate::indexes::Interval;
use crate::metadata::{ColumnChunkMetaData, Descriptor};
use crate::page::{
read_dict_page, CompressedDataPage, DataPageHeader, DictPage, EncodedDictPage, PageType,
ParquetPageHeader,
};
use super::PageIterator;
/// Type declaration for a page filter
pub type PageFilter = A... | Rust | 0 |
is
required only when **timeIncrementationMethod** = AUTOMATIC_GLOBAL, AUTOMATIC_EBE, or
FIXED_EBE. The default value is 1.0.
massScaling
A MassScalingArray object specifying mass scaling controls. The default value is
PREVIOUS_STEP.
linearBulkViscosity
... | Python | 1 |
.
Err(err) => Some(Err(err)),
}
}
/*
Copyright The containerd Authors.
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
... | Rust | 0 |
= 100
while x > 0 and not PROXY.exception:
P_MAIN_WINDOW.read(50)
x -= 5
E_MAIN_PROGRESS_BAR.update_bar(x)
E_MAIN_IMAGE.update_animation(
source=IMG_IDLE, time_between_frames=50,
... | Python | 1 |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 12 13:41:24 2024
@author: jaege
"""
import tensorflow as tf
from tensorflow.keras import layers, models
import numpy as np
import matplotlib.pyplot as plt
from keras.datasets import cifar10
from tensorflow.keras.models import Model
# Generator 모델 정의
def build_generator(... | Python | 1 |
}
}
}
use super::super::indexed_vec::IndexVec;
use super::{DirectedGraph, WithNumNodes, WithSuccessors};
use crate::bit_set::BitSet;
#[cfg(test)]
mod test;
pub fn post_order_from<G: DirectedGraph + WithSuccessors + WithNumNodes>(
graph: &G,
start_node: G::Node,
) -> Vec<G::Node> {
post_order_from_to... | Rust | 0 |
0 - cubic.endpoints[1]) * 0.5;
Some(Curve::new(&cubic.endpoints[0],
&approx_control_point_0.lerp(approx_control_point_1, 0.5).to_point(),
&cubic.endpoints[1]))
}
}
<filename>surfman/src/platform/generic/egl/error.rs
// surfman/surfman/src/platform/generic/egl... | Rust | 0 |
#Load in Statsbomb competition and match data
#This is a library for loading json files.
import json
#Load the competition file
#Got this by searching 'how do I open json in Python'
with open('Statsbomb/data/competitions.json') as f:
competitions = json.load(f)
#Womens World Cup 2019 has competition ID 72
com... | Python | 1 |
permutation)?;
if &statistic <= true_statistic {
Ok(0.0)
} else {
Ok(1.0)
}
}
struct PermutationIteration<T: Ord + Clone> {
permutation: Vec<T>,
greater_than_truth: Option<Result<f64>>,
}
fn do_permutation_iteration<T, B>(
algorithm: &B,
true_statistic: &T,
permutation_... | Rust | 0 |
import openai
import pandas as pd
import os
# 读取 OpenAI API Key
from utils import config_manager
config_manager = config_manager.ConfigManager()
api_key = config_manager.get_api_key("openai")
# 初始化 OpenAI 客户端
client = openai.OpenAI(api_key=api_key)
# **Fine-tuned Model (GPT-4o-mini)**
fine_tuned_model = "ft:gpt-4o-m... | Python | 1 |
#!/usr/bin/env python3
import json
from datetime import date
from os import path
from sys import argv
import requests
# This script downloads the statistics of localization of the project from Transifex.
# To be able to use it, you need to provide your user account token
# and run `python3 scripts/load_tx_stats.py ... | Python | 1 |
column.insert(infer(string));
}
}
}
// build schema from inference results
let fields = headers
.iter()
.zip(column_types.into_iter())
.map(|(field_name, mut possibilities)| {
// determine data type based on possible types
... | Rust | 0 |
ion,
Multiple Data) to accelerate the detection of matches in a haystack. Unlike
conventional algorithms, such as Aho-Corasick, SIMD algorithms for substring
search tend to do better with a small number of patterns, where as Aho-Corasick
generally maintains reasonably consistent performance regardless of the number
of ... | Rust | 0 |
std::process::exit(1)
}
}<gh_stars>0
struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
fn build_user(email: String, username: String) -> User {
User {
// Using the Field Init Shorthand when Variables and Fields Have the Same Name
email, //... | Rust | 0 |
=> 4,
LessEq => 4,
Greater => 4,
GreaterEq => 4,
Equality => 4,
NotEq => 4,
And => 3,
Or => 2,
}
}
fn parse_identifier(ctx: &mut ParsingContext, ident: String) -> Expr {
let t = lookup_symbol(&ident, ctx);
Expr::new(ExprKind::Identifier(ident), t)
}... | Rust | 0 |
from twitter.jeetbuzz_twitter_bot import JeetBuzzTwitterBot
import time
# This class contains test cases to automate Telegram actions
class JeetBuzzTwitterAutomation:
def __init__(self):
# Create an instance of the TelegramBot class
self.jeetbuzz_twitter_bot = JeetBuzzTwitterBot()
# Method to r... | Python | 1 |
equest_id(
{
"status": "success",
"message": "Status retrieved",
"robot_state": "active" if robot_state.is_active else "inactive",
"battery_percentage": battery_percentage,
"last_command": robot_state.last_command,
... | Python | 1 |
varying(self, dataset_group_index):
if dataset_group_index is None:
return True
if dataset_group_index < 0:
return True
if not self.layer or not self.layer.dataProvider():
return True
return self.layer.dataProvider().datasetCount(dataset_group_index... | Python | 1 |
import pyglet
from pyglet.gl import glEnable, GL_DEPTH_TEST, GL_CULL_FACE
from pyglet.math import Mat4, Vec3
window = pyglet.window.Window(resizable=True)
batch = pyglet.graphics.Batch()
time = 0
@window.event
def on_resize(width, height):
window.viewport = (0, 0, width, height)
window.projection = Mat4.p... | Python | 1 |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | Python | 1 |
# [imports]
import torch
from torch.nn.parallel import DistributedDataParallel
import modulus
from modulus.datapipes.benchmarks.darcy import Darcy2D
from modulus.distributed import DistributedManager
from modulus.metrics.general.mse import mse
from modulus.models.fno.fno import FNO
from modulus.utils import StaticCapt... | Python | 1 |
from Crypto.Cipher import AES
<target>
func = AES.new('thisisthegoodkey', AES.MODE_ECB)
msg = 'Nguyen Thac Du11'
</target>
cipher = func.encrypt(msg)
print cipher.encode('hex')
print func.decrypt(cipher) | Python | 1 |
AR")]
Sar,
/// Schilling
#[serde(rename = "ATS")]
Ats,
/// Seychelles Rupee
#[serde(rename = "SCR")]
Scr,
/// Singapore Dollar
#[serde(rename = "SGD")]
Sgd,
/// Slovak Koruna
#[serde(rename = "SKK")]
Skk,
/// Solomon Islands Dollar
#[serde(rename = "SBD")]
Sbd,
/// Som
#[serde(rename = "KGS")]
Kgs,
... | Rust | 0 |
g_sharp_image_buffer = NULL;
float4 *g_fuzzy_image_buffer = NULL;
float4 *g_integral_image_buffer = NULL;
// This image buffer is used to store input image initially.
// Then the input image gets updated as each layer is processed from the
// back-most to the focal depth. This image buffer is padded.
static SharpPixel... | Rust | 0 |
# -*- coding: utf-8 -*- # Lint as: python3
# Copyright 2020 Google Inc. 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
#
... | Python | 1 |
nctionCallExpr),
Return {
expr: ValueExpr,
},
Conditional {
condition: ValueExpr,
a: Vec<Stmt>,
b: Option<Vec<Stmt>>,
},
}
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum Type {
Float32,
LinColor,
Str,
Void,
}
#[derive(Debug)]
pub struct Parameter {
... | Rust | 0 |
ust be a hostname, not URL, and must use at most one wildcard."""
if "/" in host:
return False
if host.count("*") > 1:
return False
return True
def nomes_all(where=sys.argv[1:]):
"""Returns generator to extract all files from a list of files/dirs"""
if not where: where=['.']
for... | Python | 1 |
Some(InputKey::DigestIndex(trie_key)) = Decode::decode(&mut &key[..]) {
digest_map.entry(trie_key.key).or_default()
.insert(digest_build_block);
});
}
Ok(digest_map.into_iter()
.map(move |(key, set)| InputPair::DigestIndex(DigestIndex {
block: parent.number + 1,
key
}, set.into_iter().collect()... | Rust | 0 |
"""Elephant figure."""
from chess.core.config import UIConfig
from .base import BaseFigure, FigureColor, FigureRole
class ElephantFigure(BaseFigure):
"""Elephant figure."""
def __init__(self, config: UIConfig, color: FigureColor):
super().__init__(config, role=FigureRole.ELEPHANT, color=color)
... | Python | 1 |
# Copyright 2009-2011 Ram Rachum.
# This program is distributed under the LGPL2.1 license.
'''Module for testing the abstract methods of `ContextManager`.'''
from __future__ import with_statement
import sys
import nose
from garlicsim.general_misc.context_manager import (ContextManager,
... | Python | 1 |
sk, :] = alpha * img[mask, :] + (1 - alpha) * color[:]
obj_pose = obj_pose_dict[obj_label]
obj_center = self.project2d(self.intrinsic, obj_pose[:3, -1])
rgb_colors = [(0, 0, 255), (0, 255, 0), (255, 0, 0)]
for j in range(3):
... | Python | 1 |
.into_iter()
.collect::<Result<_, _>>()?;
Ok(caps)
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Item {
pub guid: String,
pub link: String,
}
use crate::prelude::tz::*;
use chrono::offset::{Offset, TimeZone};
use chrono::{Datelike, FixedOffset, NaiveDate, NaiveDateTime};
use chrono_tz::Chile::*;
use std::s... | Rust | 0 |
efault();
let interner:StringInterner<StringSymbol> = StringInterner::<StringSymbol>::new();
let mut instance = Self{model:model,funcLib:funcLib,interner:interner,topLevel:topLevel};
{
instance.recalculate();
}
instance
}
fn newFromJson(json:&str , funcLib: F... | Rust | 0 |
transactions to run universe-based proptests with. Set with the `UNIVERSE_SIZE`
/// environment variable (this function will return twice that).
///
/// Larger values will provide greater testing but will take longer to run and shrink. Release mode
/// is recommended for values above 100.
#[inline]
pub(crate) fn defau... | Rust | 0 |
for xx in (x - inf_radius)..=(x + inf_radius) {
for yy in (y - inf_radius)..=(y + inf_radius) {
if grid.contains(xx, yy) {
*counter.get_mut(xx as usize, yy as usize) += 1;
... | Rust | 0 |
iance between -30 and 20, so that the variance is between (circa) 1e-14 and 1e8.
# (Batch_Size, 4, Height / 8, Width / 8) -> (Batch_Size, 4, Height / 8, Width / 8)
log_variance = torch.clamp(log_variance, -30, 20)
# (Batch_Size, 4, Height / 8, Width / 8) -> (Batch_Size, 4, Height / 8, Width / 8... | Python | 1 |
wrap();
// let vector = args[2..]
// .into_iter()
// .map(|string| string.parse::<f32>().unwrap())
// .collect();
// let result = multiply(vector, scalar).unwrap();
// dbg!(result);
// }
// This example has been taken from the OCL crate
// emu for writing code
extern crate em;
us... | Rust | 0 |
Cone;
// TODO: Remove this module after switching to DAG v2.
#[derive(PartialEq, Eq, Clone)]
pub enum Cone {
Point(PointCone),
Interval(IntervalCone),
}
impl Cone {
pub fn from__timeshare_cone(mut cone: KeyCone, accept_point_cone: bool) -> Self {
if accept_point_cone && crate::util::is_point(&con... | Rust | 0 |
"""Data representation for fitbit API responses."""
from collections.abc import Mapping
from dataclasses import dataclass
from typing import Any
from .const import CONF_CLOCK_FORMAT, CONF_MONITORED_RESOURCES, FitbitScope
@dataclass
class FitbitProfile:
"""User profile from the Fitbit API response."""
encod... | Python | 1 |
import pytest
from src.logs_handler import LogsHandler
from src.path_handler import PathHandler
@pytest.mark.parametrize(
"params",
(
{"from": "ss", "path": "aboba"},
{"from": "ss"},
{"path": "https://vk.com/alsldla"},
),
)
def test_logs_handler_wrong_input(params):
path_handl... | Python | 1 |
import torch
import torchmetrics
from loguru import logger
class AUCMetric():
def __init__(self):
self.softmax = torch.nn.Softmax(dim=1)
def __call__(self, logits, labels):
"""
Parameters
----------
logits
output of the model
labels
... | Python | 1 |
{
'name': 'test of access rights and rules',
'description': "Testing of access restrictions",
'version': '0.0.1',
'category': 'Hidden/Tests',
'data': [
'ir.model.access.csv',
'security.xml',
'data.xml',
],
'license': 'LGPL-3',
}
| Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.