text string | label_name string | labels int64 |
|---|---|---|
MTU_UDP as u16;
let ip_repr = Ipv4Repr {
src_addr: src_addr,
dst_addr: dst_addr,
protocol: IpProtocol::Udp,
payload_len: remaining_len,
hop_limit: 64,
};
let ip_packet = {
let mut ip_pack... | Rust | 0 |
=> {
register_barrier(call.current_rank, call.comm, call.tsc, call.duration)
}
MpiCallType::Ibarrier => register_ibarrier(
call.current_rank,
call.comm,
call.req,
call.tsc,
call.duration,
),
MpiCallType::Test => reg... | Rust | 0 |
# 15. 3Sum
# Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
# Notice that the solution set must not contain duplicate triplets.
# Example 1:
# Input: nums = [-1,0,1,2,-1,-4]
# Output: [[-1,-1,2],[-1,0,1]]... | Python | 1 |
et mut errcode: cl_int = 0;
let program_ptr = unsafe { ffi::clCreateProgramWithIL(
context.as_ptr(),
il.as_ptr() as *mut c_void,
il.len(),
&mut errcode,
) };
eval_errcode(errcode, program_ptr, "clCreateProgramWithIL", None::<String>)
.map(|ptr| unsafe { Program::fro... | Rust | 0 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from botbuilder.core import ActivityHandler, TurnContext
from botbuilder.schema import ChannelAccount
import os
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from foundry_local... | Python | 1 |
"attributes")]
pub attributes: ::std::collections::HashMap<String, String>,
/// <p>The name of the 'addAttributes' activity.</p>
#[serde(rename = "name")]
pub name: String,
/// <p>The next activity in the pipeline.</p>
#[serde(rename = "next")]
#[serde(skip_serializing_if = "Option::is_none... | Rust | 0 |
# TencentBlueKing is pleased to support the open source community by making
# 蓝鲸智云 - PaaS 平台 (BlueKing - PaaS System) available.
# Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
# Licensed under the MIT License (the "License"); you may not use this file except
# in compliance with the Licen... | Python | 1 |
wick()
assert u_a != u_c
def test_interpret_tree_arg_none():
assert tree_app.interpret_tree_arg(None) is None
@pytest.mark.parametrize(
"tree",
[
DATA_DIR / "brca1_5.tree",
str(DATA_DIR / "brca1_5.tree"),
"(a,b,c)",
cogent3.make_tree(tip_names=["a", "b", "c"]),
... | Python | 1 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
from .Lib.DaemonClass import Daemon
class MainProcess(Daemon):
def run(self, debug_mode):
from .Core.UMRManager import UMRManager
UMRManager.run()
def main():
# ARGS
argP = argparse.ArgumentParser(
description="QQ <->... | Python | 1 |
n: varint::VarUint = digest_function.into();
let mut digest_function = digest_function.into();
bytes.append(&mut digest_function);
bytes.push(
multihash
.payload
.len()
.try_into()
.map_err(|_e| ConvertError::new(String:... | Rust | 0 |
_kms( position1.get_km_by_ms( ms_src ));
if sn_ms == sn && kms_ms == *kms { hashset_result.insert( ms_src); }
},
// 北北西
NNW =>{
if SUJI_0<dx-1 && dy+2<DAN_10 {
let ms_src = suji_dan_to_ms(dx... | Rust | 0 |
"BoolAsInt" => PrimitiveType::BoolAsInt,
name => PrimitiveType::NamedType(name.to_string()),
};
Ok(parsed_primitive_type)
}
fn parse_enum(enumeration: Pair<'_>) -> Result<Definition> {
let mut enum_elements = enumeration.into_inner();
let name = next_match(&mut enum_elements, Rule::id... | Rust | 0 |
))
}
}
pub fn is_safe_to_compass_direction(&self, dir: CompassDirection) -> bool {
self.is_safe_to_delta_xy(dir.get_delta_xy())
}
pub fn get_to_compass_direction(&self, dir: CompassDirection) -> Result<Position, Error> {
self.get_to_delta_xy(dir.get_delta_xy())
... | Rust | 0 |
.value_of("start_time")
.expect("Start time is a required field")
.parse::<DateTime<Utc>>()
.map_err(|_| {
String::from("Start time should be in ISO 8601 format, ex: x2017-11-28T12:00:09Z")
})?
.timestamp() as u64 * 1_000;
endpoi... | Rust | 0 |
let label = Label::builder()
.label("Language:")
.build();
grid.attach(&label, 0, 2, 1, 1);
let language_combo = Rc::new(ComboBoxText::new());
grid.attach(language_combo.as_ref(), 1, 2, 1, 1);
thread::spawn(move || {
let datadir = get_datadir();
let cachedir = get_... | Rust | 0 |
if "clean_alg_mean_identn" in node.features:
identity = node.clean_alg_mean_identn
elif "alg_mean_identn" in node.features:
identity = node.alg_mean_identn
if "highlighted" in node.features:
node.img_style["bgcolor"] = "LightCyan"
if "improve" in node.features:
color = "or... | Python | 1 |
n_type = EthTokenType::Erc20.to_string();
eth.m.contract_address = "0x6f259637dcd74c767781e37bc6133cd6a68aa161".to_owned();
eth.eth_chain_token_shared.decimal = 18;
eth.eth_chain_token_shared.gas_limit = 0; //todo
eth.eth_chain_token_shared.gas_price = "".to_owned(); //to... | Rust | 0 |
, data) };
Handle::new_internal(JsArrayBuffer(value))
}
}
impl Managed for JsArrayBuffer {
fn to_raw(self) -> raw::Local {
self.0
}
fn from_raw(_env: Env, h: raw::Local) -> Self {
JsArrayBuffer(h)
}
}
impl ValueInternal for JsArrayBuffer {
fn name() -> String {
... | Rust | 0 |
}
})
.flatten()
.collect::<Vec<_>>();
DatadogRequest { series }
}
#[cfg(test)]
mod tests {
use super::*;
use crate::event::metric::{Metric, MetricKind, MetricValue};
use crate::sinks::util::{http::HttpSink, test::load_sink};
use crate::test_util::runtime;
us... | Rust | 0 |
scheme registrar, and so on.
pub mod env;
/// File system.
///
/// This module manages virtual and non-virtual file systems. Furthermore, it defines URL,
/// `Scheme`, and `Resource`.
pub mod fs;
/// Graphic management.
///
/// This module contains the initial display manager and various graphics primitives.
pub mod g... | Rust | 0 |
import RPi.GPIO as GPIO
import time
import curses
# Set GPIO mode and pins
GPIO.setmode(GPIO.BOARD)
PUL_PIN = 16
DIR_PIN = 12
# Set up GPIO pins
GPIO.setup(PUL_PIN, GPIO.OUT)
GPIO.setup(DIR_PIN, GPIO.OUT)
# Function to control stepper motor
def stepper_control(direction):
GPIO.output(DIR_PIN, direction) # Set d... | Python | 1 |
[
component.salary_component for component in applicable_earnings_component
]
return applicable_earnings_component
def get_total_applicable_component_amount(employee, applicable_earnings_component, gratuity_rule):
sal_slip = get_last_salary_slip(employee)
if not sal_slip:
frappe.throw(_("No Salary Slip is fo... | Python | 1 |
build()
.await
.unwrap();
let exit_status = test.component_manager_app.wait().await.unwrap();
assert!(exit_status.success(), "component_manager failed to exit: {:?}", exit_status.reason());
}
<reponame>marot/nakama-rs<filename>examples/async.rs
use std::collections::HashMap;
use std::future::Fut... | Rust | 0 |
from typing import List
import numpy as np
from pymatgen.core import Molecule
from pymatgen.analysis.molecule_matcher import (
BruteForceOrderMatcher,
GeneticOrderMatcher,
HungarianOrderMatcher,
KabschMatcher,
)
from pymatgen.io.xyz import XYZ
from torch import Tensor
def xh2pmg(xh):
mol = Molec... | Python | 1 |
from vaultweaver.core.notes import extract_links_and_tags
def test_extract_links_and_tags():
s = "Hello [[World Note]] and #tag1 #tag2."
meta = extract_links_and_tags(s)
assert "World Note" in meta["links"]
assert "tag1" in meta["tags"] and "tag2" in meta["tags"]
| Python | 1 |
size".to_string(), page_size.to_string()));
}
if !status.to_string().is_empty() {
query_args.push(("status".to_string(), status.to_string()));
}
if !tracking_source_id.is_empty() {
query_args.push((
"tracking_source_id".to_string(),
... | Rust | 0 |
self.value, f)
}
}
#[cfg(test)]
mod tests {
use super::*;
use fnv::FnvBuildHasher;
use fxhash::FxBuildHasher;
type Filter = BloomFilter<FnvBuildHasher, FxBuildHasher>;
#[test]
fn lookup() {
let data = "a quick brown fox";
let needle1 = "quick";
let needle2 = "wn fo... | Rust | 0 |
# coding: utf-8
import io
import re
import xlwt
from pyxform import xls2json_backends
def convert_csv_to_xls(csv_repr):
"""
This method should be moved into pyxform
"""
# There should not be any blank lines in the "sheeted" CSV representation,
# but often times there are. Strip them out before an... | Python | 1 |
recpeq_f32(x: f32x4) -> f32x4;
fn arm_vrecps_f32(x: f32x2, y: f32x2) -> f32x2;
fn arm_vrecpsq_f32(x: f32x4, y: f32x4) -> f32x4;
fn arm_vsqrt_f32(x: f32x2) -> f32x2;
fn arm_vsqrtq_f32(x: f32x4) -> f32x4;
fn arm_vrsqrte_u32(x: u32x2) -> u32x2;
fn arm_vrsqrte_f32(x: f32x2) -> f32x2;
fn arm_vrsq... | Rust | 0 |
try:
with open(fname) as infile:
results = json.load(infile)
f1 = results['f1']
print(feature, num_layers, f1)
scores[num_layers - 1] = f1
except FileNotFoundError:
print('Skipping', f... | Python | 1 |
lticompartmental: bool = True,
exclusion_prefixes: list[str] = [],
exclusion_inner_parts: list[str] = [],
ignore_uncertainty: bool = False,
max_uncertainty: float = 1_000.0,
) -> tuple[dict[str, float], dict[str, float]]:
"""Compute standard Gibbs free energies (and uncertainties) for all reactions ... | Python | 1 |
clone());
}: _(RawOrigin::Signed(origin.clone()), who.clone(), BALANCE)
verify {
assert_eq!(crate::Pallet::<T>::is_mining_origin(&origin.clone()), true);
assert_eq!(T::MiningCurrency::free_balance(FungibleTokenId::MiningResource(0), &who.clone()), 1100);
}
// burn
burn {
let origin: T::AccountId = funded_ac... | Rust | 0 |
import os
import torch, torchvision
import cifar10.models.vgg as vgg
import cifar10.models.resnet as resnet
import cifar10.models.densenet as densenet
# map between model name and function
models = {
'vgg9' : vgg.VGG9,
'densenet121' : densenet.DenseNet121,
'resnet18' ... | Python | 1 |
let batch = builder.finish();
self.current_row_id += remaining_cnt;
Ok(Some((first_row_id, batch)))
}
}
fn fetch_hint(&self) -> usize {
self.row_count - self.current_row_id
}
fn fetch_current_row_id(&self) -> u32 {
self.current_row_id as u32
... | Rust | 0 |
import requests
from bs4 import BeautifulSoup
import re
# Function to extract keywords from a webpage
def extract_keywords(url):
# Send a GET request to the webpage
response = requests.get(url)
# Check if the request was successful (status code 200)
if response.status_code == 200:
# Parse ... | Python | 1 |
from __future__ import absolute_import
from abc import ABCMeta, abstractmethod
import six
def usedb(func):
def func_wrapper(*args, **kwargs):
args[0]._opendb()
x = func(*args, **kwargs)
args[0]._closedb()
return x
return func_wrapper
class RunDB(six.with_metaclass(ABCMeta, o... | Python | 1 |
from telegram.ext import CommandHandler, run_async
from bot import download_dict, dispatcher, download_dict_lock, DOWNLOAD_DIR
from bot.helper.ext_utils.fs_utils import clean_download
from bot.helper.telegram_helper.bot_commands import BotCommands
from bot.helper.telegram_helper.filters import CustomFilters
from bot.h... | Python | 1 |
# AI 엔지니어인 현식이는 데이터를 분석하는 작업을 진행하고 있습니다.
# 데이터는 ["코드 번호(code)", "제조일(date)", "최대 수량(maximum)", "현재 수량(remain)"]으로 구성되어 있으며 현식이는 이 데이터들 중 조건을 만족하는 데이터만 뽑아서 정렬하려 합니다.
# 예를 들어 다음과 같이 데이터가 주어진다면
# data = [[1, 20300104, 100, 80], [2, 20300804, 847, 37], [3, 20300401, 10, 8]]
# 이 데이터는 다음 표처럼 나타낼 수 있습니다.
# code date maxim... | Python | 1 |
from string import digits, ascii_uppercase
from itertools import product
alph = digits + ascii_uppercase
alph = alph[:12]
chet = ''.join([i for i in alph if (alph.index(i)+1)%2==0])
nechet = ''.join([i for i in alph if (int(i, 12)+1)%2==0])
def con(num):
res = ''
while num:
res += alph[num%12]
... | Python | 1 |
n)]
pub struct _MSG2VAL;
#[doc = "`read()` method returns [msg2val::R](msg2val::R) reader structure"]
impl crate::Readable for MSG2VAL {}
#[doc = "CAN Message 2 Valid"]
pub mod msg2val;
<reponame>errx/rust-analyzer<gh_stars>1000+
fn main() {
match 92 {
0 ... 100 => (),
101 ..= 200 => (),
200... | Rust | 0 |
from typing import Optional
from piel.types import DataTimeSignalAnalysisTypes, Instance, Unit, ratio
class ParsedColumnInfo(Instance):
analysis_type: DataTimeSignalAnalysisTypes = "delay"
unit: Unit = ratio
channels: str = ""
index: Optional[int] = 0
| Python | 1 |
"""
Classifies: CHEBI:73155 trienoic fatty acid
"""
"""
Classifies: trienoic fatty acid
"""
from rdkit import Chem
from rdkit.Chem import rdMolDescriptors
def is_trienoic_fatty_acid(smiles: str):
"""
Determines if a molecule is a trienoic fatty acid based on its SMILES string.
A trienoic fatty acid is any ... | Python | 1 |
import streamlit as st
from utils.build_graph import retrieve_from_graph
from langchain_core.documents import Document
import requests
# 🚀 Query Expansion with HyDE
def expand_query(query,uri,model):
try:
response = requests.post(uri, json={
"model": model,
"prompt": f"Generate a h... | Python | 1 |
s hfm9kv6ugfq, pt9xwrpygxb, hkayp82ycuz as csv779qrihn, lkk0ereuebv, fhl9cg0lrym
no8ze2bvp6_: '' = l4_wtbua452
jx0z7btn9m4 = mm31w18_yop = cx6_a8jxxo8 = p5t_5bahvm3 = vws2h86tng2 = y2ily73kjbu = bnca5aqx8f7 = ath16b44563 = ba5vrr0bz8l = ckwz3cwsgd9
def su2q2dos_9t(rh_de_tiy8x: aefjmaoy26s, w4nr20gfthj, yxtbna5z... | Python | 1 |
er::Action::Fold,
8 => input = player::Action::Raise,
9 => input = player::Action::Raise,
10 => input = player::Action::Fold,
_ => input = player::Action::Call,
}
match input {
... | Rust | 0 |
libc::c_int;
// Used in `Domain`.
pub(crate) use libc::{AF_INET, AF_INET6};
// Used in `Type`.
pub(crate) use libc::{SOCK_DGRAM, SOCK_RAW, SOCK_SEQPACKET, SOCK_STREAM};
// Used in `Protocol`.
pub(crate) use libc::{IPPROTO_ICMP, IPPROTO_ICMPV6, IPPROTO_TCP, IPPROTO_UDP};
// Used in `Socket`.
pub(crate) use std::os::un... | Rust | 0 |
// 상하좌우
n = 5
input = "R R R U D D"
commands = list(map(str, input.split()))
x, y = 1, 1
for c in commands:
match c:
case "L":
if y > 1:
y -= 1
case "R":
if 5 > y:
y += 1
case "U":
if x > 1:
x -= 1
... | Python | 1 |
-nyhkl-lnn-lunpullypun-201[tqlba]
uiovmbqk-kivlg-bmkpvwtwog-720[kpvsu]
nchhg-xtiabqk-oziaa-zmamizkp-850[aizhk]
molgbzqfib-zixppfcfba-gbiivybxk-pqloxdb-237[igmjz]
jyfvnlupj-jhukf-jvhapun-yljlpcpun-539[dmnws]
hqtyeqsjylu-sqdto-tufqhjcudj-712[cnysz]
gsvvswmzi-gerhc-gsrxemrqirx-100[dlypm]
ktwbhtvmbox-xzz-vhgmtbgfxgm-709[bg... | Rust | 0 |
ent and expression contained within it"""
ret = trace_walk_func(tree, exact_src)
yield ret
def require_transform(tree, exact_src):
ret = trace_walk_func(copy.deepcopy(tree), exact_src)
trace_walk_func(copy.deepcopy(tree), exact_src)
new = hq[ast_literal[tree] or wrap_require(lambda log: ast_litera... | Python | 1 |
ter('here_category_name'))
async def prod_category_add_name_get(message: Message, bot: Bot, state: FSM, arSession: ARS):
if len(message.text) > 50:
return await message.answer(
"<b>❌ Название не может превышать 50 символов</b>\n"
"🗃 Введите название для категории",
)
aw... | Python | 1 |
ng_spec(),
custom_sharder.rowwise_spec,
)
self.assertEqual(
emb_bags["embedding_bag_9"].weight.sharding_spec(),
custom_sharder.colwise_spec,
)
# make sure we can run sharded computation and compare outputs
# with the local model version
... | Python | 1 |
w_from_key_file<'a, P: Into<Option<&'a str>>>(key_file: &glib::KeyFile, group_name: P) -> Result<PageSetup, Error> {
assert_initialized_main_thread!();
let group_name = group_name.into();
let group_name = group_name.to_glib_none();
unsafe {
let mut error = ptr::null_mut();
... | Rust | 0 |
es. Shape: (num_res, 14).
num_res = act.shape[0]
unnormalized_angles = common_modules.Linear(
14, name='unnormalized_angles')(
jax.nn.relu(act))
unnormalized_angles = jnp.reshape(
unnormalized_angles, [num_res, 7, 2])
angles = l2_normalize(unnormalized_angles, axis=-1)
o... | Python | 1 |
crop_to_panel(
panel: np.ndarray,
crop: np.ndarray,
color: tuple[int, int, int],
crop_x: int,
crop_y: int,
):
"""Add detection crop to side panel."""
target_size = 80
crop_h, crop_w = crop.shape[:2]
# Resize if needed
if crop_h > target_size or crop_w > target_size:
scal... | Python | 1 |
num = int(input("Enter the Number for Calculating factorial"))
fact=1
for i in range(num):
fact = fact*num
num -= 1
print(fact)
#Factorial using recursion:
n = int(input("Enter number: "))
def factorial(n):
if n == 1:
return n
return factorial(n-1)*n
print(factorial(n))
| Python | 1 |
def f(nums):
copy = nums.copy()
newDict = dict()
for k in copy:
newDict[k] = len(copy[k])
return newDict | Python | 1 |
callback(step_idx, timestep, latents)
if output_type == "latent":
output = latents
else:
output = self.vqvae.decode(
latents,
force_not_quantize=True,
shape=(
batch_size,
height... | Python | 1 |
in32_System_Registry\"`*"]
pub const REGSTR_VAL_PRESERVECASE: &str = "PreserveCase";
#[doc = "*Required features: `\"Win32_System_Registry\"`*"]
pub const REGSTR_VAL_PRESERVELONGNAMES: &str = "PreserveLongNames";
#[doc = "*Required features: `\"Win32_System_Registry\"`*"]
pub const REGSTR_VAL_PRINTERS_HIDETABS: &str = ... | Rust | 0 |
from .. import algebra
import numpy as np
from .. import green
from ..hamiltonians import is_number
dagger = algebra.dagger
# Landauer Buttiker formula
def landauer(HT,energy=0.0,error=1e-9,**kwargs):
""" Calculates transmission using Landauer formula"""
delta = HT.delta
if not HT.block_diagonal:
i... | Python | 1 |
from playwright.sync_api import Page, expect
from shiny.playwright import controller
from shiny.playwright.expect._internal import _expect_nav_to_have_header_footer
from shiny.run import ShinyAppProc
def test_page_navbar_header_footer_fixed_top(
page: Page, local_app: ShinyAppProc
) -> None:
page.goto(local_... | Python | 1 |
from woningwaardering.vera.bvg.generated import Referentiedata
from woningwaardering.vera.referentiedata.onderhoudstaakstatus import (
Onderhoudstaakstatus,
)
from woningwaardering.vera.referentiedatasoort import Referentiedatasoort
class OnderhoudstaakdetailstatusReferentiedata(Referentiedata):
pass
class ... | Python | 1 |
import secrets
# Generate a random 32-byte hexadecimal key
SECRET_KEY = '4817aec6002d5fdb9d3a50e2f4d5ca05b78a81ff9e7e2452733c99445262b741'
ALGORITHM = "HS256" | Python | 1 |
f __subclasscheck__(cls, subclass):
"""Override for issubclass(subclass, cls)."""
if not isinstance(subclass, type):
raise TypeError('issubclass() arg 1 must be a class')
# Check cache
if subclass in cls._abc_cache:
return True
# Check negative cache; may ... | Python | 1 |
.current_dir(output_path)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output()
.expect("Failed to execute shell script");
Ok(vec![bundle_sh])
}
// Copyright (c) 2017-present PyO3 Project and Contributors
//
// based on <NAME>'s https://github.com/dgrunwald/rust-cpython
//! Functionality fo... | Rust | 0 |
import numpy as np
import sys
#from scipy.stats import rv_discrete
import os.path
Ne=float(sys.argv[1])
id=int(sys.argv[2])
i=int(sys.argv[3])
Q=float(sys.argv[4])
program=sys.argv[5]
#hyperparameters
rho = np.random.uniform(3e-9,2e-8) #np.random.uniform(3e-9,2e-8) draw_truncated_exponential(1e-8, 3e-8)
mu = np.ran... | Python | 1 |
#[doc = r" Reserved"]
_Reserved(u8),
}
impl PMUXER {
#[doc = r" Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
PMUXER::A => 0,
PMUXER::B => 1,
PMUXER::C => 2,
... | Rust | 0 |
"""
SGDP Optimizer Implementation copied from https://github.com/clovaai/AdamP/blob/master/adamp/sgdp.py
Paper: `Slowing Down the Weight Norm Increase in Momentum-based Optimizers` - https://arxiv.org/abs/2006.08217
Code: https://github.com/clovaai/AdamP
Copyright (c) 2020-present NAVER Corp.
MIT license
"""
import ... | Python | 1 |
assert_eq!(received_person_and_receiver.0, person);
sub_tx.send(person.clone()).unwrap();
let received_person = received_person_and_receiver.1.recv().unwrap();
assert_eq!(received_person, person);
}
#[test]
fn select() {
let (tx0, rx0) = ipc::channel().unwrap();
let (tx1, rx1) = ipc::channel()... | Rust | 0 |
# This file computes the mapping from Homosaurus to LCSH.
# The exported file is Homosaurus_links_to_LCSH.nt
from rdflib import Graph
from collections import Counter
from rdflib import URIRef, Literal
import csv
gv2 = Graph()
gv2.parse("../v2.ttl")
gv3 = Graph()
gv3.parse("../v3.ttl")
ex = 'http://www.w3.org/200... | Python | 1 |
efect:
raise HTTPException(status_code=404, detail="Дефект не найден")
db_engineer = db.query(models.User).filter(
models.User.id == engineer_data.engineer_id,
models.User.role == models.UserRole.ENGINEER
).first()
if not db_engineer:
raise HTTPException(status_code=404, de... | Python | 1 |
o = (izquierda + derecha) // 2
if lista[medio] == numero:
return medio
elif lista[medio] < numero:
izquierda = medio + 1
else:
derecha = medio - 1
return -1
import random # Importa la librería random para generar números aleatorios
# Función que permit... | Python | 1 |
pNorm_Mean.py",
"28_BMM_InstanceNorm_Sum_ResidualAdd_Multiply.py",
"33_Gemm_Scale_BatchNorm.py",
"43_Conv3d_Max_LogSumExp_ReLU.py",
]
level2_representative_subset_problem_ids = [1, 2, 8, 18, 23, 28, 33, 43]
level3_representative_subset = [
"1_MLP.py",
"5_AlexNet.py",
"8_ResNetBasicBlock.py",
... | Python | 1 |
# Write a function that will return the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string. The input string can be assumed to contain only alphabets (both uppercase and lowercase) and numeric digits.
# Example
# "abcde" -> 0 # no characters repeat... | Python | 1 |
FieldElement([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
pub(crate) static FE_ONE: FieldElement =
FieldElement([1, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
pub(crate) static FE_SQRTM1: FieldElement = FieldElement([
-32_595_792,
-7_943_725,
9_377_950,
3_500_415,
12_389_472,
-272_473,
-25_146_209,
-2_00... | Rust | 0 |
ile = join(dataset_dir, 'train.txt')
self.val_file = join(dataset_dir, 'dev.txt')
self.test_file = join(dataset_dir, 'test.txt')
self.filelist = [self.train_file, self.val_file, self.test_file]
if self.binary:
self.n_classes = 2
else:
self.n_class... | Python | 1 |
let repr_state = tensor_to_ndarray(next_board_tensor, hidden_shape);
let reward = if support_size > 0 {
tf::support_to_value(&reward, 1, support_size)[0]
} else {
reward[0]
};
DynamicsNetworkOutput { repr_state, reward }
}
/// State to representation for Muz - single batch
pub fn rep... | Rust | 0 |
| ReadyProducerWait | ConsumerNotify | ConsumerNotifyProducerWait => true,
_ => false,
}
}
fn is_producer_ready(&self) -> bool {
self.is_consumer_wait() || self.is_canceled()
}
fn is_canceled(&self) -> bool {
match self.lifecycle() {
Canceled => true,
... | Rust | 0 |
ed {len(restaurant.reviews)} reviews")
with open(f"{JSON_OUT}/{restaurant.name}.json", "w") as fd:
json.dump([review.ratings for review in restaurant.reviews], fd, indent=4)
ramsay_print_valid(f"Reviews have been written to {JSON_OUT}/{restaurant.name}.json")
ramsay_print_valid(f"Successfully ... | Python | 1 |
add_to(acc);
}
fn add_type_alias_impl(
type_def_node: &SyntaxNode,
acc: &mut Completions,
ctx: &CompletionContext,
type_alias: hir::TypeAlias,
) {
let alias_name = type_alias.name(ctx.db).to_string();
let snippet = format!("type {} = ", alias_name);
let range = TextRange::new(type_def_nod... | Rust | 0 |
"""
URL configuration for honeyport project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/5.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='ho... | Python | 1 |
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent))
from fastapi import File, UploadFile
from fastapi import APIRouter
from schemas.catdog_schema import CatDogResponse
from config.catdog_cfg import ModelConfig
from models.catdog_predictor import Predictor
router = APIRouter()
predictor = P... | Python | 1 |
) << 16)
| ((input[input.len() >> 1] as u32) << 24)
| (input[input.len() - 1] as u32)
| ((input.len() as u32) << 8);
let flip = ((read_32le_unaligned(secret.as_ptr()) ^ read_32le_unaligned(slice_offset_ptr(secret, 4))) as u64).wrapping_add(seed);
xxh64::avalanch... | Rust | 0 |
import heapq
def initialize():
# Define the adjacency matrix representing the connections between the cities
adjacency_matrix = [[0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1],
[0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0... | Python | 1 |
from typing import Optional
from matchms.filtering.filter_utils.get_neutral_mass_from_smiles import get_monoisotopic_neutral_mass
from matchms.typing import SpectrumType
def require_parent_mass_match_smiles(spectrum_in: SpectrumType, mass_tolerance) -> Optional[SpectrumType]:
"""
Validates if the parent mass ... | Python | 1 |
/// <(Sender1, Sender3) as SendXcm>::send_xcm(Parent, message.clone())
/// .is_ok()
/// );
/// # }
/// ```
pub trait SendXcm {
/// Send an XCM `message` to a given `destination`.
///
/// If it is not a destination which can be reached with this type but possibly could by others, then it *MUST*
/// retur... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from datetime import datetime
import json
import logging
import time
import redis
from tipboard import settings
log = lo... | Python | 1 |
d_chunk, since it's
# non-trivial to calculate `next_cache_start` here.
new_cache = torch.cat((k, v), dim=-1)
n_batch_pos = pos_emb.size(0)
p = self.linear_pos(pos_emb).view(n_batch_pos, -1, self.h, self.d_k)
p = p.transpose(1, 2) # (batch, head, time1, d_k)
# (batch... | Python | 1 |
lf.in_features
assert y.size() == (x.size(0), self.in_features, self.out_features)
A = self.b_splines(x).transpose(
0, 1
) # (in_features, batch_size, grid_size + spline_order)
B = y.transpose(0, 1) # (in_features, batch_size, out_features)
solution = torch.linalg.... | Python | 1 |
def compute_zico(grad_dict, mode='sum'):
for modname in grad_dict:
grad_dict[modname] = np.array(grad_dict[modname])
if mode not in ('sum', 'mean'):
raise ValueError(
f'`mode` argument for the ZiCo metric should be one of (`sum`, `mean`), but got {mode}'
)
nsr_mean_ab... | Python | 1 |
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_csv("survey.csv") # THIS IS THE SURVEY!! CALL 'DATA" TO ACCESS THE DATASET
# def image(): # rida q1
def staffAttitude():
# Do the staff in tech companies have a good attitude towards mental health?
# Columns used: coworkers, supervisors, seek_help
... | Python | 1 |
return Err(Kind::EmptyResponseProof.into());
}
let raw_proof_ops = response
.proof
.map(ProofOps::try_from)
.transpose()
.map_err(|e| Kind::MalformedProof.context(e))?;
let response = QueryResponse {
value: response.value,
proof: MerkleProof {
pr... | Rust | 0 |
);
println!("Reset...");
reset(port as u8);
println!("Done.");
return;
}
println!("Server {} unknown", server);
std::process::exit(1);
}
<gh_stars>1-10
extern crate futures;
extern crate stream_combinators;
use futures::stream::{iter_ok, Stream};
use futures::Future;
use str... | Rust | 0 |
# Copyright (c) 2023-2024, NVIDIA CORPORATION.
#
# 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 agre... | Python | 1 |
import math
import chainer
import chainer.functions as F
from chainer import links as L
from source.links.categorical_conditional_batch_normalization import CategoricalConditionalBatchNormalization
def _downsample(x):
# Down sampling
return F.average_pooling_2d(x, 2)
def downsample_conv(x, conv):
return... | Python | 1 |
ool,
"subscriber",
"system-msg" as String,
"target-msg-id",
"tmi-sent-ts" as u64,
"turbo",
"user-id" as u64,
"user-type",
"msg-param-cumulative-months" as u64,
"msg-param-displayName",
"msg-param-login",
"msg-param-months" as u64,
"msg-param-promo-gift-total" as u64,
... | Rust | 0 |
subsystem.window("TELLO drone", 1280, 720).build().unwrap();
//! let mut canvas = window.into_canvas().build().unwrap();
//!
//! let mut event_pump = sdl_context.event_pump()?;
//! 'running: loop {
//! // draw some stuff
//! canvas.clear();
//! // [...]
//!
//! // handle inpu... | Rust | 0 |
: ToString,
{
type Output = ();
fn call<DI>(&mut self, data: &DI) -> Self::Output
where
DI: DataIndex<DType = DType>,
{
debug_assert!(data.len() >= self.rows.len());
for i in 0..self.rows.len() {
self.rows[i].add_cell(cell!(data.get_datum(i).unwrap()));
}
... | Rust | 0 |
1FFF => if data == 0 {
mbc.ram_enabled = false;
} else if data & 0x0F == 0x0A {
mbc.ram_enabled = true;
},
// (Lower) ROM bank select
0x2000..=0x3FFF => {
// This is used to select the lower 5 bi... | Rust | 0 |
import sys
import logging
from features.feature import Feature
class FlowAck(Feature):
def __init__(self, name):
super().__init__(name, "flow")
# Please implement the following function
def extract_feature(self, window):
fpkts = window.get_packets("forward")
bpkts = window.get_pack... | Python | 1 |
return sorted(list(set(image_models)))
except Exception as e:
print(f"Error fetching Gemini image models: {str(e)}")
print("Using default image model list.")
return fallback_models
if __name__ == "__main__":
print("\n=== Gemini Models ===")
gemini_models = get_gemini_models()
f... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.