text string | label_name string | labels int64 |
|---|---|---|
class Indigena:
def __init__(self, nombre, edad, comunidad):
self.nombre = nombre
self.edad = edad
self.comunidad = comunidad
def __str__(self):
return f"Indígena: {self.nombre}, Edad: {self.edad}, Comunidad: {self.comunidad}"
class Gobierno:
def __init__(self, nombre_pres... | Python | 1 |
self.inner.prefix)
.or_else(|| self.inner.next())
.or_else(|| try_take_slice_padded(&mut self.inner.postfix))
}
fn size_hint(&self) -> (usize, Option<usize>) {
let n = self.inner.len()
+ (!self.inner.prefix.is_empty() as usize)
+ (!self.inner.postfix.is_... | Rust | 0 |
import supervision as sv
def extract_tracks(frames, all_detections):
tracks={
"player":{},
"goalkeeper":{},
"refree":{}
}
| Python | 1 |
use futures::TryStreamExt;
use serde_json::json;
use tokio::sync::mpsc::Sender;
use crate::client::Client;
use crate::uploader::*;
use crate::video::VideoPart;
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Uploader {
Upos,
Kodo,
Bos,
Gcs,
Cos,
}
impl Uploader {
... | Rust | 0 |
Overflow {}),
Box::new(super::overflow_exception::DoubleAddImmediateOverflowIntoR0 {}),
Box::new(super::tlb::WiredRandom {}),
Box::new(super::tlb::WiredOutOfBoundsRandom {}),
Box::new(super::tlb::WriteRandomExpectIgnored {}),
Box::new(super::tlb::IndexMasking {}),
Box::ne... | Rust | 0 |
mut query: Query<&mut DrawMode, With<ExampleShapeC>>, time: Res<Time>) {
let hue = (time.seconds_since_startup() * 80.0) % 360.0;
let outline_width = 2.0 + time.seconds_since_startup().sin().abs() * 10.0;
for mut draw_mode in query.iter_mut() {
if let DrawMode::Outlined {
ref mut fill_m... | Rust | 0 |
data_a_path.display(),
data_b_path.display(),
)
}
Self::Sample(ref points_path, ref data_path, ref grid) => {
writeln!(fmt, "Sample...")?;
fmt_report!(fmt, points_path.display(), "points");
fmt_... | Rust | 0 |
import unittest
from boto.sts.credentials import Credentials
class STSCredentialsTest(unittest.TestCase):
sts = True
def setUp(self):
super(STSCredentialsTest, self).setUp()
self.creds = Credentials()
def test_to_dict(self):
# This would fail miserably if ``Credentials.request_i... | Python | 1 |
v, c)| CollisionData {
entity: e,
position: t.translation,
velocity: v.velocity,
collision: *c,
})
.collect();
let object_count = objects.len();
for i in 0..object_count {
let obj1 = &objects[i];
for j in (i + 1)..object_count {... | Rust | 0 |
import time
import threading
from sleekxmpp.test import *
class TestOOB(SleekTest):
def tearDown(self):
self.stream_close()
def testSendOOB(self):
"""Test sending an OOB transfer request."""
self.stream_start(plugins=['xep_0066', 'xep_0030'])
url = 'http://github.com/fritzy... | Python | 1 |
puts])
padded_token_ids = jnp.array(
[
jnp.pad(
inp.token_ids,
(0, max_len - inp.token_ids.size),
constant_values=pad_token_id,
)
for inp in inputs
],
)
response_token_ids = language_model.generate_tokens(
... | Python | 1 |
import numpy as np
print(np.__version__)
# 1.26.1
a = np.arange(12).reshape(3, 4)
print(a)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
print(a.ravel())
# [ 0 1 2 3 4 5 6 7 8 9 10 11]
print(a.ravel('F'))
# [ 0 4 8 1 5 9 2 6 10 3 7 11]
print(np.ravel(a, 'F'))
# [ 0 4 8 1 5 9 2 6 10 ... | Python | 1 |
} else {
Displacement::Disp32(disp as i32)
}
}
DispNode::Label(symbol_name) => {
let cur_section = self.cur_section();
let item_index = cur_section.items.l... | Rust | 0 |
coins_hold = random.randint(800, 915)
success = self.hold_coin(token, coins_hold)
if success:
log(hju + f"Success Hold Coin | Reward {pth}{coins_hold} {hju}Coins")
countdown_timer(self.game_delay)... | Python | 1 |
mStartBytes = 9,
InnerRandomStreamID = 10,
}
struct DatabaseHeader {
#[allow(dead_code)]
version: u32,
master_seed: [u8; 32],
transform_seed: [u8; 32],
transform_rounds: u64,
encryption_iv: [u8; 16],
protected_stream_key: [u8; 32],
stream_start_bytes: Vec<u8>,
compression_algori... | Rust | 0 |
self.debug_id.assert(ctx);
// We have to mess with the scale to make everything
// be its-unit-size-in-pixels.
let scale_x = param.src.w * f32::from(self.width());
let scale_y = param.src.h * f32::from(self.height());
let param = param.transform(
glam::Mat4::from(pa... | Rust | 0 |
"98"
],
"capital": "Tehran",
"altSpellings": [
"IR",
"Islamic Republic of Iran",
"Jomhuri-ye Eslāmi-ye Irān"
],
"subregion": "Southern Asia",
"region": "Asia",
"population": 83992953,
"latlng": [
... | Python | 1 |
import os
import sys
sys.path.append(os.path.abspath(__file__).rsplit("/", 2)[0])
from argparse import ArgumentParser
import json
import math
import pickle
from data.convertsation import Conversation
from data.item_processor import FlexARItemProcessor
class ItemProcessor(FlexARItemProcessor):
def __init__(
... | Python | 1 |
with other parseXX.py routines
p = Python38Parser()
p.remove_rules_38()
p.check_grammar()
from xdis.version_info import PYTHON_VERSION_TRIPLE, IS_PYPY
if PYTHON_VERSION_TRIPLE[:2] == (3, 8):
lhs, rhs, tokens, right_recursive, dup_rhs = p.check_sets()
from uncompyle6.scanner import ... | Python | 1 |
! Click some buttons!"),
_ => info!("Other event {:?}", event),
}
}
}
info!("Exiting...");
Ok(())
}
<filename>src/builtin/cat_file.rs<gh_stars>10-100
use std::str;
use builtin::read_tree;
use cli;
use object;
use object::Object;
#[derive(Debug)]
pub enum Error {
Obj... | Rust | 0 |
FnMut(B, A) -> B>(self, zero: B, fold_fn: F) -> Source<B>
where
B: 'static + Send,
F: 'static + Send,
{
self.via(Flow::from_logic(flow::Fold::new(zero, fold_fn)))
}
pub fn map<B, F: FnMut(A) -> B>(self, map_fn: F) -> Source<B>
where
B: 'static + Send,
F: 'st... | Rust | 0 |
encoder
ai_edge_torch.signature('encode', clip_model, (prompt_tokens,)).convert(
quant_config=quant_config
).export(f'{output_dir}/clip.tflite')
# TODO(yichunk): enable image encoder conversion
# Image encoder
# ai_edge_torch.signature('encode', encoder, (input_image, noise)).convert(quant_config=quan... | Python | 1 |
from pyspark.sql.dataframe import DataFrame
from hermione.base import DataSource
class SparkDataBase(DataSource):
"""
Class used to read data from databases
Parameters
----------
spark_session : pyspark.sql.session.SparkSession
SparkSession used to read data
Attributes
-------... | Python | 1 |
ogramDataPoint| { &mut m.count },
));
fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeSfixed64>(
"sum",
|m: &IntHistogramDataPoint| { &m.sum },
|m: &mut IntHistogramDataPoint| { &mut m.sum }... | Rust | 0 |
select_action(action_state, is_training, policy_type = 'GreedyEpsilonPolicy')
state, reward, done, info = env.step(action)
episode_frames += 1
episode_reward[idx_episode-1] += reward
if episode_frames > max_episode_length:
done = True
if done:... | Python | 1 |
, permet le tri par altitudes.
pub colonne: usize,
pub ligne: usize,
}
/// Un Voisinage regroupe les Points immédiatement voisins d'un Point central.
/// Le premier Point est le Point central, suivi d'au maximum 8 voisins.
/// Les voisins sont listés sans ordre particulier.
pub type Voisinage = Vec<Point>;
//... | Rust | 0 |
c, a)];
let mut solver = Solver::new(model);
solver.add_theory(|tok| StnTheory::new(tok, StnConfig::default()));
solver.enforce_all(constraints);
assert!(solver.solve().unwrap().is_none());
}
#[test]
fn minimize() {
let mut model = Model::new();
let a = model.new_ivar(0, 10, "a");
let b =... | Rust | 0 |
t '| ' * lev + tab
lev += 1
if lev > 1:
print '| ' * lev
print
print 'cursor type name'
print '------ ------ ----------------------------------------------'
for cur in cursors:
num, type, fullname, name, tbl = cur
print '%6d %-6.6s %s' % (num, type, fullname)
... | Python | 1 |
vgError(usvg::Error),
PngEncodingError(String),
RenderError,
PixmapCreationError,
}
impl std::fmt::Display for ImageError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
match *self {
ImageError::UsvgError(ref e) => e.fmt(f),
ImageError::Png... | Rust | 0 |
[{}] = {}", i, string_from_slice(&by_col[i][..]));
assert_eq!(by_col[i][0], vectors[0][i]);
}
// println!(" {}", string_from_slice(&vec_a[..]));
// println!("+ {}", string_from_slice(&vec_b[..]));
// println!("= {}", string_from_slice(&vec_c[..]));
}
fn string_from_slice<T: fmt::Display>(slic... | Rust | 0 |
,
});
Ok(())
}
pub(crate) fn restart_sidevm_if_needed(
&mut self,
spawner: &sidevm::service::Spawner,
) -> Result<()> {
if let Some(sidevm_info) = &mut self.sidevm_info {
let guard = sidevm_info.handle.lock().unwrap();
let handle = if let Side... | Rust | 0 |
workflow_id = str(uuid.uuid4())
console.print(f"[bold yellow]📋 Workflow ID: {workflow_id}[/bold yellow]")
console.print(
f"[dim]Use --workflow-id {workflow_id} to resume if interrupted[/dim]\n"
)
with SetWorkflowID(workflow_id):
result =... | Python | 1 |
j = 0
ft_ks = sorted(ft.keys())
ic_ks = sorted(ic.keys())
print('linear scan and merge...')
while i < len(ft)-1:
ft_k = hex(ft_ks[i]) # hex str
ft_v = ft[ft_ks[i]] # cannot directly use ft_k, a hex str
merge[ft_k] = (ft_v, None)
func_cov[ft_k] = (ft_v, False)
... | Python | 1 |
.for_each(|render_spec| println!(" - {}", render_spec.target.display()));
}
if !render_result.conflicts.is_empty() {
eprintln!("There were conflicts:");
render_result.conflicts.iter().for_each(|conflict| {
eprintln!(
" > {}:",
format!(
... | Rust | 0 |
l TExp {
pub fn ty(&self) -> Type {
match *self {
TExp::Unit => Type::Unit,
TExp::Bool(_) => Type::Bool,
TExp::Int(_) => Type::Int,
TExp::Quote(ref texp) => unimplemented!(),
TExp::Let(_, ref body) => body.last().unwrap().ty(),
TExp::Va... | Rust | 0 |
m2"]),
"cbrt": Function::make(cbrt, ["num1", "num2"]),
"ceil": Function::make(ceil, ["num1", "num2"]),
"cos": Function::make(cos, ["num1", "num2"]),
"exp": Function::make(exp, ["num1", "num2"]),
"floor": Function::make(floor, ["num"]),
"log": Function::make(log, ["num1", ... | Rust | 0 |
init_policy)
while step < args.steps:
if should_report(step):
print('Evaluation')
driver_eval.reset(agent.init_policy)
driver_eval(eval_policy, episodes=args.eval_eps)
logger.add(eval_epstats.result(), prefix='epstats')
if len(replay_train):
carry_report, mets = reportfn(car... | Python | 1 |
s.values())
performance_gap = max(scores_list) - min(scores_list)
print(f"📊 Performance Gap: {performance_gap} points between best and worst")
# Average performance
avg_score = np.mean(scores_list)
avg_pct = (avg_score / max_total_score) * 100
print(f"📈 Average Performance: {avg_score:.1f}/{max_total_score} points (... | Python | 1 |
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def init_db(app):
# Use DATABASE_URL from environment or fallback to local Postgres
import os
app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv(
'DATABASE_URL',
)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(... | Python | 1 |
active_cubes.insert(Position3D::from([x, y, z]));
x += 1;
}
'\n' => {
x = 0;
y += 1;
}
_ => panic!("unexpected character {:?} at line {} column {} ", c, y, x),
}
}
PocketDimension {
ac... | Rust | 0 |
the
/// CPU cache.
///
/// # Note
/// The light object must have been initialized first using the necessary `GX_InitLight*()`
/// functions.
///
/// Another way to load a light object is with `Gx::load_light_idx()`.
pub fn load_light(lit_obj: &Light, lit_id: u8) {
unsafe { ffi::... | Rust | 0 |
log({"samples/query_responses": wandb.Table(dataframe=eval_df)}, step=update)
# save model
if args.output_dir:
output_dir = os.path.join(args.output_dir, run_name, str(update))
os.makedirs(os.path.dirname(output_dir), exist_ok=True)
time_tensor = torch.tensor([int(time.time())], device=... | Python | 1 |
from model import *
class Classifier(SavableModule):
def __init__(self, label_count):
super(Classifier, self).__init__(filename="classifier.to")
self.layers = nn.Sequential(
nn.Conv3d(in_channels = 1, out_channels = 12, kernel_size = 5),
nn.ReLU(inplace=True),
... | Python | 1 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time : 2023/12/30 00:33
@Author : alexanderwu
@File : __init__.py
"""
| Python | 1 |
#! -*- coding: utf-8 -*-
import torch
import numpy as np
import requests
import collections
def is_ch(string):
for char in string:
if not 0x4e00 <= ord(char) <= 0x9fa6:
return False
return True
def get_word_vector(word):
url = ' http://172.27.1.207:11109/vector'
data = {
... | Python | 1 |
uf))
}
}
impl AsRef<[u8]> for ZId {
fn as_ref(&self) -> &[u8] {
&self.0
}
}
impl From<[u8; 16]> for ZId {
fn from(b: [u8; 16]) -> Self {
ZId(b)
}
}
impl fmt::Display for ZId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&hex::encode(self.0))
... | Rust | 0 |
xt_takeover
else:
no_context_takeover = self.client_no_context_takeover
if no_context_takeover:
self._decompressor = None
self._inbound_compressed = None
return data
def frame_outbound(
self,
proto: Union[FrameDecoder, FrameProtocol],
... | Python | 1 |
from typing import List
from src.entities.discipline import Discipline
from src.entities.restriction import Restriction
from src.entities.teacher import Teacher
class ScheduleManager:
"""
ScheduleManager class manages the generation of class schedules
based on provided teachers, disciplines, and restrict... | Python | 1 |
"""Test LaTeX syntax in legends and titles."""
from scitools.std import *
def f1(t):
return t**2*exp(-t**2)
def f2(t):
return t**2*f1(t)
t = linspace(0, 3, 51)
y1 = f1(t)
y2 = f2(t)
plot(t, y1, 'r-', legend='t**2*exp(-t**2)',
title='Testing legend with double mult for power')
savefig('tmp1.eps')
raw_in... | Python | 1 |
CPU is halted"]
HALT_T16_3_1 = 1,
}
impl From<HALT_T16_3_A> for bool {
#[inline(always)]
fn from(variant: HALT_T16_3_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `HALT_T16_3`"]
pub type HALT_T16_3_R = crate::R<bool, HALT_T16_3_A>;
impl HALT_T16_3_R {
#[doc = r"Get enumerated ... | Rust | 0 |
= 'i':
indices = int(user_input.split(' ')[1])
increment = int(user_input.split(' ')[-1])
increase_frequency(indices, increment)
elif command == 'd':
indices = int(user_input.split(' ')[1])
decrement = int(user_input.split(' ')[-1])
decrease_frequency(indices, decrement)
elif command == 'g':... | Python | 1 |
import requests
import json
import datetime
import time
import sys
import math
ACCESS_TOKEN = '[put your API key here]' # Replace with your GitHub token or set to None
usage = """Retrieves a list of follower usernames of a GitHub user using the GitHub API.
Usage: python grab.py [target_username] [output filename] [... | Python | 1 |
::new(); // 字符串对象 String 是由 Rust 标准库提供的、拥有所有权的 UTF-8 编码的字符串类型,创建后可以为其追加内容或更改内容
let mut s = String::from("Hello, Rust!"); // 使用 String::from 函数根据指定的字符串字面量创建字符串对象
let _str = "Hello, Rust!";
let _s = str.to_string(); // 使用 to_string 方法将字符串字面值转化为字符串对象。
// s.push(' ');
... | Rust | 0 |
protocol_file_path'][0]
txt_file = ''
with open(protocol_file, 'r') as f:
lines = f.readlines()
txt_file = ' '.join(lines) # 也要去掉,只保留最主要的内容,比如”第一轮PCR反应“则保留成‘PCR反应’即可
f.close()
# 提取建库流程信息,并提取出每一步骤内容的摘要
experiment_type_prompt... | Python | 1 |
::{
test_utils::TestRandom, BeaconBlock, ChainSpec, Domain, EthSpec, Fork, Hash256, PublicKey,
SignedRoot, SigningData, Slot,
};
use bls::Signature;
use serde_derive::{Deserialize, Serialize};
use ssz_derive::{Decode, Encode};
use std::fmt;
use test_random_derive::TestRandom;
use tree_hash::TreeHash;
#[cfg_att... | Rust | 0 |
from serpent.window_controller import WindowController
import win32gui
import win32con
import re
window_id = 0
class Win32WindowController(WindowController):
def __init__(self):
pass
def locate_window(self, name):
global window_id
window_id = win32gui.FindWindow(None, name)
... | Python | 1 |
_sccs());
{
let regions_in_constraint = outlives_constraints
.iter()
.map(|constraint| [constraint.0, constraint.1])
.flatten()
.collect::<HashSet<_>>();
for region in 0 .. max_region {
let region = RegionVid::from_usize(region);
if regions_in_constraint.c... | Rust | 0 |
let coin_info = CoinInfo {
coin: "KUSAMA".to_string(),
derivation_path: "//imToken//kusama/0".to_string(),
curve: CurveType::SubSr25519,
network: "".to_string(),
seg_wit: "".to_string(),
};
let addresses = vec![
"3BMEXohjFLZJGBLkCbF... | Rust | 0 |
params.param1, ¶ms.param2, &memory)?;
current_address = if value == 0 { output } else { current_address + 3 };
}
Instruction::LessThan(params) => {
let (left, right) = get_2_param_values(¶ms.left, ¶ms.right, &memory)?;
let instr_res = i... | Rust | 0 |
ce: int, n=2) -> int:
"""Revealing the asking price of a player directly would make the game
too easy. This method sets the asking price to a random number within
a range of the true number."""
obfuscated = round(random.randrange(int(asking_price/n),
... | Python | 1 |
.get("api_endpoints", [])
score_data = score_api_response(tool_response)
score_data['api_count'] = len(api_endpoints)
score_data['session_id'] = session_id
# Save score to session file
save_session_score(session_id, score_data)
# Print score summary for ... | Python | 1 |
(rename = "YUM")]
Yum,
/// New Israeli Sheqel
#[serde(rename = "ILS")]
Ils,
/// New Kwanza
#[serde(rename = "AON")]
Aon,
/// New Taiwan Dollar
#[serde(rename = "TWD")]
Twd,
/// New Zaire
#[serde(rename = "ZRN")]
Zrn,
/// New Zealand Dollar
#[serde(rename = "NZD")]
Nzd,
/// Next day
#[serde(rename = "U... | Rust | 0 |
glib::Value::from(&month).to_glib_none().0,
);
}
}
#[doc(alias = "get_property_year")]
pub fn year(&self) -> i32 {
unsafe {
let mut value = glib::Value::from_type(<i32 as StaticType>::static_type());
glib::gobject_ffi::g_object_get_property(
... | Rust | 0 |
ext().unwrap();
assert_eq!(user.id, 1);
assert_eq!(user.name, "<NAME>");
let user = users.next().unwrap();
assert_eq!(user.id, 3);
assert_eq!(user.name, "<NAME>");
Ok(())
}
#[test]
fn order() -> Result<(), String> {
let conn = FbConnection::establish("firebird://SYSDBA:masterkey@localhost... | Rust | 0 |
r(index)+'\t'+str(i)+'\t'+str(ranks[index])+'\t'+str(top1[index])+'\t'+str(sims[index][i])+'\t'+str(sims[index][int(inds[0])])+'\n')
#fw.close()
# Compute metrics
r1 = 100.0 * len(np.where(ranks < 1)[0]) / len(ranks)
r5 = 100.0 * len(np.where(ranks < 5)[0]) / len(ranks)
r10 = 100.0 * len(np.where(r... | Python | 1 |
will_flag: true,
clean_start: true,
};
let properties = ConnectProperties {
session_expiry_interval: SessionExpiryInterval::new(30).into(),
receive_maximum: ReceiveMaximum::new(20).into(),
..Default::default()
};
let will_properties = Wil... | Rust | 0 |
= Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::current-direction\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_current_direction_trampoline::<F> as *const (),
)),
... | Rust | 0 |
# -*- coding: utf-8 -*-
"""
auto rule template
~~~~
:author: LoRexxar <LoRexxar@gmail.com>
:homepage: https://github.com/LoRexxar/Kunlun-M
:license: MIT, see LICENSE for more details.
:copyright: Copyright (c) 2017 LoRexxar. All rights reserved
"""
from utils.api import *
class CVI_100... | Python | 1 |
ogin packet
pub const ID_LOGIN_CTS_START_LOGIN: u32 = 0x00;
/// The ID of an encryption response packet
pub const ID_LOGIN_CTS_ENCRYPTION_RESPONSE: u32 = 0x01;
<filename>query-engine/core/src/interactive_transactions/mod.rs<gh_stars>10-100
use crate::CoreError;
use connector::{Connection, ConnectionLike, Transaction};... | Rust | 0 |
ar_by_registry())
winrar_bin = _find_extractor_by_cmd(winrar_cmd)
if not relative_to is None and (output_dir / relative_to).exists():
get_logger().error('Temporary unpacking directory already exists: %s',
output_dir / relative_to)
raise ExtractionError()
cmd = (wi... | Python | 1 |
my_tuple = (1, 2, 3, 4)
reversed_tuple = my_tuple[::-1]
print(reversed_tuple) | Python | 1 |
n they are used with `getsockopt` or `setsockopt`,
//! they will require the right data type.
//!
//! # Examples
//!
//! ```
//! use udt::*;
//!
//! let sock = UdtSocket::new(SocketFamily::AFInet, SocketType::Stream).unwrap();
//! let recv_buf: i32 = sock.getsockopt(UdtOpts::UDT_RCVB... | Rust | 0 |
#!/usr/bin/env python3
import argparse
import json
import subprocess
import sys
def dump_json(obj, out, pretty):
if pretty:
json.dump(obj, out, indent=2, sort_keys=True)
else:
json.dump(obj, out, separators=(",", ":"), sort_keys=True)
return
def main():
parser = argparse.ArgumentParse... | Python | 1 |
from nltk.translate.bleu_score import corpus_bleu, SmoothingFunction
# Example predictions and references
predictions = [
'The quick brown fox jumps over the lazy dog.',
'The fast brown fox leaps over the lazy dog.', ' '
]
references = [
['The quick brown fox jumps over the lazy dog.'],
['A fast brown... | Python | 1 |
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtCore import QThread, pyqtSignal
from QtGui import Ui_MainWindow
import os
from tkinter import messagebox
# Tạo một luồng xử lý riêng cho các tác vụ nặng
class WorkerThread(QThread):
progress_signal = pyqtSignal(str) # Tín hiệu để cập n... | Python | 1 |
let mut raw = BytesMut::from(b"GET htt:p// HTTP/1.1\r\nHost: hyper.rs\r\n\r\n".to_vec());
let ctx = ParseContext {
cached_headers: &mut None,
req_method: &mut None,
};
Server::parse(&mut raw, ctx).unwrap_err();
}
#[test]
fn test_decoder_request() {
... | Rust | 0 |
#Auto: Álvaro Tavares - 01/08/2025
#pip install -r requirements.txt
#streamlit run app.py
import streamlit as st
from recomendador import carregar_dados_azure, gerar_recomendacoes
st.set_page_config(page_title="Recomendador de Filmes", layout="wide")
st.title("🎬 Recomendador Híbrido de Filmes por Plataforma")
usuar... | Python | 1 |
ime = datetime.now()
# table.put_item(Item=self.to_dict())
# print(f"Item saved to DynamoDB table 'definitions' with ID {self.definition_id} and version {self.version_datetime}")
# @classmethod
# def load_from_dynamoDB(cls, definition_id: str) -> Self:
# load_dotenv() # to get AWS acc... | Python | 1 |
"""
Logging Configuration for FreeCAD AI Addon
Provides centralized logging configuration and utilities for the addon.
"""
import logging
from pathlib import Path
def setup_logging(level=logging.INFO):
"""
Set up logging configuration for the FreeCAD AI Addon.
Args:
level: Logging level (defaul... | Python | 1 |
timated income*: Kshs. *insert amount*
# """
# },
# {
# "type": "image_url",
# "image_url": {
# "url": f"data:image/jpeg;base64,{base64_image}"
# }
# ... | Python | 1 |
# Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | Python | 1 |
rottle-requests`
/// is enabled and the load test completes. The `GooseResponse` object contains a copy of the
/// request made
/// ([`goose.request`](https://docs.rs/goose/*/goose/goose/struct.GooseRawRequest)), and the
/// Reqwest response ([`goose.response`](https://docs.rs/reqwest/*/reqwest/struct.R... | Rust | 0 |
from dataclasses import dataclass, field
import numpy as np
from src.control.algorithms.base import Controller, ControllerParams
from src.control.state import Go1State
@dataclass(kw_only=True)
class SequentialControllerParams(ControllerParams):
yaw_control_threshold: float = field(default=np.pi / 18)
yaw_co... | Python | 1 |
local_vars,
} = frame;
let operand_stack = operand_stack.push_int(0);
let operand_stack = operand_stack.push_int(0);
let frame = Frame {
operand_stack,
local_vars,
};
let (ExecuteResult { frame: _, offset }, _) = IF_ICMPLT(CodeReader::new(&vec... | Rust | 0 |
::LessOrEqual => self.max = Some(value + tolerance),
Operator::Greater => self.min = Some(value + tolerance),
Operator::GreaterOrEqual => self.min = Some(value - tolerance),
}
true
}
}
impl<T: PartialOrd> OptionalRange<T> {
pub fn contains(&self, value: T) -> bool {
... | Rust | 0 |
} else {
None
}
}
};
match timestamp_format {
TimestampFormat::None => format!(""),
TimestampFormat::Redacted => "[ ] ".to_string(), // for testing
TimestampFormat::Local => {
if let Some(datetime) = datetime {
let datetime... | Rust | 0 |
::new(Vec::new(), 4096);
// writer.write_all(input).unwrap();
// let output = match writer.into_inner() {
// Ok(v) => v,
// Err(_) => panic!("Brotli error while decoding data."),
// };
// output
// let mut reader = brotli::Decompressor::new(
// input,
// 4096, // buf... | Rust | 0 |
num_workers],
["Batch size", batch_size]
]
print(tabulate(summary_table, tablefmt="grid"))
final_confirmation = input("\nDo you confirm these choices? (y/n): ")
if final_confirmation.lower() != 'y':
print("Operation cancelled.")
return
start_time = time.time()
# Creat... | Python | 1 |
, value: V) -> Option<V> {
let p = common_prefix(&self.key, key);
if p < self.key.len() {
let child = Tree {
key: self.key.split_off(p),
value: self.value.take(),
children: mem::take(&mut self.children),
};
self.children... | Rust | 0 |
# Crie um programa que utilize uma estrutura de repetição para imprimir os números de 1 a 10.
for n in range(1,11):
print(n) | Python | 1 |
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel, ValidationError
from typing import List, Type
from enum import Enum
from tester import Tester
from spec.fix import FixTester
from typing import List, Dict, Any, ... | Python | 1 |
[inline]
pub fn is_int2p0(&self) -> bool {
*self == REFSELR::INT2P0
}
#[doc = "Checks if the value of the field is `INT1P5`"]
#[inline]
pub fn is_int1p5(&self) -> bool {
*self == REFSELR::INT1P5
}
#[doc = "Checks if the value of the field is `EXT2P0`"]
#[inline]
pub f... | Rust | 0 |
"""
pygments.lexers.futhark
~~~~~~~~~~~~~~~~~~~~~~~
Lexer for the Futhark language
:copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.lexer import RegexLexer, bygroups
from pygments.token import Comment, Operator, Keyword, ... | Python | 1 |
|| {
panic!(
"unable to find type argument `{}` during monomorphisation",
tvar.source_name()
)
})
.clone(),
}
}
fn as_poly_subst(&self) -> &PartialMonomorphise<'tyargs> {
&sel... | Rust | 0 |
# path where to save gallery generated examples
"gallery_dirs": ["examples"],
# Patter to search for example files
"filename_pattern": r"\.py",
# Remove the "Download all examples" button from the top level gallery
"download_all_examples": False,
# Sort gallery example by file name instead of ... | Python | 1 |
- New Data"]
#[inline(always)]
pub fn can_if2mctl_newdat(&self) -> CAN_IF2MCTL_NEWDATR {
let bits = ((self.bits >> 15) & 1) != 0;
CAN_IF2MCTL_NEWDATR { bits }
}
}
impl W {
#[doc = r"Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &m... | Rust | 0 |
::new(Rule {
resource: "abc1".into(),
calculate_strategy: CalculateStrategy::Direct,
control_strategy: ControlStrategy::Reject,
threshold: 20.0,
..Default::default()
});
let r21 = Arc::new(Rule {
resource: "abc2".into(),
... | Rust | 0 |
_bytes().last() {
frags.push(Fragment::Text(Cow::Owned("<".into())));
input = back;
continue;
}
let mut maybeoffset = 0;
let mut kerr = None;
loop {
let (maybek, maybeback) = {
let (reserved, considered) = back.split_at(maybeoffset);
let maybeclose = reserved.len()
+ match (kerr, consi... | Rust | 0 |
class Codec:
def serialize(self, root):
# use level order traversal to match LeetCode's serialization format
flat_bt = []
queue = collections.deque([root])
while queue:
node = queue.pop()
if node:
flat_bt.append(str(node.val))
... | Python | 1 |
, account_fixture: Account
) -> None:
"""Test case update without API key."""
test_case = Case(
id=f"test-case-unauth-{uuid4()}",
job_id=job_fixture.id,
account=account_fixture,
status=EntityStatus.AWAITING,
name="Test Case",
description="Test Case Description",
... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.