text
string
label_name
string
labels
int64
import pandas as pd # full_df = pd.DataFrame( # [], # columns=['title', 'description', 'text_lemm', 'genre'] # ) # for film in get_fulls_films(): # full_df.loc[len(df)] = { # 'title': film[0], # 'description': film[1], # 'text_lemm': film[2], # 'genre': film[3] # ...
Python
1
Mul { value_off: i32, } impl ModuleMiddleware for Add2MulGen { fn generate_function_middleware(&self, _: LocalFunctionIndex) -> Box<dyn FunctionMiddleware> { Box::new(Add2Mul { value_off: self.value_off, }) } } impl FunctionMiddleware for Add2Mul { fn feed<'a>( &mut...
Rust
0
import warnings from django.core.exceptions import ImproperlyConfigured from django.utils.deprecation import RemovedInDjango60Warning try: import oracledb is_oracledb = True except ImportError as e: try: import cx_Oracle as oracledb # NOQA warnings.warn( "cx_Oracle is deprec...
Python
1
import datetime from typing import List from src.database.model import HouseInfo, get_session def add_house_info(house_info: HouseInfo): """添加房产信息 :param house_info: 房产信息 """ with get_session() as session: session.add(house_info) def query_house_info(**kwargs) -> List[HouseInfo]: """ho...
Python
1
82631493, -0.0036663906648755074, 0.13102592527866364, -0.010544195771217346, -0.08078552782535553, 0.03218182548880577, 0.01810539700090885, 0.05525807663798332, -0.05030102655291557, -0.0439252071082592, -0.01785256154835224, -0.19900473952293396, 0.048614487051963806, ...
Python
1
_mut() .iter_mut() .try_for_each(|constraint| match constraint { &mut Constraint::Eq { lh, rh: Match::Value(ref v) } if lh.field() == Field::Attribute => { let mut stmt = self.tx.prepare_cached( r#" ...
Rust
0
"loss": loss, "mask_bce_loss": mask_bce_loss, "mask_dice_loss": mask_dice_loss, "mask_loss": mask_loss, } def inference( self, images, images_evf, input_ids, resize_list, original_size...
Python
1
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class SubAccountBaseInfo(object): def __init__(self): self._account_no = None self._out_fin_inst_abbreviation = None self._sub_account_no = None @property def account_n...
Python
1
ect specifications.<br></li> <li>Enhanced system efficiency by fine-tuning wiring configurations.<br></li> <li>Ensured hardware outputs aligned seamlessly with software requirements.</li> </div> """, unsafe_allow_html=True, ) # Christopher Per...
Python
1
if opt.CCD or opt.HF_CCD: self.set_requires_grad([self.netD_21], False) self.set_requires_grad([self.netD_12], False) self.set_requires_grad([self.netG_A_1, self.netG_B_1], True) self.set_requires_grad([self.netG_A_2, self.netG_B_2], True) self.optimizer_G_1.zero_grad() self.optimizer_G_2.zero_g...
Python
1
__copyright__ = """MIT License Copyright (c) 2024 - IBM Research 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,...
Python
1
eshold, grid_step.opencv_as_extern(), interp_type, epic_k, epic_sigma, epic_lambda, ric_sp_size, ric_slic_type, use_post_proc, fgs_lambda, fgs_sigma, use_variational_refinement) }.into_result().map(|r| unsafe { core::Ptr::<dyn crate::optflow::DenseRLOFOpticalFlow>::opencv_from_extern(r) } ) } } /// "Dual TV L1" Opti...
Rust
0
ttach_level( &mut self, level: NonNull<Level<CapabilityEndpointSet, CapabilityTableNode, 512>>, _leaf: bool, ) { self.next = Some(level); } fn clear_level(&mut self) { self.next = None; } } #[derive(Clone)] pub struct CapabilityEndpointSet { pub endpoints: [...
Rust
0
d and then the `!` method on the result. #[instrument(name="Basic::!", level="trace", skip(this, args), fields(self=?this, ?args))] pub fn qs_not<'o>(this: &'o Object, args: Args<'_, 'o>) -> Result<Object> { this.call_attr_lit(&Literal::AT_BOOL, args)? .call_attr_lit(&Literal::NOT, &[]) } /// Get a hash of `t...
Rust
0
elif ( testobj.is_typeclass("world.exploration.loot.Trinket") or testobj.is_typeclass("world.exploration.loot.AncientWeapon") or testobj.is_typeclass("world.magic.materials.MagicMaterial") or testobj.is_typeclass( "world.dominion...
Python
1
from config import load_config, save_config from memory import Memory from voice import init_tts, speak, Listener from commands import CommandHandler def greet(engine, config): name = config.get('user_name', 'User') speak(f"Hello {name}, how can I help you?", engine) def main(): config = load_config() ...
Python
1
_match(output, file), CompareFileResult::FileDiffers { ref file, ref was_hash, ref new_hash } => { write_file_result_diff(output, file, was_hash, new_hash); differed_n += 1; } } } ...
Rust
0
&str) -> Span { Span::new(0, s.len() as u32) } /// Combine two spans by taking the start of the earlier span /// and the end of the later span. /// /// Note: this will work even if the two spans are disjoint. /// If this doesn't make sense in your application, you should handle it your...
Rust
0
def forward_decoder(self, masks, is_stft): # masks: [b, spk, f, t] # phase: [b, f, t, 2] if is_stft: outputs = [] for i in range(masks.shape[1]): outputs.append( self.encoder.inverse(masks[:, i, :, :].unsqueeze(-1) * self.phase).un...
Python
1
date end_date = datetime.now(timezone.utc) print("Warning: Could not find any recent papers. Using current date as end_date.") else: end_date = most_recent_date print(f"Most recent paper date: {end_date.date()}") # Calculate start date start_date = end_date - timedelta(days=...
Python
1
. Any other value: Boot loader backdoor is disabled. NOTE! Boot loader must be enabled (see BOOTLOADER_ENABLE) if boot loader backdoor is enabled."] #[inline] pub fn bl_enable(&self) -> BL_ENABLER { let bits = { const MASK: u8 = 255; const OFFSET: u8 = 0; ((self.bits ...
Rust
0
stination Buffer: let mut vec_dst = vec![0.0f32; proque.dims().to_len()]; let buf_dst = Buffer::new(queue, Some(::MEM_READ_WRITE | ::MEM_COPY_HOST_PTR), proque.dims().clone(), Some(&vec_dst)).unwrap(); // Source origin doesn't matter for this: let src_origin = [0, 0, 0]; // Lengths of the t...
Rust
0
# Copyright 2020 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models class ResCompany(models.Model): _inherit = "res.company" full_header_img = fields.Binary( string="Full header image", help="This image will replace all header."...
Python
1
sponse.text}") results[message_id] = False except requests.exceptions.RequestException as e: print(f"🚨 Exceção ao tentar deletar o e-mail {message_id}: {e}") results[message_id] = False return results def format_body(html): # Converte <a href="URL">texto</a...
Python
1
tings, console: Console, ) -> str: reply_chunks: list[str] = [] try: for chunk in engine.stream_chat(conversation.trimmed_messages(), generation): clean = _sanitize_chunk(chunk) if not clean: continue console.print(clean, end="", soft_wrap=True) ...
Python
1
rate::theory::{key::Key, piano_key::PianoKey}; use rand::{rngs::SmallRng, seq::SliceRandom, SeedableRng}; pub struct RandomSeed(SmallRng); impl Default for RandomSeed { fn default() -> Self { Self(SmallRng::from_entropy()) } } impl MusicSeed for RandomSeed { fn get_note(&mut self, key: Key) -> Pi...
Rust
0
ult=None, help='Path for the output run.') parser.add_argument('--override', dest='override', action='store_true', default=False, help='Override \'complete\' H5 file if it already exists.') args = parser.parse_args() img_size = args.img_size z_dim = ...
Python
1
# Parser for C code # Originally by Mark Shannon (mark@hotpy.org) # https://gist.github.com/markshannon/db7ab649440b5af765451bb77c7dba34 import re import sys import collections from dataclasses import dataclass def choice(*opts): return "|".join("(%s)" % opt for opt in opts) # Regexes # Longer operators must go...
Python
1
COLLECT, SCRIPTURE_RUBRIC, FIRST_LESSON, PSALM, SECOND_LESSON, GOSPEL, HOMILY, THE_MARRIAGE_HEADER, THE_MARRIAGE, THE_RINGS, RINGS_ALREADY_GIVEN, PRONOUNCEMENT_HEADER, PRONOUNCEMENT, THE_PRAYERS_HEADER, LORDS_PRAYER, THE_PRAYERS, BLESSING_OF_THE_MARRIAG...
Rust
0
query_args, doseq=True) def prefix_slash_in_url_if_missing(url): if not url.startswith("/"): return f"/{url}" else: return f"/{url.lstrip('/')}" async def create_poll_callback(ctx, blog, post_id): async def poll_callable(poll_id, expiration_timestamp): current_timestamp = round(d...
Python
1
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Bizmeka 메일 스크래퍼 - 디버그 버전 - 페이지 구조 분석 - 선택자 찾기 - 스크린샷 저장 """ import asyncio import json from pathlib import Path from datetime import datetime from playwright.async_api import async_playwright, Page from cookie_manager import CookieManager from utils import load_config,...
Python
1
import pygame import sys # Initialize Pygame pygame.init() # Screen configuration WIDTH, HEIGHT = 800, 400 screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Ball bouncing simulation") # Colors WHITE = (255, 255, 255) RED = (255, 0, 0) # Ball Configuration ball_radius = 10 ball_x = ball_r...
Python
1
s_error( SysErrorKind::NotOk, Option::<&str>::None, )), _ => unreachable!(), } .and_then(TryInto::try_into) } } impl<T: AsLeptonicaPtr> Binarize for T {} use crate::{ErrorKind, JsonValue, MyResult}; use failure::Fail; use serde_json; use std::...
Rust
0
y() should be called. */ pub fn start() -> Result<Confomat> { let args: Vec<String> = std::env::args().collect(); let mut opts = getopts::Options::new(); opts.optopt("d", "", "confomat data directory", "DIRECTORY"); let p = match opts.parse(&args[1..]) { Ok(p) => p, Err(e) => { ...
Rust
0
(actual_delay, now); if self.average_delay_base == 0 { self.average_delay_base = actual_delay; } self.sum_delay_diffs(actual_delay); // recalculate delays every 5 seconds or so if now > self.average_sample_time { ...
Rust
0
with_header(content_type) .with_body(file) } None => Response::new().with_status(StatusCode::NotFound), } } // Fallthrough for POST/PUT/CONNECT/... _ => Response::new().with_status(StatusCode::NotFoun...
Rust
0
None => None, Some(val) => Some(NativeType::String(val.to_string())), }), DateTime => Ok(match self.try_get::<Option<sqlx::types::chrono::NaiveDateTime>, usize>(index)? { None => None, Some(val) => Some(NativeType::String(val.to_string())), ...
Rust
0
convert_grouper(axis: Index, grouper): if isinstance(grouper, dict): return grouper.get elif isinstance(grouper, Series): if grouper.index.equals(axis): return grouper._values else: return grouper.reindex(axis)._values elif isinstance(grouper, MultiIndex): ...
Python
1
success = True except subprocess.CalledProcessError as e: print(f"Failed to send reply to Twitter. Error code: {e.returncode}") print(f"Error output: {e.stderr}") print(f"Standard output: {e.stdout}") if success: with open('data/processed_twee...
Python
1
import tkinter as tk from tkinter import filedialog, messagebox from bs4 import BeautifulSoup import pandas as pd from urllib.parse import urljoin from PIL import Image, ImageTk def parse_html_file(file_path): with open(file_path, 'r', encoding='utf-8') as file: content = file.read() soup = BeautifulS...
Python
1
sum() } } #[test] fn test_closest() { let coords = Coords::from_str( r" 1, 1 1, 6 8, 3 3, 4 5, 5 8, 9 ", ) .unwrap(); assert_eq!(coords.closest((0, 0)), Some(Coord::from((1, 1)))); assert_eq!(coords.closest((3, 2)), Some(Coord::from((3, 4)))); assert_eq!(coords.closest((5, 0)),...
Rust
0
"{}.wav", Utc::now().format(&self.settings.format).to_string() )); std::fs::write(&filename, w)?; Ok(Url::from_file_path(filename.canonicalize()?) .map_err(|_| crate::Error::InternalError)? .into_string()) } } /// 設定の読み込みとかをする奴。 /// リファクタリングしたい. fn l...
Rust
0
.padding(20) .border_radius(5), ); Column::new() .height(Length::Fill) .justify_content(Justify::Center) .padding(20) .push(content) .into() } } fn lorem_ipsum() -> Text { Text::new("Lorem ipsum dolor sit amet,...
Rust
0
mut(handle))) } /// Checks if a chunk exists at a coordinate position. fn chunk_exists<I: ToIndex>(&self, v: I) -> bool { let index = v.to_index(self.dimensions().x(), self.dimensions().y()); self.get_chunk_handle(index).is_some() } /// Sets a single tile at a coordinate position a...
Rust
0
() } impl Metadata { pub fn version_template(&self, ver: &str) -> Result<String> { use tera::{Tera, Context}; let mut ctx = Context::new(); ctx.insert("version", &ver.to_string()); let res = Tera::one_off(&self.gitTagTemplate, &ctx, false).map_err(|e| { warn!("Failed to ...
Rust
0
al_preds[:, :, :, 2] = ort_output[:, :, points_y.astype(np.int32), points_x.astype(np.int32)] points_y = points_y * size[0] / (h - 1) points_x = points_x * size[1] / (w - 1) final_preds[:, :, :, 0] = points_x final_preds[:, :, :, 1] = points_y # draw point # bchw->chw->hwc img = img.squeez...
Python
1
hp_deficit=[] rewards=[] # 打开文件,'r'表示以只读模式打开 with open('/home/zenu/code/rl_hw/mindspore_ddpg2/eval_log.txt', 'r') as file: # 使用for循环逐行读取文件内容 is_line_next_reward = False for line in file: # 打印每一行 if "At the end," in line: line_list = line.strip().split() # print(line_l...
Python
1
tconsume_positionalscs   iistoo few argumentssargument %s is requireds#one of the arguments %s is requiredRy(RlR/t_read_args_from_filesR3RRRRtiterRt_parse_optionalR!RRwR=R<R`RR0RRRRt basestringR...
Python
1
unsafe { &*(((self as *const Self) as *const u8).add(1288usize) as *const crate::Reg<erasepcr1::ERASEPCR1_SPEC>) } } #[doc = "0x508 - Register for erasing a page in Code area"] #[inline(always)] pub fn erasepage(&self) -> &crate::Reg<erasepage::ERASEPAGE_SPEC> { ...
Rust
0
// label //positive: // Integers let mut z_int = Mask::falsey(); let mut fact_res = one; if P::POLICY.precision > PrecisionPolicy::Worst { let zf = z.floor(); z_int = zf.eq(z); let bitmask = z_int.bitmask(); if thermi...
Rust
0
= cond.operand[0]; let lhs = self.combine_node(replace, heap, cond.operand[1]); let rhs = self.combine_node(replace, heap, cond.operand[2]); heap.alloc(DAGNode::new( match cond.kind { NodeKind::IR(IRNodeKind::Setcc) => NodeKind...
Rust
0
end(psnr) # print(gt) # print(r.shape) h = r.shape[0] w = r.shape[1] c = r.shape[2] # r = r.reshape((1, 3, h, w)) # gt = gt.reshape((1, 3, h, w)) r_tensor = tor...
Python
1
Result<usize> { diesel::delete(auth_code::table.find(code)).execute(conn) } pub fn create_token(new_token: NewToken, conn: &MysqlConnection) -> QueryResult<usize> { diesel::insert_into(tokens::table) .values(&new_token) .execute(conn) } pub fn find_token(token: &str, conn: &MysqlConnection) ->...
Rust
0
""" """ # Created on 2014.01.04 # # Author: Giovanni Cannata # # Copyright 2014 - 2020 Giovanni Cannata # # This file is part of ldap3. # # ldap3 is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either ...
Python
1
import matplotlib.pyplot as plt import numpy as np def scatter_plot(m_l, y_l, title, path): """ scatter plot for 2D matrix m Args: m_l(list): list of n-by-2 matrix y_l(list): list of len(m) labels path(str): path to save image """ fig = plt.figure(figsize=(8, 8)) ax...
Python
1
from .dependency_manager import get_dependency_manager
Python
1
# -*- coding: utf-8 -*- # # Copyright 2021 Google LLC. 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 requir...
Python
1
); } extern "C" { pub static FLAC__FRAME_HEADER_SYNC: u32; } extern "C" { pub static FLAC__FRAME_HEADER_SYNC_LEN: u32; } extern "C" { pub static FLAC__FRAME_HEADER_RESERVED_LEN: u32; } extern "C" { pub static FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN: u32; } extern "C" { pub static FLAC__FRAME_H...
Rust
0
_constructor; mod csl_line_iter; #[cfg(feature = "with-rayon")] mod csl_rayon; #[cfg(feature = "with-rand")] mod csl_rnd; mod csl_utils; use crate::utils::{ are_in_ascending_order, are_in_upper_bound, default_dims, has_duplicates, max_nnz, windows2, }; #[cfg(feature = "alloc")] use alloc::vec::Vec; use cl_traits::{C...
Rust
0
--use-environment "Uses environment variables instead of command line arguments") (@arg input: +required +takes_value ... "Paths to .thrift files") ).get_matches(); let out = matches .value_of_os("out") .map(PathBuf::from) .unwrap_or(env::current_dir()?); let input = matches...
Rust
0
lue: config[key]['RANDOM_PAUSE_BETWEEN_ACCOUNTS'] }, { key: 'RANDOM_PAUSE_BETWEEN_ACTIONS', value: config[key]['RANDOM_PAUSE_BETWEEN_ACTIONS'] }, { key: 'RANDOM_INITIALIZATION_PAUSE', value: config[key]['RANDOM_INITIALIZATION_PAUSE'] } ], key); ...
Python
1
{ let style = &modal.style(); let _ = style.set_property("display", "none"); } trace!("Modal closed"); } } fn get_window() -> Window { web_sys::window().unwrap() } fn get_canvas(window: &Window, id: &str) -> Option<HtmlCanvasElement> { Some(window.document()?.get_...
Rust
0
igh) = iter.next() { let low = iter.next().unwrap(); let big5: [u8; 2] = [*high, *low]; if let Some(c) = B2U.get(&big5) { result.push(*c); } } result } #[cfg(test)] mod test { use super::*; const UNICODE: &str = "一小段中文測試♥一小段中文测试♥中国の短いテスト♥"; const BIG5: &[...
Rust
0
# This file is part of Pynguin. # # SPDX-FileCopyrightText: 2019–2025 Pynguin Contributors # # SPDX-License-Identifier: MIT # import pytest from pynguin.ga.stoppingcondition import MaxStatementExecutionsStoppingCondition @pytest.fixture def stopping_condition(): return MaxStatementExecutionsStoppingCondition(...
Python
1
t}; use ty::reason::Reason; impl<R: Reason> Infer<R> for oxidized::aast::Class_<(), ()> { type Params = (); type Typed = tast::Class_<R>; fn infer(&self, env: &mut TEnv<R>, _params: ()) -> Result<Self::Typed> { rupro_todo_assert!(self.user_attributes.is_empty(), AST); rupro_todo_assert!(se...
Rust
0
import slicer from slicer.ScriptedLoadableModule import * # # CropVolumeSelfTest # class CropVolumeSelfTest(ScriptedLoadableModule): def __init__(self, parent): ScriptedLoadableModule.__init__(self, parent) parent.title = "CropVolumeSelfTest" # TODO make this more human readable by adding spaces...
Python
1
/// Transmit a START character, which should re-enable a connected terminal device TCION, } } // TODO: Make this usable directly as a slice index. libc_enum! { /// Indices into the `termios.c_cc` array for special characters. #[repr(usize)] pub enum SpecialCharacterIndices { VDISCA...
Rust
0
nd order delta encoding would take consecutive differences again, /// leaving `[2, -2, 2, -2, 2, -2]`. Higher-order delta encoding is good /// for time series like sensor readings that are very smooth. pub delta_encoding_order: usize, } impl Default for CompressorConfig { fn default() -> Self { Self { ...
Rust
0
def calcular_salario_final(salario_fixo, comissao_por_carro, total_vendas, carros_vendidos): """ Calcula o salário final de um vendedor, considerando salário fixo, comissão por carro, total de vendas e quantidade de carros vendidos. Args: salario_fixo (float): Valor fixo do salário do vendedor....
Python
1
from __future__ import print_function import glob import sys from setuptools import setup import pkg_resources from packaging import version # sonic_dependencies, version requirement only supports '>=' sonic_dependencies = ['sonic-py-common'] # Common dependencies for Python 2 and 3 dependencies = [ 'bitarray==2...
Python
1
"select json_build_object({sql_field_sequence}) as {sql_parent_name} \ from \"{sql_from_table_name}\" as {sql_alias_main_table} limit {sql_limit}", sql_field_sequence = sql_field_sequence, sql_parent_name = parent_name, sql_from_table_name = sql_from_table_name, sql_alias_main_table = sq...
Rust
0
)) } /// Creating new quadruples if necessary by updating quadruples_in_creation, /// considering currently avialable quadruples, quadruples in creation, and /// ecdsa configs. fn make_new_quadruples_if_needed( subnet_nodes: &[NodeId], summary_registry_version: RegistryVersion, ecdsa_config: &EcdsaConf...
Rust
0
ure Compare Unit 8 (Module 0)"] CCU80_0 = 60, #[doc = "61 - Capture Compare Unit 8 (Module 0)"] CCU80_1 = 61, #[doc = "62 - Capture Compare Unit 8 (Module 0)"] CCU80_2 = 62, #[doc = "63 - Capture Compare Unit 8 (Module 0)"] CCU80_3 = 63, #[doc = "64 - Capture Compare Unit 8 (Module 1)"] ...
Rust
0
OM users WHERE role != 'учитель' AND role != 'разработчик' """) users = cursor.fetchall() if not users: bot.send_message(user_id, "❌ Нет зарегистрированных пользователей.") return message = "📋 Список пользователей:\n" for user in users: user_id, full_name, role, cl...
Python
1
_into()?); // Ok(Statement::Expression(expr)) // } // } // } // }/* * Copyright 2019-2021 <NAME> * * 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...
Rust
0
index.iter_mut().take(end_index).skip(start_index) { if *j == INVALID_EDGE { *j = i; break; } } } // sort down_index subvectors for node in 0..nodes.len() { let subvector = &mut down_index[down_offset[node]..down_offset[node + 1]]; ...
Rust
0
for i in range(self.n_conv_stages, self.n_conv_stages + self.n_stages) ] else: masks_to_decoder = pred_masks out = self.decoder(X, skips, masks_to_decoder) if not self.dual_inpainting: return out, projs, conf_mask_hier # dual inpainting (bidirection...
Python
1
: ctp): (world_chunks, chunk id/chunk struct) > ctp.load_newchunk() > (vertices, indices) (world_chunks, chunk id/chunk struct) > ctp.load_newchunk() > (vertices, indices) (world_chunks, chunk id/chunk struct) > ctp.load_newchunk() > (vertices, indices) (world_chunks, chunk id/chunk struct) > ctp.load_n...
Rust
0
'Reported tag == %d should be %d'\ % (status.tag, pypar.default_tag) assert status.error == 0 assert status.source == numproc - 1, 'Reported source == %d should be %d'\ % (status.source, numproc - 1) print "Status object (buffered numeric real arrays) OK" # Stri...
Python
1
get_aes_key(&account.private_key, &account.public_key()) .map_err(core_err_unexpected)?; let encrypted_access_key = symkey::encrypt(&key_encryption_key, &key).map_err(core_err_unexpected)?; let use_access_key = UserAccessInfo { username: account.username.clone(), encrypted_by: ac...
Rust
0
println!("out:{}", out); assert_eq!(out, "done"); } // 自定义一个Future实现 // 1. 等待某个特定时间点的到来 // 2. 在标准输出打印文本 // 3. 生成一个字符串 struct Delay { when: Instant, } impl Future for Delay { type Output = &'static str; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { if Instant::no...
Rust
0
?; let req = surf::get("https://httpbin.org/get"); surf::client().with(Printer {}).send(req).await?; Ok(()) } <reponame>losfair/orange-rs global_asm!(include_str!("entry.asm")); use ray_tracing_show_image; use ray_tracing_utility::image; use ray_tracing_utility::serialization::core::DeserializeOptions; use...
Rust
0
, Rx1: Send + 'static, { let (tx0, rx0) = make0(); let (tx1, rx1) = make1(); (Self::wrap(tx0, rx1), <Self::Dual>::wrap(tx1, rx0)) } /// Given a transmitting and receiving end of an un-session-typed connection, wrap them in a new /// session-typed channel for the protocol...
Rust
0
# *************** Variational forms ***************** # # flow equations BigA = - dot(div(sigma),v)*dx + 0.5*dot(t*u,v)*dx BigB = 2.*mu*inner(sym(t),s)*dx - 0.5*inner(dev(outer(u,u)),s)*dx - inner(dev(sigma),s)*dx BigC = inner(tau,t)*dx + dot(u,div(tau))*dx F = dot(g+rhs_ex,v)...
Python
1
from app.models import Card, db, Game, Player from app import create_app app = create_app() with app.app_context(): Card.query.delete() # Game.query.delete() # Player.query.delete() ranks = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"] suits = ["Hearts", "Diamonds", "Clubs",...
Python
1
Returns ------- gbk_files : list[Path] Genbank files """ logger = logging.getLogger(__name__) # Check specified name dataset exists or not if name not in GBK_DATASET.keys(): raise ValueError(f"'{name}' dataset not found.") # Dataset cache local directory if cache_di...
Python
1
This function returns the x, y pairs which have the least Euclidean distance between the given target image and the source image (this is taken by iterating over the entire image). Note: This function expects the image to be in CIE LAB color scheme. """ image_height, image_width = lab_image.shape...
Python
1
const FALL_GRAV: f32 = 0.7; const MAX_V_VEL: f32 = 4.8; // Iterate over entities and update them. pub fn update(entity_mgr: &mut EntityManager, input_mgr: &InputManager) { for entity_id in 0..entity_mgr.entities.len() { if entity_mgr.entities[entity_id].exists && entity_mgr.entities[entity_id].use_player {...
Rust
0
(crate) fn decompress(input: &[u8], output: &mut [u8]) -> Result<usize, Lz4Error> { Ok(decompress_into(input, output, 0)?) } pub(crate) fn get_maximum_compressed_buffer_len(decompressed_len: usize) -> usize { get_maximum_output_size(decompressed_len) } } #[cfg(feature = "lz4-sys")] mod lz4_...
Rust
0
# -*- coding: utf-8 -*- # # Copyright 2017 Google LLC. 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 requir...
Python
1
0xbb6f865c755b9100, 0x6f6ccbea5f0c5847, 0x4cfd3606c21c2573, 0x3512ec3dc6889f67, 0xc7981de6b0710b5f, 0x109fe23f817aa0cf, ])), BN382Fr::new(BigInteger([ 0x39de13d041934215, 0x5370089a3da7c4fe, 0x512952ce97...
Rust
0
if prop in content: setattr(manufacturer, prop, content[prop]) manufacturer.save() return JsonResponse( manufacturer, encoder=ManufacturerEncoder, safe=False, ) except Manufacturer.DoesNotExist: ...
Python
1
acksVec) -> ChartBuilder<'a> { ChartBuilder { artists: a, tracks: t, colors: VecDeque::from_iter(vec![ "white", "#1DB954", "hotpink", "yellow", "cornflowerblue", "crimson", ...
Rust
0
相关表列表 """ # 查找以当前表为源的关系 source_relationships = self.db_session.query(TableRelationship, TableSchema).join( TableSchema, TableRelationship.target_table_id == TableSchema.id ).filter( TableRelationship.source_table_id == table_schema_id ).all() ...
Python
1
import json from pathlib import Path from django.core.management.base import BaseCommand from api.utils.ubc import * from api.models.building import Building class Command(BaseCommand): help = "Add building address, latitude, and longitude to existing building records" def handle(self, *args, **options) -> N...
Python
1
swith('/'): storepath = storepath[1:] tlshchecksum = None if 'tlsh' in i: tlshchecksum = i['tlsh'] cursor.execute("insert into batresult (checksum, filename, tlsh, pathname, parentname, parentchecksum) values (%s, %s, %s, %s, %s, %s)", (i['sha256'], i['name'], tlshchecksu...
Python
1
})?; Ok(result) } fn extract( _pp: &PublicParams<Tree>, _replica_id: &<Tree::Hasher as Hasher>::Domain, _data: &[u8], _node: usize, _config: Option<StoreConfig>, ) -> Result<Vec<u8>> { todo!() } } #[cfg(test)] mod tests { use supe...
Rust
0
.and_then(|(store, context)| { store .get_account_from_http_token("incoming_auth_token") .and_then(move |account| { assert_eq!( account.get_http_auth_token().unwrap(), "outgoing_auth_token" ); assert_...
Rust
0
np.array([pad_val] * (i + max_seq_len - len(q_seq))) ] ) ) proc_pid_seqs.append( np.concatenate( [ pid_seq[i:], np.array([pad_val] * (i + max_seq_len - len(q_seq))) ...
Python
1
) } } fn get_first_input_type(item: &syn::ItemFn) -> Result<&syn::Type> { let inputs = &item.sig.inputs; match inputs.first() { Some(syn::FnArg::Typed(arg)) => Ok(&arg.ty), Some(reciever) => Err(Error::new(reciever.span(), "Non method function required")), None => Err(Error::new(inputs.span(), "Requi...
Rust
0