text
string
label_name
string
labels
int64
import pandas as pd # Load PSA Excel file file_path = "psa_gdp.xlsx" df_raw = pd.read_excel(file_path, sheet_name=0, header=None) # Extract and forward-fill sparse year headers years = df_raw.iloc[35, 1:].ffill() quarters = df_raw.iloc[36, 1:] # Generate full quarter label quarter_labels = [ f"{int(y)}Q{int(str(...
Python
1
Object Registers"] pub fccob8: FCCOB, #[doc = "0x10 - Flash Option Registers"] pub fopt3: FOPT, #[doc = "0x11 - Flash Option Registers"] pub fopt2: FOPT, #[doc = "0x12 - Flash Option Registers"] pub fopt1: FOPT, #[doc = "0x13 - Flash Option Registers"] pub fopt0: FOPT, _reserved19: [u8; 4usize], ...
Rust
0
ErrorKind::Eof | ErrorKind::Aborted => None, } } } impl fmt::Display for ErrorKind { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { match self { ErrorKind::IoError(e) => write!(fmt, "IoError: {}", e), ErrorKind::Interrupted => write!(fmt, "CTRL+C"), ...
Rust
0
import torch from PIL import Image from diffsynth import save_video, VideoData from diffsynth.pipelines.wan_video_new import WanVideoPipeline, ModelConfig from modelscope import dataset_snapshot_download pipe = WanVideoPipeline.from_pretrained( torch_dtype=torch.bfloat16, device="cuda", model_configs=[ ...
Python
1
assert_eq!(json.just_updated[0].max_version, "0.2.0"); assert_eq!(json.just_updated[0].newest_version, "0.1.1"); assert_eq!(json.just_updated[1].name, "just_updated"); assert_eq!(json.just_updated[1].max_version, "0.1.2"); assert_eq!(json.just_updated[1].newest_version, "0.1.2"); assert_eq!(js...
Rust
0
shMap; use std::fs; use std::path::PathBuf; use std::time::Instant; // Cli argument container #[derive(StructOpt)] #[structopt(name = "cwim - Count Words Inside a Markdown file. (CJK friendly)")] struct Cli { /// Verbose mode (-v, -vv, etc.) #[structopt(short, long, parse(from_occurrences))] verbose: u8, /// ...
Rust
0
NR_QUEUES>(q); &highest > pri || self .last_chosen_priority .as_ref() .map_or(false, |last| last > pri) } else { q < NR_QUEUES || self.last_chosen_priority.is_some() } } pub fn choose_...
Rust
0
fn get_name(&self) -> &'static str { "janus.plugin.videoroom" } async fn handle_message(&self, message: JanusPluginMessage) -> JanusPluginResult { match self.process_message(message).await { Ok(x) => x, Err(e) => JanusPluginResult::ok(e.into()) } } a...
Rust
0
$NetBSD$ * Part of patchset to build electron on NetBSD * Based on OpenBSD's chromium patches, and FreeBSD's electron patches --- tools/protoc_wrapper/protoc_wrapper.py.orig 2025-02-24 19:59:26.000000000 +0000 +++ tools/protoc_wrapper/protoc_wrapper.py @@ -183,15 +183,19 @@ def main(argv): if not options.exclu...
Python
1
import pyopenms as oms import os # Ruta base donde están almacenados los archivos localmente base_path = "/home/jfml/Videos/Analisis/Curso/Map_Alignment" # Lista de archivos featureXML feature_files = [ "aligned_131_B_FiltNoise_filtered.featureXML", "aligned_131_C_FiltNoise_filtered.featureXML", "aligned_...
Python
1
(c); } for n in (0..prod_vector.len()).rev() { rev_string.push(prod_vector[n]); } if rev_string == prod_string { if prod_string.parse::<i32>().unwrap() > current { current = prod_string.parse::<i32>().unwrap(); ...
Rust
0
-> result::Result<tls_api::TlsStream<S>, tls_api::HandshakeError<S>> where S : io::Read + io::Write + fmt::Debug + Send + Sync + 'static { self.0.connect(domain, stream) .map(|s| tls_api::TlsStream::new(TlsStream(s))) .map_err(map_handshake_error) } fn d...
Rust
0
connection_context() def filter_delete(cls, filters): with DB.atomic(): num = cls.model.delete().where(*filters).execute() return num @classmethod @DB.connection_context() def filter_update(cls, filters, update_data): with DB.atomic(): return cls.mode...
Python
1
.as_ptr() as *const _, Some(transmute(notify_label_trampoline::<Self, F> as usize)), Box_::into_raw(f)) } } fn connect_property_selected_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe { let f: Box_<F> = Box_::new(f); connect_raw(s...
Rust
0
: Deserializer<'de>, { u64::deserialize(deserializer).map(Value) } } pub mod address { use super::*; use chain_addr::{Address, AddressReadable}; pub fn serialize<S>(address: &Address, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { if serializer.is_...
Rust
0
, context::ContextDatabase, databases::SourceDatabase, }; pub use crunch_typecheck::TypecheckDatabase; pub use ladder::HirDatabase; use crunch_codegen::CodegenDatabaseStorage; use crunch_mir::MirDatabaseStorage; use crunch_parser::database::ParseDatabaseStorage; use crunch_shared::{ config::ConfigDatabaseStorage, ...
Rust
0
FromIterator::from_iter`] → constructs a //! new matrix from an iterator. //! - [`::new(..)`][`Matrix::new()`] → constructs a new vector using the //! provided components. //! //! ### Accessing elements //! //! Three types of element access are available. //! //! - `usize` indexing selects the nth element in the ma...
Rust
0
s gebruik zoals douchen, toiletspoeling, schoonmaken, en koken. Of water als service voor bijv. schoonmaak. """ witgoed = PrijscomponentdetailsoortReferentiedata( code="WIT", naam="Witgoed", parent=Prijscomponentsoort.service, ) """ Maandelijkse kosten voor het gebruik v...
Python
1
def _tune(config): """ Trains the YOLO model with the specified hyperparameters and additional arguments. Args: config (dict): A dictionary of hyperparameters to use for training. Returns: None """ model_to_train = ray.get(model_in_store) model_to_tr...
Python
1
n indices] # make a copy for i in range(n): indices[p] = i x = base[tuple(indices)] args.append(x) return args def _visit_Comment(self, expr, **kwargs): return expr # .................................................... def _visit...
Python
1
python_words = { 'integer':'Butun son', 'float': "O'nlik son", 'boolean':"Mantiqiy qiymat", 'for':"Biror amalni qayta-qayta bajarish tsikli", 'if':'Shartlarni tekshirish operatori'} for key, value in sorted(python_words.items()): print(f"{key.title()} - {value}") davlatlar = { "o'...
Python
1
""" 物体的位姿操作(模型矩阵操作) """ from PyQt5.QtGui import QVector3D from .basic_op import Operation class MoveToOperation(Operation): """ 移动到操作 """ def __init__(self, sectionHandler, target_pos: QVector3D = None, edits=None): """ 移动到操作 :param sectionHandler: 被移动的元素 :param target...
Python
1
Option<&QParams>, mmm: impl Fn(usize, usize, usize) -> MMMWrapper<TA, TB, TC, TI>, ) -> TractResult<Tensor> where TA: Datum + Copy + Zero, TB: Datum + Copy + Zero, TC: Datum + Copy + Zero + fmt::Debug, TI: Datum + Copy + Add + Mul + Zero + fmt::Debug, { let a = a.to_array_view::<TA>()?; let...
Rust
0
mod pyarrow; pub mod record_batch; pub mod temporal_conversions; pub mod tensor; pub mod util; <filename>src/myke/macros.rs<gh_stars>1-10 #[macro_export] macro_rules! val { ($yml:ident, $yml_key:expr, $default:expr) => { String::from($yml[$yml_key].as_str().unwrap_or($default)) }; } #[macro_export] ma...
Rust
0
new_input_session::<R>(&self.inputs[1], self.tag); session.for_each_batch(func) } pub fn subscribe_left_notify(&mut self) { let tag = self.tag; if let Some(ref mut n) = self.left_subscriber { n.subscribe(tag); } } pub fn subscribe_right_notify(&mut self) { ...
Rust
0
h_up_tasks_item) catch_up_tasks_total_cnt = d.pop("catch_up_tasks_total_cnt") catch_up_tasks_page_size = d.pop("catch_up_tasks_page_size") birthday_tasks = [] _birthday_tasks = d.pop("birthday_tasks") for birthday_tasks_item_data in _birthday_tasks: birthday_tasks_...
Python
1
ze(1)//2, offset.size(2), offset.size(3) # (1, 2N, 1, 1) p_n = self._get_p_n(N, dtype) # (1, 2N, h, w) p_0 = self._get_p_0(h, w, N, dtype) p = p_0 + p_n + offset return p def _get_x_q(self, x, q, N): b, h, w, _ = q.size() padded_w = x.size(3) ...
Python
1
) reference_control_writer.clear() # progress bar end if interpolation_factor > 0: latents = self.interpolate_latents(latents, interpolation_factor, device) # Post-processing images = self.decode_latents(latents) # (b, c, f, h, w) # Convert to tensor ...
Python
1
# -*- coding: utf-8 -*- """ Created on Mon May 18 14:10:00 2020 @author: HPK """ from PIL import Image import numpy as np from ctypes import * import copy # pixelpitch(0: 20um 1: 12.5um) pitch = 1 # LCOS pixel size x = 1280 y = 1024 # LCOS-SML monitor number setting monitorNo = 2 windowNo = 0 xShift ...
Python
1
# SmolLM2 Text Generation") if not display_names: gr.Markdown("⚠️ No models found! Please train the model first.") else: gr.Markdown( f"Found {len(display_names)} models/checkpoints. Select one and enter a prompt to generate text." ) gr.Markdown("Available models: " ...
Python
1
}) .map_err(|e| { eprintln!("========ENV VARS======"); for x in vars.iter() { eprintln!("{}={}", x, env::var(x).ok().unwrap_or_default()); } e }) } fn config_and_build(is_static: bool) -> Result<()> { eprintln!("is static: {}", is_static); #[cfg(windows)...
Rust
0
a'], ['b'], ['c', 'd', 'c'], ['b'], ['a']] rNr4rrr)rpredmaxsplitkeep_separatorbufrrrrrr3s$     rccs|dkr t|VdSg}t|}|D]%}||r4|r4|V|dkr.|gt|VdSg}|d8}||...
Python
1
self.assertRaises(asyncio.InvalidStateError): await call.write(_STREAM_OUTPUT_REQUEST_ONE_RESPONSE) # But read should be unaffected response = await call.read() self.assertEqual(_RESPONSE_PAYLOAD_SIZE, len(response.payload.body)) response = await call.read() self.as...
Python
1
oat]): (H, W) scale values. Default is (2.0, 2.0). """ super().__init__() self.scale = scale def forward(self, inputs): """ Args: inputs (Tuple[torch.Tensor, torch.Tensor]): (tensor to zero upsample, jitter) Returns: torch.Tensor: zero upsamp...
Python
1
# Copyright 2016 Julien Danjou # Copyright 2016 Joshua Harlow # Copyright 2013-2014 Ray Holder # # 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 #...
Python
1
episode = episode[:num] # 保持与training_step一致的处理方式 batch_size = episode.shape[0] seq_len = episode.shape[1] # print("batch_size: ", batch_size) # 为每个样本随机选择一帧 random_indices = torch.randint...
Python
1
_complex_chain5.csv", ) .unwrap()); assert!(are_contents_same( output7, "./tests/reference/test_split_merge_complex_chain7.csv", ) .unwrap()); } async fn drive( input: &str, output2: &str, output3: &str, output4: &str, output5: &str, output7: &str, ts_con...
Rust
0
import pytest from unittest.mock import patch from src.cloner import clone_repository from git import InvalidGitRepositoryError, GitCommandError @patch("driller.cloner.os.path.exists") @patch("driller.cloner.Repo") def test_clone_repository_already_cloned(mock_repo, mock_path_exists): mock_path_exists.return_valu...
Python
1
am) -> Result<Vec<u8>, super::GlusterError> { let mut record: Vec<u8> = Vec::new(); let mut last = false; while !last { let (last_frag, frag) = recv_fragment(sock)?; last = last_frag; for byte in frag { record.push(byte); } } Ok(record) } /// Used to get ...
Rust
0
0`"] #[inline(always)] pub fn is_enbl_0(&self) -> bool { *self == ENBL_A::ENBL_0 } #[doc = "Checks if the value of the field is `ENBL_1`"] #[inline(always)] pub fn is_enbl_1(&self) -> bool { *self == ENBL_A::ENBL_1 } } #[doc = "Write proxy for field `ENBL`"] pub struct ENBL_W...
Rust
0
acc.span.merge(op.span).merge(expr.span), Expression::BinaryExpression(BinaryExpression { op, lhs: Box::new(acc), rhs: Box::new(expr), }), ) }) } /// Parses a term in an expression, containing operators of the highest precedence,...
Rust
0
r.info("开始导入Codex相关模块...") from core.codex_manager import CodexManager logger.info("CodexManager模块导入成功") from core.reference_detector import ReferenceDetector logger.info("ReferenceDetector模块导入成功") from core.prompt_functions import PromptFunctionRegistry, crea...
Python
1
data=PDFbyte, file_name="HarshaVardhini_Viyyuri_Resume.pdf", mime='application/octet-stream', help="Click to download my resume", type="primary") except FileNotFoundError: st.warning("Resume 'Hars...
Python
1
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Checks that files whose file case changes get rebuilt correctly. """ import os import TestGyp test = TestGyp.TestGyp() CHDIR = 'fileca...
Python
1
import pandas as pd df = pd.read_csv("datasets/youtube-ing.csv") # 1- İlk 10 kaydı getiriniz. result = df.head(10) # 2- İkinci 5 kaydı getiriniz. result = df[5:20].head(5) # 3- Dataset' de bulunan kolon isimleri ve sayısını bulunuz. result = df.columns result = len(df.columns) # 4- Aşağıda bulunan bazı kolonları sili...
Python
1
: &I::TestParams) -> Result<(), SynthesisError> { let template_params = TemplateParams { num_iterations: NUM_ITERATIONS, num_inputs_per_iteration: vec![1], }; assert!(Self::test_template(&template_params, test_params)?); Ok(()) } ...
Rust
0
#!/usr/bin/env python import vtk from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() RENWIN_WIDTH = 512 RENWIN_HEIGHT = 512 def setCameraTravelMatrix(cam, mat): global renWin cam.SetModelTransformMatrix(mat) cam.Modified() p2w = vtk.vtkMatrix4x4() p2w.DeepCopy(mat) p2w....
Python
1
import numpy as np import pandas as pd if __name__ == '__main__': df = pd.read_csv('../../Datasets/Patients.csv', sep=',', decimal='.', index_col='id', dtype=str) df['age'] = df['age'].astype(int) df['bmi'] = df['bmi'].astype(float) # fill in missing values assuming that individuals don't smoke befor...
Python
1
[]{:target="_blank"} object directly from 64-bit Python to the 32-bit Python. The [ctypes][]{:target="_blank"} module on the 32-bit server can load the [pickle][]{:target="_blank"}d [ctypes.Structure][]{:target="_blank"}. Returns: The total distance connecting the 4 ...
Python
1
t, ); Ok(()) })?; Ok(RMapDropCleanup(rmap, uniq, msg_id)) } /// A connection handle - use this to manage an open connection. #[derive(Clone)] pub struct Tx2ConHnd<C: Codec + 'static + Send + Unpin> { local_cert: Tx2Cert, con: ConHnd, url: TxUrl, rmap: ShareRMap<C>, metrics: ...
Rust
0
US" => { shifted = true; key = Some(Key::EQUAL); } "\"" => { shifted = true; key = Some(Key::SINGLEQUOTE); } _ => {} } // aliases if key.is_none() { key = match token.as_str() { "RETURN" => Some(Key::ENTER), "=" => Some(Key::EQUA...
Rust
0
from .. import Provider as PhoneNumberProvider class Provider(PhoneNumberProvider): formats = [ "%######", "60%%######", "5760%%######", "+5760%%######", "(+57)60%%######", "%## ## ##", "60% %## ## ##", "57 60% %## ## ##", "+57 60% %## ## ##"...
Python
1
1, REG: CH1SET (chan::Chan => chan::ChanSetReg)); write_reg!(FAM: ads1298, FN: set_chan_2, REG: CH2SET (chan::Chan => chan::ChanSetReg)); write_reg!(FAM: ads1298, FN: set_chan_3, REG: CH3SET (chan::Chan => chan::ChanSetReg)); write_reg!(FAM: ads1298, FN: set_chan_4, REG: CH4SET (chan::Chan => chan::ChanSetR...
Rust
0
from django.db.models.sql.compiler import ( SQLAggregateCompiler, SQLCompiler, SQLDeleteCompiler, ) from django.db.models.sql.compiler import SQLInsertCompiler as BaseSQLInsertCompiler from django.db.models.sql.compiler import SQLUpdateCompiler __all__ = [ "SQLAggregateCompiler", "SQLCompiler", ...
Python
1
import numpy as np import matplotlib.pyplot as plt import seaborn as sns # 1. Две функции с twinx() x = np.linspace(0, 5, 100) y1 = np.sin(2 * np.pi * x) y2 = np.exp(-x) fig1, ax1 = plt.subplots() ax2 = ax1.twinx() ax1.plot(x, y1, 'g-', label='y1 = sin(2πx)') ax2.plot(x, y2, 'b--', label='y2 = exp(-x)') ax1.set_xl...
Python
1
Some(info) = node.op().info()? { println!(" * {}", info); } if self.options.debug_op { println!(" * {:?}", node.op()); } if let Some(node_sections) = self.node_sections.get(&node.id) { for section in node_sections { if section.is_emp...
Rust
0
import numpy as np import torch import math import torch.nn.functional as F import scipy.io as sio import os from scipy.io import savemat def density_estimate(num_bins, data, upper, lower): bin_interval = (upper-lower)/num_bins counter = [0 for i in range(num_bins)] N = data.size(0) for i in range(N):...
Python
1
] extern crate json; /// A strongly-typed AST for ES6. pub mod ast; /// Computing scope information from a strongly-typed AST. pub mod scopes; <gh_stars>0 // Conditionals - Used to check the condition of something and act on it pub fn run() { let age: u8 = 21; let check_id: bool = false; // If/Else if check...
Rust
0
}' | '\u{0370}'..='\u{037D}' | '\u{037F}'..='\u{1FFF}' | '\u{200C}'..='\u{200D}' | '\u{2070}'..='\u{218F}' | '\u{2C00}'..='\u{2FEF}' | '\u{3001}'..='\u{D7FF}' | '\u{F900}'..='\u{FDCF}' | '\u{FDF0}'..='\u{FFFD}' | '\u{10000}'..='\u{EFFFF}' => (), ...
Rust
0
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import pandas as pd import numpy as np import json from sacrebleu.metrics import METRICS as sacreBLEU_metrics def obtain...
Python
1
::test(flavor = "multi_thread")] async fn test_direct_sanity() { let (bootstrap, driver, bootstrap_close) = new_quick_bootstrap_v1(Default::default()).await.unwrap(); tokio::task::spawn(driver); let (proxy, driver, proxy_close) = new_quick_proxy_v1(Default::default()).await.unwrap(); tokio::tas...
Rust
0
elf_i386 -nostdlib -static -Tx86.ld -gc-sections -n"] extern "C" {} #[no_mangle] #[naked] pub unsafe extern "C" fn _start() -> ! { //let top = STACK.last().unwrap(); set_stack(); asm!("call hello"); // Avoid prelude. loop {} } #[inline(always)] #[naked] unsafe fn set_stack() { asm!("lea esp, [ST...
Rust
0
ctx_hash = get_latest_commit_hash() print(f"[EventMessage: Root-Context-Saved] ID: {current_branch}, {ctx_hash}") print(f"[EventMessage: Execution-Mode] Linting validation failed") # Check if context file...
Python
1
sentence = input("Enter sentence") lowercase_count=uppercase_count = 0 for i in sentence: if i.islower(): lowercase_count+=1 if i.isupper(): uppercase_count+=1 print(f"THE no of lower case letter is :{lowercase_count}"",and ""no of upper case :", uppercase_count) #second method # for i in se...
Python
1
omp = spec["components"]["schemas"]["WidgetBulkReplaceResponse"] assert resp_comp["items"]["$ref"].endswith("WidgetRead") def test_bulk_merge_request_and_response_schemas(): spec = _openapi_for([("bulk_merge", "bulk_merge")]) path = f"/{Widget.__name__.lower()}" # request schema req_schema = spec[...
Python
1
rs>0 #[doc = "Reader of register READCTRL"] pub type R = crate::R<u32, super::READCTRL>; #[doc = "Writer for register READCTRL"] pub type W = crate::W<u32, super::READCTRL>; #[doc = "Register READCTRL `reset()`'s with value 0x01"] impl crate::ResetValue for super::READCTRL { type Type = u32; #[inline(always)] ...
Rust
0
", a)?; b.fmt(f)?; write!(f, ") → ")?; c.fmt_b(f) } &Let(a, None, ref c, ref d) => { write!(f, "let {} = ", a)?; c.fmt(f)?; write!(f, ") → ")?; d.fmt_b(f) } &L...
Rust
0
import multiprocessing from decimal import Decimal from enums.currency import CURRENCY from enums.currency_pair import CURRENCY_PAIR # # Please note that routine below may trigger some trades # which may lead to money loss # Do NOT enable it without understanding of consequences # YES_I_...
Python
1
ped to the length of the sequence (`sequence_length`). Position outside of the sequence are not taken into account for computing the loss. """ outputs = self.roberta_prelayernorm( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, ...
Python
1
script { fun two_params(a:u8, b:u8){ assert(a==b,2); } }")?; // scripts/with_type.move let mut with_type_scripts = fs::File::create(project_path.join("scripts").join("with_type.move"))?; with_type_scripts.write_all(b"script { fun with_type<T>(_a:u8){ assert(true, 3); } }")?; // scripts/multipl...
Rust
0
* Vectors are columns matrices when operating with a matrix //! * Vectors cartesian coordinates are accessible using `vector.i` syntax with `i` the name of the coordinate //! * Matrices components can be accessed using `matrix.ij` where `i` is the row index and `j` the column index //! * Rows and columns are indexed w...
Rust
0
fn(arg1: root::DB::RawVoidPtr, arg2: root::DB::RawCppPtrType), >, pub fn_insert_batch_read_index_resp: ::std::option::Option< unsafe extern "C" fn( arg1: root::DB::RawVoidPtr, arg2: root::DB::BaseBuffView, arg3: u64, ...
Rust
0
`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ef_key_slot_4_w2](index.html) module"] pub struct EF_KEY_SLOT_4_W2_SPEC; impl crate::RegisterSpec for EF_KEY_SLOT_4_W2_SPEC { type Ux = u32; } #[doc = "`read()` method return...
Rust
0
from storage import Storage import os def main(): # 使用测试文件 test_file = "data/test_addresses.json" # 如果测试文件已存在,先删除 if os.path.exists(test_file): os.remove(test_file) # 初始化存储 storage = Storage(data_file=test_file) # 测试添加地址 print("=== 测试添加地址 ===") test_address = ...
Python
1
fbits >> 52); // Shift based on the exponent and bias. m >> s } else if fbits <= 2047 << 52 { // >= max (incl. inf) u32::MAX } else { // Negative or NaN 0 } } #[arm_aeabi_alias = __aeabi_d2ulz] pub extern "C" fn __fixunsdfdi(f: f64) -> u64 { ...
Rust
0
_output return encoder_hidden_states_dict, pooled_output_dict else: return_dict = return_dict if return_dict is not None else self.config.use_return_dict text_feat_list = {'last_hidden_state':{}, 'pooler_output':{}, 'hidden_states':{}, 'attentions':{}} for name i...
Python
1
# use std::time::Duration; /// # /// # use pyo3::prelude::*; /// # /// # Python::with_gil(|py| -> PyResult<()> { /// # let event_loop = py.import("asyncio")?.call_method0("new_event_loop")?; /// # #[cfg(feature = "tokio-runtime")] /// pyo3_asyncio::generic::run_until_complete::<MyCustomRuntime, _, _>(event_loop, async...
Rust
0
maior = 0 menor = 0 for i in range (1, 5): p1 = int(input('digite um peso - ')) if i == 1: maior = i menor = p1 else: if p1 > maior: maior = p1 if p1 < menor: menor = p1 print(menor, maior)
Python
1
}) } /// Return number of qubits simulated by Simulator. /// /// Returns: /// int: The number of qubits. /// pub fn number_qubits(&self) -> usize { self.internal.number_qubits() } /// Return the URL of the remote host executing Circuits. /// /// Returns...
Rust
0
import numpy as np from ..cython.cpu_nms import cpu_nms try: from ..cython.gpu_nms import gpu_nms except ImportError: gpu_nms = None def py_nms_wrapper(thresh): def _nms(dets): return nms(dets, thresh) return _nms def cpu_nms_wrapper(thresh): def _nms(dets): return cpu_nms(dets,...
Python
1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Name: Aayog Koirala Desc: Project 1 - CSCI-420: Game Randomizer Date: Feb 3, 2020 Bias: Picks user based on two randomly highest repeating characters in their name i.e. Java has a repeating character with count of 2 which so has a bias of two, compared to...
Python
1
0"}"#; let serialized = serde_json::to_string(&structure).unwrap(); assert_eq!(str, serialized); } #[test] fn deserialize_works_for_point_g1() { let structure = TestPointG1Structure { field: PointG1::from_string("1 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0").unwrap() }; ...
Rust
0
): rmgs.append(rho_map.gs[2*i, :]) rmps.append(rho_map.ps[2*i]) for rmg, rg, rmp, rp in zip(rmgs, rho.gs, rmps, rho.ps): assert np.allclose(rmg, rg) assert rmp == rp def test_entropy(): nqubits = 4 pauli_vals = np.random.randint(4, size=(nqubits,)) a = clifford_rotatio...
Python
1
s(), picked_fortune )?; Ok(()) } #[cfg(test)] mod test { use std::io::Read; use super::*; #[test] fn test_fortunes_from_file() { let fortunes = fortunes_from_file(FORTUNES).unwrap(); // Some assorted fortunes assert_eq!(fortunes[15], "To teach is to learn.");...
Rust
0
et fr4 = fr3 | maskr & (fr3 >> dir2); fl4 << dir | fr4 >> dir } #[derive(Clone, Copy)] enum Dir { Left, Right, } #[derive(Clone, Copy)] struct Transfer(Dir, u64, usize); const TRANSFERS: [Transfer; 8] = [Transfer(Dir::Right, 0xffffffffffffff00, 8), // up Transfer(Dir::Right, 0xfefefefefefefe00,...
Rust
0
from io import BytesIO import pygame import requests api_key = "23e13d6a-fa45-4007-a3c9-c8a414778dfb" slides = [ {"ll": "37.6176,55.7558", "spn": "0.1,0.1"}, # Москва {"ll": "30.3351,59.9343", "spn": "0.1,0.1"}, # Санкт-Петербург {"ll": "39.7231,43.5855", "spn": "0.1,0.1"}, # Сочи {"ll": "131.8856...
Python
1
import torch import torch.nn as nn import numpy as np import matplotlib.pyplot as plt from realnvp import NVPNet import objectives if __name__=='__main__': import argparse parser = argparse.ArgumentParser(description='') parser.add_argument("-cuda", type=int, default=-1, help="use GPU") parser.add...
Python
1
), } } } impl XsdChoice for Effect { fn is_choice_member<T>(name: T) -> bool where T: AsRef<str>, { match name.as_ref() { "cont" | "effect" | "alphaBiLevel" | "alphaCeiling" | "alphaFloor" | "alphaInv" | "alphaMod" | "alphaModFix" | "alphaOutset" | "alpha...
Rust
0
.clone() } pub fn archive_history(&mut self) { let mut histories = self.history.borrow_mut(); self.archived.append(&mut *histories); } pub fn archived_history(&self) -> &Vec<History> { &self.archived } pub fn push_history(&mut self, history: History) { let mut ...
Rust
0
w(self.hwnd) except: pass # 忽略可能的错误 self.hwnd = None self.physical_keys.clear() def is_physically_pressed(self, key): """检查按键是否被物理按下""" if not self.is_running: return False if key.lower() n...
Python
1
reate_dir, File}; use std::process::Command; use tempfile::tempdir; #[test] fn test_sort_assemble_sorters_by_name_with_dirs_first() { let tmp_dir = tempdir().expect("failed to create temp dir"); // Create the file; let path_a = tmp_dir.path().join("zzz"); File::create(&...
Rust
0
opt.niter) / float(opt.niter_decay + 1) return lr_l scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule) elif opt.lr_policy == 'step': scheduler = lr_scheduler.StepLR(optimizer, step_size=opt.lr_decay_iters, gamma=0.1) elif opt.lr_policy == 'platea...
Python
1
#------------------------------------------------------------ def gcd(n, m): # Write your statements here #..... gcd_result = 1 min_value = min(n, m) for i in range(1, min_value + 1): if n % i == 0 and m % i == 0: gcd_result = i return gcd_result # End your statements #en...
Python
1
apturederror)] #[doc = "Setter for the `onuncapturederror` field of this object."] #[doc = ""] #[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/GPUDevice/onuncapturederror)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `GpuDevice...
Rust
0
self.variant(TXLOC_A::LOC12) } #[doc = "Location 13"] #[inline(always)] pub fn loc13(self) -> &'a mut W { self.variant(TXLOC_A::LOC13) } #[doc = "Location 14"] #[inline(always)] pub fn loc14(self) -> &'a mut W { self.variant(TXLOC_A::LOC14) } #[doc = "Locatio...
Rust
0
one, tags: Some(tag("production")), }, Metric::Histogram { name: "hist-4".into(), val: 4.0, sample_rate: 10, timestamp: None, tags: Some(tag("production")), ...
Rust
0
: &mut R) -> Result<Self, Error> { let server_id = ServerId::read(reader)?; let server_pubkey = Pubkey::read(reader)?; let channel_id = reader.read_u64()?; let name = SerString::read(reader)?; let description = SerString::read(reader)?; Ok(Self { channel_id, server_id, server_pubkey, name, de...
Rust
0
# # Wolfinch Auto trading Bot # Desc: NOOBS_DT (noobs day trading strategy) # # Copyright: (c) 2017-2020 Joshith Rayaroth Koderi # This file is part of Wolfinch. # # Wolfinch is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free ...
Python
1
import requests API_KEY = "164ba2ac9bd64ece806122553250501" def main(): """ Основная функция программы. """ print("Добро пожаловать в клиент погоды!") get_weather() def get_weather(): print("получаем погоду") params = { "q": "Samara", # Название города "key": API...
Python
1
ervice( web::scope("/variants") .route( "/service-info", web::get().to(variants_service_info::<AsyncHtsGetStorage>), ) .route( "/service-info", web::post().to(variants_service_info::<AsyncHtsGetStorage>), ) .route( "/{id:.+}...
Rust
0