text string | label_name string | labels int64 |
|---|---|---|
# Problem: Island Perimeter - https://leetcode.com/problems/island-perimeter/description/
class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
rl, cl = len(grid), len(grid[0])
visited = [[0]*cl for _ in range(rl)]
def dfs(row, col):
if row < 0 or row >= rl o... | Python | 1 |
from datetime import datetime
import requests
from countryinfo import CountryInfo
parameters = {
'appid': 'your-api',
'units': 'metric',
'lang': 'ru'
}
def weather_info(city):
parameters['q'] = city
try:
weather = requests.get('https://api.openweathermap.org/data/2.5/weather', params=param... | Python | 1 |
on);
let f: &F = &*(f as *const F);
f(
TextBuffer::from_glib_borrow(this).unsafe_cast_ref(),
&mut location_copy,
str::from_utf8(slice::from_raw_parts(text as *const u8, len as usize)).unwrap(),
)
}
... | Rust | 0 |
,
}
#[derive(Copy, Clone)]
#[repr(u32)]
#[derive(Debug)]
#[derive(PartialEq,Eq,PartialOrd,Ord,Hash)]
pub enum UTimeZoneTransitionType {
UCAL_TZ_TRANSITION_NEXT = 0,
UCAL_TZ_TRANSITION_NEXT_INCLUSIVE = 1,
UCAL_TZ_TRANSITION_PREVIOUS = 2,
UCAL_TZ_TRANSITION_PREVIOUS_INCLUSIVE = 3,
}
#[link(name = "icuuc",... | Rust | 0 |
from collections.abc import Sequence
from collections import deque
def topological_sort(precedence_map: dict[int, list[int]], n_tasks: int) -> list[int]:
"""
Perform a topological sort on a directed acyclic graph.
Parameters
----------
precedence_map: dict
A dictionary containing the prec... | Python | 1 |
low(safe_extern_statics)]
#![allow(non_upper_case_globals)]
#![allow(dead_code)]
#![allow(non_camel_case_types)]
use ec;
use partition::*;
use partition::TxSize::*;
const PLANES: usize = 3;
const PARTITION_PLOFFSET: usize = 4;
const PARTITION_CONTEXTS: usize = 16;
const PARTITION_TYPES: usize = 4;
const MI_SIZE_LOG... | Rust | 0 |
+= 1;
}
}
}
}
}
impl Drop for MyQueryContext {
// Execute some operations on the context before the Connection is dropped.
fn drop(&mut self) {
println!("{:?}", self);
}
}
}
<reponame>zhyass/databend
// Copyright 2... | Rust | 0 |
43(self):
# Some large number with weird prime factors. Known values taken from
# wolfram alpha result (assuming WA is correct).
self.assertListEqual(
factors.prime_factors(600851475143),
[71, 839, 1471, 6857]
)
class TestFactors (unittest.TestCase):
def t... | Python | 1 |
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from core.models import Inscripciones, Estudiantes, Materias
from core.serializers import InscripcionSerializer
class InscripcionViewSet(viewsets.ModelViewSet):
queryset = Inscripciones.obj... | Python | 1 |
Action {
if depth > 0 && ui.add(Button::new("delete").text_color(color::RED)).clicked {
return Action::Delete;
}
self.0 = std::mem::take(self)
.0
.into_iter()
.enumerate()
.filter_map(|(i, mut tree)| {
if tree.ui_impl(... | Rust | 0 |
(|| String::from("Unknown error creating shader")),
)
}
}
pub fn link_program(
context: &WebGlRenderingContext,
vert_shader: &WebGlShader,
frag_shader: &WebGlShader,
) -> Result<WebGlProgram, String> {
let program = context
.create_program()
.ok_or_else(|| String::from("Unable to create shader ob... | Rust | 0 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Cigar Inventory</title>
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
/>
<style>... | Python | 1 |
await get_or_create_peers(
db, workspace_name, [schemas.PeerCreate(name=peer_name)]
)
)[0]
if peer.metadata is not None:
honcho_peer.h_metadata = peer.metadata
if peer.configuration is not None:
honcho_peer.configuration = peer.configuration
await db.commit()
... | Python | 1 |
exception_report = ErrorReport(ErrorReason.EXCEPTION, message)
traceback.print_exc()
finally:
if pipeline is not None:
pipeline.cleanup_cache()
run_info = pipeline.run_info
captured = capsys.readouterr()
write_logs(captured, pipeline)
if ... | Python | 1 |
\\]
Slave-mode output disabled This bit is relevant only in the slave mode, MS=1. In multiple-slave systems, it is possible for an SSI master to broadcast a message to all slaves in the system while ensuring that only one slave drives data onto its serial output line. In such systems the RXD lines from multiple slaves ... | Rust | 0 |
9 to DER"),
*cert.as_der()
);
}
#[test]
fn should_create_certificate_from_valid_der() {
let cert_der = generate_ed25519_cert()
.1
.to_der()
.expect("Failed to convert X509 to DER");
let cert = TlsPublicKeyCert::new_from_der(cert_der.c... | Rust | 0 |
#!/usr/bin/env python3
"""Plots the optimal cost-to-go for an elevator in 3D."""
import sys
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from scipy.linalg import solve_discrete_are
from scipy.signal import StateSpace
from bookutil import latex
if "--noninteractive" in sys.argv:
m... | Python | 1 |
ases::new().case("tests/*.md");
}
<reponame>bitwalker/lumen<gh_stars>0
use std::convert::TryInto;
use std::sync::Arc;
use liblumen_alloc::atom;
use liblumen_alloc::erts::process::code::stack::frame::{Frame, Placement};
use liblumen_alloc::erts::process::{code, Process};
use liblumen_alloc::erts::term::prelude::Encoded... | Rust | 0 |
GENDER_CHOICES = [
('male', 'Male'),
('female', 'Female')
]
EMPLOYEE_STATUS = [
('active', 'Active'),
('on leave', 'On Leave'),
('resigned', 'Resigned'),
]
LEAVE_TYPE = [
('sick leave', 'Sick Leave'),
('anual leave', 'Anual Leave'),
('paternity', 'Paternity'),
]
STATUS_CHOICE... | Python | 1 |
{error}")]
Migration {
name: Cow<'static, str>,
version: u64,
error: MigrationError,
},
#[error("error reverting migration: {error}")]
Revert {
name: Cow<'static, str>,
version: u64,
error: MigrationError,
},
#[error("expected migration {version} ... | Rust | 0 |
class KeyboardCoordinates:
def __init__(self):
# Dictionary to store the coordinates of each key
self.key_coordinates = {
"A": (10.0, 2.0), "B": (13.4, 3.4), "C": (9.6, 3.4), "D": (8.6, 5.3), "E": (8.1, 7.2),
"F": (10.5, 5.3), "G": (12.4, 5.3), "H": (14.3, 5.3), "I": (17.6,... | Python | 1 |
from tempfile import TemporaryDirectory
import numpy as np
from building3d.sim.rays.dump_buffers import dump_buffers
from building3d.sim.rays.dump_buffers import read_buffers
from building3d.geom.building import Building
from building3d.sim.rays.simulation_config import SimulationConfig
def test_dump_buffers():
... | Python | 1 |
ippy::cast_possible_truncation)]
fn mul(self, other: Color) -> Color {
let (r1, r2) = (self.0.r as u16, other.0.r as u16);
let (g1, g2) = (self.0.g as u16, other.0.g as u16);
let (b1, b2) = (self.0.b as u16, other.0.b as u16);
let (a1, a2) = (self.0.a as u16, other.0.a as u16);
... | Rust | 0 |
'[\u0902अ-आई-उएओकगचजञ-टडण-तदनपबम-रलवस-ह\u093C\u093E\u0940-\u0941\u0947\u094B]',
# Sangu
'sbp': r'[a-ps-wy]',
# Sardinian
'sc': r'[a-jl-pr-vzàèìòù]',
# Sicilian
'scn': r'[a-jl-vzàâèêìîòôùûḍ]',
# Sindhi
'sd': r'[ء-آا-بت-غف-قل-ويٺ-ٻٽ-ڀڃ-ڄچ-ڇڊڌ-ڍڏڙڦک-ڪگڱڳڻھ]',
# Sindhi (Devanagari)
'... | Python | 1 |
from django.contrib import admin
from django.urls import path, include
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
schema_view = get_schema_view(
openapi.Info(
title="Infern Bot API Documentation",
default_version='v1',
desc... | Python | 1 |
oudSDKException(code, message, reqid)
except Exception as e:
if isinstance(e, TencentCloudSDKException):
raise e
else:
raise TencentCloudSDKException(e.message, e.message)
def DescribeTaskStatus(self, request):
"""接口使用于:客户平台可使用该接口查询任务执行状态或者执行... | Python | 1 |
fig = px.pie(
names=labels,
values=values,
title=title,
hole=data.get('hole', 0), # 支持环形图
color_discrete_sequence=data.get('colors') # 自定义颜色
)
st.plotly_chart(fig, use_c... | Python | 1 |
mic_name(name);
Ok(this.property_is_enumerable(qname).into())
}
/// `Object.prototype.setPropertyIsEnumerable`
pub fn set_property_is_enumerable<'gc>(
activation: &mut Activation<'_, 'gc, '_>,
this: Option<Object<'gc>>,
args: &[Value<'gc>],
) -> Result<Value<'gc>, Error> {
let this: Result<Object<'... | Rust | 0 |
# Faça um Programa que peça a temperatura em graus Farenheit, transforme e mostre a temperatura em graus Celsius. C = (5 * (F-32) / 9).
farenheit = float(input("Digite um n. de graus celsius para ser calculado: "))
celsius = (5 * (farenheit-32) / 9)
print(F'O Graus Celsius calculados é calculado é {celsius:.2f} °F.'... | Python | 1 |
"""
Tests GitHub's public API to verify that all assumptions made by Grip
are still in place.
Note that these tests assume a reliable internet connection, so they
may fail despite being correct. To run the tests without making any
external calls, use `py.test -m "not assumption"`
"""
from __future__ import print_func... | Python | 1 |
e),
/// Allows const generic types (e.g. `struct Foo<const N: usize>(...);`).
(active, const_generics, "1.34.0", Some(44580), None),
/// Allows using `#[optimize(X)]`.
(active, optimize_attribute, "1.34.0", Some(54882), None),
/// Allows using C-variadics.
(active, c_variadic, "1.34.0", Some(... | Rust | 0 |
_ic2eq) {
v3 = x - ic2eq
v1 = a1 * ic1eq + a2 * v3
v2 = ic2eq + a2 * ic1eq + a3 * v3
n_ic1eq = 2.0 * v1 - ic1eq
n_ic2eq = 2.0 * v2 - ic2eq
n_x = m0 * x + m1 * v1 + m2 * v2
}
fn main(iterations: i64, output_arr: &[f32]) -> (sum) {
output_slice = output_arr[..iterations]
fs = 48000.0
f... | Rust | 0 |
# This file is Copyright 2019 Volatility Foundation and licensed under the Volatility Software License 1.0
# which is available at https://www.volatilityfoundation.org/license/vsl-v1.0
#
"""The interfaces module contains the API interface for the core volatility
framework.
These interfaces should help developers attem... | Python | 1 |
ney_flow_index;
pub use money_flow_index::MoneyFlowIndex;
mod parabolic_sar;
pub use parabolic_sar::{ParabolicSAR, ParabolicStopAndReverse};
mod pivot_reversal_strategy;
pub use pivot_reversal_strategy::PivotReversalStrategy;
mod price_channel_strategy;
pub use price_channel_strategy::PriceChannelStrategy;
mod rela... | Rust | 0 |
# Copyright 2024 DeepMind Technologies Limited.
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | Python | 1 |
parse.ArgumentParser(description="Python Windows MAC changer")
parser.add_argument("-r", "--random", action="store_true", help="Whether to generate a random MAC address")
parser.add_argument("-m", "--mac", help="The new MAC you want to change to")
args = parser.parse_args()
if args.random:
# if ... | Python | 1 |
merged_item["name_en"] = i_en.get("name", "")
merged_item["name_ko"] = i_ko.get("name", "")
merged_item["name_ja"] = i_ja.get("name", "")
del merged_item["name"]
merged_items.append(merged_item)
merged_obj["items"] = merged_items
... | Python | 1 |
mentions or other segments before the command
m = CMD_JM.search(text or "")
if not m:
return
album_id = m.group(1)
log_info(f"命令触发:group={group_id} jm {album_id}")
# 群开关检查
if not is_group_enabled(int(group_id)):
await _call_and_get_message_id(
... | Python | 1 |
= std::ptr::null_mut();
assert_eq!(GA_OK, unsafe {
GDKRPC_GA_register_user(sess, hw_device, mnemonic_c.as_ptr(), &mut auth_handler)
});
let mut auth_handler: *const GA_auth_handler = std::ptr::null_mut();
assert_eq!(GA_OK, unsafe {
GDKRPC_GA_login(sess, hw_device, mnemonic_c.as_ptr(), p... | Rust | 0 |
///
/// [`discard_reply`]: crate::Xcb::xcb_discard_reply
/// [`xcb_xf86dri_query_direct_rendering_capable_reply`]: Self::xcb_xf86dri_query_direct_rendering_capable_reply
#[inline]
pub unsafe fn xcb_xf86dri_query_direct_rendering_capable(
&self,
c: *mut xcb_connection_t,
screen: u... | Rust | 0 |
::libc::c_char)
-> LLVMBool;
pub fn LLVMGetTargetName(T: LLVMTargetRef) -> *const ::libc::c_char;
pub fn LLVMGetTargetDescription(T: LLVMTargetRef) -> *const ::libc::c_char;
pub fn LLVMTargetHasJIT(T: LLVMTargetRef) -> LLVMBool;
pub fn LLVMTargetHasTargetMachine(T: LL... | Rust | 0 |
the `if` expression, which was
// executed, and counted, 4 times, before reaching the overflow add.
// If the program did not overflow, the coverage for `might_overflow()` would look like this:
//
// 4| |fn might_overflow(to_add: u32) -> u32 {
// 5| 4| if to_add > 5 {
// 6| 0| ... | Rust | 0 |
component associated to the entity.
///
/// Behaves somewhat similarly to `std::collections::HashMap`'s entry api.
///
/// ## Example
///
/// ```rust
/// # extern crate specs;
/// # use specs::prelude::*;
/// # struct Comp {
/// # field: u32
/// # }
/// # impl Componen... | Rust | 0 |
let bpv = input.read_byte()?;
match bpv {
0 => DocIdsWriter::read_delta_vints(input, count, doc_ids),
32 => DocIdsWriter::read_ints32(input, count, doc_ids),
24 => DocIdsWriter::read_ints24(input, count, doc_ids),
_ => bail!(UnsupportedOperation(Cow::Own... | Rust | 0 |
KeyCode::Esc),
];
KEYCODE.iter()
}
}
impl Display for ReedLineCrossTermKeyCode {
fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
match self {
ReedLineCrossTermKeyCode(kc) => match kc {
KeyCode::Backspace => write!(f, "Backspace"),
KeyCo... | Rust | 0 |
return regs[n]
return "arg[%i]" % n
def argument(n: int, abi: pwndbg.lib.abi.ABI | None = None) -> int:
"""
Returns the nth argument, as if $pc were a 'call' or 'bl' type
instruction.
Works only for ABIs that use registers for arguments.
"""
abi = abi or pwndbg.aglib.arch.function... | Python | 1 |
"""Bartlett's trasmission chain experiment from Remembering (1932)."""
from dallinger import db
from dallinger.experiment import Experiment
from dallinger.networks import Chain
try:
from . import models
except ImportError:
import models
class IteratedDrawing(Experiment):
"""Define the structure of the e... | Python | 1 |
_digit {
doubled_digits = true;
} else if next_digit > current_digit {
not_decreasing = false;
}
current_digit = next_digit;
password /= 10;
}
doubled_digits && not_decreasing
}
fn is_valid2(password: u32) -> bool {
if password > <PASSWORD> || passw... | Rust | 0 |
ack.format_exc()}")
return []
def generate_broader_query(query):
"""生成更宽泛的搜索策略"""
try:
# 移除一些限制性标签
broader = query.replace('[Title/Abstract]', '[All Fields]')
broader = broader.replace('[Mesh]', '[All Fields]')
# 如果包含多个AND条件,只保留部分
terms = broader.split('... | Python | 1 |
!self.initiator && self.pattern.is_oneway() {
bail!(StateProblem::OneWay);
} else if payload.len() + TAGLEN > MAXMSGLEN || payload.len() + TAGLEN > message.len() {
bail!(Error::Input);
}
let cipher =
if self.initiator { &mut self.cipherstates.0 } else { &mut... | Rust | 0 |
from idautils import *
from idaapi import *
from idc import *
import struct
# Wait for auto analysis to complete
idaapi.auto_wait()
print("Analysis done, generating meso")
image_base = idaapi.get_imagebase()
input_name = GetInputFile()
if len(ARGV) >= 4 and ARGV[1] == "cmdline":
input_name = ARGV[3]
filename =... | Python | 1 |
ruct CurrencyIdConvert;
impl Convert<CurrencyId, Option<MultiLocation>> for CurrencyIdConvert {
fn convert(id: CurrencyId) -> Option<MultiLocation> {
match id {
CurrencyId::R => Some(Parent.into()),
CurrencyId::A => Some((Parent, Allychain(1), GeneralKey("A".into())).into()),
CurrencyId::B => Some((Parent, ... | Rust | 0 |
cit => (1 << 33) | (cp as u64),
Alias => (1 << 34) | (cp as u64),
Hangul => (1 << 35) | (cp as u64),
Ideograph => (1 << 36) | (cp as u64),
}
}
}
/// Build one big map in memory from every possible name of a character to its
/// corresponding codepoint. One codepoint may ... | Rust | 0 |
from solution import *
import pytest
from solution import is_valid_identifier
def test_is_valid_identifier():
assert is_valid_identifier("myIdentifier123") == True
assert is_valid_identifier("123myIdentifier") == False
assert is_valid_identifier("for") == False
assert is_valid_identifier("") == False
... | Python | 1 |
nce_ids = instances[:, feature_id].argsort()
let mut sorted_instance_ids = indices.to_vec();
sorted_instance_ids.sort_unstable_by_key(|&row_id| train.features_rank[(row_id, feature_id)]);
for &idx in &sorted_instance_ids {
assert!(!train.features[(idx, feature_id)].is_nan());
assert_ne!(tra... | Rust | 0 |
!(bigint::PUBLIC_EXPONENT_MAX_BITS < N_MIN_BITS);
// XXX: Steps 4 & 5 / Steps d, e, & f are not implemented. This is also the
// case in most other commonly-used crypto libraries.
Ok((n, e))
}
// Type-level representation of an RSA public modulus *n*. See
// `super::bigint`'s modulue-level documentation.... | Rust | 0 |
import socket
import sys
# Create socket (allows two computers to connect)
def socket_create():
try:
global host
global port
global s
host = ''
port = 9999
s = socket.socket()
except socket.error as msg:
print("Socket creation error: " + str(msg))
# Bi... | Python | 1 |
''' main.py The purpose of this program is to be the primary executable Vyrtuous.
Copyright (C) 2024 github.com/brandongrahamcobb
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, ei... | Python | 1 |
_("Unable to display the groups of this"
" project."))
else:
# Construct Groups list, adding the role attribute
for group_id in project_groups_roles:
group = groups[group_id]
group.roles = [role.name for role in roles
... | Python | 1 |
me(new_passwd))
})?;
Ok(())
}
fn register_shells_to_system(mut shell_paths: HashSet<String>) -> Result<()> {
{
let mut open_opts = std::fs::OpenOptions::new();
open_opts.read(true).write(false).create(false);
let shells = open_opts
.open("/etc/shells")
.with_... | Rust | 0 |
"""Provide class for testing in French locale
"""
import sys
import locale
import pytest
__ALL__ = ['CommaDecimalPointLocale']
def find_comma_decimal_point_locale():
"""See if platform has a decimal point as comma locale.
Find a locale that uses a comma instead of a period as the
decimal point.
R... | Python | 1 |
Op::FpToFp(64) => Ok(Sort::F64),
Op::FpToFp(32) => Ok(Sort::F32),
Op::PfUnOp(_) => Ok(check_raw(&t.cs[0])?),
Op::PfNaryOp(_) => Ok(check_raw(&t.cs[0])?),
Op::UbvToPf(m) => Ok(Sort::Field(m.clone())),
Op::Select => array_or(&check_raw(&t.cs[0])?, "select").map(|(_, v)| v.c... | Rust | 0 |
876498576, -68.545323706},
{0xac2ba4ed9b96149b, "phpu9vdvksb9", -66.677845024, 145.979312412},
{0xb0d2c56c5b10a02f, "q39dbv2v22h2", -36.049361083, 103.393380636},
{0x496b7cb4bc7cb6f5, "95prte5wgkvg", 18.211023728, -124.558034493},
{0x4c24062e90c0e832, "9hk0dcnhs3n3", 24.000411826, -129.2... | Rust | 0 |
ig(v: &Value) -> Result<()> {
let homedir = dirs::home_dir();
let path = match homedir {
Some(p) => p.join(SHUTTLE_CONFIG),
None => return Err(Error::new(ErrorKind::Other, "home dir not found!")),
};
let mut file = OpenOptions::new()
.truncate(true)
.write(true)
... | Rust | 0 |
colors.append(self.colors['classical']['primary'])
else:
colors.append(self.colors['quantum']['primary'])
y_pos = np.arange(len(models))
bars = ax.barh(y_pos, accuracies, color=colors, alpha=0.8, edgecolor='black', linewidth=0.5)
# 設置標籤
ax.s... | Python | 1 |
name_acquired_stream.into_future(),
);
let changed_signal = changed_signal.0.unwrap();
let (acquired_name, _, new_owner) = changed_signal
.body::<(
BusName<'_>,
Optional<UniqueName<'_>>,
Optional<UniqueName<'_>>,
... | Rust | 0 |
{
bk_core_core::<FnvHashSet<Vertex>>(orderstr, size, samples, set_type, &func_indices)
}
SetType::Hashbrown => bk_core_core::<hashbrown::HashSet<Vertex>>(
orderstr,
size,
samples,
set_type,
&func_indi... | Rust | 0 |
de")]
use serde::Serialize;
use crate::{ConversionError, Error};
use super::{validate_bytes, FullTimeStr};
/// Owned string for a time in RFC 3339 [`full-time`] format, such as `12:34:56.7890-23:12`.
///
/// Available when `alloc` feature is enabled.
///
/// # Examples
///
/// ```
/// # use datetime_string::rfc3339:... | Rust | 0 |
from django.db import models, transaction
from django.utils import timezone
from django_fsm import FSMField, transition
from apps.company.models import Company
from apps.products.models import Product
from apps.suppliers.models import Supplier
from apps.users.models import CustomUser
class InventoryManager(models.Ma... | Python | 1 |
app_details += "\n<code>Rating :</code> " + app_rating.replace(
"Rated ", "⭐ "
).replace(" out of ", "/").replace(" stars", "", 1).replace(
" stars", "⭐ "
).replace(
"five", "5"
)
app_details += (
"\n<code>Features :</code> <a href='"
... | Python | 1 |
1 validation error for Model
value
Input should be a valid string [type=string_type, input_value=42, input_type=int]
'''
class Model(BaseModel):
model_config = ConfigDict(coerce_numbers_to_str=True)
value: str
repr(Model(value=42).value)
#> "42"
repr(Mod... | Python | 1 |
ustc_private)]
extern crate rustc_ast;
extern crate rustc_errors;
extern crate rustc_lint;
extern crate rustc_session;
extern crate rustc_span;
use rustc_ast::ast::Expr;
use rustc_errors::{Applicability, DiagnosticBuilder};
use rustc_lint::{EarlyContext, EarlyLintPass, Lint, LintContext};
use rustc_session::{declare_... | Rust | 0 |
'filename')
self.handler = SocketlessRequestHandler()
def test_query_arguments(self):
path = self.handler.translate_path('/filename')
self.assertEqual(path, self.translated)
path = self.handler.translate_path('/filename?foo=bar')
self.assertEqual(path, self.translated)
... | Python | 1 |
pallet_transaction_payment_rpc_runtime_api::{FeeDetails, InclusionFee};
use primitives::{Balance, CurrencyId, ReserveIdentifier};
use sp_runtime::{
traits::{
Bounded, CheckedSub, Convert, DispatchInfoOf, One, PostDispatchInfoOf, SaturatedConversion, Saturating,
SignedExtension, UniqueSaturatedInto, Zero,
},
tra... | Rust | 0 |
8]) -> IResult<&[u8], Token> {
do_parse!(i,
len: be_u32 >>
nameoff: be_u32 >>
value: take!(len) >>
take!(residue_to_align(len as usize)) >>
(Token::Prop {
len: len,
nameoff: nameoff,
value: value,
})
)
}
fn parse_token_nop(i: ... | Rust | 0 |
import requests
import time
import re
import os
import textwrap
from encryption.srun_md5 import *
from encryption.srun_sha1 import *
from encryption.srun_base64 import *
from encryption.srun_xencode import *
os.system("cls")
header = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (... | Python | 1 |
ected fields"""
# Arrange
eval_id = "eval-complete"
agent_id = "agent-123"
eval_name = "complete-eval"
avg_score = 8.5
num_iterations = 3
mock_result = Mock()
mock_result.compute_stats = Mock(return_value={"avg_score": avg_score})
with patch(
... | Python | 1 |
def update(self, sequence):
list_of_detections = []
for frame in sequence:
detections = self.detection_model(frame)
detections = detections[0].to_list()
if len(detections) > 0 and self.image_model is not None:
embeds = self.image_model.embed_detections(detections, frame)
... | Python | 1 |
from langchain_core.utils.strings import comma_list, stringify_dict, stringify_value
__all__ = ["stringify_value", "stringify_dict", "comma_list"]
| Python | 1 |
docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [pcr2](pcr2) module"]
pub type PCR2 = crate::Reg<u32, _PCR2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _PCR2;
#[doc = "`read()` method returns [pcr2::R](pcr2::R) reader structure"]
impl crate::Readable for PCR2 {}
#[doc = ... | Rust | 0 |
>, effects: &mut EditEffects) {
// TODO Copying from make/buildings.rs
let mut center_per_bldg: BTreeMap<BuildingID, HashablePt2D> = BTreeMap::new();
let mut query: HashSet<HashablePt2D> = HashSet::new();
for id in input {
let center = map.get_b(id).polygon.center().to_hashable();
center... | Rust | 0 |
mut a = NumpyVector::new(3);
let result = a.map(&|x| { x + 2.0});
assert_eq!(result.data, vec![2.0, 2.0, 2.0]);
}
#[test]
fn vector_max_test() {
let a = NumpyVector::from_vec(&vec![2.0, 3.0, 0.0]);
assert_eq!(3.0, a.max());
}
#[test]
fn vector_sum_test() {
let a = NumpyVector::from_vec(&vec![1.0... | Rust | 0 |
"m[{}] = {} < {} => {}",op.v3,op.v1,op.v2,prog[op.v3 as usize]);
ic.pos += 4;
},
8 => {
let op = read3(&ic.prog, mode, ic.pos);
ic.prog[op.v3 as usize] = if op.v1 == op.v2 { 1 } else { 0 };
//println!("m[{}]... | Rust | 0 |
expose_headers=['*']
)
try:
OGC_SCHEMAS_LOCATION = Path(CONFIG['server']['ogc_schemas_location'])
except KeyError:
OGC_SCHEMAS_LOCATION = None
if (OGC_SCHEMAS_LOCATION is not None and
not OGC_SCHEMAS_LOCATION.name.startswith('http')):
if not OGC_SCHEMAS_LOCATION.exists():
raise... | Python | 1 |
]
fn reverse_dependencies_includes_published_by_user_when_present() {
let (app, anon, user) = TestApp::init().with_user();
let user = user.as_model();
app.db(|conn| {
let c1 = CrateBuilder::new("c1", user.id)
.version("1.0.0")
.expect_build(conn);
CrateBuilder::new("... | Rust | 0 |
strides=strides,
activation=activation,
batch_normalization=batch_normalization,
conv_first=False)
y = resnet_layer(inputs=y,
num_filters=num_filters_in,
... | Python | 1 |
#!/usr/bin/python3
import brownie
def test_check_bounds(accounts, nft):
"""check bounds"""
with brownie.reverts("dev: index out of bounds"):
nft.transferRange(accounts[2], 0, 1000, {"from": accounts[0]})
with brownie.reverts("dev: index out of bounds"):
nft.transferRange(accounts[2], 1000... | Python | 1 |
t = input()
result = list()
if not str(t).isdigit():
result.append('Invalid Test')
if str(t).isdigit():
t = int(t)
if t > 10 or t == 0:
result.append('Invalid Test')
else:
while t > 0:
stirng = input()
lower = 0
upere = 0
if len(stirng) > 1... | Python | 1 |
import numpy as np
import chromadb
import os
import time
NB_WORDS = 100
word_file = "/usr/share/dict/words"
WORDS = open(word_file).read().splitlines()
def random_word():
return WORDS[np.random.randint(len(WORDS))]
cache_path = "/tmp/cache_db_bench/"
os.system("rm -rf " + cache_path + "/*")
client = chromadb.... | Python | 1 |
br#"a:3:{s:3:"foo";b:1;s:3:"bar";s:3:"xyz";s:3:"sub";a:1:{s:1:"x";i:42;}}"#,
Outer {
foo: true,
bar: "xyz".to_owned(),
sub: Inner { x: 42 },
}
);
}
#[test]
fn deserialize_struct_with_optional() {
#[derive(Debug, ... | Rust | 0 |
_eq!(Solution::regions_by_slashes(grid), res);
let grid = vec_string![" /", " "];
let res = 1;
assert_eq!(Solution::regions_by_slashes(grid), res);
let grid = vec_string!["\\/", "/\\"];
let res = 4;
assert_eq!(Solution::regions_by_slashes(grid), res);
}
<reponame>genos/online_problems<filename>... | Rust | 0 |
size=SizeReference(tensor_id=TensorId("input"), axis_id=AxisId("x"))),
],
test_tensor=FileDescr(source=root + test_output),
sample_tensor=FileDescr(source=root + sample_output),
data=IntervalOrRatioDataDescr(type="float32"),
)
# puts all metadata together and generates model here
my_model_descr = Mo... | Python | 1 |
can occur when interacting with I2C
#[derive(Fail, Debug, Clone, PartialEq)]
pub enum I2CError {
/// An error occurred when converting a Rust string to a C string.
/// Specifically, the Rust string contained a null character, which cannot be represented
/// in C strings.
#[fail(
display = "Strin... | Rust | 0 |
.long("image")
.value_name("FILE")
.help("Path to background image (PNG, JPG, BMP, GIF)"))
.arg(Arg::with_name("mode")
.short("m")
.long("mode")
.value_name("BG_MODE")
.help("Mode affecting image render on screen (fill, fit, stretch, ... | Rust | 0 |
import numpy as np
from .utils import hadamard_matrix, get_mask
from .utils import validate_stats, visualize
from .sequency import get_matrix as get_sequency_matrix
def get_matrix(n):
return hadamard_matrix(n)
def get_index_matrix(n):
H = get_sequency_matrix(n)
Hbig = get_matrix(n**2)
index_matrix... | Python | 1 |
Pad7,
Kp8 => NumPad8,
Kp9 => NumPad9,
Kp0 => NumPad0,
KpPlus => NumPadPlus,
KpMinus => NumPadMinus,
KpMultiply => NumPadMultiply,
KpDivide => NumPadDivide,
KpEnter => NumPadEnter,
LCtrl => LeftCtrl,
LShift => LeftShift,
LAlt => Lef... | Rust | 0 |
#!/bin/env python3
# 提取OUTCAR中每一步的原子坐标和能量
# 用法:excoor.py
# 或:excoor.py 20 24 35 (将分别提取第20,24,35步的构型并生成相应的POSCAR文件)
import re
import math
import sys
import os
from VASP import execCmd, CmdRrror
def writePOSCAR(content, base, number_of_atoms, step):
os.system("head -7 POSCAR > POSCAR%d" % step)
with open("POSC... | Python | 1 |
#
'''
Flag (Bandeira) - Marcar um local
None = Não valor
is e is not = é ou não é (tipe, valor, identidade)
id = identidade
'''
v1 = 'a'
v2 = 'a'
print(id(v1))
print(id(v2))
# condição = False
# if confição:
# print("Faça algo")
# else:
# print("Não faça algo")
| Python | 1 |
.. let’s just say I’m all caked up 🍑<br />\n<br />\nA place for me to strip down into my lewdest sets 🙈 with angles of all of me 🥵 Cosplay, Lingerie, A.I. Nude art, twerking, feet, and more of me 😉 so what are you waiting for?<br />\n<br />\nFor more content check out my monthly subscription page: @lin... | Python | 1 |
lor_jitter,
erasing=erasing,
)
transformed_image = transform(Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)))
assert transformed_image.shape == (3, 224, 224)
assert torch.is_tensor(transformed_image)
assert transformed_image.dtype == torch.float32
@pytest.mark.slow
@pytest.mark.s... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.