text string | label_name string | labels int64 |
|---|---|---|
k(());
}
let font = font.0;
let text_color = text_color.unwrap_or_else(|| Color::Red.to_colorcode());
let background_color = background_color.unwrap_or_else(|| Color::Transparent.to_colorcode());
let buffer = get_emoji_data(
&ctx.data().client,
&ctx.data().config,
&text,
... | Rust | 0 |
| t j D]^ \ } } | d k sMt j
| pD| | k rt | | | rx|
j | | f qxqqWg }
x~ t j | t j D]g \ } } | d k st j | st j
| | k rt | | | r|
j | | f qqqWg } xH t j | t D]4 \ } } t | | | r| j | | f qqWg } t ... | Python | 1 |
"""
Challenge 27
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place.
The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.
Consider the number of elements in nums which are not equal to val be k, to get accepted, ... | Python | 1 |
"22nd",
"23rd",
"24th",
"25th",
"26th",
"27th",
"28th",
"29th",
"2nd",
"30th",
"31st",
"32nd",
"33rd",
"34th",
"35th",
"36th",
"37th",
"38th",
"39th",
"3rd",
"40th",
"41st",
"42nd",
"43rd",
"44th",
"45th",
"46th",
... | Rust | 0 |
'''
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
'''
for i in range(1,7):
for j in range(1,i):
print(i-j,end=" ")
print(" ") | Python | 1 |
)
fig.update_layout(title_font=dict(size=18, color="#eaf5ff", family="Segoe UI"))
fig.update_yaxes(tickprefix=_SYMBOLS.get(currency.upper(), "") or None)
_range_tools(fig)
_legend_top_left(fig)
return fig_to_html(fig)
def plot_runs_overlay(
df: pd.DataFrame,
run_df: pd.DataFrame,
tit... | Python | 1 |
ygen_set = oxygen_set.intersection(&diagnostics_by_bits[index].ones).map(|d|d.to_string()).collect();
}
index += 1;
}
// co2
index = 0;
while co2_set.len() > 1 {
let bit_count = count_bits_at_index(&co2_set, index);
if bit_count.zeros > bit_count.ones {
co2_set = co2_set.intersection(&d... | Rust | 0 |
ern (default: "*" for every day)
exclude_server_id: Optional server ID to exclude when checking restart conflicts
Returns:
Complete cron expression string (5 fields: minute hour day month weekday)
"""
hour, minute = await self.find_next_available_restart_time(exclude_ser... | Python | 1 |
irst_wav)
return alignment
# In[5]:
def create_combined_wav_audio_sample(
wav_list,
samplerate = 44100,
alignment = None,
wfn = "output.wav", # WriteFileName
nbits = 16,
force_mono = False,
):
'''Combines the wav files after aligning
so you can listen and see if they are ... | Python | 1 |
farm.eq(&Farm::Orca {
name: Orca::UNKNOWN
}));
assert!(farm.name().eq(&"ORCA-UNKNOWN".to_string()));
assert!(Farm::from(Orca::from("UNKNOWN")).eq(&Farm::Orca {
name: Orca::UNKNOWN
}));
let farm2 = Farm::from([2_u64, 6969420_u64]);
assert!(farm.eq(&... | Rust | 0 |
ze).strip()
return result
def get_paragraph_max_height(paragraph: PdfParagraph) -> float:
"""
获取段落中最高的排版单元高度。
Args:
paragraph: PDF 段落对象
Returns:
float: 最大高度值
"""
max_height = 0.0
for composition in paragraph.pdf_paragraph_composition:
if composition is None:
... | Python | 1 |
API/Document/convertPointFromNode)"]
#[doc = ""]
#[doc = "*This API requires the following crate features to be activated: `Document`, `DomPoint`, `DomPointInit`*"]
pub fn convert_point_from_node_with_document(
this: &Document,
point: &DomPointInit,
from: &Document,
) -> Result<D... | Rust | 0 |
rY rZ r[ r\ r] r^ r_ rs )rc r\ ro r rS rU rT r r
r rx r torch_definitionsr torch_cflags
torch_ldflagsr r torch_passthrough_argsr! s r) rd CppTorchOptions.__init__X %##/%
"
"+%/-
... | Python | 1 |
lines.add(_g)
return lines
class ExitCode(IntEnum):
"""Enums for TarTeX exit codes"""
SUCCESS = 0
FAIL_GENERIC = 1
FAIL_CACHE = 2
FAIL_GIT = 3
FAIL_LATEXMK = 4
FAIL_TAR = 5
class SetEncoder(json.JSONEncoder):
"""A class to allow JSONEncoder to interpret ... | Python | 1 |
== 0 {
return String::from("zero");
}
let mut number:u64 = input;
let mut result = String::new();
if number >= 1_000_000_000_000_000_000 {
number /= 1_000_000_000_000_000_000;
result.push_str(&translate_hundreds(number));
result.push_str(" quintillion ");
numbe... | Rust | 0 |
"""
data_exploration.py
Written by Yin-Xi Chloe Lin, Alice Kjar and Annisa Chyntia Yusup for COMP20008 Assignment 2
Graphing of subplots adapted from https://matplotlib.org/stable/gallery/statistics/histogram_multihist.html
"""
from matplotlib import pyplot as plt
import pandas as pd
from wordcloud import WordCloud
... | Python | 1 |
Result<Layout> {
ctx.resolve_item((*self).into()).try_get_layout(ctx, &())
}
}
impl<T> TryToRustTy for T
where
T: Copy + Into<ItemId>
{
type Extra = ();
fn try_to_rust_ty(
&self,
ctx: &BindgenContext,
_: &(),
) -> error::Result<quote::Tokens> {
ctx.resolve_i... | Rust | 0 |
he lifetime for a consensus, return the time range during which
/// clients should fetch the next one.
fn client_download_range(lt: &Lifetime) -> (SystemTime, Duration) {
let valid_after = lt.valid_after();
let fresh_until = lt.fresh_until();
let valid_until = lt.valid_until();
let voting_interval = fre... | Rust | 0 |
import pandas as pd
import numpy as np
from scipy import stats
class PerformanceAnalyzer:
def __init__(self, config):
self.metrics = config['analysis']['metrics']
self.grouping = config['analysis']['grouping']
def calculate_department_metrics(self, df):
"""Calculate key metrics by ... | Python | 1 |
# Sidebar
display_sidebar()
# Inicialización del agente
if not st.session_state.agent_initialized:
st.markdown('<div class="info-box">🚀 <strong>Inicializando sistema...</strong> El agente se está configurando para conectar con los sensores remotos.</div>', unsafe_allow_html=True)
... | Python | 1 |
pub fn to_oct_key(self, key_len: usize) -> Result<Cow<'a, [u8]>> {
match self {
Secret::Arr(arr) => {
if arr.len() >= key_len {
return Ok(Cow::Borrowed(arr));
}
}
Secret::Jwk(jwk) => {
let params: &JwkParamsOct = jwk.try_oct_params()?;
let k: Vec<u8> = d... | Rust | 0 |
rror;
fn try_from((config, account_name): (&'a Config, Option<&str>)) -> Result<Self, Self::Error> {
debug!("init account `{}`", account_name.unwrap_or("default"));
let (name, account) = match account_name.map(|name| name.trim()) {
Some("default") | Some("") | None => config
... | Rust | 0 |
# Copyright (c) 2023 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 appli... | Python | 1 |
'a>(
&self,
parameter: &'a ParameterData<ChalkIr>,
) -> &'a ParameterData<ChalkIr> {
parameter
}
fn intern_goal(&self, goal: GoalData<ChalkIr>) -> Arc<GoalData<ChalkIr>> {
Arc::new(goal)
}
fn goal_data<'a>(&self, goal: &'a Arc<Goa... | Rust | 0 |
;
} else {
let start_date = hour;
let end_date = hour + chrono::Duration::hours(1);
let mut production_metrics = ProductionMetrics::new(model, start_date, end_date);
production_metrics.update((prediction, true_value));
let data = serde_json::to_string(&production_metrics)?;
sqlx::query(
"
insert int... | Rust | 0 |
# -*- coding: utf-8 -*-
#use: python file_check.py ./
import os
import hashlib
import shutil
import ntpath
import time
CWD = os.getcwd()
FILE_MD5_DICT = {} # 文件MD5字典
ORIGIN_FILE_LIST = []
# 特殊文件路径字符串
Special_path_str = 'drops_JWI96TY7ZKNMQPDRUOSG0FLH41A3C5EXVB82'
bakstring = 'bak_EAR1IBM0JT9HZ75WU4Y3Q8KLPCX26ND... | Python | 1 |
# Section 4.8 snippets
import math
ma # press <Tab> after ma
# Viewing Identifiers in a Module
math. # press <Tab> after the dot
# Using the Currently Highlighted Function
math.fabs?
##########################################################################
# (C) Copyright 2019 by Deitel & Associates, Inc. an... | Python | 1 |
import typer
from pathlib import Path
import numpy as np
def part1(records: list[np.ndarray]):
is_ok = 0
for record in records:
is_ok += is_safe(record)
return is_ok
def is_safe(record: np.ndarray) -> bool:
all_increasing = (record[1:] > record[:-1]).all()
all_decreasing = (record[1:] < ... | Python | 1 |
import urllib.request, urllib.parse, urllib.error
import xml.etree.ElementTree as ET
import ssl
sum = 0
count = 0
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
url = input('Enter url: ')
uh = urllib.request.urlopen(url, context=ctx)
dat... | Python | 1 |
TODO slerp on quat
//TODO inverse on mats
//TODO add .as_quat() on vec4
//TODO .extend() on mats, .sub_mat2() .sub_mat3() on mats
//TODO .extend(s) on Vectors
//TODO to_quat() to_mat3() to_angle_axis() on quat and mat3 (as applicable)
//TODO to_rotation_angle() on mat2
//TODO static look_at() on mat3
//TODO add rotate(... | Rust | 0 |
&String) {
let timestamp = ctx.timestamp().clone();
tracing::debug!("SinkOperator @ {:?}: Received {}", timestamp, data,);
}
fn on_watermark(&mut self, _ctx: &mut SinkContext<()>) {}
}
// Defines a function that converts a ROS String message to a vector containing an ERDOS message
// with Str... | Rust | 0 |
mb_values = np.asarray(mb_values, dtype=np.float32).swapaxes(0, 1)
mb_dones = np.asarray(mb_dones, dtype=np.bool).swapaxes(0, 1)
mb_masks = mb_dones[:, :-1]
mb_dones = mb_dones[:, 1:]
true_rewards = np.copy(mb_rewards)
last_values = self.model.value(self.obs, self.states, self.d... | Python | 1 |
` from a view pair mapped to
/// their Sub-address indexes
pub fn new(keys: &'a ViewPair, major: Range<u32>, minor: Range<u32>) -> Self {
let mut table = HashMap::new();
major.for_each(|maj| {
minor.clone().for_each(|min| {
let index = Index {
majo... | Rust | 0 |
Documented below. A maximum of 1 are allowed.
"""
return pulumi.get(self, "retry_policy")
@_builtins.property
@pulumi.getter(name="roleArn")
def role_arn(self) -> pulumi.Output[Optional[_builtins.str]]:
"""
The Amazon Resource Name (ARN) of the IAM role to be used for this t... | Python | 1 |
할 경우 radius와 함께 사용 가능
y (str): 중심 좌표의 Y 혹은 위도(latitude) 값. 특정 지역을 중심으로 검색할 경우 radius와 함께 사용 가능
radius (str): 중심 좌표부터의 반경거리. 특정 지역을 중심으로 검색하려고 할 경우 중심좌표로 쓰일 x,y와 함께 사용. (단위: 미터(m), 최소: 0, 최대: 20000)
rect (str): 사각형의 지정 범위 내 제한 검색을 위한 좌표. 지도 화면 내 검색 등 제한 검색에서 사용 가능. 좌측 X 좌표, 좌측 Y 좌표, 우... | Python | 1 |
from livre import Livre
livre1 = Livre("Les Misérables", "Victor Hugo", 3)
livre2 = Livre("Les fleurs du mal", "Charles Baudelaire", 1)
print(livre1)
print('*'*10)
livre2.degrade()
print(livre2) | Python | 1 |
/// Auxiliary information
NOTE = 4,
/// Reserved
SHLIB = 5,
/// Entry for header table itself
PHDR = 6,
/// Thread-local storage segment
TLS = 7,
/// Number of defined types
NUM = 8,
/// GCC .eh_frame_hdr segment
GNU_EH_FRAME = 0x6474e550,
/// Indicates stack executa... | Rust | 0 |
pub fn set_arc_mode(&mut self, val: bool) -> &mut Self {
if val {
self.inner |= 1 << 22;
} else {
self.inner &= !(1 << 22);
}
self
}
#[inline]
pub fn new(
function: bool,
plane_mask: bool,
foreground: bool,
background: b... | Rust | 0 |
sanitized_name = sanitize_identifier(&symbol.r#type);
let method_name = format_ident!("visit_{}", sanitized_name);
let doc_name = format!("{:?}", raw_name).replace('`', "\\`");
let doc_string = format!("Visits a node of type `{}`", doc_name);
let trait_fn: TraitItem = p... | Rust | 0 |
0,
},
Point {
interval: now - 14,
value: 1400.0,
},
] {
file.update(point, now)?
}
let points = file.dump(2)?;
for delta in &[2, 4, 6, 8, 10, 12, 14, 16] {
assert!(
points.iter().any(|p| p.interval == (now - delta)
... | Rust | 0 |
1 + x),
}
});
horizontal * vertical
}
pub fn determine_aimed_position(input: &[Position]) -> i64 {
let nav = input.iter().fold(Navigation::default(), |acc, item| {
match item {
Position::Forward(x) => acc.forward(*x),
Position::Up(x) => acc.up(*x),
Posit... | Rust | 0 |
}
fn poly_poly_inter(su1: &ShapeUnion, su2: &ShapeUnion) -> bool {
unsafe { su1.poly.poly_test(&su2.poly) }
}
type ShapeTestHeader = fn(&ShapeUnion, &ShapeUnion) -> bool;
const SHAPE_JUMP_TABLE: [[ShapeTestHeader; 3]; 3] = [
[circle_circle_inter, circle_aabb_int... | Rust | 0 |
/ (2 * math.sqrt(T))
return (
(
term
- r * K * math.exp(-r * T) * norm.cdf(d2)
+ r * F * math.exp(-r * T) * norm.cdf(d1)
)
/ 252
if is_call
else (
term
+ r * K * math.exp(-r * T) * norm.cdf(-d2)
- r * F ... | Python | 1 |
sql.pest`.
//! The syntax is written in [PEG](https://en.wikipedia.org/wiki/Parsing_expression_grammar).
//!
//! This file is internally parsed by [pest](https://github.com/pest-parser/pest)
//! but the main purpose is to describe the apllodb-SQL syntax for humans.
//!
//! # APIs Overview
//!
//! `ApllodbSqlParser` pro... | Rust | 0 |
tch()
if mode == 2:
# OK or Cancel
if key_in in [9, curses.KEY_LEFT, curses.KEY_RIGHT]:
tab = [1, 0][tab]
if key_in in [ord('a'), ord('c')]:
key_in -= (ord('a') - ord('A'))
if ... | Python | 1 |
se std::collections::HashMap;
/// use std::borrow::Borrow;
///
/// let mut hashmap: HashMap<Vec<String>, usize> = HashMap::default();
/// let _ = hashmap.insert(vec!["a".to_string(), "b".to_string()], 123);
///
/// // Let's try to retrieve the value
/// // The following won't compile
///... | Rust | 0 |
#!/usr/bin/env python3
# --- Copyright Disclaimer ---
#
# In order to support PyInstaller with numpy<1.20.0 this file will be duplicated for a short period inside
# PyInstaller's repository [1]. However this file is the intellectual property of the NumPy team and is
# under the terms and conditions outlined their repo... | Python | 1 |
# This file was generated by 'versioneer.py' (0.22) from
# revision-control system data, or from the parent directory name of an
# unpacked source archive. Distribution tarballs contain a pre-generated copy
# of this file.
import json
version_json = '''
{
"date": "2024-11-30T11:04:11-0800",
"dirty": false,
"error... | Python | 1 |
from django.contrib import admin
from .models import Fanmavzusi
# Register your models here.
admin.site.register(Fanmavzusi)
| Python | 1 |
tent in prompt_message.content:
if isinstance(content, dict):
if content.get("type") == "text":
text += "\n" + content.get("text", "")
elif content.get("type") == "image_url":
image_url = content.... | Python | 1 |
import json
def remove_duplicates_from_json(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
lines = file.readlines()
unique_lines = []
seen = set()
for line in lines:
parts = line.strip().split()
if len(parts) > 1 and parts[1] not in seen:
... | Python | 1 |
#[macro_use]
mod macros;
mod error;
#[cfg(feature = "image")]
pub mod image;
#[cfg(feature = "runtime")]
pub mod runtime;
pub use error::*;
/*!
All test cases are placed within this module.
We expose the modules as public so that cargo doc
will pick up the definition by default.
*/
pub mod clear_packet;
pu... | Rust | 0 |
contents = {}
contents["sbd"]= '''On {nodeA}, once the sbd process get killed, there are two situations:
a) sbd process restarted
Systemd will restart sbd service immediately.
Restarting sbd service will also lead to restart corosync and pacemaker services because of the pre-defined dependencies among the ... | Python | 1 |
::MockListener::new();
mock_listener.expect_info().times(1).return_const(());
let mut scripts = ScriptFragments::new();
match debhelper_script_subst(Path::new(""), &mut scripts, "mypkg", "myscript", None, &mut mock_listener) {
Ok(_) => (),
Err(CargoDebError::DebHelperRe... | Rust | 0 |
from typing import Dict, Optional, Union
import time
from ..client import SeamHttpClient
from ..exceptions import SeamActionAttemptFailedError, SeamActionAttemptTimeoutError
from ..routes.models import ActionAttempt
TIMEOUT = 5.0
POLLING_INTERVAL = 0.5
def get_action_attempt(client: SeamHttpClient, action_attempt_i... | Python | 1 |
e(color) = *opt_color {
cube.set_color(color[0], color[1], color[2]);
}
Ok(cube)
}
urdf_rs::Geometry::Cylinder { radius, length } => {
let mut base = group.add_group();
let mut cylinder = base.add_cylinder(radius as f32, length as f32);
... | Rust | 0 |
import pyautogui as pa
import time
import pyperclip as pc # Necessário para lidar com caracteres especiais
# Configuração de pausa para segurança entre comandos
pa.PAUSE = 1
def abrir_navegador():
"""Abre o navegador Chrome usando o menu iniciar."""
pa.press('win') # Pressiona a tecla Windows
pa.write('... | Python | 1 |
king_loss",
"log_loss",
"make_scorer",
"nan_euclidean_distances",
"matthews_corrcoef",
"max_error",
"mean_absolute_error",
"mean_squared_error",
"mean_squared_log_error",
"mean_pinball_loss",
"mean_poisson_deviance",
"mean_gamma_deviance",
"mean_tweedie_deviance",
"me... | Python | 1 |
# Suma números en un rango
def suma_rango(ini, fin):
s = 0
for i in range(ini, fin+1):
s += i
return s
print(f'{suma_rango(1,3)}') | Python | 1 |
# coding: utf-8
# ## Writeup for _Acebear Security Contest 1/2018_
# ### (Crypto challenge) _CNV Service_
# #### Tóm tắt đề bài
# Cho dịch vụ tại _cnvservice.acebear.site:1337_ gồm 2 lựa chọn như sau:
# - _Register_: Người dùng gửi lên `name` và `username`, server trả về bản mã của cookie là một chuỗi văn bản có các ... | Python | 1 |
{
#[allow(unused_mut)]
let mut scope_173 = writer.prefix("ContainerFormat");
if let Some(var_174) = &input.container_format {
scope_173.string(var_174.as_str());
}
#[allow(unused_mut)]
let mut scope_175 = writer.prefix("DiskImageFormat");
if let Some(var_176) = &input.disk_image_for... | Rust | 0 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-05 17:02
from __future__ import unicode_literals
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('crm', '... | Python | 1 |
y--write-api).\n\nFor information about available fields see [puel](index.html) module"]
pub struct PUEL_SPEC;
impl crate::RegisterSpec for PUEL_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [puel::R](R) reader structure"]
impl crate::Readable for PUEL_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..... | Rust | 0 |
fn get_filter_from_hash() -> Self {
let hash = web_sys::window().unwrap().location().hash().unwrap();
match hash.as_str() {
"#/active" => Filter::Active,
"#/completed" => Filter::Completed,
_ => Filter::All,
}
}
}
#[derive(Debug, Default, Clone)]
pu... | Rust | 0 |
oc(hidden)]
pub struct _CSI_DATA06_SELECT_INPUT;
#[doc = "`read()` method returns [csi_data06_select_input::R](csi_data06_select_input::R) reader structure"]
impl crate::Readable for CSI_DATA06_SELECT_INPUT {}
#[doc = "`write(|w| ..)` method takes [csi_data06_select_input::W](csi_data06_select_input::W) writer structur... | Rust | 0 |
#!/usr/bin/env python
"""
Example: Using OllamaModelHandler with GitCogni
This script demonstrates how to use the OllamaModelHandler with GitCogni
to review a PR using a local model from Ollama instead of OpenAI API.
"""
import sys
import logging
from pathlib import Path
# Add project root to Python path
project_roo... | Python | 1 |
t remote_terminal: RemoteTerminal| -> bool {
let mut step_is_complete = false;
if remote_terminal.cursor_position_is(119, 20) {
// all lines have been written to the pane
remote_terminal.send_key(&SCROLL_MODE);
remote_terminal.s... | Rust | 0 |
predicate(*c))?;
let mut ix = 1;
for c in s.get(1..)? {
if !predicate(*c) {
break;
}
ix += 1;
}
Some((&s[ix..], &s[0..ix]))
}
}
pub fn many<'a, P, R>(parser: P) -> impl Fn(&'a [u8]) -> ParseResult<Vec<R>>
where
P: Fn(&'a [u8... | Rust | 0 |
GTraverseFlags = c_uint;
pub const G_TRAVERSE_LEAVES: GTraverseFlags = 1;
pub const G_TRAVERSE_NON_LEAVES: GTraverseFlags = 2;
pub const G_TRAVERSE_ALL: GTraverseFlags = 3;
pub const G_TRAVERSE_MASK: GTraverseFlags = 3;
pub const G_TRAVERSE_LEAFS: GTraverseFlags = 1;
pub const G_TRAVERSE_NON_LEAFS: GTraverseFlags = 2;
... | Rust | 0 |
d `FrameFreezeClock` for `Hit` interactions.
let Interaction {
kind: InteractionKind::Hit(_),
..
} = ev.interaction;
let frame_freeze_clock = FrameFreezeClock::new(3);
frame_freeze_clocks
.insert... | Rust | 0 |
verifier(v, pos)
}
}
impl flatbuffers::SimpleToVerifyInSlice for RpcMessage {}
pub struct RpcMessageUnionTableOffset {}
use super::util::{EventAggregator, HasTypeInfo, TypeInfo};
use mun_memory::gc::{Event, GcRootPtr, GcRuntime, MarkSweep};
use std::sync::Arc;
#[test]
fn alloc() {
let runtime = MarkSweep::<&'s... | Rust | 0 |
ions, with func to parse the option values, and match func
// to valid the values
($param:ident, $key:ident, $field:expr, $func:ident, $guard:expr) => {
if $param.starts_with(format!("{}=", $key).as_str()) {
let val = $func($param)?;
if $guard(val) {
$field = val;... | Rust | 0 |
# common/utils_ts.py
# 封装所有与 Tushare API 相关的通用函数
import tushare as ts
import pandas as pd
import time
from common import config
def initialize_tushare():
"""使用config中的token初始化tushare并返回pro_api实例"""
if config.TUSHARE_TOKEN == 'YOUR_REAL_TOKEN_HERE' or not config.TUSHARE_TOKEN:
raise ValueError("Tushare... | Python | 1 |
# Copyright 2020 The HuggingFace Datasets Authors and the TensorFlow Datasets Authors.
#
# 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
#
# U... | Python | 1 |
`Peripherals::take`"]
#[inline]
pub unsafe fn steal() -> Self {
DEVICE_PERIPHERALS = true;
Peripherals {
WATCHDOG0: WATCHDOG0 { _marker: PhantomData },
WATCHDOG1: WATCHDOG1 { _marker: PhantomData },
SSI0: SSI0 { _marker: PhantomData },
SSI1: SSI1 ... | Rust | 0 |
# -*- coding: utf-8 -*-
"""
Created on Sat May 13 20:07:10 2023
@author: 24807
"""
# 用python语言编写一个程序:实现以下步骤:
#①在一个有向图中,为各条边进行编号,编号名称为edge_id。找到该有向图中的所有环,为各环进行编号,编号名称为circuit_id
#②计算各条边分别经过几个环,统计该数据(称该数据为该边的重复值),用duplicate_values表示
#③找到duplicate_values最大的那条边,删除该边及该边所在的环。然后再次重复②、③步骤。
#④若在进行上述操作后,图中仍存在环,且环中各边的重复值相同。则选... | Python | 1 |
let data: TaskTransfer = data_transfer.get_data();
// assign task to human
Msg::Assign(data)
});
let status_class = format!("human-status-{}", self.props.status);
let name_style = format!("border-color: {}", self.props.color);
let outer_classes = match (self.... | Rust | 0 |
fn extends(&self) -> harfbuzz_sys::hb_font_extents_t {
let mut extends = harfbuzz_sys::hb_font_extents_t {
ascender: 0,
descender: 0,
line_gap: 0,
reserved1: 0,
reserved2: 0,
reserved3: 0,
reserved4: 0,
reserved5... | Rust | 0 |
'''
服务器
和客户端编程相比,服务器编程就要复杂一些。
'''
'''
服务器进程首先要绑定一个端口并监听来自其他客户端的连接。
如果某个客户端连接过来了,服务器就与该客户端建立Socket连接,随后的通信就靠这个Socket连接了。
'''
'''
服务器会打开固定端口(比如80)监听,每来一个客户端连接,就创建该Socket连接。
由于服务器会有大量来自客户端的连接,所以,服务器要能够区分一个Socket连接是和哪个客户端绑定的。
一个Socket依赖4项:服务器地址、服务器端口、客户端地址、客户端端口来唯一确定一个Socket。
'''
'''
服务器还需要同时响应多个客户端的请求
所以,每个连接都需要一个新的进程或者新... | Python | 1 |
(board: Board, color: Color) -> ScoreTy {
let new_board = if board.side_to_move() == color {
Some(board)
} else {
board.null_move()
};
return (new_board
.map(|b| b.enumerate_moves(&mut [ChessMove::default(); 256]))
.unwrap_or(20) as ScoreTy)
/ 3
* MOBILIT... | Rust | 0 |
just to make sure no errors happened.
stmt.execute(params!{
"customer_id" => p.customer_id,
"amount" => p.amount,
"account_name" => &p.account_name,
}).unwrap();
}
}
// Let's select payments from database
let selected_payments... | Rust | 0 |
u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). S... | Rust | 0 |
atoms
fig, ax = plt.subplots(figsize=figsize)
ax.scatter(X_pca[0],X_pca[1],c=dat['NIONS'],cmap='rainbow',alpha=0.5,s=5)
ax.set_xlabel('PC1')
ax.set_ylabel('PC2')
# set colorbar
sm = plt.cm.ScalarMappable(cmap='rainbow', norm=plt.Normalize(vmin=dat['NIONS'].min(), vmax=dat['NIONS'].max()))
# add the colorbar to the figu... | Python | 1 |
def starts_one_ends(n):
"""
Given a positive integer n, return the count of the numbers of n-digit
positive integers that start or end with 1.
"""
# Your code here
if n == 0:
return 0
elif n == 1:
return 1
else:
return int(str(10**n - 9*10**(n-1) + 10**(n-1))/10) ... | Python | 1 |
from typing import TYPE_CHECKING
from langchain_community.document_loaders.parsers.language.tree_sitter_segmenter import ( # noqa: E501
TreeSitterSegmenter,
)
if TYPE_CHECKING:
from tree_sitter import Language
CHUNK_QUERY = """
[
(create_table_statement) @create
(select_statement) @selec... | Python | 1 |
shape.set_no_err(0, 2, color);
shape.set_no_err(1, 2, color);
shape
}
fn get_j_shape(color: Colors) -> Desk {
let color = Some((color, true));
let mut shape = Desk::new(2,3);
shape.set_no_err(1, 0, color);
shape.set_no_err(1, 1, color);
shape.set_no_err(1, 2, color);
shape.set_no_err(0,... | Rust | 0 |
:Decoder as GzDecoder;
use sqs_executor::errors::{CheckedError,
Recoverable};
#[derive(Debug, PartialEq)]
pub enum PayloadDecompression {
Gzip,
None,
Zstd,
}
impl FromStr for PayloadDecompression {
type Err = ();
fn from_str(input: &str) -> Result<PayloadDecompression, S... | Rust | 0 |
settings_name = widget.settings_name
setting_t = tuple(setting + [settings_name])
settings.set(*setting_t, value=value)
def confirm_action_dialog():
msgBox = QMessageBox()
msgBox.setWindowTitle("Confirmation")
msgBox.setText("Are you sure?")
msgBox.setStandardButtons(QMessageBox.O... | Python | 1 |
regex_automata::Error> {
/// // First, build a regex that uses dense DFAs.
/// let dense_re = Regex::new("foo[0-9]+")?;
///
/// // Second, build sparse DFAs from the forward and reverse dense DFAs.
/// let fwd = dense_re.forward().to_sparse()?;
/// let rev = dense_re.reverse().to_sparse()?;
///
/// // Third, build a n... | Rust | 0 |
string(&self.message)?,
])?;
}
Ok(String::from_utf8(buf)?)
}
}
impl TryFrom<quick_csv::Row> for Entry {
type Error = Error;
fn try_from(r: quick_csv::Row) -> Result<Self> {
let mut cols = r.columns()?;
let date = cols
.next()
.ok_or_else... | Rust | 0 |
[error("node '{alias}' failed to shutdown, message: {message}")]
NodeFailedToShutdown {
alias: String,
message: String,
#[debug(skip)]
logs: Vec<String>,
},
}
/// send query to a running node
pub struct VitStationController {
alias: NodeAlias,
rest_client: RestClient,
... | Rust | 0 |
.0, -1));
println!("Sigmoid: {:?}", Sigmoid::<2>::sigmoid(out_act_mat.clone()));
}pub mod stage_1;
pub mod stage_2;
mod baggage;//! Test utilities
use bls12_381::{G2Projective, Scalar};
/// Convert an unsigned number into the corresponding field element. This is so
/// that we can make tests on Scalar that are e... | Rust | 0 |
import torch
class FGM():
'''
Example
# 初始化
fgm = FGM(model,epsilon=1,emb_name='word_embeddings.')
for batch_input, batch_label in data:
# 正常训练
loss = model(batch_input, batch_label)
loss.backward() # 反向传播,得到正常的grad
# 对抗训练
fgm.attack() # 在embedding上添加对抗扰动
... | Python | 1 |
seek_to_min(self.raw)})
}
/// Move to the max key in range
pub fn to_max_key(&self) -> FdbResult<()> {
lift_error!(unsafe {ffi::fdb_iterator_seek_to_max(self.raw)})
}
/// Moves to specified key, uses options to determine what to do
/// if key wasn't found
pub fn to_key<K>(&self, ke... | Rust | 0 |
let faster_pulse = [0, 1, 2, 1];
let fastest_pulse = [0, 2];
for _ in 0..1 {
for _ in 0..4 {
flash_backlight(&mut backlights, &mut delay, &slower_pulse)?;
}
for _ in 0..4 {
flash_backlight(&mut backlights, &mut delay, &slow_pul... | Rust | 0 |
val_labels, all_val_preds
def test_model(model, test_loader, device):
"""
Evaluates the model on the provided test data loader.
Args:
model (torch.nn.Module): The model to evaluate.
test_loader (torch.utils.data.DataLoader): The data loader providing test batches.
device (torch.dev... | Python | 1 |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# NO CHECKED-IN PROTOBUF GENCODE
# source: quote_statistics.proto
# Protobuf Python Version: 6.31.0
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool a... | Python | 1 |
divider.append_axes('right', size='5%', pad=0.2)
im = ax.imshow(errmap, cmap = 'jet', vmin = 0.0, vmax = 0.2)
fig.colorbar(im, cax=cax, orientation='vertical')
im.set_data(colors)
plt.savefig('./heat_map/' + str(batchindex) + '_' + str(i) + ' ' + datatype + '.png')
bestoffset[i]... | Python | 1 |
}
Ok(())
}
fn test() -> io::Result<()> {
// println!("File extensions, registered in system:");
for i in RegKey::predef(HKEY_CLASSES_ROOT)
.enum_keys().map(|x| x.unwrap())
.filter(|x| x.starts_with("."))
{
println!("root打印{}", i);
}
println!("开始打印user:");
for i in RegKey::predef... | Rust | 0 |
# The MIT License (MIT)
# Copyright © 2023 Yuma Rao
# Copyright © 2025 Mobius Fund
# 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 right... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.