text string | label_name string | labels int64 |
|---|---|---|
string = "aabccaaddaxxaabb"
d = {}
for i in string:
d[i] = d.get(i, 0) + 1
print(d)
| Python | 1 |
Default for APG {
fn default() -> APG {
APG {
name: "".to_string(),
elements: HashSet::default(),
// values: HashSet::default(),
labels: HashSet::default(),
lambda_upsilon: HashMap::default(),
}
}
}
type ElemMapping = fn(Rc<Element>)... | Rust | 0 |
running_tasks.remove(completed_task)
# Check for exceptions in completed tasks
try:
await completed_task
except Exception as e:
logger.error(f"Task processing failed: {e}")
#... | Python | 1 |
};
use crate::Value;
fn invalid_argument(arg: Value, expected: &str) -> Value {
make_error!("invalid argument, expected {}", expected; arg)
}
fn too_few_arguments(procedure: &str, args: &[Value]) -> Value {
make_error!("too few arguments to `{}'", procedure; Value::list(args.iter().cloned()))
}
fn wrong_num... | Rust | 0 |
# 739 Daily Temperatures
# use monotonic stack to save index
# {temperature: index}
# 二刷
# 496 Next Greater Element 1
# 非常绕
class Solution(object):
def nextGreaterElement(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
re... | Python | 1 |
", "=E,,,,",
"=F,,,,", "^F,,,,", "=G,,,,", "^G,,,,", "=A,,,,", "^A,,,,", "=B,,,,", "=C,,,", "^C,,,",
"=D,,,", "^D,,,", "=E,,,", "=F,,,", "^F,,,", "=G,,,", "^G,,,", "=A,,,", "^A,,,", "=B,,,",
"=C,,", "^C,,", "=D,,", "^D,,", "=E,,", "=F,,", "^F,,", "=G,,", "^G,,", "=A,,", "^A,,", "=B,,",
"=C,", "^C,", "=D... | Rust | 0 |
-search",
AdminRoute::ImageSearch(_) => "image-search",
AdminRoute::Curation(_) => "curation",
AdminRoute::Export => "export",
AdminRoute::Landing => "",
};
let locked = match profile {
None => true,
Some(user) => !target_route.all... | Rust | 0 |
from collections import deque
def solution(maze):
N = len(maze)
M = len(maze[0])
r_s_x, r_s_y = 0, 0
b_s_x, b_s_y = 0, 0
# 시작 위치 찾기
for i in range(N):
for j in range(M):
if maze[i][j] == 1:
r_s_x, r_s_y = i, j
elif maze[i][j] == 2:
... | Python | 1 |
` event. See
/// [`nix::sys::ptrace`] and [`ptrace`(2)] for more information. All
/// currently-defined events use `SIGTRAP` as the signal; the third
/// field is the `PTRACE_EVENT_*` value of the event.
///
/// [`nix::sys::ptrace`]: ../ptrace/index.html
/// [`ptrace`(2)]: https://man7.org/linux... | Rust | 0 |
1243,
Swann = 1244,
DrakkenLaserDrill = 1245,
MindSiphonReturnWeapon = 1246,
KerriganEgg = 1247,
ChrysalisEgg = 1248,
PrisonerSpectre = 1249,
PrisonZealot = 1250,
ScrapSalvage1x1 = 1251,
ScrapSalvage2x2 = 1252,
ScrapSalvage3x3 = 1253,
RaynorCommando = 1254,
Overmind = 1255,
OvermindRemains = 1256,
Infest... | Rust | 0 |
_Control_S4_COMMON_INCLUDES_
# define M1SA_F_Control_S4_COMMON_INCLUDES_
#include "rtwtypes.h"
#endif /* M1SA_F_Control_S4_COMMON_INCLUDES_ */
#include "M1SA_F_Control_S4_types.h"
/* Macros for accessing real-time model data structure */
#ifndef rtmGetErrorStatus
# define rtmGetErrorS... | Rust | 0 |
egory)
texinfo_documents = [
(master_doc, 'SAWRemote', 'SAW Remote API Documentation',
author, 'SAW Remote API', 'One line description of project.',
'Miscellaneous'),
]
# -- Options for Epub output -------------------------------------------------
# Bibliographic Dublin Core info.
epub_title = project
... | Python | 1 |
neric::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [interrupt_core0_rsa_int_map](interrupt_core0_rsa_int_map) module"]
pub type INTERRUPT_CORE0_RSA_INT_MAP = crate::Reg<u32, _INTERRUPT_CORE0_RSA_INT_MAP>;
#[allow(missing_docs)]
#[doc(hidden)]... | Rust | 0 |
uncMap<A, B, P>,
{
}
}
trait AssertNotOriginalFuncMap {}
impl<T> AssertNotOriginalFuncMap for T where T: funcmap::FuncMap<T1, T2> {}
#[derive(Debug)]
struct T1;
#[derive(Debug)]
struct T2;
use std::fmt;
use application::{Application, Stopping};
use cli::Options;
use config::Config;
/// Core program logic
... | Rust | 0 |
ast::AssocItem::TypeAlias(def) => def.name(),
ast::AssocItem::Const(def) => def.name(),
ast::AssocItem::MacroCall(_) => None,
}
.is_some()
}
items
.iter()
// Note: This throws away items with no source.
.filter_map(|i| {
let item = mat... | Rust | 0 |
from datetime import datetime
# Инициализация пустого списка словарей для заметок
notes = []
def add_note():
"""Добавляет новую заметку в список"""
while True:
username = input("Введите имя пользователя: ").strip()
if username:
break
print("Имя пользователя не может быть п... | Python | 1 |
cale)
# print("baseline: \n", base_time * 1000 / epoch)
official_ref_time = run_benchmark(epoch, warmup, flash_attn_func_offical, q, k, v, causal=is_causal, softmax_scale=sm_scale)
print("official_ref: \n", official_ref_time * 1000 / epoch)
my_flash_attn_time = run_benchmark(epoch, warmup, my_flash_at... | Python | 1 |
from __future__ import (absolute_import, division, print_function)
"""
example showing how to plot data from a DEM file and an ESRI shape file using
gdal (http://pypi.python.org/pypi/GDAL).
"""
from osgeo import gdal, ogr
from mpl_toolkits.basemap import Basemap, cm
import numpy as np
import matplotlib.pyplot as plt
... | Python | 1 |
# 1 - Números Pares em um Intervalo:
# Crie um programa que solicite dois números ao usuário,
# representando um intervalo. Use um laço while para exibir
# todos os números pares dentro desse intervalo.
n = in | Python | 1 |
from _pydevd_bundle.pydevd_extension_api import TypeResolveProvider
from _pydevd_bundle.pydevd_resolver import defaultResolver
from .pydevd_helpers import find_mod_attr
from _pydevd_bundle import pydevd_constants
TOO_LARGE_MSG = "Maximum number of items (%s) reached. To show more items customize the value of the PYDEV... | Python | 1 |
impl $crate::unit::scale::exp::ScaleExponent<$type> for $name {
const EXPONENT: $type = $value;
}
};
}
use std::rc::Rc;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use web_sys::{HtmlImageElement, WebGl2RenderingContext, WebGlTexture};
pub fn create_rgba_texture_from_array_buffe... | Rust | 0 |
ToConstant(x), _) if x == "x"
));
Ok(())
}
<filename>ditto-registry-operator/src/controller/device/thing.rs
use super::{ConstructContext, DeconstructContext};
use crate::{
controller::{policy_id, ControllerConfig},
ditto::{
self,
api::ThingOperation,
data::{EntityId, Thing},
... | Rust | 0 |
<(), Error<W::Error>> {
match self.indices() {
[] => {
e.encode(self.attribute)?;
}
a => {
e.array(2)?.encode(self.attribute)?;
let mut chunks = a.chunks(2).peekable();
while let Some(chunk) = chunks.next() {
... | Rust | 0 |
nts as gfc
import numpy as np
import marimo as mo
import matplotlib.pyplot as plt
return gfc, gfosd, mo, np, plt
@app.cell
def __():
import importlib
import modules.components as complib
import modules.intro_problem as intro_problem
import modules.problems as problems
import module... | Python | 1 |
elf::MouseButton(x) => x.window_id,
Self::MouseWheel(x) => x.window_id,
Self::AxisMotion(x) => x.window_id,
Self::TouchpadPressure(x) => x.window_id,
Self::Touch(x) => x.window_id,
Self::ScaleFactorChanged(x) => x.window_id,
Self::ThemeChanged(x) => x.window_id,
}
}
}
/// A redraw was requested by... | Rust | 0 |
may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the ... | Rust | 0 |
e."""
# First: Group all suborganization names by their "normalized" names (finding duplicates).
# Returns a dict that looks like this:
# {
# "amtrak": [<Suborganization: AMTRAK>, <Suborganization: aMtRaK>, <Suborganization: AMTRAK >],
# "usda/oc": [<Suborganization: USDA/OC... | Python | 1 |
/0 via <REDACTED-IPV6: 1> nic 4]",
ipv6_ll: "IPv6LL: fe80::7d84:c1dc:ab34:656a" => "IPv6LL: fe80::<REDACTED-IPV6-LL: 1>",
uuid: "UUID: ddd0fA34-1016-11eb-adc1-0242ac120002" => "UUID: <REDACTED-UUID>",
mac_address: "MAC address: 00:0a:95:9F:68:16 12:34:95:9F:68:16" =>
"MAC address: 00... | Rust | 0 |
CREATE_BOOK_HOTEL = """ This endpoint create boocking """
UPDATE_BOOK_HOTEL = """ This endpoint update booking hotel """
DELETE_BOOK_HOTEL = """ This endpoint delete booking hotel """
GET_BOOK_HOTEL = """ This endpoint get booking hotel """
SORT_DESCRIPTION = """ Filter by sort """
| Python | 1 |
import pandas as pd
from pypm.data_io import load_eod_data
def calculate_simple_moving_average(series: pd.Series, n: int=20) -> pd.Series:
"""Calculates the simple moving average"""
return series.rolling(n).mean()
def calculate_simple_moving_sample_stdev(series: pd.Series, n: int=20) -> pd.Series:
"""Ca... | Python | 1 |
def get_labels(self):
return self.label_list
| Python | 1 |
is executed at the beginning of the block before any extrinsics are
// dispatched.
//
// This function must return the weight consumed by `on_initialize` and `on_finalize`.
fn on_initialize(_n: T::BlockNumber) -> Weight {
// Anything that needs to be done at the start of the block.
// We don't do anythin... | Rust | 0 |
mask = None
if mask_segment_id is not None:
# mask for regions that are not in the same semantic class
mask_id, mask_count = np.unique(mask_segment_id, return_counts=True)
merged_mask = mask_id[mask_count > merge_threshold]
merged_mask_skeletons = np.unique(
skeleton_segm... | Python | 1 |
ow(np.linspace(0, 1, len(prec.keys())))
for i in range(len(prec.keys())):
cat = prec.keys()[i]
if recall[cat] is not None:
plt.plot(recall[cat], prec[cat], color = colors[i], label=cat_id_to_cat[cat])
plt.xlim([0, 1])
plt.ylim([0, 1])
plt.ylabel("Precision")
plt.... | Python | 1 |
,
Pos0_7 = 5,
Pos0_5 = 6,
Pos0_3 = 7,
Zero = 8,
Neg0_3,
Neg0_5,
Neg0_7,
Neg1_0,
Neg1_3,
Neg1_5,
Neg1_7,
Neg2_0,
}
#[repr(i32)]
pub enum RtcCheckValidError {
InvalidYear = -1,
InvalidMonth = -2,
... | Rust | 0 |
b: 106,
name: Some("<NAME>"),
},
ParsedColour {
r: 38,
g: 17,
b: 5,
name: Some("<NAME>"),
},
ParsedColour {
r: 38,
g: 20,
b: 20,
name: Some("Gondola"),
},
ParsedColour {
r: 38,
g: 35,
b: 53,
... | Rust | 0 |
actionPayload},
vm_error::StatusCode,
};
use move_core_types::identifier::IdentStr;
use serde::{Deserialize, Serialize};
use std::convert::TryFrom;
use transaction_builder::get_transaction_name;
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
pub struct AmountView {
pub amount: u64,
pub currency... | Rust | 0 |
::Readable for COMB_PVT_ERR_NVT_SITE0_SPEC {
type Reader = R;
}
#[doc = "`reset()` method sets COMB_PVT_ERR_NVT_SITE0 to value 0"]
impl crate::Resettable for COMB_PVT_ERR_NVT_SITE0_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
<reponame>BoredPerson/rbpf<gh_stars>0
// Copyright 20... | Rust | 0 |
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Literal
from ..enums import BotCommandScopeType
from .bot_command_scope import BotCommandScope
class BotCommandScopeAllGroupChats(BotCommandScope):
"""
Represents the `scope <https://core.telegram.org/bots/api#botcommandscope>`_ of bo... | Python | 1 |
artichoke ruby"
//! );
//! assert_eq!(
//! roe::uppercase("Αύριο".as_bytes(), UppercaseMode::Full).collect::<Vec<_>>(),
//! "ΑΎΡΙΟ".as_bytes()
//! );
//! ```
//!
//!
//! Roe provides fast path routines that assume the byte slice is ASCII-only.
//!
//! # Crate Features
//!
//! Roe is `no_std` compatible with an ... | Rust | 0 |
# Atividade 03:
# Tabuada de um Número:
# Faça um programa que solicite um número ao usuário e use
# um laço while para exibir a tabuada desse número (de 1 a 10).
n = 0
while n < 10:
n += 1
print(n) | Python | 1 |
0001 => Condition::NotEqual,
0b0010 => Condition::UnsignedGTE,
0b0011 => Condition::UnsignedLT,
0b0100 => Condition::Negative,
0b0101 => Condition::NonNegative,
0b0110 => Condition::Overflow,
0b0111 => Condition::NoOverflow,
0b1000 => Condition::UnsignedGT,
0b1001 => Condition::UnsignedLTE,
0b1010 => ... | Rust | 0 |
FUNCTION_WRAPPER: u32 = 1;
pub const CONFIG_FREERTOS_CHECK_MUTEX_GIVEN_BY_OWNER: u32 = 1;
pub const CONFIG_FREERTOS_DEBUG_OCDAWARE: u32 = 1;
pub const CONFIG_HEAP_POISONING_DISABLED: u32 = 1;
pub const CONFIG_HEAP_TRACING_OFF: u32 = 1;
pub const CONFIG_LOG_DEFAULT_LEVEL_INFO: u32 = 1;
pub const CONFIG_LOG_DEFAULT_LEVEL... | Rust | 0 |
_descriptor,
)),
)
} else {
(
TxOut {
value: unvault_value - cpfp_value - fees,
..TxOut::default()
},
None,
)
};
let mut spend_tx = SpendTransaction::new(
vec![spend_unvault_txin.clone()],
... | Rust | 0 |
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC # Importing SVC for SVM
from sklearn.metrics import accuracy_score, classification_report
# Load datasets
df_train = pd.read_csv(r'E:\01 - Northeastern\2024 Spring\01 - Data Science\Final Project\dataset\train_dataset_1to... | Python | 1 |
mut self) -> _CidschgW {
_CidschgW { w: self }
}
#[doc = "Bit 29 - Disconnect detected interrupt"]
#[inline(always)]
pub fn discint(&mut self) -> _DiscintW {
_DiscintW { w: self }
}
#[doc = "Bit 30 - Session request/new session detected interrupt"]
#[inline(always)]
pub f... | Rust | 0 |
:FileDescriptor) -> Result<(), EventPollRegistrationError>>(&self, arena: &A, reactor_compressed_type_identifier: CompressedTypeIdentifier, file_descriptor: R::FileDescriptor, add_flags: EPollAddFlags, initializer: F) -> Result<(), EventPollRegistrationError>
{
let (mut non_null, arena_index) = arena.allocate()?;
... | Rust | 0 |
crate) use peer_message::PeerMessage;
pub(crate) use peer_state::PeerState;
pub(crate) use request_message::request_message;
pub(crate) use torrent_peer_state::TorrentPeerState;
use std::ffi::CString;
use std::ptr;
use std::mem::size_of;
use gl;
use gl::types::*;
use gx;
use gx::GLResource;
use grx;
use v::{Vec2, Vec3,... | Rust | 0 |
SpiralIndex = 16;
let player = *player;
for _ in 0..ATTEMPTS_PER_NON_OVERLAPPING_CALL {
let offset = offset_from_spiral_index(*spiral_index);
let new_player = Player {
xy: player.xy + offset,
..player
};
if bounce_vector_if_overlapping(
&ne... | Rust | 0 |
et file = io_util::directory::open_file(
&proxy,
"message",
fio::OpenFlags::RIGHT_READABLE | fio::OpenFlags::RIGHT_EXECUTABLE,
)
.await
.unwrap();
let message = io_util::file::read_to_string(&file).await.unwrap();
assert_eq!(message, "test-cont... | Rust | 0 |
"""Constants for the Bluetti BT integration."""
DOMAIN = "bluetti_bt"
MANUFACTURER = "Bluetti"
CONF_OPTIONS = "options"
CONF_USE_CONTROLS = "use_controls"
CONF_PERSISTENT_CONN = "persistent_conn"
CONF_POLLING_INTERVAL = "polling_interval"
CONF_POLLING_TIMEOUT = "polling_timeout"
CONF_MAX_RETRIES = "max_retries"
DATA... | Python | 1 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models, fields
from odoo.osv import expression
import textwrap
class ChatbotScriptAnswer(models.Model):
_name = 'chatbot.script.answer'
_description = 'Chatbot Script Answer'
_order =... | Python | 1 |
> QDate as "QDate" {
return QDate(y, m, d);
})
}
/// Wrapper around [`QDate::getDate(int *year, int *month, int *day)`][method] method.
///
/// # Wrapper-specific
///
/// Returns the year, month and day components as a tuple, instead of mutable references.
///
/// [m... | Rust | 0 |
ern crate log;
#[macro_use]
extern crate lazy_static;
pub(crate) mod contents;
pub(crate) mod emojis;
pub(crate) mod error;
pub(crate) mod features;
pub(crate) mod listeners;
pub(crate) mod monsters;
pub(crate) mod rate_limit;
pub(crate) mod resistances;
pub(crate) mod tmp_file;
pub(crate) mod utils;
pub(crate) mod m... | Rust | 0 |
self.pher_map.insert((n1,n2), self.pher_map[&(n1,n2)]+update_const/dist);
}
curr_best_dist
}
pub fn ant_tour(&self)->(f32,Vec<u8>){
let mut remaining_nodes:&mut Vec<u8> = &mut (0..self.node_cnt).collect();
let mut curr_node = utils::pick_random_node(&mut remainin... | Rust | 0 |
crate::OutOfScopeVar{variable,used} => {
__formatter.write_str("OutOfScopeVar{")?;
::std::fmt::Debug::fmt(variable, __formatter)?;
__formatter.write_str(",")?;
::std::fmt::Debug::fmt(used, __formatter)?;
__formatter.write_str("}")
... | Rust | 0 |
import os
def procesar_elemento(ruta, primer_elemento=False):
# Obtener el nombre del elemento (sin la ruta)
nombre_elemento = os.path.basename(ruta)
# Verificar si es una carpeta
if os.path.isdir(ruta):
# Si es una carpeta, procesar cada archivo dentro de ella
for archivo in os.listdi... | Python | 1 |
re_delta = now;
sphere_scale = arg as f32;
}
play_pos += 1;
}
}
static mut cam_count : u32 = 1918; // (1753 0 )
fn setup_random_camera( ) {
let seed : u32;
unsafe{
cam_count += 1;
setup_camera( cam_count, 0);
camera_mode = 0;
}
}
fn s... | Rust | 0 |
rate::manifest::visit_file_hashes(manifest, |file_hash| {
if let FileHash::Missing(path) = file_hash {
let path = std::fs::canonicalize(path).unwrap();
if !collected.contains_key(&path) {
need_checksums.insert(path);
}
}
... | Rust | 0 |
with
facilities to load a value bit by bit.
*/
struct HuffTree {
// True iff every sub-tree in this tree
// either has two direct children or none
even_childs :bool,
payload :Option<u32>,
l :Option<Box<HuffTree>>,
r :Option<Box<HuffTree>>,
}
/*
use std::fmt;
impl fmt::Debug for HuffTree {
fn fmt(&self, f: &mu... | Rust | 0 |
attach a object detector before it.
Yielding a list of frames instead of a video file allows for better control
of test data and frame specific manipulations to trigger certain code
branches.
"""
sequence_dir = TEST_DATA_DIR / "video_sequences" / request.param
with open(sequence_dir / "det... | Python | 1 |
UMMARY] Input pages={input_count}, Output pages={page_num}", file=sys.stderr)
# Write merged output
os.makedirs(os.path.dirname(abs_output), exist_ok=True)
with open(abs_output,'wb') as f:
merger.write(f)
merger.close()
print(f"Merged PDF created at {abs_output}", file=sys.stderr)
# Cl... | Python | 1 |
'No due date':
# Convert Google's datetime format to more readable form
try:
due_dt = datetime.fromisoformat(due_date.replace('Z', '+00:00'))
due_date = due_dt.strftime('%Y-%m-%d')
except ValueError:
... | Python | 1 |
from pythonx.compose.runtime import Composable
from androidx.compose.material3 import TextKt
__COMPILED_CODE__ = None
Unit = None
class Text(Composable):
""" M3 text """
def __init__(self):
super().__init__()
self.__kotlin_composable = None
def find_composable(self):
super().__i... | Python | 1 |
curr, _ = self._get_snapshot()
while curr:
if curr.key == key:
return curr.val
elif curr.key > key:
curr, _ = self._resolve(curr.left)
else:
curr, _ = self._resolve(curr.right)
return None
def preorder(self):
... | Python | 1 |
#!/usr/bin/env python3
import os
import shutil
import tempfile
import unittest
from protofuzz import log
class TestLog(unittest.TestCase):
def setUp(self):
self.fd, self.tempfile = tempfile.mkstemp()
def _get_logger(self, n):
return log.LastNMessagesLogger(self.tempfile, n)
def tearDow... | Python | 1 |
y_power_update_interval: int = 3600
@property
def lora_preset_name(self) -> str:
"""String form of the selected LoRa preset."""
return config_pb2.Config.LoRaConfig.ModemPreset.Name(self.lora_preset)
@property
def device_role_name(self) -> str:
"""String form of the selected dev... | Python | 1 |
import inspect
import pydantic
import pytest
import dspy
def test_code_validate_input():
# Create a `dspy.Code` instance with valid code.
code = dspy.Code["python"](code="print('Hello, world!')")
assert code.code == "print('Hello, world!')"
with pytest.raises(ValueError):
# Try to create a ... | Python | 1 |
ialOrd)]
pub enum RandomNumber {
Float(Fp),
Integer(Int),
}
impl ConvertMut<RandomNumber, Value> for Artichoke {
fn convert_mut(&mut self, from: RandomNumber) -> Value {
match from {
RandomNumber::Integer(num) => self.convert(num),
RandomNumber::Float(num) => self.convert_mu... | Rust | 0 |
) # shape: (n_unique_sources, embed_dim)
embeds["src"] = unique_speech_embeds[
source_idx_lang
] # shape: (n_sources, embed_dim)
else:
unique_text_embeds = self.text_embedder.predict(
unique_sources_lang, source_lang=... | Python | 1 |
',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
# NOTE:👇解决:Access to XMLHttpRequest at 'xxxxxxxxxxx' from origin 'xxxxxxxxx' has been blocked by CORS policy: Request header field x-token is not allowed by Access-Control-Allow-Headers in preflight respon... | Python | 1 |
!(
ron::from_str::<MyNewtypeStruct>("42"),
Err(SpannedError {
code: Error::ExpectedNamedStructLike("MyNewtypeStruct"),
position: Position { line: 1, col: 1 }
}),
);
}
#[test]
fn test_struct_name_mismatch() {
assert_eq!(
ron::from_str::<MyStruct>("(a: true... | Rust | 0 |
pub struct SfFlags: c_int {
/// Causes `sendfile` to return EBUSY instead of blocking when attempting to read a
/// busy page.
SF_NODISKIO;
/// Causes `sendfile` to sleep until the network stack releases its reference to the
/// VM pages re... | Rust | 0 |
# ______ Exercício 0065 outra solução ______
# Crie um programa que leia vários números inteiros pelo teclado. No final da execução, mostre a média entre todos os
# valores e qual foi o maior e o menor valores lidos. O programa deve perguntar ao usuário se ele quer ou não continuar
# a digitar valores.
# Lista de cor... | Python | 1 |
r#interface })
}
}
#[allow(dead_code)]
pub struct VarlinkInterfaceProxy {
inner: Box<dyn VarlinkInterface + Send + Sync>,
}
#[allow(dead_code)]
pub fn new(inner: Box<dyn VarlinkInterface + Send + Sync>) -> VarlinkInterfaceProxy {
VarlinkInterfaceProxy { inner }
}
impl varlink::Interface for VarlinkInter... | Rust | 0 |
from llama_index.packs.searchain.base import SearChainPack
__all__ = ["SearChainPack"]
| Python | 1 |
nvironment=self.environment))
#add spring links
#add springs between nearest neighbours without repetition
for i in self.particles:
for j in self.nearest_neighbours(i, 4):
if i != j[0]:
self.spring_links.append(Spring_link(i, j[0], k=1... | Python | 1 |
&new_path,
expected_json,
expected_crate_name,
expected_files,
);
}
fn _validate_upload(
new_path: &Path,
expected_json: &str,
expected_crate_name: &str,
expected_files: &[&str],
) {
let mut f = File::open(new_path).unwrap();
// 32-bit little-endian integer ... | Rust | 0 |
{1cdd}', 'ᯬ', 'ԍ', 'ᨶ', '𐔷', 'ḽ', '🚗', '⟙', 'త', '𐔑',
'𝟧', '⨩', 'm', 'ැ', '𐀓', '🈕', 'ⰾ', '௨', '𞢥', '𒑌', '\u{11300}',
'𐹸', '꧱', 'ꅊ', '⛮', '\u{13438}', '⯰', 'ᛜ', 'ᅄ', '⯻', '𐽗', '𘫓',
'𑰚', 'ᎉ', '𔗌', '𝚢', '𒅌', 'ﶸ', 'ゔ', '𐀸', '⤡', '\u{11d41}', '𝋭',
'լ', '⼢', '⬎', 'ꖞ', '𐩕', '⬦', '⚀', 'ꃵ', '𝀲... | Rust | 0 |
import matplotlib.pyplot as plt
import numpy as np
import pickle
from matplotlib.lines import Line2D
#LOAD DATA
with open('saved_figs_roberta/qnli.pkl', 'rb') as f:
qnli = pickle.load(f)
with open('saved_figs_roberta/sst2.pkl', 'rb') as f:
sst2 = pickle.load(f)
with open('saved_figs_roberta/qqp.pkl', 'rb') as... | Python | 1 |
ject_with_ino!(self, SETATTR, ino);
// TODO: support setattr with fh
let inode_map = self.inode_map.read().await;
let path = inode_map.get_path(ino)?;
async_lchown(&path, uid, gid).await?;
if let Some(mode) = mode {
async_fchmodat(&path, mode).await?;
}
... | Rust | 0 |
ill be used to create a Box<[u8]>
/// let slice: &[u8] = &[104, 101, 108, 108, 111];
/// let boxed_slice = Box::from(slice);
///
/// assert_eq!(boxed_slice, boxed_str);
/// # }
/// # }
/// ```
#[inline]
fn from(s: Box<str, A>) -> Self {
unsafe {
let a = ptr::read(... | Rust | 0 |
class Solution:
def isMatch(self, s: str, p: str) -> bool:
m, n = len(s), len(p)
# dp[i][j] = True if s[0:i] matches p[0:j]
dp = [[False] * (n + 1) for _ in range(m + 1)]
dp[0][0] = True # Empty string matches empty pattern
# Initialize first row for patterns like ... | Python | 1 |
ApiError::IncorrectRequest),
};
let ss = s.clone()
.ok()
.map(|r| {
r.err()
.map(|_| istatus::BadRequest)
.unwrap_or(istatus::Created)
})
.unwrap_or(istatus::BadReq... | Rust | 0 |
ruction>, String> {
use self::Instruction::*;
use self::Type::*;
use self::Comparison::*;
fn next(index: &mut usize, bytes: &[u8]) -> Result<u8, String> {
if *index >= bytes.len() {
return Err("incomplete instruction".to_owned());
}
*in... | Rust | 0 |
else:
cropped_sr_img = sr_img
cropped_gt_img = gt_img
avg_psnr += util.calculate_psnr(cropped_sr_img * 255, cropped_gt_img * 255)
avg_psnr = avg_psnr / idx
# log
logger.info('# Validation # PSNR: {:... | Python | 1 |
""",
[table_name],
)
for constraint, columns, other_table, other_column in cursor.fetchall():
constraint = self.identifier_converter(constraint)
constraints[constraint] = {
"primary_key": False,
"unique": False,
"... | Python | 1 |
464usize,
// concat!(
// "Offset of field: ",
// stringify!(_xsltTransformContext),
// "::",
// stringify!(maxTemplateDepth)
// )
// );
// assert_eq!(
// unsafe {
// &(*(::std::ptr::null::<_xsltTransformContext>())).maxTempla... | Rust | 0 |
ormation
"""
account_id: UUID
provider_name: List[CIPProvider]
created_at: datetime
updated_at: datetime
kyc: Optional[CIPKYCInfo] = None
document: Optional[CIPDocument] = None
photo: Optional[CIPPhoto] = None
identity: Optional[CIPIdentity] = None
watchlist: Optional[CIPWatchli... | Python | 1 |
from enum import Enum
class Color(Enum):
kWhite = 0
kRed = 1
kGreen = 2
class Solution:
def isBipartite(self, graph: List[List[int]]) -> bool:
colors = [Color.kWhite] * len(graph)
for i in range(len(graph)):
# Already colored, do nothing
if colors[i] != Color.kWhite:
continue
... | Python | 1 |
labels = get_batch_transformer(batch)
if USE_GPU:
test_labels = test_labels.cuda()
model.batch_size = len(test_labels)
# model.hidden = model.init_hidden()
output = model(test_code, test_code_versions, test_calling, test_called, test_number_of_days, test_number_of_v... | Python | 1 |
ldDatasetEval(data_dir=config.dataset_root_dir,
name=line.strip('\n'),
mode='DB',
transforms=eval_transform)
eval_dataloader_db = DataLoader(eva_dataset_db,
batch_size... | Python | 1 |
pub fn write_nuc_error(&mut self, seq_name: &str, message: &str) -> Result<(), Report> {
self.writer.write(&ErrorCsvEntry {
seq_name,
errors: message,
warnings: "",
failed_genes: "",
})
}
/// Writes one row into errors.csv file for the case of aa alignment errors
pub fn write_aa... | Rust | 0 |
Japanese Northern and Southern Court period)",
"3KLY" => "15th century, c 1400 to c 1499",
"3KLY-GB-F" => "Wars of the Roses (c 1455 to c 1487)",
"3KLY-IT-E" => "Italy: Renaissance (c 1400 to c 1499)",
"3KLY-JP-M" => "1392 to 1573 (Japanese Muromachi period)",
"3KLY-PL-A" => "Period of the Jagiellon... | Rust | 0 |
<M, H>,
S: LineageStore<M, H, R>,
D: DispersalSampler<M, H, G>,
C: CoalescenceSampler<M, H, R, S>,
T: TurnoverRate<M, H>,
N: SpeciationProbability<M, H>,
> GillespiePartialSimulation<M, H, G, R, S, D, C, T, N>
{
#[inline]
pub fn without_emigration_exit<X: EmigrationEx... | Rust | 0 |
# Global counters for persistent IDs
customer_counter = 0
order_counter = 0
lineitem_counter = 0
# Aggregation tracking
current_order_total = 0.0
current_customer_total = 0.0
current_customer_orders = 0
def customer_id():
global customer_counter
customer_counter += 1
return f"C{customer_counter}"
def ord... | Python | 1 |
request: Request<Queries>) -> Result<Response<ListValue>, Status> {
let queries = request.into_inner().queries;
let queries = if queries < 1 {
1
} else if queries > 500 {
500
} else {
queries
};
let worlds = self.postgres.db_world_queri... | Rust | 0 |
= reverse(
'calcification:rate_table_download', args=[atlantic_table_2.pk])
indo_pacific_download_url = reverse(
'calcification:rate_table_download', args=[indo_pacific_table.pk])
# Latest Atlantic table only, and Indo-Pacific table
self.assertNotIn(
atlanti... | Python | 1 |
Signature, Verifier as SignatureVerifier};
use protobuf::{Message, RepeatedField};
use crate::admin::store::{
AdminServiceStore, Circuit as StoreCircuit, CircuitBuilder as StoreCircuitBuilder,
CircuitPredicate, CircuitProposal as StoreProposal, CircuitStatus as StoreCircuitStatus,
ProposalType, ProposedCi... | Rust | 0 |
use std::f64;
use std::sync::Arc;
fn main() {
const WIDTH: u16 = 350;
const HEIGHT: u16 = 200;
const SAMPLES: u64 = 200;
let look_from = Point3::new(13.0, 2.0, 3.0);
let look_at = Point3::new(0.0, 0.0, 0.0);
// let dist_to_focus = (look_from - look_at).magnitude();
let dist_to_focus = 10.0... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.