text
string
label_name
string
labels
int64
'ukrainian', 'en': 'english', # Добавьте другие языки при необходимости } # Преобразовываем код языка в его полное название return language_names.get(code.lower(), code) def get_genre_and_franchise_on_Steam(soup): # Извлекаем нужную информацию details_block = soup.find('div', {'id'...
Python
1
# MIT License # # Copyright (c) 2021 Soohwan Kim # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, ...
Python
1
_map)) list_of_image_paths.append(path_name) avg_heatmaps.append(average) avg_gradient_heatmaps.append(average_gradient) # return the index of the heatmap having the highest gradient score # TODO: refine to take sequence into account print(f"avg_heatmaps {avg_heatmaps}") min_a...
Python
1
lmV1 content"), } } #[test] fn deserialization_failure() { assert!(from_json_value::<EventJson<EncryptedEventContent>>( json!({ "algorithm": "m.megolm.v1.aes-sha2" }) ) .unwrap() .deserialize() .is_err()); } } use super::{HitRecord, Material, ...
Rust
0
dic.append(('0122324515', '[' + domain + '_' + 'phone' + ']')) dic.append((normalize('Addenbrookes Hospital'), '[' + domain + '_' + 'name' + ']')) elif domain == 'police': dic.append((normalize('Parkside'), '[' + domain + '_' + 'address' + ']')) dic.append((normalize('C...
Python
1
ill do nothing if no additional-action corresponding"] #[doc = " to the specified |aaType| exists."] pub fn FORM_DoPageAAction( page: FPDF_PAGE, hHandle: FPDF_FORMHANDLE, aaType: ::std::os::raw::c_int, ); } extern "C" { #[doc = " Function: FORM_OnMouseMove"] #[doc = " ...
Rust
0
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import json import pytest import sys from logging import getLogger from flowmachine.core.context import get_redis from...
Python
1
vec![1u8; 2 * page_size]; mem.write(&ones[..], GuestAddress(0)).unwrap(); // Remove the first page. assert!(remove_range(&mem, (GuestAddress(0), page_size as u64), false).is_ok()); // Check that the first page is zeroed. let mut actual_page = vec![0u8; page_size]; mem....
Rust
0
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware import requests from bs4 import BeautifulSoup app = FastAPI() # CORS middleware for Chrome extension access app.add_middleware( CORSMiddleware, allow_origins=["*"], # Adjust for production allow_credentials=True, allow_met...
Python
1
text) .unwrap(); assert_eq!(&PLAINTEXT, plaintext.as_slice()); } // Cipher operations are only supported by cryptoauthlib provider. #[cfg(feature = "cryptoauthlib-provider")] #[test] fn cipher_encrypt_decrypt_ofb() { let key_name = auto_test_keyname!(); let mut client = TestClient::new(); if ...
Rust
0
#!/usr/bin/env python # -*- coding: utf-8 -*- from evo.core.trajectory import PoseTrajectory3D from evo.tools import file_interface import numpy as np DESC = "Combine KITTI poses and timestamps files to a TUM trajectory file" def kitti_poses_and_timestamps_to_trajectory(poses_file, timestamp_file): pose_path = ...
Python
1
import copy import random class Robot: def __init__(self, nama, attack, hp): self.nama = nama self.attack = attack self.hp = hp def attack_enemy(self, target, multiplication): if multiplication == 0: target.hp = target.hp - self.attack else: targ...
Python
1
request .app_data::<web::Data<Handlebars>>() .map(|x| x.get_ref()); match hb { Some(hb) => { let data = json!({ "error": error, "status_code": res.status().as_str() }); let body = hb.render("error", &data); ma...
Rust
0
# make new noise noise = np.random.uniform(-1, 1, (2 * num_test, latent_size)) sampled_labels = np.random.randint(0, 2, 2 * num_test) trick = np.ones(2 * num_test) generator_test_loss = combined.evaluate( [noise, sampled_labels.reshape((-1, 1))], ...
Python
1
le::new(temp_f)) }, SavedData::Bytes(bytes) => { let kind = infer::get(&bytes) .ok_or_else(|| anyhow::Error::msg("File type unknown"))?; if kind.mime_type() != Mime::content_type() { return Err(anyhow::Error::msg(format!( ...
Rust
0
the credentials are service account credentials, then always try to use self signed JWT. if ( always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr( service_account.Credentials, "with_always_use_jwt_access" ) ...
Python
1
import cv2 import pafy from YOLOv6 import YOLOv6 # Initialize video # cap = cv2.VideoCapture("input.avi") videoUrl = 'https://youtu.be/trNO5Imf1Q8' videoPafy = pafy.new(videoUrl) print(videoPafy.streams) cap = cv2.VideoCapture(videoPafy.streams[-1].url) start_time = 0 # skip first {start_time} seconds cap.set(cv2.C...
Python
1
UnvaultDescriptor::new(stakeholders.clone(), managers, 2, cosigners, 2021).unwrap(); let emergency_address = EmergencyAddress::from( Address::from_str("bc1q906h8q49vu20cyffqklnzcda20k7c3m83fltey344kz3lctlx9xqhf2v56") .unwrap(), ) .unwrap(); let sc...
Rust
0
); assert_near!(res, ans); let res_uder = surface.uder(u, v); let ans_uder = Vector3::new(f64::cos(v) - f64::sin(v), -2.0, -f64::sin(v) - f64::cos(v)); assert_near!(res_uder, ans_uder); let res_vder = surface.vder(u, v); let ans_...
Rust
0
::SourcesQueueInput<f32>>, /// Whether the loop is stopped. /// Playing will cause a new source to be played. stopped: Arc<AtomicBool>, /// Whether the loop is paused. /// Playing will resume the source. paused: Arc<AtomicBool>, /// Whether current playing sound should be skipped. skippe...
Rust
0
#!/usr/bin/env python # Capstone by Nguyen Anh Quynnh <aquynh@gmail.com> # PPC Branch testing suite by kratolp from __future__ import print_function import sys from capstone import * CODE32 = b"\x48\x01\x05\x15" # bl .+0x10514 CODE32 += b"\x4B\xff\xff\xfd" # bl .-0x4 CODE32 += b"\x48\x00\x00\x0c" # b .+0xc CODE32 +=...
Python
1
# Copyright 2020 Soda # 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 applicable law or agreed to in writing, software #...
Python
1
#[test] fn u512_multi_adds() { let (result, _) = U512([0, 0, 0, 0, 0, 0, 0, 0]).overflowing_add(U512([0, 0, 0, 0, 0, 0, 0, 0])); assert_eq!(result, U512([0, 0, 0, 0, 0, 0, 0, 0])); let (result, _) = U512([1, 0, 0, 0, 0, 0, 0, 1]).overflowing_add(U512([1, 0, 0, 0, 0, 0, 0, 1])); assert_eq!(result, U51...
Rust
0
file_type(); let mut file = tokio::fs::File::create(format!("{version}.{file_type}")).await?; let mut downloaded: u64 = 0; while let Some(item) = response_bytes.next().await { let chunk = item.or(anyhow::private::Err(anyhow::Error::msg("hello")))?; ...
Rust
0
.run( # ["cd ..", "&&", "git", "rev-parse", "--short", "HEAD"], stdout=subprocess.PIPE # ).stdout.decode("utf-8") # build_version.strip() # new_db.version = build_version # print(f"Generated DBC hash: {new_db.version}") cantools.db.dump_file(new_db, outfilename + ".dbc") # cantools.db.d...
Python
1
::ArgminWeightedDot; impl<T, U, V> ArgminWeightedDot<T, U, V> for T where Self: ArgminDot<T, U>, V: ArgminDot<T, T>, { #[inline] fn weighted_dot(&self, w: &V, v: &T) -> U { self.dot(&w.dot(v)) } } #[cfg(test)] mod tests_vec { use super::*; use paste::item; macro_rules! make_te...
Rust
0
Vec<Stmt>) -> Fallible<Self> { let root_type = seek_root_type(&stmt)?; let namespace = seek_namespace(&stmt)?; let mut tables = seek_tables(&stmt); let root = tables .remove(&root_type) .ok_or(format_err!("Cannot find table: {}", root_type))?; Ok(Buffer ...
Rust
0
Mut(&dyn salsa::plumbing::QueryStorageMassOps), ) { #for_each_ops } } // ANCHOR_END:group_storage_methods }); if std::env::var("SALSA_DUMP").is_ok() { println!("~~~ query_group"); println!("{}", output.to_string()); println!("~~~ q...
Rust
0
aphical_fn::win_clear(buf); for i in 0..para.WIN_W { let idxf = (i as f32 / para.WIN_W as f32)* FFT_SIZE as f32 / math::log2i(para.WIN_W) as f32 * 0.1; let idx = idxf.floor() as usize; let idx_next = idx+1; let t = idxf.fract(); let scaling = (math::log2i((idx + 2)*para.WIN_H)) as f32; ...
Rust
0
b; assert_eq!(expected, actual); } #[test] fn impl_div_for_f64x4() { let a = f64x4::from([4.0, 9.0, 10.0, 12.0]); let b = f64x4::from([2.0, 2.0, 5.0, -3.0]); let expected = f64x4::from([2.0, 4.5, 2.0, -4.0]); let actual = a / b; assert_eq!(expected, actual); } #[test] fn impl_bitand_for_f64x4() { let a...
Rust
0
&mut dyn (::std::any::Any) } fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { self } fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { Self::descriptor_static() } fn new() -> CFriendMessages_IsInFriendsUIBeta_Respo...
Rust
0
from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker import os from dotenv import load_dotenv load_dotenv() DB_URL = os.getenv('DATABASE_URL') engine = create_engine(DB_URL) SessionLocal = sessionmaker(autocommit=False, autoflush=False,...
Python
1
t, store_nums, tolerant_rate, allow_split) def greedyTest(): print("argv:", sys.argv) store_nums = int(sys.argv[1]) tolerant_rate = float(sys.argv[2]) repeat_nums = 10 alg = "GREEDY-GLOBAL" if len(sys.argv) >= 4: repeat_nums = int(sys.argv[3]) if len(sys.argv) >= 5: alg = sy...
Python
1
import re import sys import matplotlib matplotlib.use('Qt5Agg') import matplotlib.pyplot as plt def append(d, key, entry): if key not in d: d[key] = [] d[key] += [entry] def plot_xy(X, Y, label, color, linewidth, linestyle, markersize, markerstyle): plt.plot(X, Y, label=label, color=color, l...
Python
1
} } /// <p>The specified CIDR IP range or Amazon EC2 security group might not be authorized /// for the specified DB security group.</p> /// <p>Or, RDS might not be authorized to perform necessary actions using IAM on your /// behalf.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct A...
Rust
0
import cv2 import numpy as np from ultralytics import YOLO from config import DEBUG class Yolo_segmentor: def __init__(self): self._model = YOLO(r"ai\best.pt") self._roi = None self._roi_coord = None # (x,y,w,h) def get_contours(self, image): results = self._model(image) ...
Python
1
level : int, default None Alignment level if needed. Returns ------- Same type as caller or None if ``inplace=True``. See Also -------- :func:`DataFrame.{name_other}` : Return an object of same shape as self. Notes -----...
Python
1
# -*- coding: utf-8 -*- import numpy as np import pylab as pl import scipy.signal as signal def logfreqz(b, a, f0, f1, fs, N): """ 以对数频率坐标计算滤波器b,a的频率响应 f0, f1: 计算频率响应的开始频率和结束频率 fs: 取样频率 """ w0, w1 = np.log10(f0/fs*2*np.pi), np.log10(f1/fs*2*np.pi) # 不包括结束频率 w = np.logspace(w0, w1, N, en...
Python
1
obj.clone()), vec![json!("plane")]); // Dot notation let expr = jsonpath::parse("$._").unwrap(); assert_eq!(expr.eval(obj.clone()), vec![json!("underscore")]); // Asterisk // return all elements // There is no ordering in JSON keys // You must compare with their string values sorted le...
Rust
0
(()); } std::thread::sleep(std::time::Duration::from_millis(1000)); } } fn wait_for_idle() -> Result<()> { wait_for_write_condition(6, |old_writes, new_writes| old_writes == new_writes) } fn wait_for_active() -> Result<()> { wait_for_write_condition(1, |old_writes, new_writes| old_writes !...
Rust
0
ntent'][0]['text'] # returning the final string to the end user return llm_output def text_to_text(text): """ This function is used if a user does not upload an image, and only uploads text, this text is directly passed into Claude3. :param text: This is the text that the user inserts on the f...
Python
1
# https://www.acmicpc.net/problem/1018 # 체스판 다시 칠하기 # 1018 # import numpy as np # import copy def solution(): # 사용자 입력 부분 n, m = map(int, input().split(" ")) maps = [] for i in range(n): row = input() maps.append(list(row)) # print(maps) # 자를 수 있는 위치 : (0,0) ~ (n-8, m-8) ...
Python
1
version = settings.VERSION_FLAG # V2 else: version = "v1" # 读取历史记录 if self._clearflag: history = [] else: history: List[dict] = self.get_data('history') or [] for user_id in self._users.split(","): # 同步每个用户的豆瓣数据 if no...
Python
1
gh_stars>10-100 // Copyright 2020 <NAME> // SPDX-License-Identifier: Apache-2.0 #![cfg(feature = "sha")] use crypto::hashes::sha::{SHA256, SHA256_LEN, SHA384, SHA384_LEN, SHA512, SHA512_LEN}; struct TestVector { msg: &'static str, digest: &'static str, } #[test] fn test_sha256() { let tvs = include!("fi...
Rust
0
().await.is_some() {} })); }; let mut file = OpenOptions::new() .write(true) // Fails to write full item at exit. that is why not append // TODO: think of workaround with dropcheck? // //.append(true) .create(true) .tru...
Rust
0
from(vec![ Span::styled("cpu usage:", s), Span::raw(format!("{:.2}%", usage)) ])); // second line: // │user time:70ms kernel time:10ms u/k:87.50% let percent_user = stat.utime as f32 / (stat.utime + stat.stime) as f32; text.push(Spans::from(vec![ ...
Rust
0
_set_state, mock_verify_files, mock_validate_config, mock_request_bundle_dir, tmp_path, task_passes_state_check, ): bundle_dir, root, sub = mock_bundle_dir(tmp_path) mock_request_bundle_dir.return_value = bundle_dir mock_resolve_yarn.side_effect = [InvalidRequestData("oops")] with ...
Python
1
# coding=UTF-8 # ex:ts=4:sw=4:et=on # ------------------------------------------------------------------------- # Copyright (C) 2014 by Mathijs Dumon <mathijs dot dumon at gmail dot com> # # mvc is a framework derived from the original pygtkmvc framework # hosted at: <http://sourceforge.net/projects/pygtkmvc/> # # ...
Python
1
let mut args = cargo_arguments.to_owned(); let manifest_path = output_directory.join(&api.lib_cargo_file); args.push("--manifest-path".into()); args.push(manifest_path.into()); command_info(&api.lib_crate_name, &args); let output = Command::new("cargo") .arg...
Rust
0
help="Prompt to guide image generation") with col2: negative_prompt = st.text_area("Negative Prompt", "", help="The prompt not to guide image generation. Write things that you dont want to see in the image.") scheduler = st.sidebar.selectbox("Scheduler", available_schedulers, index=0, help...
Python
1
nts[..i]; } } } }; populate_covers(None); if let Some(rect) = &crop { if rect.horizontal.start > 0 { populate_covers(Some(rect.horizontal.start as i16 - 1)); } } workbench .init...
Rust
0
e Space Rust Library is free software; you can redistribute it and/or * // modify it under the terms of the MIT License as published by the * // Massachusetts Institute of Technology. * // * // Th...
Rust
0
s): matched = [] normalized_keywords = [kw.strip().lower() for kw in keywords] for product in products.values(): product_name = product["name"].strip().lower() for kw in normalized_keywords: if kw in product_name: matched.append(product) break ...
Python
1
help="Path to the extraction JSON file") parser.add_argument("--output", type=str, default=None, help="Path to save the HTML visualization (optional)") args = parser.parse_args() input_path = Path(args.input) # Load extraction data extraction_data = lo...
Python
1
from enum import Enum from typing import Callable, Tuple from langchain.agents.agent import AgentExecutor from langchain.agents.tools import BaseTool, Tool class ToolScope(Enum): GLOBAL = "global" SESSION = "session" SessionGetter = Callable[[], Tuple[str, AgentExecutor]] def tool( name: str, des...
Python
1
(var_1353) = &input.default_user_settings { let mut object_1354 = object.key("DefaultUserSettings").start_object(); crate::json_ser::serialize_structure_crate_model_user_settings(&mut object_1354, var_1353)?; object_1354.finish(); } if let Some(var_1355) = &input.domain_settings_for_upda...
Rust
0
-> IonCResult<ION_TYPE> { let mut tid = ptr::null_mut(); ionc!(ion_reader_next(self.reader, &mut tid))?; Ok(tid) } #[inline] fn get_type(&self) -> IonCResult<ION_TYPE> { let mut tid = ptr::null_mut(); ionc!(ion_reader_get_type(self.reader, &mut tid))?; Ok(...
Rust
0
writer), RRData::A(ip) => writer.write_u32::<BigEndian>(ip.into()), RRData::AAAA(ip) => { for segment in ip.segments().into_iter() { try!(writer.write_u16::<BigEndian>(*segment)); } Ok(()) } RRData::SRV...
Rust
0
pad=[0, 3], iters=[(0, 3), (3, 3), (6, 2)], ) ntt_dilithium_l123.export("../naive/aarch64/ntt_dilithium_123_456_78_twiddles.s") ntt_dilithium_l123.export("../opt/aarch64/ntt_dilithium_123_456_78_twiddles.s") intt_dilithium = NttRootGen( size=256, inverse=True, bitsize=32, modulus=8...
Python
1
NO_RAYS)) } /// Test that unpacking and packing doesn't shift the value, which could lead /// to runaway light values. #[test] fn packed_light_roundtrip() { for i in PackedLightScalar::MIN..PackedLightScalar::MAX { assert_eq!(i, PackedLight::scalar_in(PackedLight::scalar_out(i))...
Rust
0
b_preprocessor.continuous_cols, mlp_hidden_dims=[16, 8], ) if problem == "classification": loss = MultiTargetClassificationLoss( binary_config=[0], multiclass_config=[(1, 3)], ) pred_dim = 1 + 3 target = df[["target3_binary", "target4_multiclass"]...
Python
1
`](crate::model::IdentityProviderDetails) pub fn build(self) -> crate::model::IdentityProviderDetails { crate::model::IdentityProviderDetails { url: self.url, invocation_role: self.invocation_role, directory_id: self.directory_id, funct...
Rust
0
#!/usr/bin/env python import pandas as pd import numpy as np N_students = 1800 prefix = 19000 weekdays = [d for d in pd.date_range(start='2018-09-01', end='2019-06-13') if d.dayofweek < 5] student_attendance_table = [] student_record_table = [] np.random.seed(52) def get_grade(frac): if frac < 0.15:...
Python
1
# Feladat 1: Változók, user input, string metódusok, type conversion, f-string használata ######################################################################################### import datetime as dt # Dátumkezelési modul importálása, az age*365 helyett pontosabb napban számolt érték meghatározásához # 1. Input ál...
Python
1
=cols[6]) print("DEBUG: loaded {0} polypeptides from ILRI file".format(len(polypeptides)) ) for assembly_id in assemblies: for gene in assemblies[assembly_id].genes(): for mRNA in gene.mRNAs(): if mRNA.id not in polypeptides: print("DEBUG: {0} not found ...
Python
1
""" HTML шаблоны для веб-приложения Meeting Processor """ class WebTemplates: """Класс для хранения HTML шаблонов веб-приложения""" def get_index_template(self): """Возвращает HTML шаблон главной страницы""" return ''' <!DOCTYPE html> <html lang="ru"> <head> <meta charset="UTF-8"> ...
Python
1
32) -> WebGLActiveInfo { let res = js! { return @{self.as_reference()}.getActiveAttrib(@{program.deref()},@{location}) }; let name = js! { return @{&res}.name }; let size = js!{ return @{&res}.size }; let kind = js!{ return @{&res}.type }; let k: u32 = kind.try_into()...
Rust
0
ode) == remove_empty_lines(expected_code) def file_content(file_path): with open(file_path, "r") as file: return file.read() def test_mover_move_test1(): src_folder = "tests/fixtures/mover_test1" dest_folder = "tests/fixtures/mover_test1_expected" project_root = "tests/fixtures/mover_test1" ...
Python
1
t_eq!(error.kind, dataplane::smartmodule::SmartModuleKind::Filter); let rendered = format!("{}", error); assert_eq!(rendered, "Oops something went wrong\n\nCaused by:\n 0: Failed to parse int\n 1: invalid digit found in string\n\nSmartModule Info: \n Type: Filter\n Offset: 10\n Key:...
Rust
0
ewgroup: *mut MPI_Group) -> c_int; pub fn MPI_Group_range_incl(group: MPI_Group, n: c_int, ranges: *mut c_int, newgroup: *mut MPI_Group) -> c_int; pub fn MPI_Info_create(info: *mut MPI_Info) -> c_int; pub fn MPI_Info_set(info: MPI_Info, key: *const c_char, value: *const c_char) -> c_int; pub fn MPI_Win_create...
Rust
0
mask: mx.array = None, cache=None, ) -> mx.array: h = self.embed_tokens(inputs) if mask is None: mask = create_attention_mask(h, cache) if cache is None: cache = [None] * len(self.layers) for layer, c in zip(self.layers, cache): h...
Python
1
-separator($single);\ \n}" ) .unwrap(), "div {\ \n _list-space: space;\ \n _list-comma: comma;\ \n _single-item: space;\ \n}\ \n" ); } <reponame>jazzfool/otway //! Otway is a Rust GUI toolkit built on Reclutch and Sinq. //! //! Its prima...
Rust
0
cmp::max(4096, (mem.avail - (4 * size + 2) * 1024 * 1024) / 1024), } } /// Compute master cpu: host cpu - 2 * clusterSize, minimum of 2 fn get_master_cpu(libvirt_auto_size: bool, size: u32) -> u32 { let default = 2; if !libvirt_auto_size { return default; } match cpu_num() { Err(e)...
Rust
0
search_entry_sep = re_compile(re_escape(entry_sep)).search else: search_entry_sep = entry_sep.search d: dict[AnyStr, AnyStr] = {} start = 0 length = len(s) while start < length: match = search_kv_sep(s, start) if match is None: break l, r = match.span...
Python
1
ition { BorderPosition::Left => String::from("borderLeft"), BorderPosition::Right => String::from("borderRight"), BorderPosition::Top => String::from("borderTop"), BorderPosition::Bottom => String::from("borderBottom") }; let style = match self.style { ...
Rust
0
: Vec<TestRepeatedBool>, pub test_repeated_messages: Vec<TestRepeatedMessages>, pub test_optional_messages: Vec<TestOptionalMessages>, pub test_strings: Vec<TestStrings<'a>>, pub test_repeated_packed_int32: Vec<TestRepeatedPackedInt32>, pub test_repeated_packed_float: Vec<TestRepeatedPackedFloat<'a>...
Rust
0
use tokio::fs; use prolink::{message::Track, Config, Message, Prolink}; #[tokio::main] async fn main() -> Result<()> { let mut prolink = Prolink::join(Config { name: "prolink-util".to_string(), device_num: 4, }) .await?; println!("connected"); prolink.run().await?; println!("...
Rust
0
match generate_gif(file_name, maze) { Ok(grid) => println!("{}", grid), Err(err) => println!("{:?}", err), } } else { let grid = Grid::from(maze); println!("{}", grid); } } fn generate_gif<I: Iterator<Item=Grid>>(file_name: &str, iter: I) -> io::Result<Grid> { ...
Rust
0
"""Configuration for the whole application""" from __future__ import annotations import sys from pathlib import Path from pydantic import BaseModel, Field, ValidationError from pydantic_settings import ( BaseSettings, PydanticBaseSettingsSource, SettingsConfigDict, YamlConfigSettingsSource, ) from b...
Python
1
""" Contains the definition of Group. """ from xdtools.utils import Point from xdtools.artwork import Artwork class Group(Artwork): """ A Group. === Attributes === uid - The unique id of this Group. name - The name of this Group as it appears in the Layers panel. position - the position of t...
Python
1
32; #[repr(C)] #[doc = "*Required features: 'Win32_Media_MediaFoundation'*"] pub struct MFVideoCompressedInfo { pub AvgBitrate: i64, pub AvgBitErrorRate: i64, pub MaxKeyFrameSpacing: u32, } impl ::core::marker::Copy for MFVideoCompressedInfo {} impl ::core::clone::Clone for MFVideoCompressedInfo { fn cl...
Rust
0
1 = X86Arg::WordMem(X86Reg::R15, 0, is_pic), LtacArg::U16(_v) => instr.arg1 = X86Arg::WordMem(X86Reg::R15, 0, is_pic), LtacArg::I64(_v) => instr.arg1 = X86Arg::QwordMem(X86Reg::R15, 0, is_pic), LtacArg::U64(_v) => instr.arg1 = X86Arg::QwordMem(X86Reg::R15, 0, is_pic), ...
Rust
0
) -> bool { *self == PARALLEL_MODER::SHIFT_2_BITS_PER_CLO } #[doc = "Checks if the value of the field is `SHIFT_4_BITS_PER_CLO`"] #[inline] pub fn is_shift_4_bits_per_clo(&self) -> bool { *self == PARALLEL_MODER::SHIFT_4_BITS_PER_CLO } #[doc = "Checks if the value of the field is...
Rust
0
from dash import Dash, html import pandas as pd import dash_ag_grid as dag df_gapminder = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv') df = df_gapminder[:500] app = Dash(__name__) def data_bars(df, column): n_bins = 100 bounds = [i * (1.0 / n_bins) for ...
Python
1
r'(conv_cls|retina_cls|rpn_cls|fc_cls|fcos_cls|' r'fovea_cls).(weight|bias)', new_key) else: m = re.search( r'(conv_cls|retina_cls|fc_cls|fcos_cls|' r'fovea_cls).(weight|bias)', new_key) if m is not None: print(f'reor...
Python
1
def trees_only(i, _d): return i.type == "tree" trees = list(root.traverse(predicate=trees_only)) assert len(trees) == len([i for i in root.traverse() if trees_only(i, 0)]) # Test prune. def lib_folder(t, _d): return t.path == "lib" pruned_tree...
Python
1
import os import datetime from config.settings import DEFAULT_LOG_FILE, LOG_FORMAT, OUTPUT_VERBOSE class Logger: _log_file = None @classmethod def init(cls, path=None): cls._log_file = path or DEFAULT_LOG_FILE # Ensure directory exists os.makedirs(os.path.dirname(cls._log_file) or...
Python
1
ate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [ccactrl...
Rust
0
lags: libc::c_int, addr: Option<libc::sockaddr_in>, addr_len: libc::socklen_t, } struct RecvfromArguments<'a> { fd: libc::c_int, buf: Option<&'a mut [u8]>, len: libc::size_t, flags: libc::c_int, addr: Option<libc::sockaddr_in>, addr_len: Option<libc::socklen_t>, } impl Default for Send...
Rust
0
BindingA(stringbinding: *const u8, binding: *mut *mut ::core::ffi::c_void) -> RPC_STATUS; #[doc = "*Required features: `\"Win32_System_Rpc\"`*"] pub fn RpcBindingFromStringBindingW(stringbinding: *const u16, binding: *mut *mut ::core::ffi::c_void) -> RPC_STATUS; #[doc = "*Required features: `\"Win32_System_...
Rust
0
ack(&mut self, id: Uuid) { self(id) } } impl MutationAck for Sender<Uuid> { fn ack(&mut self, id: Uuid) { let _ = self.send(id); } } #[cfg(test)] mod tests { use super::*; use fuzzy_log_server::tcp::run_server; use std::sync::mpsc::{channel, Receiver}; struct Bank { ...
Rust
0
#!/usr/bin/env python3 # # Copyright (c) 2020 Raspberry Pi (Trading) Ltd. # # SPDX-License-Identifier: BSD-3-Clause # # sudo pip3 install pyusb import usb.core import usb.util import numpy as np import time dev = usb.core.find(idVendor=0x0000, idProduct=0x0001) # find our device #dev = usb.core.find(idVendor=0x0...
Python
1
that!( p.volta("run --node 12.16.1 --yarn 1.22.0 yarn --version"), execs().with_status(0).with_stdout_contains("1.22.0") ); } #[test] fn inherits_project_platform() { let p = temp_project().package_json(PACKAGE_JSON).build(); assert_that!( p.volta("run --yarn 1.21.0 yarn --version"...
Rust
0
from django.http import HttpResponse from django.shortcuts import render def index(request): return render(request,"text_utils/index.html") def analyze(request): djtext = request.GET.get("text","default") remove_punc = request.GET.get("remove_punc","off") uppercase = request.GET.get("uppercase","off"...
Python
1
"last_price": round(last_price, 2), "absolute_change": round(absolute_change, 2), "percentage_change": round(percentage_change, 2), } else: historical_data[ticker] = { "error": "No data available for this ticker in the given period."...
Python
1
print("Found no games.") print( "\n" "NOTE: A game must be launched at least once before Protontricks " "can find the game." ) return # 6. Find globally active Proton version now proton_app = _find_proton_app_or_exit( steam_path=s...
Python
1
from .base import ConversionHandler from pathlib import Path class RvzHandler(ConversionHandler): """Handler pour conversion ISO vers RVZ (GameCube/Wii)""" def convert(self) -> dict: """Convertit les ISOs GameCube/Wii en RVZ avec extraction à la volée""" dest_path = Path(self.dest_folder) ...
Python
1
t txs = vec![hash(&[1]), hash(&[2]), hash(&[2])]; let (public_key, secret_key) = gen_keypair(); // write let propose = Propose::new(VALIDATOR, HEIGHT, ROUND, &prev_hash, &txs, &secret_key); // read assert_eq!(propose.validator(), VALIDATOR); assert_eq!(propose.height(), HEIGHT); assert_eq!(...
Rust
0
# 去除Alpha通道 处理彩色为黑白 (三通道->单通道, 非白色均视为黑色) mask = mask_transform_color_to_black(mask=mask[:, :, :3], quick_method=quick_method) # 根据mask保留的阿尔法通道, 在其透明的区域, 取mask_from_template的对应区域进行合并 mask[mask_alpha_channel != 255] = mask_from_template[mask_alpha_channel != 255] else: ...
Python
1
CONTROL_ALLOW_METHODS) .unwrap() .to_str() .unwrap(); assert!(res_cors_methods.contains("GET")); assert!(res_cors_methods.contains("OPTIONS")); assert!(res_cors_methods.contains("POST")); } async fn test_cors_method_get(cl: &reqwest::Client) { ...
Rust
0