text string | label_name string | labels int64 |
|---|---|---|
1 = nes.registers.a & nes.registers.x & (nes.cpu.temp_address.wrapping_add(0x100) >> 8) as u8;
if low_byte > 0xFF {
// Fix the high byte of the address by adding 1 to it
nes.cpu.temp_address = (nes.cpu.temp_address & 0x00FF) | ((nes.cpu.data1 as u16) << 8);
}
},
5 => {
let data... | Rust | 0 |
test the string repr
index.name = "foo"
assert "'foo'" in str(index)
assert type(index).__name__ in str(index)
class TestReductions:
def test_argmax_axis_invalid(self, index):
# GH#23081
msg = r"`axis` must be fewer than the number of dimensions \(1\)"
with pytest.r... | Python | 1 |
""
Sol_symbol = ""
try:
response = requests.get(url)
# Check if the request was successful (status code 200)
if response.status_code == 200:
resp = response.json()
print("Response:", resp['pairs'][0]['baseToken']['symbol'])
... | Python | 1 |
import json
import time
from io import StringIO
from os import path
from typing import Any
import pandas as pd
import pymysql
import pytest
from docker.types import Ulimit
from sqlalchemy import create_engine, text
from tests.utils import (
BEERS_TABLE_COLUMNS,
assert_dataframes_equals,
docker_container,
... | Python | 1 |
The [`DirEntry`]'s full path.
pub fn path(&self) -> &'static Path {
match self {
DirEntry::Dir(d) => d.path(),
DirEntry::File(f) => f.path(),
}
}
/// Try to get this as a [`Dir`], if it is one.
pub fn as_dir(&self) -> Option<&Dir> {
match self {
... | Rust | 0 |
# -*- coding: utf-8 -*-
# Copyright 2015 Donne Martin. 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://www.apache.org/licenses/LICENSE-2.0
#
# or in the "lice... | Python | 1 |
e<Stage2>, mailbox: Mailbox) -> Self {
Self { ptable, mailbox }
}
}
// TODO(@jeehoonkang)
pub struct Vm {
id: u32,
pub state: SpinLock<VmState>,
vcpus: ArrayVec<[VCpu; MAX_CPUS]>,
wait_entries: [WaitEntry; MAX_VMS],
aborting: AtomicBool,
}
impl Vm {
pub fn new(id: u32, vcpu_count:... | Rust | 0 |
Rule/sing-box/BanEasyPrivacy.srs"],
["📢 谷歌FCM", "https://raw.githubusercontent.com/SubConv/ZJU-Rule/sing-box/Ruleset/GoogleFCM.srs"],
["📢 谷歌服务", "https://raw.githubusercontent.com/SubConv/ZJU-Rule/sing-box/Ruleset/Google.srs"],
# ["🎯 全球直连", "https://raw.githubusercontent.com/SubCo... | Python | 1 |
from typing import Dict, Optional
from pydantic import ConfigDict, Field
from openapi_pydantic_v2 import OpenAPI, Operation, PathItem
def test_swagger_openapi_v3():
with open("tests/data/swagger_openapi_v3.0.1.json", "r") as file:
data = file.read()
data_as_json = ExtendedOpenAPI.model_validate_jso... | Python | 1 |
import re
st = "LCNO-TLG-08-2008-0001"
res = re.search(r'LCNO-(KAR|KER|APN|TND|TLG|MAH)-([0-6][1-9]|[1-7][0-3])-([2-9][0-9]{3})-(?!0000)([0-9]{4})' , st)
if res:
print("Match found.....")
print(res.group(0)) # matched string
else:
print("Match not found.....") | Python | 1 |
Status::Typed(t),
};
// Might overwrite (i.e. shadow) the current local's type
self.locals.remove(&var);
self.locals.add(var, status).unwrap();
}
fn module_info(&self, m: &ModuleIdent) -> &ModuleInfo {
self.modules
.get(m)
.expect("ICE should have... | Rust | 0 |
# coding: utf-8
from __future__ import absolute_import
import flask
import auth
import config
import model
import util
from main import app
microsoft_config = dict(
access_token_method='POST',
access_token_url='https://login.microsoftonline.com/common/oauth2/v2.0/token',
api_base_url='https://graph.microsoft... | Python | 1 |
g playback."""
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
transient=True,
) as progress:
task = progress.add_task(f"Playing: {self.current_title}", total=100)
for _ in range(100):
tim... | Python | 1 |
"type": "string",
"example": "/path/to/cache",
"description": "缓存目录路径"
},
"image_directory": {
... | Python | 1 |
states)."]
#[doc = "@param state Key or button change (\\c KB_PRESS or \\c KB_RELEASE)."]
#[doc = "@return \\c 0 if OK, else send link error."]
#[doc = ""]
#[doc = "\\b Example:"]
#[doc = "<pre>"]
#[doc = "\\code"]
#[doc = ""]
#[doc = "UINT16 echo_key(void)"]
#[doc = "{"]
#[doc =... | Rust | 0 |
ll;
loop {
let mut status_raw = 0;
match syscall::waitpid(pid as usize, &mut status_raw, 0) {
Ok(0) => (),
Ok(_pid) => {
let status = ExitStatus::from_raw(status_raw as i32);
if let Some(code) = status.code() {
... | Rust | 0 |
ch_size):
minibatch_indices = indices[minibatch_start:minibatch_start + minibatch_size]
yield [minibatch(d, minibatch_indices) for d in data] if list_data \
else minibatch(data, minibatch_indices)
if __name__ == "__main__":
train = pd.read_csv(os.path.join(data_path, 'train.tsv'), sep... | Python | 1 |
'|[^'])*'", String),
# -- DoubleQuotedString
(r'"(\\\\|\\[^\\]|[^"\\])*"', String),
# Tokens
(r'(~=|\^=|%=|\*=|==|!=|>>>=|>>>|>>=|>>|>=|<=>|\?=|-\>'
r'|<<=|<<|<=|\+\+|\+=|--|-=|\|\||\|=|&&|&=|\.\.|/=)'
r'|[-/.&$@|\+<>!()\[\]{}?,;:=*%^~#\\]', Punc... | Python | 1 |
504,
99518671430235219628894890102423325116913619626622,
73267460800591547471830798392868535206946944540724,
76841822524674417161514036427982273348055556214818,
97142617910342598647204516893989422179826088076852,
87783646182799346313767754307809363333018982642090,
10848802521674670883215120185883543223812876952786,
713... | Python | 1 |
# mypy: allow-untyped-defs
import torch
from torch.export import Dim
x = torch.randn(3, 2)
y = torch.randn(2)
dim0_x = Dim("dim0_x")
class CondOperands(torch.nn.Module):
"""
The operands passed to cond() must be:
- a list of tensors
- match arguments of `true_fn` and `false_fn`
NOTE: If the `pre... | Python | 1 |
Reg<usbhs_hstpipier_ctrl_mode::USBHS_HSTPIPIER_CTRL_MODE_SPEC>;
10])
}
}
#[doc = "0x620..0x648 - Host Pipe Disable Register"]
#[inline(always)]
pub fn usbhs_hstpipidr_intrpt_mode(
&self,
) -> &[crate::Reg<usbhs_hstpipidr_intrpt_mode::USBHS_HSTPIPIDR_INTRPT_MODE_SP... | Rust | 0 |
from django import forms
from .models import ClientMessage
class RatingForm(forms.Form):
rating = forms.IntegerField(widget=forms.HiddenInput())
class ClientMessageForm(forms.ModelForm):
class Meta:
model = ClientMessage
fields = '__all__'
widgets = {
'name': forms.Te... | Python | 1 |
e's current mtime.
self.mtimes[filename] = mtime
#self.log_message('changed files:' + str(self.changed_files))
#self.schedule_message(100, self._scan)
def rebuild_sys(self):
filenames = self.changed_files
modules = [m for m in list(sys.modules.values()) if _normalize_filename(getattr(m, '__file__', None)... | Python | 1 |
: MaskData, min_area: int, nms_thresh: float) -> MaskData:
"""
Removes small disconnected regions and holes in masks, then reruns
box NMS to remove any new duplicates.
Edits mask_data in place.
Requires open-cv as a dependency.
"""
if len(mask_data['rles']) == 0... | Python | 1 |
import sys
import PIL.Image
import modules.upscaler
from modules import devices, errors, modelloader, script_callbacks, shared, upscaler_utils
class UpscalerScuNET(modules.upscaler.Upscaler):
def __init__(self, dirname):
self.name = "ScuNET"
self.model_name = "ScuNET GAN"
self.model_name... | Python | 1 |
).toarray()[0].reshape(1, -1)
head_tfidf = tfidf_vectorizer.transform([head]).toarray().reshape(1, -1)
heads_track[head] = (head_tf, head_tfidf)
else:
head_tf = heads_track[head][0]
head_tfidf = heads_track[head][1]
if body_id not in bodies_track:
... | Python | 1 |
import torch
import torch.nn as nn
from utils.utils import *
from collections import OrderedDict
from copy import deepcopy
class MAML(nn.Module):
def __init__(self, model):
super(MAML, self).__init__()
self.model = model
self.loss = nn.CrossEntropyLoss()
def forward(self, arg... | Python | 1 |
print("[loading parlAI text data:" + path + "]")
self.episodes = []
self.num_exs = 0
eps = []
with open(path) as read:
for line in read:
msg = str_to_msg(line.rstrip('\n'))
if msg:
self.num_exs += 1
... | Python | 1 |
d.
Returns:
- numpy.ndarray: Image with filled rectangles drawn.
"""
for bbox, class_label, score in zip(bboxes, classes, scores):
if class_label != 'person':
x1, y1, x2, y2 = map(int, bbox)
if colors is None:
color = (int... | Python | 1 |
),
}
impl SHAMD5_MODE_ALGOR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
SHAMD5_MODE_ALGOR::SHAMD5_MODE_ALGO_MD5 => 0,
SHAMD5_MODE_ALGOR::SHAMD5_MODE_ALGO_SHA1 => 2,
SHAMD5_MODE_ALGOR::SHAMD5_MODE_ALGO_SHA... | Rust | 0 |
PC")?;
soft_assert_eq(((unsafe { *(exception_context.exceptpc as *const u32) }) >> 6) & 0xFFFFF, 0xF123F, "ExceptPC points to wrong instruction")?;
soft_assert_eq(exception_context.cause, 0x20, "Cause")?;
soft_assert_eq(exception_context.status, 0x24000002, "Status")?;
Ok(())
}
}
p... | Rust | 0 |
from django.urls import path
from apps.interview import views
app_name = 'interview'
urlpatterns = [
# Interview session routes
path('', views.InterviewSessionListView.as_view(), name='session_list'),
path('create/', views.InterviewSessionCreateView.as_view(), name='session_create'),
path('generate/<u... | Python | 1 |
let entity = table_head + DESCRIPTOR_SIZE * prev;
Descriptor {
addr: dram.read64(entity) - self.dram_base_addr,
len: dram.read32(entity.wrapping_add(8)),
flags: dram.read16(entity.wrapping_add(12)),
next: (dram.read16(entity.wrapping_add(14)) as u64) % qu... | Rust | 0 |
);
}
fn visit_assignment(&mut self, l: &VerilogExpression, r: &VerilogExpression) {
self.visit_expression(l);
self.io.write(" = ");
self.visit_expression(r);
self.io.writeln(";");
}
fn visit_paren(&mut self, e: &VerilogExpression) {
self.io.write("(");
s... | Rust | 0 |
"""facebook_Implement_Second_Minute_Hour_Day_Counters
facebook/google
Given a server that has tons of requests coming in. Design a data structure such
that you can fetch the count of the number requests in the last second, minute,
hour and day.
"""
class Counters(object):
"""Counters class.
Using array to ... | Python | 1 |
(&mut self) -> Option<DateTime<Tz>> {
for x in &mut self.inner {
if self.spec.matches(x.clone()) {
return Some(x);
}
}
None
}
}
/// Returns the default set of plugins, currently only including `r`.
pub fn default_plugins() -> HashMap<String, Box<dyn P... | Rust | 0 |
__MODULE__ = "YoutubeDL"
__HELP__ = """
Bantuan Untuk YoutubeDL
• Perintah: <code>{0}song</code> [song title]
• Penjelasan: Untuk mendownload music yang diinginkan.
• Perintah: <code>{0}video</code> [video title]
• Penjelasan: Untuk mendownload video yang diinginkan.
"""
| Python | 1 |
task_building_lod2 = asyncio.create_task(loadBuilding(mapIndex, True, defaultMaterialPath))
await task_building_lod2
if in_load_bridge and in_load_lod2:
task_bridge = asyncio.create_task(loadBridge(mapIndex, defaultMaterialPath))
await task_bridge
if in_loa... | Python | 1 |
heet\n\
\nError: blah is not a number.\
\n ,\
\n3 | bar: call(max, $foo...);\
\n | ^^^^^^^^^^^^^^^^^^\
\n \'\
\n input.scss 3:8 root stylesheet",
);
}
<reponame>EnderNightLord-ChromeBook/zircon-rpi<filename>src/connectivity/wlan/lib/sme/src/client/... | Rust | 0 |
;
let value = "World";
let field = Field::new(id, Type::S(Some(S::new(value))));
assert_eq!(Field::from_bytes(&field.to_bytes().unwrap()).unwrap(), field);
}
}<filename>packages/layout/src/references.rs<gh_stars>0
use super::starlark_repr::StarlarkContainer;
pub enum LiteralOrReference {
... | Rust | 0 |
ER_METHODS[dither_method_grayscale]
quantize_grayscale = QUANTIZATION_METHODS[quantization_method_grayscale]
dither_palette = DITHER_METHODS[dither_method_palette]
def process_image(original_image):
original_width, original_height = original_image.size
if original_image... | Python | 1 |
import cv2
from sklearn.cluster import KMeans
import numpy as np
class DominantColors:
def __init__(self, image, clusters=3):
self.CLUSTERS = clusters
self.IMAGE = image # Espera imagem RGB
self.COLORS = None
self.LABELS = None
def dominantColors(self):
# converte em ... | Python | 1 |
"Check network connection.")
await self._async_sleep(self._update_interval)
async def _fetch_data(self):
await self._update_asset_prices()
self._ready_event.set()
async def _update_asset_prices(self):
price_dict: Dict[str, float] = {}
... | Python | 1 |
_stream
.next_if_any(&mut session.async_client_session),
)
}
}
fn main() {
let a = [1, 2, 3, 4, 5];
let b = [1; 10];
println!("{:?} {:?}", a, b);
}
use crate::command::inlet::InletCommand;
use crate::command::outlet::OutletCommand;
use crate::config::OckamCommand::{Inlet, Outlet... | Rust | 0 |
# @track_context("dependencies.md")
import logging
from typing import Any
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from jose import JWTError, jwt
from src.core.config import settings
from src.core.messages import ErrorMessages, LogMessag... | Python | 1 |
ConstantInt::SignedInt(SignedInt::I128(seri128)) => assert_eq!(seri128.val(), v),
_ => panic!(),
}
}
}
<filename>src/repr/scalar/decimal.rs
// Copyright Materialize, Inc. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE ... | Rust | 0 |
0;
match program {
Handle::Id(program) => {
assert!(ctxt.version >= &Version(Api::Gl, 2, 0) ||
ctxt.version >= &Version(Api::GlEs, 2, 0));
ctxt.gl.GetProgramiv(program, gl::TESS_GEN_MODE, &mut value);
},
Handle::Handle(program) => {
a... | Rust | 0 |
}
for pattern, context in context_indicators.items():
if re.search(pattern, prompt):
return context
return ""
async def _add_specific_requirements(self, prompt: str) -> str:
"""添加具体要求"""
# 如果提示词缺乏具体性,添加一些通用的具体要求
if not re.search(r'字|个|项|... | Python | 1 |
error_b64 = self._generate_error_chart(f"Insufficient data for {symbol} ({len(df) if df is not None else 0} pts).")
return error_b64, ""
current_metrics_for_title = tech_metrics or {}
indicators_data = self._calculate_chart_indicators(df.copy(), current_me... | Python | 1 |
self.out_convs.append(
conv(
in_channels[i],
out_channels,
3,
padding=1,
conv_cfg=conv_cfg,
norm_cfg=norm_cfg,
act_cfg=act_cfg))
def forward(self, inputs:... | Python | 1 |
_ = some_calculation;
});
});
}
<reponame>rust-linting/api-types
// Span and Id types are going to be tough/interesting, we need to keep the information in order to
// use rustc but it will tightly couple us to rustc's repr of id's and spans.
#[derive(Clone, Debug)]
pub struct Path;
#[derive(Clone, Debug... | Rust | 0 |
, payload).map(|res| res.context("Write payload"));
let read_fut = read_assert_payload(&mut reader, payload).map(|res| res.context("Assert payload"));
tokio::try_join!(write_fut, read_fut)?;
writer.shutdown().await.context("Shutdown operation")?;
Ok(())
}
async fn round_trip_server(payload: &[u8], port... | Rust | 0 |
=Entry(ventana,textvariable=num1) #x=480,y=80
caja1.place(x=355,y=450)
caja2=Entry(ventana,textvariable=cadena1) #x=480,y=120
caja2.place(x=355,y=490)
caja3=Entry(ventana,textvariable=cadena2) #x=480,y=160
caja3.place(x=355,y=530)
caja4=Entry(ventana,textvariable=cadena3) #x=480,y=200
caja4.place(x=355,y=570)
caja5=... | Python | 1 |
unwrap().select();
let a = Matrix::from((
&device,
(3, 3),
[-10f32, -2., -3., -4., -5., -6., -7., -8., -9.],
));
let res = device.max(&a);
assert!(res == -2.);
let res = device.max_cols(&a);
assert_eq!(res.read(), vec![-2., -4., -7.]);
let res = device.max_rows(&a... | Rust | 0 |
%s"%(err))
print("Now printing define input:")
print("--------------------------")
print(instring)
print("--------------------------")
with open("define.input",'w') as defineinput:
defineinput.write(instring)
exit()
def setulimit():
resource.setrlimit(re... | Python | 1 |
dateURL")]
pub update_url: String,
#[serde(rename = "licenseURL")]
pub license_url: String,
}
#[derive(Debug)]
pub struct DownloadedUpdate {
pub license_filename: Option<String>,
pub update_filename: String,
}
pub fn print(software: &Software, update: &SoftwareUpdate) {
let cyan = Style::new()... | Rust | 0 |
#!/usr/bin/env python3
from typing import Tuple, Iterable
from auxilaries.LoopTranslator import LoopTranslator, \
LoopsStatementsContexts
class ForLoopTranslator(LoopTranslator):
@classmethod
def _counters(cls, listener) -> Tuple[str, str, str, str]:
return tuple(listener._fors.next())
@clas... | Python | 1 |
// static ref M2: BitMap<[u64; 1024]> = generate!(BitMap; thread_rng(), *NBITS, BOUND);
static ref M0: BitMap<[u64; 512]> = generate!(BitMap; thread_rng(), *NBITS, BOUND);
static ref M1: BitMap<[u64; 512]> = generate!(BitMap; thread_rng(), *NBITS, BOUND);
static ref M2: BitMap<[u64; 512]> = generate!(BitM... | Rust | 0 |
from scipy.stats import f
def cal_fullmodel(data_df, out_col, consist_col, category_col, rank, RSS, originRSS):
"""
This function is used to calculate rsquared, rsquared_adj, fvalue, f_pvalue, and DoF of F-test for full model(
data before demean process)
"""
k0 = 0
if ('const' in consist_col... | Python | 1 |
├── node.hh
│ ├── pool.hh
│ ├── state_stack.hh
│ └── token.hh
└── progressbar
├── progressbar
│ ├── progressbar.h
│ └── statusbar.h
└── src
├── progressbar.c
└── statusbar.c
";
super::common_test(paths, expected);
}
use :... | Rust | 0 |
which represents
//! a regex replacement rule, as well as several functions
//! that return lists of predefined filter rules.
//!
//! Creating a `FilterRule` compiles a [regular expression](https://docs.rs/regex/1/regex/struct.Regex.html),
//! which means it is potentially expensive to call these predefined
//! filter... | Rust | 0 |
ier are created at the same time, but that is not
/// observable from `add_interface`. It does not provide guardrails to
/// prevent identifier reuse, however.
pub fn add_interface(
&self,
id: BindingId,
properties: InterfaceProperties,
) -> Result<InterfaceEventProducer, WorkerC... | Rust | 0 |
# -*- coding: utf-8 -*- #
# Copyright 2019 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
#
# Unless requir... | Python | 1 |
).to(torch.float)
model = BioGptForSequenceClassification(config)
model.to(torch_device)
model.eval()
result = model(input_ids, attention_mask=attention_mask, labels=sequence_labels)
self.assertEqual(result.logits.shape, (self.model_tester.batch_size, self.model_tester.num_lab... | Python | 1 |
-> fmt::Result {
match self {
Address(n) => write!(f, "Address({})", n),
Quantity(n) => write!(f, "Quantity({})", n),
}
}
}
use Val::*;
#[derive(Clone)]
pub struct Intcode {
program: Vec<IntcodeWord>,
input: Vec<IntcodeWord>,
output: Vec<IntcodeWord>,
relat... | Rust | 0 |
def getrole():
tmp=self.main.gptsovitsw.role.toPlainText().strip()
role=None
if not tmp:
return role
for it in tmp.split("\n"):
s=it.strip().split('#')
if len(s)!=3:
QMessageBox.criti... | Python | 1 |
::NEG_INFINITY),
2 => dep_samples.push(f64::NAN),
3 => dep_samples.push(f64::MAX),
_ => dep_samples.push(f64::MIN),
}
} else {
dep_samples.push(sample_float_range(rng, ... | Rust | 0 |
ert_datetime_array_equal(result, expected)
dta = dta.tz_localize("UTC")
expected = expected.tz_localize("UTC")
fv = dta[-1]
for fill_value in [fv, fv.to_pydatetime()]:
result = dta.shift(1, fill_value=fill_value)
tm.assert_datetime_array_equal(result, expected)
... | Python | 1 |
# -*- coding: utf-8 -*-
# Scrapy settings for design project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://doc.scrapy.org/en/latest/topics/settings.html
# https://doc.scrapy.org/en/latest/topics... | Python | 1 |
super::ACS_VCC_CTRL {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0x0004_020a
}
}
#[doc = "Inductor charge current trimming\n\nValue on reset: 4"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum ICH_TRIM_A {
#[doc = "0: Charge pump max current to 16 mA"... | Rust | 0 |
.
Normal = bgfx_sys::bgfx_attrib_BGFX_ATTRIB_NORMAL as u32,
/// Tangent.
Tangent = bgfx_sys::bgfx_attrib_BGFX_ATTRIB_TANGENT as u32,
/// Bitangent.
Bitangent = bgfx_sys::bgfx_attrib_BGFX_ATTRIB_BITANGENT as u32,
/// Color 0.
Color0 = bgfx_sys::bgfx_attrib_BGFX_ATTRIB_COLOR0 as u32,
/... | Rust | 0 |
ed_cli_deps)
call_args.update(dependencies)
# Check for unsupported CLI dependencies in function parameters
for p_name in sig.parameters:
_check_unsupported_dependency(p_name, unsupported_cli_deps, fn)
# Map tool arguments to function parameters
for p_name in sig.parameters:
if p_... | Python | 1 |
g: String) -> PyResult<String> {
py_try_compile(py, prog)
}
m.add_class::<DatapathInfo>()?;
m.add_class::<PyDatapath>()?;
m.add_class::<PyReport>()?;
Ok(())
}
fn py_start_inner<'p>(py: Python<'p>, ipc: String, alg: PyObject) -> PyResult<i32> {
// Check args
if let Err(e) = portus::... | Rust | 0 |
ll_soon_threadsafe(_set_state, destination, source)
destination.add_done_callback(_call_check_cancel)
source.add_done_callback(_call_set_state)
def wrap_future(future, *, loop=None):
"""Wrap concurrent.futures.Future object."""
if isfuture(future):
return future
assert isinstance(future, ... | Python | 1 |
<label for="latitude">{"Latitude"}</label>
<input
type="number"
name="latitude"
id="latitude"
required={true}
/>
</div>
... | Rust | 0 |
;
parcel.write(get_frame_timestamps as u32)?;
parcel.write(usage)?;
let mut response_parcel = self.transact_parcel(dispdrv::ParcelTransactionId::DequeueBuffer, &mut parcel)?;
let slot: i32 = response_parcel.read()?;
let has_fences_v: u32 = response_parcel.read()?;
let h... | Rust | 0 |
mented!()
}
/// Configures the read-only flag.
///
/// [`fs::set_permissions`]: fn.set_permissions.html
///
/// # Examples
///
/// ```no_run
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use a... | Rust | 0 |
import csv
# Paths to your files
text_file_path = 'tutte.txt' # Path to the text file
csv_file_path = 'quizzes.csv' # Path to the existing CSV file
# Step 1: Read the text file line by line
with open(text_file_path, 'r', encoding='utf-8') as txt_file:
lines_to_add = txt_file.readlines()
# Step 2: Clean lin... | Python | 1 |
#!/usr/bin/env python3
'''Test for signing on a slave Knot w/o zonefile and journal'''
import shutil
from dnstest.utils import *
from dnstest.test import Test
t = Test()
master = t.server("knot")
slave = t.server("knot")
slave.zonefile_sync = "-1"
zone = t.zone_rnd(1, dnssec=False)
t.link(zone, master, slave)
slave... | Python | 1 |
from stable_baselines3 import PPO
from snakeEnv import SnakeEnv
models_dir = "models/PPO"
model_path = f"{models_dir}/best_model.zip"
env = SnakeEnv(render_mode='human')
model = PPO.load(model_path, env=env, device='cpu')
for ep in range(10):
obs, _ = env.reset()
done = False
while not done:
env... | Python | 1 |
sher.result()[..]);
hash = Some(h);
}
// TODO Possible to check if error is because it doesn't exist?
Ok(hash)
}
fn backup_file(path: &Path) -> Result<()> {
if let Ok(f) = File::open(path) {
drop(f); // FIXME Does this actually close the file?
// FIXME This is pretty shady. Po... | Rust | 0 |
,
/*focus: */ Focus::Distance(f), //if aperture == 0 focus dist is irrelevant
35.0,
fstop,
CropFactor::FULL_FORMAT, //perfect camera => 0 => no DoF ; bigger aperture => stronger DoF
);
// https://hdrihaven.com/
let skybox = Arc::new(ImageTexture::... | Rust | 0 |
self.radio_sourceno_2.setText(
_translate(
"Form",
"No Sources were used. The dataset represents 100% original content, derived first-hand (e.g. field collection, lab experiments, etc.)",
)
)
self.label.setText(_translate("Form", "OR"))
s... | Python | 1 |
erstukken = kamerstukken.shuffle(seed=42).select(range(N_docs))
kamerstukken = add_column(kamerstukken, 'source', 'gigacorpus-nl-kamerstukken-extra')
kamerstukken = add_column(kamerstukken, 'subset', None)
kamerstukken = add_column(kamerstukken, 'id', None)
dataset[split].append(kamers... | Python | 1 |
());
assert_eq!(buf, vec![1; 200]);
let payload = vec![1; 200];
writer.write(&payload).expect("write");
let result = writer.flush();
assert!(result.is_err());
}
fn create_reader_and_writer(runtime: &mut Runtime) -> (ByteStreamWriter, ByteStreamReader) {
let conf... | Rust | 0 |
/// eg.
/// oid_map contains 4 algos [0..3]
/// OID_MAX_ID = 3
pub(crate) const OID_MAX_ID: usize = 12;
lazy_static! {
/// search oid index by oid binary
pub static ref OID_MAP: HashMap<Bytes, usize> = vec![
(OCSP_EXT_NONCE_HEX.to_vec(), OCSP_EXT_NONCE_ID),
(OCSP_EXT_CRLREF_HEX.to_vec(), ... | Rust | 0 |
ingDesc(
ResourceIndex: UINT,
pDesc: *mut D3D12_SHADER_INPUT_BIND_DESC,
) -> HRESULT,
fn GetVariableByName(
Name: LPCSTR,
) -> *mut ID3D12ShaderReflectionVariable,
fn GetResourceBindingDescByName(
Name: LPCSTR,
pDesc: *mut D3D12_SHADER_INPUT_BIND_DESC,
) -> HR... | Rust | 0 |
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def DeleteVar(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,... | Python | 1 |
let core = test_core_with_account();
let account = core.get_account().unwrap();
let root = core.get_root().unwrap();
// create documents
let doc = core.create_at_path(&path(&core, "doc1.md")).unwrap().id;
let mut doc = core.db.local_metadata.get(&doc).unwrap().unwrap();
let doc2 = core.crea... | Rust | 0 |
,
value=0.000000003,
unit='seconds',
metadata=common_metadata,
),
sample.Sample(
metric='Cluster Expected Boots',
value=6,
unit='',
metadata=common_metadata,
),
sample.Sample(
metric='Cluster ... | Python | 1 |
ly formatted click errors.
Called by custom exception handler to print richly formatted click errors.
Mimics original click.ClickException.echo() function but with rich formatting.
"""
console = _get_rich_console(stderr=True)
ctx: Union[click.Context, None] = getattr(self, "ctx", None)
if ctx i... | Python | 1 |
from django.test.utils import override_settings
from allauth.socialaccount.tests import OAuth2TestsMixin
from allauth.tests import MockedResponse, TestCase
from .provider import PinterestProvider
class PinterestTests(OAuth2TestsMixin, TestCase):
provider_id = PinterestProvider.id
def get_mocked_response(se... | Python | 1 |
event.result.content,
)
},
)
],
citation... | Python | 1 |
bstractmethod
def denoise(
self,
inputs: Dict[str, torch.Tensor],
**kwargs,
) -> Tuple[Dict[str, torch.Tensor], torch.Tensor, List[Dict[str, torch.Tensor]]]:
"""
Peforns denoising/sampling using the reverse diffusion process.
Returns the denoised/sampled data, the... | Python | 1 |
_pairs(population)
return await asyncio.gather(*(self.merge(pair) for pair in pairs))
@ls.traceable
async def merge(self, pair: tuple[Variant, Variant]) -> pm_types.PromptWrapper:
cluster_prompts = [v.prompt.get_prompt_str_in_context() for v in pair]
existing_prompts = "\n".join(cluster... | Python | 1 |
filter_config = config['filters']
else:
logger.warning(f"No 'filters' section found in {config_path}")
return FilterChain([])
return cls.create_filter_chain(filter_config)
except Exception as e:
logger.error(f"Error loading filter ... | Python | 1 |
= OrderedDict()
self._attrs["exec_path"]["true"] = ""
def _signature(self):
signature = "upsampling2d: S=[{s}], M=[{m}]]".format(
s=self._attrs["scale_factor"], m=self._attrs["mode"]
)
return signature
def __call__(self, x: Tensor) -> List[Tensor]:
self._at... | Python | 1 |
from __future__ import print_function
import cv2 as cv
import numpy as np
import argparse
source_window = 'Source image'
corners_window = 'Corners detected'
max_thresh = 255
def cornerHarris_demo(val):
thresh = val
# Detector parameters
blockSize = 2
apertureSize = 3
k = 0.04
# Detecting cor... | Python | 1 |
buf.put_slice(digits);
buf.put_slice(CRLF);
}
StreamEnd => {
buf.put_u8(STREAM_END);
buf.put_slice(CRLF);
}
}
}
/// Process recursive type stack with self token.
/// Start with the stack with `vec![Some(amt)]`
... | Rust | 0 |
assert_eq!(100, <balances::Module<Test>>::free_balance(1)); // 100 - 1(exit) - 1(fee) + 1(exit) + 1(return fee)
assert_eq!(0, Parent::total_deposit()); // +- 0
});
}
}
<reponame>LeonGGX/axum-partitions-sqlx
//! src/handlers/login_hdl.rs
use anyhow::Error;
use axum::extract::{Extension, Form};
use axum::r... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.