text string | label_name string | labels int64 |
|---|---|---|
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from collections.abc import Sequence
BORDER = {'TL': '┌', 'TR': '┐', 'BL': '└', 'BR': '┘', 'H': '─', 'V': '│', 'TM': '┬', 'BM': '┴'}
def make_table(rows: Sequence[Sequence[str]], width: int = 100) -> str:
"""Create a text... | Python | 1 |
= "min-samd51j")]
adc_pins! {
Pb0: (ADC0, 12),
Pb1: (ADC0, 13),
Pb4: (ADC1, 6),
Pb5: (ADC1, 7),
Pb6: (ADC1, 8),
Pb7: (ADC1, 9),
}
#[cfg(feature = "min-samd51n")]
adc_pins! {
Pc2: (ADC1, 4),
Pc3: (ADC1, 5),
Pc0: (ADC1, 10),
Pc1: (ADC1, 11),
}
#[cfg(feature = "min-samd... | Rust | 0 |
from django.conf import settings
from django_elasticsearch_dsl import Document, Index, fields
from django_elasticsearch_dsl_drf.compat import KeywordField, StringField
from django_elasticsearch_dsl_drf.analyzers import edge_ngram_completion
from django_elasticsearch_dsl_drf.versions import ELASTICSEARCH_GTE_5_0
from ... | Python | 1 |
mu;
mod io;
pub mod keyboard;
}
pub mod kernel {
pub mod main;
pub mod interrupts;
mod stdio;
mod keyboard;
}
#[no_mangle]
pub extern "C" fn _Unwind_Resume() -> ! {
loop {}
}
/// Check a Luhn checksum.
pub fn is_valid(code: &str) -> bool {
const RADIX: u32 = 10;
// check if the code is too short OR... | Rust | 0 |
ichlet_bcs: Option<&dyn DirichletBoundaryConditions>) {
if self.model_matrix_storage.is_none() {
let mut mass_matrix = self
.model
.assemble_mass(self.material.density)
.to_csr(Add::add);
apply_homogeneous_dirichlet_bc_csr::<f64, U2>(&mut m... | Rust | 0 |
# This file is not meant for public use and will be removed in SciPy v2.0.0.
# Use the `scipy.optimize` namespace for importing the functions
# included below.
import warnings
from . import _cobyla_py
__all__ = [ # noqa: F822
'OptimizeResult',
'RLock',
'fmin_cobyla',
'functools',
'izip',
'sy... | Python | 1 |
2 = generate_sentence_from_vector(sentence_vec)
s_1s.append(s1)
s_2s.append(s2)
l_s.append(sentence_vec)
print(s1,s2)
print(sentence_val)
s1_embeddings = model_1.encode(s_1s)
s1_embeddings_2 = model_2.encode(s_1s)
#s2_embeddings = model.encode(s_2s)
from sklearn.metrics.pairwise import cosine_sim... | Python | 1 |
pub fn overflowing_shr(self, rhs: u32) -> (Ipv6Address, bool) {
let (i, b) = self.0.overflowing_shr(rhs);
(i.into(), b)
}
// pub fn overflowing_pow(self, rhs: u32) -> (Ipv6Address, bool) {
// self.0.overflowing_pow(rhs).map(|res| (res.0.into(), res.1))
// (i.into(), b)
// }
}... | Rust | 0 |
import pytest
from remove_covered_point_dbx_python import Solution
def test_remove_point_example_1_split_middle_interval():
intervals = [[10, 12], [13, 16], [4, 8]]
idx = 3
expected = [[10, 12], [13, 14], [15, 16], [4, 8]]
assert Solution().deleteCoveredPoint(intervals, idx) == expected
def test_re... | Python | 1 |
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent / '..'))
from pydsl.type import UInt32, F64, Index
from pydsl.memref import MemRefFactory
from pydsl.frontend import compile
from pydsl.affine import \
affine_range as arange, \
affine_map as am, \
... | Python | 1 |
let idx = all.iter().position(|x| x == current).unwrap();
if idx == all.len() - 1 {
app.session.modal_filters.intersections.remove(&i);
} else {
app.session
.modal_filters
.intersections
... | Rust | 0 |
'''
i = 0
while i < 3:
print("a")
i += 1
'''
'''
for i in [0,1,2]:
print("a")
'''
for i in range(3):
print("a")
#as i in not used we can use valid _ as var name
for _ in range(3):
print("b")
#for infinite loop
#while True:
print("d") | Python | 1 |
import gymnasium as gym
class EvalSyncEnv(gym.Env):
"""A sequential execution of multiple environments, with predefined zones and tasks."""
def __init__(self, envs, world_info_paths, tasks):
assert len(envs) >= 1, "No environment given."
self.envs = envs
self.observation_space = self... | Python | 1 |
?;
(v_prev, w_next)
};
if dbg {
mesh.add_debug_vertex(v_prev, DebugMark::new("v_prv", egui::Color32::BLUE));
mesh.add_debug_vertex(v, DebugMark::new("v", egui::Color32::BLUE));
mesh.add_debug_vertex(w, DebugMark::new("w", egui::Color32::BLUE));
mesh.add_debug_vertex(w_ne... | Rust | 0 |
s.raycing.pyTTE_x',
'xrt.gui', 'xrt.gui.commons', 'xrt.gui.xrtGlow', 'xrt.gui.xrtQook'],
package_data={
'xrt.backends.raycing': ['data/*.npz', 'data/*.dat', '*.cl'],
'xrt': ['*.cl, *.ico'],
'xrt.gui': ['*.pyw'],
'xrt.gui.commons': ['_images/*.*',
'... | Python | 1 |
E_VENDOR_ID: u16 = 0x43f;
vendor == APPLE_VENDOR_ID &&
// Odd parity
(bits.count_ones() & 0x1) == 1
}
fn unpack(bits: u32, repeat: bool) -> Option<Self> {
if !Self::validate(bits) {
return None;
}
// 5 Bits
let command_page = (bits & ... | Rust | 0 |
self.sprite = owner
.get_node(NodePath::from_str("Sprite"))
.expect("Missing Sprite node")
.cast::<Sprite>()
.expect("Unable to cast to Sprite");
godot_print!("Paddle created!");
}
#[export]
unsafe fn _physics_process(&mut self, mut owner: KinematicB... | Rust | 0 |
::Result {
// FIXME: This only seems to print "TaggedPtr"?
f.debug_struct("TaggedPtr").finish()
}
}
impl PartialEq for TaggedPtr {
fn eq(&self, rhs: &TaggedPtr) -> bool {
// Note: this will make -0 != 0
if self.is_ptr() != rhs.is_ptr() {
return false;
}
... | Rust | 0 |
ull "
f"cartesian product appears. (Even in sample {(cartesian_product_completeness * 100):.2f}% were"
f" reached")
else:
# try again with larger sample
cartesian_product_completeness, value_combinations, _ = compute_cartesian_p... | Python | 1 |
state.windows(2) {
for rule in &input.rules {
if w[0] == rule.0 && w[1] == rule.1 {
inserts.push((idx, rule.2));
}
}
idx += 1;
}
inserts.reverse();
for (idx, char) in &inserts {
next_state.insert... | Rust | 0 |
igs
#
# def _stop_criterion(self, configs, last_results):
# if last_results is not None:
# if (global_cfg.hpo.larger_better
# and last_results.iloc[0]['performance'] >=
# global_cfg.hpo.pbt.perf_threshold) or (
# (not global_cfg.hpo.large... | Python | 1 |
t ri = r.into_iter();
while let Some(x1) = ri.next() {
let x2 = ri.next().unwrap();
r2.push((x1, x2));
}
r2
}
fn intervals_auto(p: usize, q: usize, accu: i64) -> (Vec<(Self, Self)>, Option<i64>) {
let mut int = vec![];
for accu2 in accu..accu+20 {
int = Self::intervals(p, q, accu2);
let vl = i... | Rust | 0 |
import os
from urllib.parse import urlparse
from dotenv import load_dotenv
load_dotenv()
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
from gpt_index import (GPTSimpleVectorIndex, PromptHelper,
)
from gpt_index.prompts.prompts import QuestionAnswerPrompt, RefinePrompt
from gpt_index.prompts.d... | Python | 1 |
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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 appl... | Python | 1 |
a_phone', 'batch_1.xlsx'),
random_state=random_seed,
)
# print(f"Batch1: X shape = {batch1_X.shape}, y shape = {batch1_y.shape}")
# Process repeat-measure data
(batch_1_rm_X_train, batch_1_rm_y_train, batch_1_rm_X_test, batch_1_rm_y_test,
batch_1_rm_train_id, batch_1_rm_test_id, feature_na... | Python | 1 |
out.\x00"),
(b"A crowd of people, and at the center, a popular misconception.\x00"),
(b"It\'s a blind man. When you touch, he exclaims \"It\'s a kitten prospecting robot!\"\x00"),
(b"It\'s a lost wallet. It\'s owner didn\'t have pets, so you discard it.\x00"),
(b"This place is c... | Rust | 0 |
mod test {
use crate::of_sequence;
use crate::prelude::*;
use crate::test_scheduler::ManualScheduler;
use std::cell::RefCell;
use std::rc::Rc;
use std::time::Duration;
#[test]
fn simple_integer() {
let mut ret = String::new();
{
let s = of_sequence!(1, 2, 3);
s.start_with(vec![-1... | Rust | 0 |
"""\
Return an expletive for a 'že'-clause that this verb governs,
or False. Lemmas must include reflexive particles for reflexiva
tantum.
"""
return EXPLETIVE_VERBS.get(lemma, False)
def is_coord_conj(self, lemma):
"""Return 'Y'/'N' if the given lemma is a coord... | Python | 1 |
p_type
]
def retrieve_data_cfg(config_path, skip_type, cfg_options, show_origin=False):
cfg = Config.fromfile(config_path)
if cfg_options is not None:
cfg.merge_from_dict(cfg_options)
train_data_cfg = cfg.data.train
if isinstance(train_data_cfg, list):
for _data_cfg in train_da... | Python | 1 |
69),
(r"meshes\a\a_wolf_greaves_gnd.nif", 0x7E16_1B3B, 0xD756_F15B),
(r"meshes\a\a_wolf_greaves_ul.nif", 0x7E16_1B3B, 0xF858_DE53),
(r"meshes\r\undeadwolf_2.nif", 0x7E41_6354, 0x2777_4224),
(r"meshes\r\xudyrfrykte.nif", 0x7E5A_6E54, 0x3834_374C),
(r"meshes\a\a_wolf_boot_gnd.nif", 0x7E70_1B3B, 0... | Rust | 0 |
s()),
Some(r#"1"#.as_bytes()),
Some(r#""c""#.as_bytes()),
None,
]),
},
TestCase {
rec: r#"{}"#,
want: Ok(vec![None, None, None, None, None]),
},
];
for t in tes... | Rust | 0 |
from enum import Enum
import modules.util.multi_gpu_util as multi
class LearningRateScaler(Enum):
NONE = 'NONE'
BATCH = 'BATCH'
GLOBAL_BATCH = 'GLOBAL_BATCH'
GRADIENT_ACCUMULATION = 'GRADIENT_ACCUMULATION'
BOTH = 'BOTH'
GLOBAL_BOTH = 'GLOBAL_BOTH'
def __str__(self):
return self.v... | Python | 1 |
# This file was auto-generated by Fern from our API Definition.
from __future__ import annotations
from ..core.unchecked_base_model import UncheckedBaseModel
from .array_json_schema_property import ArrayJsonSchemaProperty
from .object_json_schema_property import ObjectJsonSchemaProperty
from .webhook_tool_api_schema_c... | Python | 1 |
_range_at(cursor);
if !r.ch.is_whitespace() {
return None;
}
cursor = r.next;
col -= 1;
}
return Some(cursor);
}
fn trim_whitespace_prefix_and_push_line(lines: &mut ~[~str],
s: ~str, col: CharPos) {
let len = s.len();
l... | Rust | 0 |
..uv_sphere.tessellation_stack + 1 {
let stack_angle = std::f32::consts::PI / 2.0 - i as f32 * stack_step;
let xy = uv_sphere.radius * stack_angle.cos();
let z = uv_sphere.radius * stack_angle.sin();
for j in 0..uv_sphere.tessellation_sector + 1 {
let sec... | Rust | 0 |
{}]
",
self.pieces_num + 1,
self.turn
);
s.push_str(&format!(
"\
+---+---+---+ Please select a square. Example `do 7`
|{0}|{1}|{2}| マスを選んでください。例 `do 7`
+---+---+---+
|{3}|{4}|{5}| 7 8 9
+---+---+---+ 4 5 6
|{6}|{7}|{8}| 1 2 3
+---+---+---+",
sel... | Rust | 0 |
import os
import asyncio
name = 'upx'
async def check_dependencies(app_svc):
return await app_svc.validate_requirement('upx', dict(type='installed_program', command='upx --version',
version='0.0.0', optional=True))
class Packer:
def __init__(self, f... | Python | 1 |
md: Cmd, val: &Json) -> Option<bool> {
let r = apply(cmd, val).ok();
if let Some(g) = r {
g.as_bool()
} else {
None
}
}
//TODO refactor to take Json val instead of rows to make more generic
pub fn eval_rows_cmd(cmd: Cmd, rows: &Json) -> Option<Json> {
apply(cmd, rows).ok()
}
#[cfg(... | Rust | 0 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.nn import GATConv
class LookupTableLayer(nn.Module):
# 定义特征提取模块中的查找表,根据std中的方法进行2到2d的特征升维,依据索引输出对应向量,需要保证输入是int
def __init__(self, length, dimension, cfg):
super(LookupTableLayer, self).__init__()
self.cfg ... | Python | 1 |
"""Contains utility functions for the Flask web app."""
import os
import shutil
from flask import Flask
def set_root_folder(app: Flask, root_folder: str = None, create_folders: bool = True) -> None:
"""
Sets the root folder for the config along with subfolders like the data and checkpoint folders.
:par... | Python | 1 |
= 0
while self.preview_running:
frames = self._get_frames()
resized_frames = []
for frame in frames:
if frame is not None:
# h, w = frame.shape[:2]
w, h = self.base_width, self.base_height
new_size =... | Python | 1 |
Info`] mapping.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Asset {
pub appid: AppId,
pub contextid: ContextId,
pub assetid: AssetId,
pub amount: Amount,
pub classinfo: Arc<ClassInfo>,
}
impl Asset {
pub fn key(&self) -> ClassInfoClass {
(self.appid, self.class... | Rust | 0 |
<Vec<_>>();
let mut v = make_grid(&strings[2..]);
for i in 0..=1 {
v = enhance(&v, &enhancement, i & 1);
}
v.iter().map(|x| -> i64 { x.iter().sum() }).sum::<i64>()
}
#[allow(dead_code)]
pub fn solve_part2() -> i64 {
let strings = get_input_string("20");
let enhancement = strings
... | Rust | 0 |
azure::cosmos::client::*;
use hyper::Uri;
#[test]
fn string_to_sign_00() {
let time =
chrono::DateTime::parse_from_rfc3339("1900-01-01T01:00:00.000000000+00:00").unwrap();
let time = time.with_timezone(&chrono::Utc);
let time = format!("{}", time.format(TIME_FORMAT));
... | Rust | 0 |
_result.num_gts, rng=rng)
if rng.rand() > 0.2:
# sometimes algorithms squeeze their data, be robust to that
gt_bboxes = gt_bboxes.squeeze()
bboxes = bboxes.squeeze()
if assign_result.labels is None:
gt_labels = None
else:
gt_labels = ... | Python | 1 |
are processed.
///
/// Useful for upload / download progress.
Bytes(u64),
}
impl Default for ProgressLimit {
fn default() -> Self {
Self::Unknown
}
}
use logos::Logos;
use std::convert::TryFrom;
use std::ops::Range as StdRange;
use text_size::{TextRange, TextSize};
mod token_kind;
pub use... | Rust | 0 |
&[char], hem_nospace: &[char]) -> u32 {
// Mutable u32 to count markers
let mut long_second_syl_markers: u32 = 0;
// Check for alif maddah as third character *or* letter
if hem_reconst[2] == 'آ' || hem_nospace[2] == 'آ' {
long_second_syl_markers += 1;
}
// Check for alif as third char... | Rust | 0 |
other => panic!("unexpected expr: {:?}", other),
};
assert_matches!(function_value, Expr::FnDefinition(_));
}
#[test]
fn method_expr_works() {
let input = InputSpan::new("x.sin();");
let (_, call) = simple_expr::<FieldGrammar, Complete>(input).unwrap();
assert_eq!(
call,
sp(... | Rust | 0 |
use super::Selector;
use async_trait::async_trait;
use std::net::SocketAddr;
use thiserror::Error;
use tokio::sync::{mpsc, oneshot};
/// A round-robin selector.
#[derive(Debug)]
pub struct RoundRobin {
msgs: mpsc::Sender<Message>,
}
/// A request to select a backend.
#[derive(Debug)]
pub struct Message {
cb: ... | Rust | 0 |
<_>) = lines.into_iter().unzip();
if n_examples != feature_lists.len() {
return Err(Error::new(
ErrorKind::InvalidData,
format!(
"Expected {} examples, but read {}",
n_examples,
feature_lists.len()
... | Rust | 0 |
# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from django.core.management import call_command
from django.test import TestCase
from frontend.models import EmailMessage, EventType, MailLog
class MailLogGarbageCollectTest(TestCase):
def test_maillog_garbage_collect(self):
# Make some Ema... | Python | 1 |
: Storage>(store: &mut S, fardel_id: u128) -> StdResult<()> {
let mut store = PrefixedStorage::new(PREFIX_SEALED, store);
set_bin_data(&mut store, &fardel_id.to_be_bytes(), &false)
}
*/
// get sealed status of a given fardel
// true means sealed, false means not sealed
pub fn get_sealed_status<S: ReadonlyStor... | Rust | 0 |
_use]
pub fn cu(&self) -> usize {
self.0.cu()
}
pub(crate) fn hint(&self) -> Option<String> {
self.0.hint()
}
pub(crate) fn token(&self) -> Option<UnfinishedToken> {
self.0.token()
}
/// If possible locate this error inside the given source.
/// This is done wit... | Rust | 0 |
ional {
#[new]
#[args(
fmt_version = "FMTVersion::WhiteBear",
max_eta = "0.5",
max_iter_cross_assoc = "50",
tol_cross_assoc = "1e-10",
dq_variant = "\"dq35\""
)]
fn new(
parameters: PyPcSaftParameters,
fmt_version: FMTVersion,
max_eta: f64,... | Rust | 0 |
Unsafe> = unsafe { VolAddress::new(0xCC00_2068) };
#[repr(transparent)]
pub struct VideoClockControl(u16);
pub const VIDEO_CLOCK_SELECT_REGISTER: VolAddress<VideoClockControl, Safe, Safe> = unsafe { VolAddress::new(0xCC00_206C) };
#[repr(transparent)]
pub struct VideoSelect(u16);
pub const VIDEO_DTV_SELECT_REGISTER: ... | Rust | 0 |
"""
AI配置管理页面视图
"""
from flask import Blueprint, render_template, session, redirect, url_for, request, jsonify
from app.utils.permissions import super_admin_required, get_user_context
from app.services.ai.ai_config_service import AIConfigService
from app import db
import logging
logger = logging.getLogger(__name__)
ai... | Python | 1 |
spawn(sys1.meta.dir_aborted(&cmd1.virtual_path)
.map_err(|e| unreachable(e))
.map(move |()| {
sys1.dir_aborted(&cmd1, "commit_error")
}));
})
})
.and_then(move |()| {
sys2.meta.dir_committ... | Rust | 0 |
window_days: 图像窗口长度(监督期)
prediction_days: 预测持有期(应与window_days相同)
Returns:
sequences: 窗口期数据列表
labels: 标签列表
dates: 每个序列对应的最后一天日期
"""
sequences = []
labels = []
dates = []
# 论文要求:监督期=持有期,即window_days = ... | Python | 1 |
# Grade calculator
""""
Assign a letter grade based on a student's score:
A (90-100),
B (80-89),
C (70-79),
D (60-69),
F (below 60).
"""
# Get student's score
score = int(input("Enter student's score (0-100): "))
if 90 <= score <= 100:
print("A")
elif 80 <= score <= 89:
print("B")
elif 70 <= score <= 79:
... | Python | 1 |
traint_function), to_numpy(ts_brat), to_numpy(values_brat))
fig = plt.figure(figsize=(8, 8))
ax = fig.add_subplot(111)
vis_2d_level_set(fig, ax, grid_in_np, target_function, contour_color='k', colormap=False)
vis_2d_level_set(fig, ax, grid_in_np, -constraint_function, contour_color='r', contour_linestyl... | Python | 1 |
"""
helper functions for creating default CSS sheet
"""
from mGui.styles import CSS, Bounds
from mGui.core.controls import *
from mGui.core.layouts import *
from mGui.core.menus import *
from mGui.core import Control
def defaults(labels=128, controls=128, label_space=8, field_space=1, margin=(0,)):
with CSS(Cont... | Python | 1 |
ng },
Get { key: String },
Remove { key: String },
}
/// Used to communicate between clients and server.
#[derive(Debug, Serialize, Deserialize)]
pub enum Response {
// impl Trait can not be written here.
Set(Result<(), String>),
Get(Result<Option<String>, String>),
Remove(Result<(), String>),
... | Rust | 0 |
", opk.get_name(), opk.get_revision()),
&opk.get_body(),
],
).map_err(SrvError::OriginPublicSigningKeyCreate)?;
match rows.iter().nth(0) {
Some(row) => Ok(self.row_to_origin_public_key(row)),
None => Err(SrvError::NoRowsReturnedAfterInsert()),
... | Rust | 0 |
mask: {
if bpe_output.len() > 1 {
if idx == 0 {
Mask::Begin
} else {
Mask::Continuation
}
} else {
Mask::None
... | Rust | 0 |
class Solution:
def new21Game(self, n: int, k: int, maxPts: int) -> float:
# When the game ends, the point is in [k..k - 1 + maxPts]
# P = 1, if n >= k - 1 + maxPts
# P = 0, if n < k (note the constraints already have k <= n)
if k == 0 or n >= k - 1 + maxPts:
return 1.0
ans = 0.0
dp... | Python | 1 |
# SPDX-FileCopyrightText: 2022 - 2025 Orthanc Team SRL <info@orthanc.team>
#
# SPDX-License-Identifier: GPL-3.0-or-later
import logging
import jsonc
import os
from .models import *
from typing import Dict, Any, List, Tuple
class RolesConfiguration:
_configured_roles: RolesConfigurationModel = None
_permiss... | Python | 1 |
NSION;
while n < num_lines {
jpeg_read_scanlines(
cinfo,
crate::stddef_h::NULL as crate::jpeglib_h::JSAMPARRAY,
1 as libc::c_int as crate::jmorecfg_h::JDIMENSION,
);
n = n.wrapping_add(1)
}
if color_convert.is_some() {
(*(*cinfo).cconvert).... | Rust | 0 |
stubheapzeroheapr- in_degout_degr6 freeoutfreeinr7 r9 stuboutstubinr: s r r r w o X((44[A8855lC
!!S%93?O;PPE3s>D
EqyRh
4[8&)G7$'FA:1$~v/?UASuA:OOR'\2;78
q[OOBL)
MM( MM(x519%H
... | Python | 1 |
import os
from jinja2 import Template
from pathlib import Path
from typing import Dict, Any
from airflow.providers.postgres.operators.postgres import PostgresOperator # type: ignore
from airflow.models import BaseOperator
from ..post_execute_monkey_patch import monkey_post_execute
SQL_TEMPLATE = (
Path(os.path.dir... | Python | 1 |
Integer> {
let fail_len = buf.len();
match len {
0 => Ok(v.into()),
1 => {
let v = buf.read_u8()?;
if v > 127 {
Ok(v.into())
}
else {
Err(not_shortest(fail_len))
}
},
2 => {
le... | Rust | 0 |
block_scope!(self, {
let mut last_node = None;
for node in node.children_by_field_name("statements", &mut cursor) {
last_node = Some(node.child_by_field_name("inner").unwrap());
statements.extend(self.visit_statement(node)?);
}
match node.... | Rust | 0 |
# Generated by Django 5.0.3 on 2024-03-20 12:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myapp', '0002_teacher'),
]
operations = [
migrations.CreateModel(
name='Cars',
fields=[
('id', model... | Python | 1 |
nel_id_or_name> <your_query>`", response_type="ephemeral")
return
channel_param = parts[0]
user_query = parts[1]
# Create synthetic parameters
channel_id = command.get('channel_id')
thread_ts = str(int(time.time()))
# Generate query ... | Python | 1 |
import pytest
from unittest.mock import patch
from _includes import config
from _includes.app.ConfigManager import override_config
def chat_test(app_config, expected_content, callback, module, should_pass, argument, overrides):
if not should_pass:
with pytest.raises(ValueError) as exc_info:
... | Python | 1 |
K: u64 = 0xffffffffffffffff;
// Masks applied when left-shifting or right-shifting.
const LEFT_MASKS: u64x8 = u64x8::new(
NOT_A_FILE, FULL_MASK, NOT_H_FILE, NOT_A_FILE, NOT_A_FILE, FULL_MASK, NOT_H_FILE,
NOT_A_FILE,
);
const RIGHT_MASKS: u64x8 = u64x8::new(
NOT_H_FILE, FULL_MASK... | Rust | 0 |
from time import localtime
from datetime import date, datetime, time, timedelta
Date = date
Time = time
TimeDelta = timedelta
Timestamp = datetime
def DateFromTicks(ticks):
return date(*localtime(ticks)[:3])
def TimeFromTicks(ticks):
return time(*localtime(ticks)[3:6])
def TimestampFromTicks(ticks):
... | Python | 1 |
if !self.liveness_constraints.contains(constraint.sub, elem) {
None
} else {
influenced_fr1[constraint.sup]
.map(|distance| (distance, i))
}
})
.min() // constraining fr1 with fewer hop... | Rust | 0 |
();
let subject = new_resource.get_subject().clone();
println!("subject new {}", new_resource.get_subject());
new_resource.save_locally(&store).unwrap();
let found_resource = store.get_resource(&subject).unwrap();
println!("subject found {}", found_resource.get_subject());
... | Rust | 0 |
get_mut() };
let ret = unsafe {
libc::poll(
fds_mut as *mut EmPollFd as *mut libc::pollfd,
nfds as _,
timeout,
)
};
ret
}
// pread
pub fn ___syscall180(ctx: &mut Ctx, _which: c_int, mut varargs: VarArgs) -> c_int {
debug!("emscripten::___syscall180 ... | Rust | 0 |
from typing import Any, TYPE_CHECKING
if TYPE_CHECKING:
from client import BSClient
try:
from models.parse_error import ParseException
except ImportError:
class ParseException(Exception):
"""Custom exception for parsing errors."""
pass
class SiegeStats:
"""
Represents statistics ... | Python | 1 |
#[doc = "0: All Capacitive Touch IOs are disabled. Signal towards timers is 0."]
CAPTIOEN_0 = 0,
#[doc = "1: Selected Capacitive Touch IO is enabled"]
CAPTIOEN_1 = 1,
}
impl From<CAPTIOEN_A> for bool {
#[inline(always)]
fn from(variant: CAPTIOEN_A) -> Self {
variant as u8 != 0
}
}
#... | Rust | 0 |
-templates. In case `<path>` points to an existing
/// `tp-note`-file, the note's meta-data is analysed and, if necessary, its
/// filename is modified. For all other file types, `tp-note` creates a new note
/// that annotates the file `<path>` points to. If `<path>` is a directory (or,
/// when omitted the current wor... | Rust | 0 |
from exprsVisitor import exprsVisitor
class EvalVisitor(exprsVisitor):
def visitRoot(self, ctx):
[expressio] = list(ctx.getChildren())
print(self.visit(expressio))
def visitSuma(self, ctx):
[expressio1, operador, expressio2] = list(ctx.getChildren())
return self.visit(expressio1... | Python | 1 |
_bytes = json_value_path.as_bytes();
if json_value_path_bytes.len() > 100 {
panic!("json_value_path is too long! {}", json_value_path);
}
let mut json_value_path_bytes_padded: Vec<u8> = json_value_path_bytes.to_vec();
json_value_path_bytes_padded.resize(100, 0);
// img_url_https
let img_u... | Rust | 0 |
es, Clone, PartialEq)]
pub struct PurePreviewCell {
pub fixture_state: FixtureState,
}
impl PureComponent for PurePreviewCell {
fn render(&self) -> Html {
let beam = &self.fixture_state.beams[0];
let color = beam.color.unwrap_or((0.0, 0.0, 0.0));
let opacity = self.fixture_state.dimmer *... | Rust | 0 |
from_url(provider.authorize_uri.clone()),
Some(::oauth2::TokenUrl::from_url(provider.token_uri.clone())),
)
.set_redirect_url(::oauth2::RedirectUrl::from_url(
ServerUri::oauth2_redirect(domain),
));
Ok(Some(client))
} else {
... | Rust | 0 |
g: *mut c_char,
error_size: size_t,
) -> c_int {
if error_msg.is_null() || error_size <= 0 {
return -1;
}
let result = if forced { force_reboot() } else { reboot() };
match result {
Ok(_) => 0,
Err(error) => {
let msg = to_c_str!(error.to_string()).unwrap();
... | Rust | 0 |
contr._pre_argument_parsing()
self.app._parse_args()
for contr in self._controllers:
contr._post_argument_parsing()
contr._process_parsed_arguments()
if hasattr(self.app.pargs, '__dispatch__'):
# if __dispatch__ is set that means that we have hit a... | Python | 1 |
textureCompressionBC: VkBool32,
occlusion_query_precise => occlusionQueryPrecise: VkBool32,
pipeline_statistics_query => pipelineStatisticsQuery: VkBool32,
vertex_pipeline_stores_and_atomics => vertexPipelineStoresAndAtomics: VkBool32,
fragment_stores_and_atomics => fragmentStoresAndAto... | Rust | 0 |
PyramidFairyBow,
PyramidFairyLeft,
PyramidFairyRight,
Ganon,
Brewery,
CShapedHouse,
ChestGame,
HammerPegs,
BumperCave,
Blacksmith,
PurpleChest,
HypeCaveTop,
HypeCaveMiddleRight,
HypeCaveMiddleLeft,
HypeCaveBottom,
Stumpy,
HypeCaveNPC,
DiggingGame,
SuperbunnyCaveTop,
SuperbunnyCav... | Rust | 0 |
eduler.TuningOptions(
num_measure_trials=1,
num_measures_per_round=1,
builder=auto_scheduler.LocalBuilder(timeout=60),
measure_callbacks=[auto_scheduler.RecordToFile(log_file)],
)
tuner.tune(tune_option, search_policy="sketch.random")
# Compile
... | Python | 1 |
(0.76, 0.78, 0.48, 1)
#C2C77B
Qt.rgba(0.6, 0.79, 0.77, 1):q
use crate::framework::context::Context;
use crate::framework::error::GameResult;
use crate::framework::filesystem::{user_create, user_open};
use crate::framework::keyboard::ScanCode;
use crate::graphics::VSyncMode;
use crate::input::keyboard_player_con... | Rust | 0 |
# Esta implementación utiliza el pivote como el último elemento en la lista nums
# Tiene un puntero para realizar un seguimiento de los elementos más pequeños que el pivote
# Al final de la función partition(), el puntero se intercambia con el pivote
# para obtener una lista "ordenada" en relación al pivote
import matp... | Python | 1 |
raw(self) -> Vec<[u8; 32]> {
self.0
}
}
impl From<&[u8]> for LogMemory {
fn from(bytes: &[u8]) -> Self {
let mut result = Vec::with_capacity(bytes.len() / 32);
let mut buf = [0u8; 32];
for (i, b) in bytes.iter().enumerate() {
let j = i % 32;
buf[j] = *b;
... | Rust | 0 |
ots) == {10, 20}
subtree_ids = set(exporter._get_subtrees(10)) # pyright: ignore[reportPrivateUsage]
assert subtree_ids == {10, 11, 12}
popped = exporter._pop_subtrees(10) # pyright: ignore[reportPrivateUsage]
assert {sp.get_span_context().span_id for sp in popped} == { # pyright: i... | Python | 1 |
artifacts.
The process involves downloading the MLmodel file in the model artifacts (if it's non-local),
updating its model signature, and then overwriting the existing MLmodel file. Should the
artifact repository associated with the model artifacts disallow overwriting, this function will
fail.
F... | Python | 1 |
import numpy as np
def global_stretching(img_L,height, width):
length = height * width
R_rray = (np.copy(img_L)).flatten()
R_rray.sort()
print('R_rray',R_rray)
I_min = int(R_rray[int(length / 100)])
I_max = int(R_rray[-int(length / 100)])
print('I_min',I_min)
print('I_max',I_max)
ar... | Python | 1 |
he Python profiler and PyTorch\'s
autograd profiler. Because your script will be profiled, please ensure that it
exits in a finite amount of time.
For more complicated uses of the profilers, please see
https://docs.python.org/3/library/profile.html and
https://pytorch.org/docs/main/autograd.html#profiler for more info... | Python | 1 |