text
string
label_name
string
labels
int64
OW() WHERE map_id = %s", (actor_map_id,)) details = douban_api.celebrity_details(actor_douban_id) if details and not details.get("error"): avatar_url = (details.get("avatars", {}) or {}).get("large") ...
Python
1
From<UartDataBits> for uart::DataBits { fn from(value: UartDataBits) -> Self { match value.0 { 5 => Self::Five, 6 => Self::Six, 7 => Self::Seven, 8 => Self::Eight, _ => panic!("Incompative UART data bits."), } } } impl TryFrom<u8> for ...
Rust
0
in_dir == "-": print("Reading filenames from stdin", file=sys.stderr) for fname in sys.stdin: process_file(fname.rstrip(), out_dir, indexer, splitter) else: # scan input dir print(f"Looking up files in {in_dir}", file=sys.stderr) for entry in os.scandir(in_dir): ...
Python
1
self.custom_dts = BaseFilter.parse_as_dict(str, str, "custom_dts", data) # Missing Info self.is_missing_info = BaseFilter.parse_as_type(bool, "is_missing_info", data) # Reject leftover parameters for key in data: raise ValueError( f"'{key}' is not a re...
Python
1
ies[3].file_type) assert(entries[3].path == $sub1_path_str, "Wrong path: " .. entries[3].path) assert(entries[3].depth == 1, "Wrong depth") }) .exec(); assert!(result.is_ok(), "Failed: {}", result.unwrap_err()); } #[rstest] fn should_support_returning_canonicalized_paths(ctx...
Rust
0
Direction::North, GridDirection::NorthEast, GridDirection::East, GridDirection::SouthEast, GridDirection::South, GridDirection::SouthWest, GridDirection::West, GridDirection::NorthWest, ]; /// The set of initial parameters for a match #[derive(Debug, Clone, Serialize, Deserialize, Default)]...
Rust
0
tup(mode="rev") om.n2(prob, show_browser=False, outfile="n2.html") prob.run_model() mass1 = prob.get_val("multipoint.aerostructural1.mass", get_remote=True) func_struct1 = prob.get_val( "multipoint.aerostructural1.func_struct", get_remote=True ) C_L1 = prob.get_val("multipoint.aerostr...
Python
1
| cat" try: output = subprocess.check_output(command, shell=True).decode("utf-8") except: return set() if(len(output) == 0): return set() output = output.split("\n") ignore_flag = True line_nums = list() for i, line in enumerate(output): if(ignore_flag and (not line.startswith("@@"))): continue if(i...
Python
1
from pydub import AudioSegment import numpy as np import matplotlib.pyplot as plt import os # Load audio file def load_audio(file_path): audio = AudioSegment.from_file(file_path) return audio # Simple function to visualize audio wave def plot_audio_wave(audio): samples = np.array(audio.get_array_of_sample...
Python
1
from dspy.utils import download def main(): # download_file() print("Downloading file...") download("https://huggingface.co/dspy/cache/resolve/main/ragqa_arena_tech_corpus.jsonl") if __name__ == "__main__": main()
Python
1
# This is an automatically generated file. # DO NOT EDIT or your changes may be overwritten from __future__ import annotations import base64 from xdrlib3 import Packer, Unpacker from .signature import Signature from .time_sliced_survey_stop_collecting_message import ( TimeSlicedSurveyStopCollectingMessage, ) __...
Python
1
2i { x: 1, y: 2 }; assert_eq!(v / 2, Vec2i { x: 0, y: 1 }); assert_eq!(v / 2 as i32, Vec2i { x: 0, y: 1 }); } #[test] fn test_div_assign() { let mut v = Vec2i { x: 1, y: 2 }; v /= 2; assert_eq!(v, Vec2i { x: 0, y: 1 }); } } <reponame>m-lima/rucl...
Rust
0
Info) -> ValTCM { use Neutral::*; let info = val.loc; let val = val.ast.try_map_neutral(&mut |neut| match neut { Meta(mi) => tcs .meta_context .take_meta(mi) .ok_or_else(|| TCE::MetaUnsolved(mi)), e => Ok(Val::Neut(e)), })?; Ok((val.into_info(info)...
Rust
0
{Event, Key, Modifiers}; pub use cushy_gl::{TexFilter, TexFilters}; mod color; pub use color::Color; mod quad; pub use quad::{Quad, QuadRenderer, QuadRendererType}; mod geo; pub use geo::{Size, SizeAny, SizeU32, Rect, RectAny, RectU32, Point, PointAny, PointU32}; pub use geo::{Transform, Rotation, Scaling}; mod cam...
Rust
0
ct): Sampled and reestructured model parameters. Returns: dict: Model parameters ready to recreate the model. """ columns = [] univariates = [] for column, univariate in model_parameters["univariates"].items(): columns.appe...
Python
1
EscolhaLanche = int(input("-------------------Bem Vindo ao Maquimeleca, qual opção você gostaria?---------------------\n Digite 1 para Hamburguer - R$10,00 \n Digite 2 para Batata Frita - R$10,00 \n Digite 3 para refrigerente - R$10,00 \n Digite 4 para combo (os 3 itens) - R$22,00 \n")) item1 = "Hamburguer" item2 = "B...
Python
1
Game of Bottles Problem Description Given an array of integers A of size N which denotes N cylindrical empty bottles. The radius of the ith bottle is A[i]. You can put the ith bottle into the jth bottle if the following conditions are met: ith bottle is not put into another bottle. jth bottle dosen't contain any other ...
Python
1
from abc import ABC, abstractmethod from typing import Any, Dict, Iterable, Mapping, Optional, Tuple from .weather import WeatherReport class WeatherService(ABC): @abstractmethod async def get_weather(self, lat: float, lon: float) -> WeatherReport: pass class GeocodeService(ABC): @abstractme...
Python
1
from .. import Provider as BaseProvider class Provider(BaseProvider): """ A Faker provider for the Portuguese VAT IDs """ vat_id_formats = ("PT#########",) def vat_id(self) -> str: """ http://ec.europa.eu/taxation_customs/vies/faq.html#item_11 :return: A random Portuguese...
Python
1
đồng)", "(đồng)") # Handle duplicated column names - use the enhanced duplicated_columns_handling method target_report_df = self.duplicated_columns_handling(target_report_df) return target_report_df except Exception as e: ...
Python
1
process_queue: true, stop_rx, command_tx, command_rx, } } async fn run(mut self) { while self.accept_jobs || self.running > 0 { tokio::select!( _ = self.stop_rx.changed() => { self.accept_jobs = false; self.process_queue = false; }, command = self.command_rx.recv() => { mat...
Rust
0
let positions2: Vec<f64> = vec![-2.0, 0.0, 2.0, -2.0, 0.0, -2.0, -2.0, 0.5, 0.0]; let mesh2 = MeshBuilder::<()>::new().with_indices(indices2).with_positions(positions2).build().unwrap(); mesh1.merge_with(&mesh2).unwrap(); assert_eq!(mesh1.num_faces(), 2); assert_eq!(mesh1.num_verti...
Rust
0
0) } #[doc = "Bit 6"] #[inline(always)] pub fn gpio9_edge_low(&self) -> GPIO9_EDGE_LOW_R { GPIO9_EDGE_LOW_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 5"] #[inline(always)] pub fn gpio9_level_high(&self) -> GPIO9_LEVEL_HIGH_R { GPIO9_LEVEL_HIGH_R::new(((self.bit...
Rust
0
# Copyright 2021 DeepMind Technologies Limited # # 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 agr...
Python
1
assert_impl_all!(EventWriter::<i32>: Send, Sync, Clone); } } /* Copyright (c) 2020-2021 Alibaba Cloud and Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ pub const ERR_CODE_CLASS_SHIFT: u32 = 28; pub const ERR_CODE_SUBCLASS_SHIFT: u32 = 23; pub const ERR_CODE_CLASS_MASK: u32 = 1879048192; pub const...
Rust
0
import numpy as np import pandas as pd from tensorflow.keras.models import Sequential from tensorflow.keras.layers import LSTM, Dense, Dropout from tensorflow.keras.optimizers import Adam import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler ...
Python
1
eader = WarcReader::new(shard_reader).iter_records(); for s in shard_reader { println!("{:?}", s); } let content = String::from( "foo bar baz quux", ); let warc_headers = HashMap::new(); let metadata = Metadata::new( ...
Rust
0
from pytest import approx import numpy as np from lap import lapmod, lapjv def prepare_sparse_cost(shape, cc, ii, jj, cost_limit): ''' Transform the given sparse matrix extending it to a square sparse matrix. Parameters ========== shape: tuple - cost matrix shape (cc, ii, jj): tuple o...
Python
1
{ self.0 += 4; } /// This returns a bit that is shared by all streams created by this role. pub fn role_bit(role: Role) -> u64 { match role { Role::Server => 1, Role::Client => 0, } } } impl From<u64> for StreamId { fn from(val: u64) -> Self { ...
Rust
0
lue()] == 5 { //check for flush hand_value = HandValue::Flush(hand[4].rank); if hand[4].rank.value() - hand[0].rank.value() == 4 { hand_value = HandValue::StraightFlush(hand[4].rank); } return Hand { hand, hand_value }; ...
Rust
0
x[0][n].imag) / math.sqrt(2) output = y else: print str(N_ant) + "\tantenna port not supported!" return data return output def interleave_row(data): interleave_vector = tuple( [1, 17, 9, 25, 5, 21, 13, 29, 3, 19, 11, 27, 7, 23, 15, 31, 0, 16, 8, 24, 4, 20, 12, 28, 2, 18, 1...
Python
1
------|------------|--------|\n" # 定义价值链环节数据 value_chain_data = [ { "stage": "研发设计", "activities": "产品概念与技术研发、标准制定、知识产权", "value": "★★★★★", "leaders": "A公司、B公司", "tren...
Python
1
eatures: `\"Win32_System_Ole\"`*"] pub const PS_MAXLINKTYPES: u32 = 8u32; #[doc = "*Required features: `\"Win32_System_Ole\"`*"] pub type PictureAttributes = i32; #[doc = "*Required features: `\"Win32_System_Ole\"`*"] pub const PICTURE_SCALABLE: PictureAttributes = 1i32; #[doc = "*Required features: `\"Win32_System_Ole...
Rust
0
( i ) ? ; Self ::").ident(&variant); } else { return parser.unexpected(); } tb.add("}"); parser.eat_punct(','); } else { return parser.unexpected(); } ...
Rust
0
= &mut bodies[player.body_handle]; // get collision // set if grounded player.is_grounded = check_grounded(physics, player); // set movement let gravity = Vec2::from(0., 5.); // gravity only happens when not grounded if !player.is_grounded { player_body.velocity = player_body.ve...
Rust
0
result) == 4 assert result[0]["op"] == "register_model" assert result[1]["op"] == "create_md" assert result[2]["op"] == "delete_md" assert result[3]["op"] == "delete_model" mocks._consent.assert_called_once() mocks._prompt.assert_called_once() mocks._test_model_r...
Python
1
mie::SET); // Setup the console. let console = components::console::ConsoleComponent::new( board_kernel, capsules::console::DRIVER_NUM, uart_mux, ) .finalize(components::console_component_helper!()); // Create the debugger object that handles calls to `debug!()`. compone...
Rust
0
2, 3, 4, 5, 6, 7, 8, 9] } pub(crate) fn test_data_gps_times() -> Vec<f64> { vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0] } pub(crate) fn test_data_colors() -> Vec<Vector3<u16>> { vec![ Vector3::new(0, 1 << 4, 2 << 8), Vector3::new(1, 2 << 4, 3 << 8), Vector3::new(2, 3 << 4,...
Rust
0
fail!( ErrorKind::Repo, "no signature on commit {}: {} ({})", latest_commit.commit_id, latest_commit.summary, latest_commit.author ); } // Ensure that the upstream repository hasn't gone stale ...
Rust
0
from __future__ import annotations def find_max_iterative(nums: list[int | float]) -> int | float: """ >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]): ... find_max_iterative(nums) == max(nums) True True True True >>> find_max_iterative([2, 4, 9, 7, 19, 94, 5...
Python
1
( read: &mut R, scratch: &mut Vec<u8>, ) -> Result<ElispEscape> { let ch = next_or_eof(read)?; match ch { b'"' => scratch.push(b'"'), b'\\' => scratch.push(b'\\'), b' ' => {} // Escaped blank is ignored b'a' => scratch.push(0x07), b'b' => scratch.push(0x08), ...
Rust
0
es/8) top_idx = np.argsort(Samples[:,num_nodes])[-top:] for i in range(num_samples): if i in top_idx: Samples[i,num_nodes] = 1 else: Samples[i,num_nodes] = 0 return Samples def explain(self, num_samples = 10, percenta...
Python
1
import numpy as np from sapien.core import Pose from copy import deepcopy from scipy.spatial.transform import Rotation as R from robot_sim.tasks.control_tasks import BaseControlTask from robot_sim.tasks.basic_actions.gripper_actions import GripperOpenCloseAction, GraspAction # from robot_sim.tasks.basic_actions.end_ef...
Python
1
.expect("Failed to parse"); if stmts.len() > 1 { panic!("Should only generate one function literal"); } match stmts.remove(0) { ast::Statement::Expression { value, .. } => ast::Function::from_expression(value), other => panic!("not an expression: {:?}", other), } } <gh_star...
Rust
0
ATHDR, // hydraulic status header ENERHDR, // energy usage header NODEHDR, // node results header LINKHDR // link results header } pub enum FlowDirection { NEGATIVE = -1, // flow in reverse of pre-assigned direction ZERO_FLOW = 0, // zero flow POSITIVE = 1 // fl...
Rust
0
fn albums(&self) -> Albums { Albums(&self) } pub const fn artists(&self) -> Artists { Artists(&self) } pub const fn playlists(&self) -> Playlists { Playlists(&self) } pub const fn searches(&self) -> Search { Search(&self) } pub const fn tracks(&self) ...
Rust
0
, min_weight_fraction_leaf=0.0, max_features=1.0, random_state=None, min_impurity_decrease=0.0, max_leaf_nodes=None, ccp_alpha=0.0, monotonic_cst=None, ): super().__init__( criterion=criterion, splitter=splitter, max...
Python
1
ain_process=accelerator.is_main_process, save_function=accelerator.save, state_dict=unwrapped_model.state_dict(), # state_dict=accelerator.get_state_dict(unwrapped_model), # state_dict=accelerator.get_state_dict(accelerate_model), max_shard_size="2GB" ...
Python
1
else: current_gesture = ml_gesture gesture_count = 0 # Detect face and expression frame_with_face, face_rects = face_detector.detect_faces(frame_with_hand) face_expression = None face_confidence = None i...
Python
1
# Copyright (c) 2019 PaddlePaddle Authors. 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 by app...
Python
1
}; // Initialize logger let handle = match init_config(config) { Ok(handle) => handle, Err(e) => { eprintln!("salty_log_init_callback: Could not initialize logger: {}", e); return false; } }; // Update static logger instance *handle_opt = Some(handle...
Rust
0
self.bit(variant.into()) } } #[doc = "Disable shortcut"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(COMPARE3_CLEAR_A::DISABLED) } #[doc = "Enable shortcut"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(COMPARE3_CLE...
Rust
0
t_state_dict["conv1.weight"] avgWs = torch.mean(conv1_weights, dim=1, keepdim=True) own_state["audio_conv1.weight"].copy_(avgWs) print("loaded audio weights from resnet") def _load_video_pretrained_weights_into_model(model: nn.Module, model_path): """加载预训练权重""" model = model.video_backbone # typ...
Python
1
{ let params: BTreeMap<String, String> = BTreeMap::new(); let data = self.post_signed("/swap-api/v1/swap_batchorder", params, &orders_data)?; let order: BatchOrder = from_str(data.as_str())?; Ok(order) } // cancel orders pub fn cancel_orders<S1, S2, S3>(&self, order_...
Rust
0
0x8030_ae7c; const KVM_GET_CPUID2: u64 = 0xc008_ae91; const KVM_GET_FPU: u64 = 0x81a0_ae8c; const KVM_GET_LAPIC: u64 = 0x8400_ae8e; const KVM_GET_MSR_INDEX_LIST: u64 = 0xc004_ae02; const KVM_GET_MSRS: u64 = 0xc008_ae88; const KVM_GET_SREGS: u64 = 0x8138_ae83; const KVM_GET_XCRS: u64 = 0x818...
Rust
0
tionCheck(transaction): # 格式正确 # 之后需要继续检测签名是否合法 transaction.append(transaction) # 将交易信息全部放入 return True else: return False # 左右两个节点生成方法是通过直接拼接得到的 def data_hash(self, data): # 要求输入的data是字符串类型 data_hash = hashlib.sha256(data.encode...
Python
1
dPlayer) self.videoLayer = True self.engine.ticksAtStart = pygame.time.get_ticks() while not vidPlayer.finished: self.engine.run() self.engine.view.popLayer(vidPlayer) self.engine.view.pushLayer(MainMenu(self.engine)) ...
Python
1
---------[ MACHINE-SUPPORT ]---------------# def alvino_xy(u): for e in u + "\n":sys.stdout.write(e);sys.stdout.flush();time.sleep(0.005) def clear(): os.system('clear') def back(): login() def contact(): # os.system('xdg-open https://www.facebook.com/Harisakhtar0') back() def linex(): print...
Python
1
-20], ]; #[rustfmt::skip] const MG_QUEEN_TABLE: [[i32; 8]; 8] = [ [-28, 0, 29, 12, 59, 44, 43, 45], [-24, -39, -5, 1, -16, 57, 28, 54], [-13, -17, 7, 8, 29, 56, 47, 57], [-27, -27, -16, -16, -1, 17, -2, 1], [ -9, -26, -9, -10, -2, -4, 3, -3], [-14, 2, -11, -2, -5, 2, ...
Rust
0
} } } } #[doc = "Register `INTR` reader"] pub struct R(crate::R<INTR_SPEC>); impl core::ops::Deref for R { type Target = crate::R<INTR_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<INTR_SPEC>> for R { #[inline(always)] ...
Rust
0
FER[10, 0] = -(x1 - x2)*(-15*L*w1*x1**2 - 10*L*w1*x1*x2 - 5*L*w1*x2**2 - 5*L*w2*x1**2 - 10*L*w2*x1*x2 - 15*L*w2*x2**2 + 12*w1*x1**3 + 9*w1*x1**2*x2 + 6*w1*x1*x2**2 + 3*w1*x2**3 + 3*w2*x1**3 + 6*w2*x1**2*x2 + 9*w2*x1*x2**2 + 12*w2*x2**3)/(60*L**2) return FER # %% # Returns the fixed end reaction vector for an...
Python
1
}) .collect::<Vec<_>>(); let llvm_type: BasicTypeEnum = CompilerState::get_type( self.current_state.get_context(), &inner_type, self.variables, Some(expression_values.len()), ) .expect("Unexpected void expression type"); se...
Rust
0
import ctypes import os import re import winreg from regedit_tools.zero_sensitivity import apply_zero_sensitivity, RegistryOperationError from regedit_tools.regunlockFPS import apply_regunlockfps, RegistryOperationError root_key = winreg.HKEY_CURRENT_USER sub_key = r"SOFTWARE\Tencent\Call-of-Duty" pattern = [re.compil...
Python
1
import os # API Configuration API_HOST = os.getenv("API_HOST", "kokoro-tts") API_PORT = os.getenv("API_PORT", "8880") API_URL = f"http://{API_HOST}:{API_PORT}" # File paths INPUTS_DIR = "app/ui/data/inputs" OUTPUTS_DIR = "app/ui/data/outputs" # Create directories if they don't exist os.makedirs(INPUTS_DIR, exist_ok...
Python
1
# -*- coding: utf-8 -*- """ 请求登录的http基础方法 Rules: 1. POST/DELETE/PUT: json in - json out, 如果resp.json报错, 则是登录接口问题 2. GET带参数 HEAD不带参数 3. 以统一的header头发送请求 """ import requests from django.conf import settings from common.log import logger def _gen_header(): headers = { "Content-Type": "application/json", ...
Python
1
e_config_and_inputs() self.model_tester.create_and_check_model(*config_and_inputs) def test_model_various_embeddings(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: config_and_inputs[0].posi...
Python
1
let foo: &[u32] = match true { true => &[1, 2], false => &[1, 2, 3], }; let foo: &[u32] = if true { &[1, 2] } else { &[1, 2, 3] }; } "#, ); } #[test] fn coerce_unsize_expected_type_2() { check_no_mismatches( r#" //- minicore: coerce_unsized stru...
Rust
0
self, cursor: &mut SliceCursor) -> Result<()> { cursor.write(&self.emote_id)?; if let Some(emote) = self.emote.as_ref() { cursor.write(&self.anchor_type)?; cursor.write(emote)?; } else { cursor.write(&255u8)?; } Ok(()) } fn from_body(c...
Rust
0
, }) } } /// Marker trait: implements "ToPolar" via a registered class pub trait HostClass {} use std::{io, string}; use thiserror::Error; /// The top-level Error type that captures all failure scenarios /// of the epub -> book conversion #[derive(Error, Debug)] pub enum ParseError { #[error("File er...
Rust
0
c_uint, dims.get().as_ptr() as *const DimT, 3, ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() } } #[allow(unused_mut)] impl ConstGenerator for bool { type OutType = bool; fn generate(&self, dims: Dim4) -> Array<Self::OutType> ...
Rust
0
EndpointSpec) -> Pipe { Pipe(Endpoint::from_spec(id, spec)) } pub fn open(&self, network: &mut dyn Context) { self.0.open(network, true) } pub fn send(&self, network: &mut dyn Context, msg: Rc<Message>) { self.0.send(network, msg) } pub fn recv(&self, network: &mut dyn ...
Rust
0
t.instance().account_balance(address, False) return int(actual['balance']) - pending_send async def get_available_balance_dec(self) -> float: """Get available balance of user (in normal unit)""" address = await self.get_address() pending_send, pending_receive = await self.get_pendin...
Python
1
, uploading image to cdn bucket"); let kind = infer::get(&data).unwrap(); let path = format!( "mg/{}/{}", message.message.media_group_id.as_ref().unwrap(), best_photo.file_id, ); let put = rusoto_s3::PutObjectRequest { acl: Some("download...
Rust
0
r.standing = self.imu_api.imu_processor.positions[-1] position = self.imu_api.processor.positions[-1] located_screw = self.current_screw_map.locate_closest_screw( position, self.current_screw_map.filter_screws_in_range(position) ) completed_count...
Python
1
.update(1) # 更新总进度 batch_pbar.update(1) # 更新批处理进度 # 清空当前批次 papers = [] # 如果达到最大数量,停止获取 if i >= MAX_RESULTS - 1: break # 处理剩余的论文 ...
Python
1
""" =========================== Glass Symmetry from Vectors =========================== This example shows how to identify symmetry (in a glassy system but this could be useful other places) by looking at the angles between 3 vectors in the diffraction pattern at some radial ring in k to identify groups of 3 vectors t...
Python
1
//! driver initialization. #![no_std] #![no_main] use usb_device::prelude::*; const UART_BAUD: u32 = 115_200; #[cortex_m_rt::entry] fn main() -> ! { let support::Peripherals { mut led, mut ccm, .. } = support::setup(core::time::Duration::from_millis(500), UART_BAUD); let (ccm, ccm_analog) = cc...
Rust
0
import requests from bs4 import BeautifulSoup headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' } url = "https://finance.yahoo.com/video/jensen-huang-sets-nvidia-apart-220744099.html" try: response = requests.get(ur...
Python
1
very_broken_open) with RaisesGroup(AttributeError, AttributeError): await run_process(EXIT_TRUE, capture_stdout=True) # regression test for #2209 async def test_subprocess_pidfd_unnotified() -> None: noticed_exit = None async def wait_and_tell(proc: Process) -> None: nonlocal noticed_exi...
Python
1
from sklearn.datasets import load_iris import pandas as pd import collections ordata = load_iris() frist_c = ordata.keys() data = pd.DataFrame(ordata.data,columns=ordata.feature_names) data['target'] = ordata.target print(data) # 120训练集,30测试集 train = data.sample(n=120) test = data.sample(n=len(data) - 120) # 划分训练集和...
Python
1
print msg sys.stdout.flush() def append_file(file_path,msg): f = open(file_path,'a') f.write(msg) f.close() #更新Job执行信息 def update_jobstatus(job_name,execute_time,execid,status=None,isUpdateStart=False): job_status = JobStatus() job_status.job_name = job_name job_status.execute_time = execu...
Python
1
return self._pool = cast(Pool, self._pool) self._pool.terminate() self._pool.join() self._pool = None class ThreadedTaskManager(TaskManager): """A threaded task manager.""" def __init__( self, nb_workers: int = DEFAULT_WORKERS_AMOUNT, is_lazy_pool_...
Python
1
""" 1. string that didn't match the regex 2. string that matched the regex 3. string that is not checked """ import re st = "the quick brown fox jumps ove the lazy dog" res = re.search(r'fox', st) if res: print("Match found.....") print(f"String that didn't match regex :{st[:res.start()]}") print("Strin...
Python
1
} } } // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "Licen...
Rust
0
ur_component + pynutil.insert(" ") + minute_component + pynutil.insert(" ") + second_component ) graph_clock_period = ( hour_component | minute_component | second_component | hour_minute | hour_se...
Python
1
#!/usr/bin/python ''' This example illustrates how to use cv.ximgproc.EdgeDrawing class. Usage: ed.py [<image_name>] image argument defaults to board.jpg ''' # Python 2/3 compatibility from __future__ import print_function import numpy as np import cv2 as cv import random as rng import sys rng.seed(12345) ...
Python
1
ttrs func_aliases = {} # name -> canonical name with gzip.open(path) as f: for obj in stream.loadjson(f): name, cl, members, aliases = obj['canonical_name'], obj['classification'], obj['members'], obj['names'] func_aliases[name] = name if pkgs is not None and not any(name.startswith(pkg+".") for pkg in...
Python
1
''' These scraping implementations are used only for detecting PDF direct download links as necessary ''' from html.parser import HTMLParser class RSC(HTMLParser): ''' Scraper for RSC publications ''' download_link = None #RSC scraping implementation def handle_starttag(self, tag, attrs): ''' PD...
Python
1
thin_seed: (Optional) random seed is set to thin_seed + rep prior to running thinning for replication rep results_dir: Folder where the results are loaded from """ # Create results directory if necessary pathlib.Path(results_dir).mkdir(parents=True, exist_ok=True) # Construct resu...
Python
1
#!/usr/bin/python3 """ function that prints a square with the character # """ def print_square(size): """ Parameter: size: represents size of suare Prints: square with the character # """ if not isinstance(size, int): raise TypeError('size must be an integer') if size <...
Python
1
user: user.clone(), change_type: Some(change_msg::ChangeType::Add(ObjectMsg { id: id_3.clone(), dependencies: None, obj_data: String::from("modified").into_bytes(), })), change_source: Some(change_msg::ChangeSource::UserAction(EmptyMsg ...
Rust
0
ject { inner_string: intermediate_rep.inner_string.into_iter().next(), }) } } impl AnotherXmlObject { /// Associated constant for this model's XML namespace. #[allow(dead_code)] pub const NAMESPACE: &'static str = "http://foo.bar"; } impl AnotherXmlObject { /// Helper function...
Rust
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Author: www @Date: 2024/6/25 下午5:29 @Description: """ from dataclasses import dataclass, field from typing import TypeVar from utils.types.config import Script, DictCFG, KoiConfig, ScriptType @dataclass class BaseItem(DictCFG): name: str = "BASE" script: Sc...
Python
1
# Copyright (C) 2022 Intel Corporation # SPDX-License-Identifier: MIT import logging from functools import partial from itertools import filterfalse from pprint import pformat from typing import Generator from attrs import Factory from vmsifter.config import settings from .xen import XL, XlInfo, XlVcpuInfo def ge...
Python
1
t::Result { if self == &Time::forever() { write!(f, "the end of time") } else { let date_time = chrono::NaiveDateTime::from_timestamp(self.0, 0); let date_time = chrono::DateTime::<chrono::Utc>::from_utc(date_time, chrono::Utc); write!(f, "{}", date_time....
Rust
0
"""Test of the SpectraFit utilities."""
Python
1
_winhttp: core.requires.append("wil::wil") core.system_libs.append("winhttp") if self.options.build_transport_curl: core.requires.append("libcurl::curl") # Add all crypto libs here, skip them for components if self.settings.os in ["Windows", "WindowsSt...
Python
1
9628}, {"name": "Ohio", "value": 11544225}, {"name": "Oklahoma", "value": 3814820}, {"name": "Oregon", "value": 3899353}, {"name": "Pennsylvania", "value": 12763536}, {"name": "Rhode Island", "value": 1050292}, ...
Python
1
(other.path()) } } impl PartialOrd for Location { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl PartialEq for Location { fn eq(&self, other: &Self) -> bool { self.path() == other.path() } } impl Eq for Location { } impl fmt::Display for ...
Rust
0
fg(not(windows))] impl<T: AsReadWriteFd> AsReadWriteGrip for T { #[inline] fn as_read_grip(&self) -> BorrowedGrip<'_> { self.as_read_fd() } #[inline] fn as_write_grip(&self) -> BorrowedGrip<'_> { self.as_write_fd() } } #[cfg(windows)] impl<T: AsReadWriteHandleOrSocket> AsReadWr...
Rust
0