text string | label_name string | labels int64 |
|---|---|---|
.private_caps.low_power,
adapt.physical_device.shared.private_caps.headless,
)
});
adapters
}
unsafe fn create_surface(
&self,
has_handle: &impl raw_window_handle::HasRawWindowHandle,
) -> Result<Surface, hal::window::InitError> {
match ha... | Rust | 0 |
er = Cursor::new(images_mmap.clone());
let magic = reader.read_u32::<BigEndian>().unwrap();
assert_eq!(0x803, magic);
let num_items = reader.read_u32::<BigEndian>().unwrap();
let num_rows = reader.read_u32::<BigEndian>().unwrap();
let num_cols = reader.read_u32::<BigEndian>().unwrap();
... | Rust | 0 |
Ok(Some(Token::OP(TokenMeta { pos: 12 }, OpType::MUL)))));
assert!(matches!(lexer.next(), Ok(Some(Token::ID(TokenMeta { pos: 13 }, 60.0)))));
assert!(matches!(lexer.next(), Ok(Some(Token::CBR(TokenMeta { pos: 15 })))));
assert!(matches!(lexer.next(), Ok(None)));
}
#[test]
fn parser_... | Rust | 0 |
A1SrgbBlock => FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK [(4, 4)] [Some(8)] [compressed=texture_compression_etc2] {u8},
ETC2_R8G8B8A8UnormBlock => FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK [(4, 4)] [Some(16)] [compressed=texture_compression_etc2] {u8},
ETC2_R8G8B8A8SrgbBlock => FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK [(4, 4)] [Some(16)] ... | Rust | 0 |
shuffle=False)
print('\n\nRademacher Noise Detection')
logger.info('\n\nRademacher Noise Detection')
get_and_print_results_syn(logger,ood_loader)
# /////////////// Blob ///////////////
ood_data = np.float32(
np.random.binomial(n=1,
p=0.7,
... | Python | 1 |
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _TASKS_LFCLKSTART;
#[doc = "`write(|w| ..)` method takes [tasks_lfclkstart::W](tasks_lfclkstart::W) writer structure"]
impl crate::Writable for TASKS_LFCLKSTART {}
#[doc = "Start LFCLK source"]
pub mod tasks_lfclkstart;
#[doc = "Stop LFCLK source\n\nThis register you ca... | Rust | 0 |
l {
self.native().fVkRTSupportsInputAttachment
== sb::SkSurfaceCharacterization_VkRTSupportsInputAttachment::kYes
}
pub fn vulkan_secondary_cb_compatible(&self) -> bool {
self.native().fVulkanSecondaryCBCompatible
== sb::SkSurfaceCharacterization_VulkanSecondaryCBCompati... | Rust | 0 |
_fg: RGBA,
_bg: RGBA,
) {
// Does nothing
}
/// Fills a rectangle with the specified rendering information
fn fill_region(&mut self, _target: Rect, _glyph: FontCharType, _fg: RGBA, _bg: RGBA) {
// Does nothing
}
/// Draws a horizontal progress bar
fn draw_bar_hor... | Rust | 0 |
ines;
use crate::errors::Result;
use byteorder::{BigEndian, ByteOrder, ReadBytesExt};
use bytes::buf::Buf;
use bytes::BytesMut;
use std::io::{self, Read};
//pub type Lines = lines::Lines;
pub type Preprocessors = Vec<Box<dyn Preprocessor>>;
pub trait Preprocessor: Sync + Send {
fn process(&mut self, ingest_ns: ... | Rust | 0 |
lf.mem.as_ptr() as *mut u8, self.mem.len() as u32)
}
fn has_outstanding_borrows(&self) -> bool {
self.bc.has_outstanding_borrows()
}
fn is_shared_borrowed(&self, r: Region) -> bool {
self.bc.is_shared_borrowed(r)
}
fn is_mut_borrowed(&self, r: Region) -> bool {
self.bc.is... | Rust | 0 |
pub(crate) const fn equal<const N: usize, const M: usize>() {
Assert::<N, M>::EQ;
}
#[allow(dead_code)]
pub struct Assert<const L: usize, const R: usize>;
#[allow(dead_code)]
impl<const L: usize, const R: usize> Assert<L, R> {
/// Const assert hack
pub const GREATER_EQ: usize = L - R;
/// Const asse... | Rust | 0 |
agedSectorMetadata = Default::default();
sealed_sector_b.pieces.push(PieceMetadata {
piece_key: String::from("x"),
num_bytes: UnpaddedBytesAmount(508),
comm_p: [0u8; 32],
});
let staged_sectors = vec![sealed_sector_a.clone(), sealed_sector_b.clone()];
... | Rust | 0 |
šią", "apie", "kiek", "daug", "kai", "gal", "tų", "jog", "jos", "gana", "man", "dėl",
"tą", "jums", "šis", "gera", "bet", "per", "negu", "tarp", "tokį", "toli", "liko", "kaip",
"teko", "nuo", "tapo", "būna", "vos", "jūsų", "po", "turi", "ką", "link", "čia", "šie", "tai",
"jie", "tuo", "štai", "ar", "nors", ... | Rust | 0 |
ef endElement(self, name, value, connection):
setattr(self, name, value)
def to_xml(self):
"""
Returns a string containing the XML version of the Lifecycle
configuration as defined by S3.
"""
s = '<?xml version="1.0" encoding="UTF-8"?>'
s += '<LifecycleConfig... | Python | 1 |
;
fn notify(&self, _state: State) -> Self::NotifyFuture {
future::ready(Ok(()))
}
}
#[test]
fn test_inspect_initial_state() {
let inspector = fuchsia_inspect::Inspector::new();
let _update_monitor = UpdateMonitor::<FakeStateNotifier>::from_inspect_node(
... | Rust | 0 |
import structlog
from django.utils import timezone
from ..models import Dependency, DependencyUsage
from . import docker, git_api, gitlab_ci, package_json, requirements_py
log = structlog.get_logger()
ANALYZERS = [docker, git_api, gitlab_ci, package_json, requirements_py]
def unpack_version(version: str) -> dict:
... | Python | 1 |
try!(write!(f, " _in[12]"))}
if self._in(13) != 0 { try!(write!(f, " _in[13]"))}
if self._in(14) != 0 { try!(write!(f, " _in[14]"))}
if self._in(15) != 0 { try!(write!(f, " _in[15]"))}
if self._in(16) != 0 { try!(write!(f, " _in[16]"))}
if self._in(17) != 0 { try!(write!(f, " _i... | Rust | 0 |
sPoint],
stroke_style: &JsValue,
) {
// As long as we have at least two points...
if points.len() >= 2 {
ctx.save();
ctx.set_stroke_style(&stroke_style);
// First point
ctx.begin_path();
ctx.move_to(points[0].at.x, points[0].at.y);
// Are there only 2 points?
if points.len() == 2 {
... | Rust | 0 |
let sk = SecretKey::from_slice(&bytes[..]).unwrap();
let scalar = Scalar::from(sk);
assert_eq!(&sk[..], scalar.to_bytes().as_ref());
}
#[test]
fn public_key() {
let pk = PublicKey::from_str("<KEY>").unwrap();
let point = Point::from(pk);
assert_eq!(pk.serial... | Rust | 0 |
from django.urls import path
from . import views
# from .forms import CustomPasswordResetForm
# from django.contrib.auth import views as auth_views
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
TokenVerifyView
)
urlpatterns = [
path('twoFactor/', views.twoFactor, name='twoFac... | Python | 1 |
'''Два узла, находящиеся в одной сети, имеют
IP-адреса 121.171.5.70 и
121.171.5.107. Укажите наименьшее возможное количество
адресов в этой сети.
'''
from ipaddress import*
for mask in range(33):
net1 = ip_network(f'121.171.5.70/{mask}',0)
net2 = ip_network(f'121.171.5.107/{mask}',0)
if net1 ==net2:
... | Python | 1 |
um(
torch_data[split_mask][torch_data.room_mask].sum().item()
for torch_data in self
)
if is_room
else sum(
torch_data[split_mask][torch_data.object_mask].sum().item()
for torch_data in self
... | Python | 1 |
return min(dist1, dist2) / 2
try:
gt_points_pattern = r'<points>\((\d+),(\d+)\),\((\d+),(\d+)\)</points>'
gt_match = re.search(gt_points_pattern, ground_truth)
if gt_match:
gt_points = [[int(gt_match.group(1)), int(gt_match.group(2))], [int(gt_match.group(3)), int... | Python | 1 |
query = indoc!(
r##"
mutation {
createOnetimestamps(
data: {
time_date: "2020-03-10T12:00:00Z",
}
) {
id
serial
time_date
bigserial
}
}
... | Rust | 0 |
$atomic_new:expr,
$int_type:ident $atomic_type:ident $atomic_init:ident) => {
/// An integer type which can be safely shared between threads.
///
/// This type has the same in-memory representation as the underlying
/// integer type, [`
#[doc = $s_int_type]
/// `... | Rust | 0 |
osition_std = np.std(positions, axis=0) # 每个轴的标准差
# 正确计算角度标准差(处理角度环绕问题)
orientation_std = []
for axis in range(3): # 对每个轴(Roll, Pitch, Yaw)分别计算
angles = orientations[:, axis]
# 将角度转换为弧度
angles_rad = np.deg2rad(angles)
... | Python | 1 |
"""AWEL: Simple dag example
DERISK will automatically load and execute the current file after startup.
Example:
.. code-block:: shell
DERISK_SERVER="http://127.0.0.1:5555"
curl -X GET $DERISK_SERVER/api/v1/awel/trigger/examples/hello\?name\=zhangsan
"""
from derisk._private.pydantic import BaseModel, Fiel... | Python | 1 |
sumers_failed:
# Include this node since its consumers failed
non_redundant_nodes.append(child)
logger.info(f" DependencyChainTracker: Including {child.task_id} - consumers failed")
else:
logger.info(f" DependencyChainTrac... | Python | 1 |
key (i.e. a string)
Key,
/// Any JSON value
Value,
/// The given [`char`]
Char(char),
/// Any digit (0 through 9)
Digit,
}
impl Error {
/// Given the value from the [`Iter`]ator and an expected value, generate either an
/// [`Error::ExpectedXFoundY`] or an [`Error::ExpectedXFoundEo... | Rust | 0 |
ialize, Clone, Debug, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum Action {
PayByFrom = 0,
LendByFrom,
PayByTo,
}
impl Action {
fn to_scripts(&self) -> Vec<ScriptType> {
match self {
Action::PayByFrom => vec![ScriptType::Secp256k1],
Action::LendByFrom => ... | Rust | 0 |
ss_word_analysis(word)
if result:
all_rows.extend(result)
else:
print("⚠️ Lisame tühja rea järjekorra säilitamiseks")
all_rows.append({
"Sõna": word,
"Tähenduse nr": 1,
"Tähendus": "töötlemata",
"Tähendus... | Python | 1 |
"""
ProfitDrawDownHyperOptLoss
This module defines the alternative HyperOptLoss class based on Profit &
Drawdown objective which can be used for Hyperoptimization.
Possible to change `DRAWDOWN_MULT` to penalize drawdown objective for
individual needs.
"""
from pandas import DataFrame
from main.data.metrics import c... | Python | 1 |
or `Reg<STALL_STATUS_SPEC>`"]
pub type STALL_STATUS = crate::Reg<stall_status::STALL_STATUS_SPEC>;
#[doc = "DMA stall status"]
pub mod stall_status;
#[doc = "DMA_REQ_STATUS register accessor: an alias for `Reg<DMA_REQ_STATUS_SPEC>`"]
pub type DMA_REQ_STATUS = crate::Reg<dma_req_status::DMA_REQ_STATUS_SPEC>;
#[doc = "DM... | Rust | 0 |
s_statfs()
fn _fs_statfs<CB: Into<crate::FsCB<'static>>>(&self, path: &str, cb: CB) -> FsReqErrResult {
let cb = cb.into();
let uv_cb = use_c_callback!(crate::uv_fs_cb, cb);
let path = CString::new(path)?;
let mut req = FsReq::new(cb)?;
let result = crate::uvret(unsafe {
... | Rust | 0 |
eport", &context)
.expect("Failed to render summary report template");
try_else_return!(save_string(&text, &report_path,), || {});
}
}
<gh_stars>10-100
use crate::error::{VcxErrorKind, VcxResult, VcxResultExt};
#[derive(Debug, Serialize, Deserialize)]
pub struct ObjectWithVersion<'a, T> {
p... | Rust | 0 |
#elif ve else
#test
"""
x=10
y=20
if(x>y):
print('x, y\'den büyük')
elif x==y:
print('x ve y eşit')
else:
print('y, x\'ten büyük')
x=int(input('x: '))
y=int(input('y: '))
if(x>y):
print('x, y\'den büyük')
elif x==y:
print('x ve y eşit')
else:
print('y, x\'ten büyük')
"""
num=int(input('sayı: '... | Python | 1 |
l_current_colr_ptr.offset(1);
opj_write_bytes_LE(
l_current_colr_ptr,
(*jp2).approx,
1 as libc::c_int as OPJ_UINT32,
);
l_current_colr_ptr = l_current_colr_ptr.offset(1);
if (*jp2).meth == 1 as libc::c_int as libc::c_uint {
/* Meth value is restricted to 1 or 2 (Table I.9 of part 1) */
opj_w... | Rust | 0 |
output128b: [u32; 44] = [0; 44];
setkey_dec_auto(&origin128, &mut output128a);
setkey_dec_k128(&origin128, &mut output128b);
for i in 0..44 {
assert_eq!(output128a[i], output128b[i]);
}
let origin192: [u8; 24] = [
0x8E, 0x73, 0xB0, 0xF7, 0xDA, 0x0E, 0x64, ... | Rust | 0 |
_owned()), None),
_ => unsupported_type(),
};
ColumnType {
full_data_type,
family,
arity,
native_type: native_type.map(|x| x.to_json()),
}
}
// Separate from get_column_type_postgresql because of native types.
fn get_column_type_cockroachdb(row: &ResultRow, enums: &... | Rust | 0 |
# s="caberqiitefg"
s="klkhjgfyyp"
k=5
i=0
j=k
def countvowel(str):
c=0
l=['a','e','i','o','u']
for i in range(len(str)):
if str[i] in l:
c+=1
return c
# st=set(l)
# print(st)
map={}
while j < len(s):
t=s[i:j]
map[t]=countvowel(t)
print(map)
i+=1
| Python | 1 |
(Bound::Included(s), Bound::Included(e)) => debug_assert!(s <= e),
(Bound::Included(s), Bound::Excluded(e)) => debug_assert!(s < e),
(Bound::Excluded(s), Bound::Included(e)) => debug_assert!(s < e),
(Bound::Excluded(s), Bound::Excluded(e)) => debug_assert!(s < e),
... | Rust | 0 |
ription(input);
self
}
/// <p>Required. The cadence to generate the report.</p>
pub fn report_frequency(mut self, input: crate::model::ReportFrequency) -> Self {
self.inner = self.inner.report_frequency(input);
self
}
pub fn set_report_frequenc... | Rust | 0 |
#kata
#https://www.codewars.com/kata/5977ef1f945d45158d00011f/train/python
def sep_str(st):
ans=[]
words=st.split()
if not words:
return []
maxlength=max(len(word) for word in words)
i=0
while i<maxlength:
row=[]
for word in words:
if i<len(word):
... | Python | 1 |
});
}
fn do_bench_clone_std(b: &mut Bencher, src_len: usize) {
let src: Vec<_> = FromIterator::from_iter(0..src_len);
b.bytes = src_len as u64;
b.iter(|| {
let dst = src.clone();
assert_eq!(dst.len(), src_len);
assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
});
}
... | Rust | 0 |
bits >> 4) & 0x07) as u8)
}
}
impl W {
#[doc = "Bits 0:3 - SPI Baud Rate Divisor"]
#[inline(always)]
pub fn spr(&mut self) -> SPR_W {
SPR_W { w: self }
}
#[doc = "Bits 4:6 - SPI Baud Rate Prescale Divisor"]
#[inline(always)]
pub fn sppr(&mut self) -> SPPR_W {
SPPR_W { w: ... | Rust | 0 |
import re
def safe_equal(prediction, answer):
try:
if prediction == answer:
return True
return False
except Exception as e:
print(e)
return False
def has_numbers(inputString):
return bool(re.search(r'\d', inputString))
def convert_string(input_string):
#... | Python | 1 |
м последние данные о рейтинге
rankings_data = last_scrape_data if last_scrape_data else scheduler.scraper.scrape_category_rankings()
# Получаем данные Fear & Greed Index
fear_greed_data = scheduler.fear_greed_tracker.get_fear_greed_index()
# Отпр... | Python | 1 |
from discord.ext import commands
from Classes.TextVoice_Class import textvoice
import discord
class Modding(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name='create-channel', help = "Creates a text/voice channel (mods only)") # creating channels
@commands.has_role("R... | Python | 1 |
#!/usr/bin/env python
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
from __future__ import with_statement
import string, os, subprocess, platform, base64,random, string
import os
import requests
import urllib2
import re
try:
from setuptools import setup
from setuptools.command.inst... | Python | 1 |
#!/usr/bin/env python3
# Copyright (C) 2022 Checkmk GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.
# mypy: disable-error-code="type-arg"
from collec... | Python | 1 |
test_mask])
return val_acc, test_acc, logits
@time_logger
def train(self):
for epoch in range(self.epochs):
t0, es_str = time(), ''
if self.gnn_model_name == "GCN_LPA":
loss, loss_gcn, loss_lpa, loss_lpa2, train_acc = self._train()
else:
... | Python | 1 |
t)
# Measure inference time over multiple iterations
num_iterations = 100
count = 10
with jtop() as jetson:
if not jetson.ok():
raise RuntimeError("jtop is not running or initialized properly.")
power_readings = []
start_time = time.time()
for _... | Python | 1 |
u32, _INTRPTCLR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _INTRPTCLR;
#[doc = "`read()` method returns [intrptclr::R](intrptclr::R) reader structure"]
impl crate::Readable for INTRPTCLR {}
#[doc = "`write(|w| ..)` method takes [intrptclr::W](intrptclr::W) writer structure"]
impl crate::Writable for INTRPTCLR {... | Rust | 0 |
},
},
}
}
}
/// Create build with parameters.
///
/// [See Heroku documentation for more information about this endpoint](https://devcenter.heroku.com/articles/platform-api-reference#build-create-required-parameters)
#[derive(Serialize, Clone, Debug)]
pub struct BuildCreatePara... | Rust | 0 |
fn get_period(&self) -> Self::Time {
()
}
fn get_duty(&self, _channel: Self::Channel) -> Self::Duty {
//self.read_duty(channel).unwrap_or(0)
0
}
fn get_max_duty(&self) -> Self::Duty {
255u8
... | Rust | 0 |
import streamlit as st
import pandas as pd
from st_pages import Page, show_pages
#Page Config
st.set_page_config(page_title="Prices", layout="wide")
#Title and Intro
st.title(":open_book: :rainbow[Amazon Books Reviews - 2023]", anchor=False)
st.divider()
# Specify what pages should be shown in the sidebar, and what ... | Python | 1 |
await update.message.reply_text(f"已移除管理员:{del_admin}")
async def button_handler(update: Update, context):
query = update.callback_query
if query.data == "help":
await help_handler(query, context)
await query.answer()
elif query.data == "start":
await start_handler(query, context)
... | Python | 1 |
"""
==================
Stacked bar charts
==================
"""
# sphinx_gallery_thumbnail_number = 4
###############################
# Read in tutorial data and show a summary
# ****************************************
#
# This gallery uses the scenario data from the first-steps tutorial.
#
# If you haven't cloned... | Python | 1 |
ttings_system_daydream;
pub mod icon_share_location;
pub mod icon_shortcut;
pub mod icon_signal_cellular_0_bar;
pub mod icon_signal_cellular_4_bar;
pub mod icon_signal_cellular_alt;
pub mod icon_signal_cellular_connected_no_internet_0_bar;
pub mod icon_signal_cellular_connected_no_internet_4_bar;
pub mod icon_signal_ce... | Rust | 0 |
}
<gh_stars>1-10
use std::io::BufRead;
use crate::converter::{Converter, ConverterTrait};
use crate::error::Result;
use crate::models::chord::fmt::Formatting;
use crate::models::chord::TransposableTrait;
use crate::models::song_meta_trait::SongMetaTrait;
use crate::parser::{Parser, ParserResult, ParserTrait};
use cra... | Rust | 0 |
Party
/// Identifier][3pid].
///
/// This is the first step in registering a phone number as 3PID. Next,
/// call [`Account::add_3pid()`] with the same `client_secret` and the
/// returned `sid`.
///
/// # Arguments
///
/// * `client_secret` - A client-generated secret string used t... | Rust | 0 |
,
resp.status()
);
}
},
}
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
}
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
async fn cluster() -> Result<(), Box<dyn std::error::Error>> {
let _ = pret... | Rust | 0 |
assert_eq!(req.headers[0].value, &b"1234567890some\t1234567890agent1234567890"[..]);
}
}
req! {
test_request_headers_max,
b"GET / HTTP/1.1\r\nA: A\r\nB: B\r\nC: C\r\nD: D\r\n\r\n",
|req| {
assert_eq!(req.headers.len(), NUM_OF_HEADERS);
}
}
... | Rust | 0 |
plit each string element in ``a``.
Returns
-------
out : 3-tuple:
- array with ``StringDType``, ``bytes_`` or ``str_`` dtype with the
part before the separator
- array with ``StringDType``, ``bytes_`` or ``str_`` dtype with the
separator
- array with ``StringDTyp... | Python | 1 |
"""Test swig-style wrapped pointers
Created on Oct 2, 2014 by David Gobbi
"""
import sys
from vtkmodules.vtkCommonCore import (
vtkInformation,
vtkIntArray,
vtkObject,
)
from vtkmodules.test import Testing
class TestSwigPointer(Testing.vtkTest):
def testVoidPointer(self):
a = vtkIntArray()
... | Python | 1 |
cap of 2 seconds
wait_time = min(wait_time * 2, 2.0)
self.logger.error("Timeout waiting for topic '%s' after %ds", topic_name, max_wait_time)
return False
def add_partitions(self, topic_name, new_partition_count):
"""Add partitions to an existing topic"""
try:
... | Python | 1 |
sw_num = int(input()) # 스위치 개수
sw_con = list(map(int, input().split())) # 스위치 상태
# 스위치 번호는 1부터 시작함.
stu_num = int(input()) # 학생 수
list_stu = [] # 성별, 기준 수 저장할 리스트
ch_dict = {1: 0, 0: 1}
for _ in range(stu_num):
sx, given_num = map(int, i... | Python | 1 |
lf.emb_pdrop
]):
raise ValueError(
"self.attn_config['attn_pdrop'], resid_pdrop, emb_pdrop are "
"probabilities and must be between 0 and 1")
if self.attn_config['attn_impl'] not in ['torch', 'flash', 'triton']:
raise ValueError(
... | Python | 1 |
from langchain_groq import ChatGroq
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from module.config import GROQ_API_KEY, MODEL_NAME
def get_sql_query(user_query: str, schema_description: str) -> str:
prompt = ChatPromptTemplate.from_template(f"""
... | Python | 1 |
f, menuitem, plugin, query, query_is_source):
plugin.lookup(query, query_is_source, srclang, tgtlang)
def _on_populate_popup(self, textbox, menu):
buf = textbox.buffer
if not buf.get_has_selection():
return
selection = buf.get_text(*buf.get_selection_bounds()).decode('u... | Python | 1 |
def solution(my_str, n):
answer = [my_str[i:i+n] for i in range(0, len(my_str), n)]
return answer | Python | 1 |
is_not_start: size != 0,
is_not_end: size.to_string().parse::<i32>().unwrap() != page - 1
};
let mut resp = Response::new();
resp.set_mut(Template::new("index", posts.to_json())).set_mut(status::Ok);
Ok(resp)
}<reponame>fornwall/advent-of-code-2019-rs
use std::collections::VecDeque;
pub type RegisterSpecifie... | Rust | 0 |
assert_allclose(
transform_module(copy.deepcopy(results))['img'].astype(np.int32),
_adjust_brightness(img, factor).astype(np.int32),
rtol=0,
atol=1)
def test_adjust_contrast(nb_rand_test=100):
def _adjust_contrast(img, factor):
from PIL.ImageEnhance import ... | Python | 1 |
### u-chart ###
# Import required libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import statistics
# Set random seed
np.random.seed(42)
# Create dummy data
u = {'defects':np.random.randint(1,5,10).tolist(),
'group_size':np.random.randint(10,15,10).tolist()}
# Convert data to da... | Python | 1 |
ect fact-checking method"""
with patch.object(reasoning_engine.agent_coordinator.fact_checking_agent, 'reason') as mock_reason:
mock_reason.return_value = ReasoningResult(
reasoning_type="fact_checking",
confidence=0.8,
explanation="Fact check result",... | Python | 1 |
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Hash, Serialize, Deserialize)]
#[repr(u8)]
pub enum StoreEvalMutResult {
None,
Dropped,
DroppedRange,
DroppedPrefix,
}
impl Default for StoreEvalMutResult {
fn default() -> StoreEvalMutResult {
StoreEvalMutResult::None
}
}
impl Si... | Rust | 0 |
import discord
from discord.ext import commands
from collections import defaultdict
# Default dict to store per-server user activity
user_thread_activity = defaultdict(lambda: defaultdict(set))
class ThreadTracker(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
asy... | Python | 1 |
back, eval_callback],
reset_num_timesteps=False,
)
# Save trained model.
save_dir = config.logdir / "train"
save_dir.mkdir(parents=True, exist_ok=True)
time = datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
model.save(save_dir / ("model_" + time))
... | Python | 1 |
<Vec<u8>> {
self.received_handshake.take()
}
}
impl InProtocol {
pub fn new(protocol_name: Cow<'static, [u8]>) -> Self {
Self { protocol_name }
}
}
impl UpgradeInfo for InProtocol {
type Info = Cow<'static, [u8]>;
type InfoIter = iter::Once<Self::Info>;
fn protocol_info(&self) -> Self::InfoIter {
iter::o... | Rust | 0 |
let v_x = angle.sin();
let v_y = angle.cos();
for step in 0..steps {
// Rays are only drawn until non-walkable is found and thus the cannot go out of bounds
let step_f32 = step as f32 / step_mult;
let new_pos = ((position.0 + v_x * step_f32) as usize, (position.1... | Rust | 0 |
_cancel_order(self, order: Order):
"""subclasses should implement this method"""
pass
@abstractmethod
def _update_order(self, order: Order):
"""subclasses should implement this method"""
pass
@abstractmethod
def _place_order(self, order: Order):
"""subclasses sh... | Python | 1 |
get is a number, the predicted answer needs to be correct to the last significant figure in the gold answer. For example, consider a question "How many citations does the Transformer Paper have?" with gold target "120k".
- Predicted answers "120k", "124k", and 115k" are all CORRECT.
- Predicted answers "100k" and "113k... | Python | 1 |
# Reshape, transpose, and view into desired shape
b, f, c, h, w = control_camera_video.shape
control_camera_video = control_camera_video.contiguous().view(b, f // 4, 4, c, h, w).transpose(2, 3)
control_camera_video = control_camera_video.contiguous().view(b, f // 4, c * 4, h, w).transpo... | Python | 1 |
"""
Parameter sweep tool: Invoke Canvas across a smoke test, using various parameter combinations, to review overall accuracy.
"""
import os
import traceback
# Set up which parameters to vary, and which values to try:
CanvasCallerParameters = []
#CanvasCallerParameters.append(("-D", [1.25, 1.5, 1.75, 2.0, 2.25, 2.5]))... | Python | 1 |
rKind::SemanticError(
meta,
format!("{:?} cannot be in the left hand side", self.hir_exprs[expr]).into(),
))
}
};
Ok((Some(handle), meta))
}
}
#[derive(Debug, Clone)]
pub struct VariableReference {
pub expr: Handle<Expression>... | Rust | 0 |
"""
UserBot Module to search the internet
All-in-one by @its_xditya
(c)TeleBot
Available commands:
.ggl - howtogoogle
.duckduckgo - search on duckduckgo
.go - search on google
"""
from re import findall
import requests
from search_engine_parser import GoogleSearch
from telebot import CMD_HELP
from telebot.utils imp... | Python | 1 |
#[should_panic(expected = "assertion failed: self.variants.len() < 4")]
fn test_five_variants() {
let mut test = BinaryTest::new();
for _ in 0..5 {
test.add(2, 1);
}
}
#[test]
#[should_panic(expected = "assertion failed: conversions <= participants")]
fn test_too... | Rust | 0 |
ESS_NAME_FORMAT",
"PROFILEINFOA",
"PROFILEINFOW",
"PROG_INVOKE_SETTING",
"PROPERTYKEY",
"PROPERTYORIGIN",
"PROPSHEETHEADERA_V2",
"PROPSHEETHEADERW_V2",
"PROPSHEETPAGEA",
"PROPSHEETPAGEW",
"PROPVARIANT",
"PROVIDER_ENUMERATION_INFO",
"PROVIDER_EVENT_INFO",
"PROVIDER_FIE... | Rust | 0 |
ntials) = parse_authorization(value)?;
if _type.eq_ignore_ascii_case("Basic") {
Some(String::from_utf8(base64_decode(credentials).ok()?).ok()?)
} else {
None
}
});
Box::pin(async move {
match credentials {
Some(ref c... | Rust | 0 |
import collections
class Solution:
def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
'''
dominoes[i] = [a,b] == dominoes[j] = [c,d]
|
a==c & b==d or (a==d and b==c) -> (i,j)
dominoes = [[1,2],[2,1],[3,4],[5,6]] -> 1
'''
#count the domino... | Python | 1 |
url: "nats://127.0.0.1:4224".to_owned(),
tls: None,
auth: Some(NatsAuthConfig::Token {
token: NatsAuthToken {
value: "secret".into(),
},
}),
};
let r = publish_and_check(conf).await;
assert!(
... | Rust | 0 |
args.zone,
params=util.GetParamsForRegistry(api_version, args),
collection='dns.managedZones')
try:
get_request = dns.MESSAGES_MODULE.DnsManagedZonesGetRequest(
project=zone_ref.project, managedZone=zone_ref.managedZone)
if api_version == 'v2':
get_request.location ... | Python | 1 |
from setuptools import setup
try:
setup(
name='gcp_iac',
version='1.0.0',
entry_points={'console_scripts': [
'giac = gcp_iac.cli:iac_parent',
]},
)
exit(0)
except Exception as error:
print(f'Failed to setup package: {error}')
exit(1)
| Python | 1 |
import torch
from torch import nn
from torch.nn.functional import binary_cross_entropy_with_logits
LABEL_REAL = 0.95
LABEL_FAKE = 0.05
class GANLoss(nn.Module):
def generator(self, discriminator, generator, real_batch, fake_batch, device):
raise NotImplementedError
def discriminator(self, discrimin... | Python | 1 |
//! Tables of approximations of powers of ten.
//! DO NOT MODIFY: Generated by `src/etc/dec2flt_table.py`
pub const MIN_E: i16 = -305;
pub const MAX_E: i16 = 305;
pub const POWERS: ([u64; 611], [i16; 611]) = (
[
0xe0b62e2929aba83c,
0x8c71dcd9ba0b4926,
0xaf8e5410288e1b6f,
0xdb71e9... | Rust | 0 |
9243728 32
30 0.0007610033706666666 4
use crate::api::Submission;
use crate::handlers::error::{sub_extractor, Error};
use crate::state::State;
use actix_web::{web, HttpResponse};
use deadpool_postgres::Pool;
use grpc_api::test_client::TestClient;
use grpc_api::{Assignment, AssignmentMsg, AssignmentResult};
use std::tim... | Rust | 0 |
e super::{
buffer_pool::BufferPool,
page::{
BTreeLeafPage, BTreeLeafPageIterator, BTreeLeafPageReverseIterator,
BTreePageID, BTreeRootPointerPage, Entry,
},
};
use crate::btree::page::PageCategory;
use super::consts::PAGE_SIZE;
use core::fmt;
use log::{debug, info};
use std::{borrow::Borrow... | Rust | 0 |
etup();
let console = static_init!(
lora_console::LoraConsole<'static, Capability>,
lora_console::LoraConsole::new(
console_uart,
&mut lora_console::WRITE_BUF,
&mut lora_console::READ_BUF,
&mut lora_console::COMMAND_BUF,
... | Rust | 0 |
join('/home/changfu/shopify_producting/processed_product', 'shoplazza-api-request_unknow_unknow_clothing_processed-product_20241110000000_unknow.tsv')
# df_process = pd.read_csv(process_filePath, sep='\t', dtype=str).fillna('')
# df_product_agg_total.vendor
#
filePath = os.path.join('/home/changfu/shopify_producting/li... | Python | 1 |
x);
output.push_str(&asm);
return
},
BrainfuckInstr::DataAdd(x) => {
let asm = format!("add byte [rsi],{x}\n", x = x);
output.push_str(&asm);
return
},
BrainfuckInstr::Print(x) => {
// Copypasted from the PutByte arm... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.