text
string
label_name
string
labels
int64
led = fail_s + fail_d if not options.quiet: count_passed = done_d + done_s - count_failed print(("%d passed and %d failed." % (count_passed, count_failed))) print(("Test failed." if count_failed else "Test passed.")) if count_failed: sys.exit(1) if opt...
Python
1
import pytest from librelingo_fakes import fakes from librelingo_json_export.export import _export_course_skills from librelingo_json_export.settings import DEFAULT_SETTINGS from librelingo_types import Module @pytest.fixture def export_path(): return fakes.path() @pytest.fixture def mock_export_skill(mocker): ...
Python
1
#!/usr/bin/env python """ Dummy script to handle the case where TensorFlow 1.x is not available """ import os import sys import numpy as np # Create a basic path setup for benchmarking def create_dummy_paths(relation): """Create dummy path files for benchmarking""" repo_root = os.path.abspath(os.path.join(os.p...
Python
1
行时的当前任务,并在指定的其它运行时上派发一个指定的异步任务,等待其它运行时上的异步任务完成后,唤醒当前运行时的当前任务,并返回其它运行时上的异步任务的值 pub async fn wait<R, V, F>(&self, rt: AsyncRuntime<R>, future: F) -> Result<V> where R: Default + 'static, V: Send + 'static, F: Future<Output = Result<V>> + Send + 'static { AsyncWait::new...
Rust
0
-> ArrowWhen: return ArrowWhen.from_expr(predicate, context=self) def concat_str( self, *exprs: ArrowExpr, separator: str, ignore_nulls: bool ) -> ArrowExpr: def func(df: ArrowDataFrame) -> list[ArrowSeries]: align = self._series._align_full_broadcast compliant_...
Python
1
ple(sig[lo:hi]) buckets[(band, band_val)].append(idx) # 4. Candidate duplicate pairs (by bucket, undirected, distinct) candidate_pairs = set() for bucket in buckets.values(): if len(bucket) > 1: for i in range(len(bucket)): ...
Python
1
xx:f64,yy:f64,zz:f64,angle:(f64,f64,f64,f64))->(f64,f64,f64){ let px = xx*angle.2-yy*angle.3; let py = xx*angle.3+yy*angle.2; let rx = px*angle.0-zz*angle.1; let rz = px*angle.1+zz*angle.0; return (rx,py,rz); } /** * * t1<-t2->t3 というベクトルが作る三角形を s1<-s2->s3 というベクトルが作る三角形に合うように vset を回転する ...
Rust
0
"/demonlist/statsviewer/heatmap.css")] pub async fn heatmap_css(state: PointercrateState) -> ViewResult<HttpResponse> { let mut connection = state.connection().await?; let mut css = String::new(); let mut stream = sqlx::query!(r#"SELECT iso_country_code as "code!", score as "score!" from nations_with_score...
Rust
0
sub_r(val2, flag.into()); (Number::from(res.value), res.status) } Layout::Float(FloatLayout::IeeeQuad) => { let val1 = ieee::Quad::from(self); let val2 = ieee::Quad::from(rhs); let res = val1.sub_r(val2, flag.into()); ...
Rust
0
from backend.game_engine.chess_engine import ChessEngine from backend.game_engine.cn_chess_engine import CNChessEngine from backend.game_engine.js_red_alert_engine import JSRedAlertEngine from typing import Dict, Any, Optional import time import logging from functools import lru_cache from tenacity import retry, stop_a...
Python
1
audio_semantic_result = self.audio_self_att(audio_semantic_result)# [length, batch, hidden_dim] audio_semantic_result = audio_semantic_result.transpose(0, 1).contiguous() # [batch, length, hidden_dim] audio_vq, video_vq, text_vq, a_quant_list, v_quant_list,t_quant_list, audio_embedding_loss, video_em...
Python
1
dden)] pub struct _UCA0BRW_SPI; #[doc = "`read()` method returns [uca0brw_spi::R](uca0brw_spi::R) reader structure"] impl crate::Readable for UCA0BRW_SPI {} #[doc = "`write(|w| ..)` method takes [uca0brw_spi::W](uca0brw_spi::W) writer structure"] impl crate::Writable for UCA0BRW_SPI {} #[doc = "eUSCI_Ax Bit Rate ...
Rust
0
: "volatile"); } // Mock implementation for tests on Travis-CI. #[cfg(not(any(target_arch = "arm", target_os = "none")))] pub unsafe extern "C" fn hard_fault_handler() { unimplemented!() } #[cfg(all(target_arch = "arm", target_os = "none"))] #[naked] pub unsafe extern "C" fn hard_fault_handler() { let fa...
Rust
0
import os from google.genai import types schema_write_files = types.FunctionDeclaration( name="write_files", description="Writes to a file, constrained to the working directory. Creates the file if it doesn't exist.", parameters=types.Schema( type=types.Type.OBJECT, properties={ ...
Python
1
from kivy.lang import Builder from kivy.properties import StringProperty, NumericProperty, ListProperty from kivy.metrics import dp from kivy.clock import Clock from kivymd.app import MDApp from kivymd.uix.screen import MDScreen from github_api import get_latest_release import requests import os KV = ''' MDNavigationL...
Python
1
criterion, eg. DF_STOP_ON_CALL. or other features, eg. DF_RETURN_FC_ONLY. @rtype: generator of TODO @return: Generator of TODO @raise ValueError: Invalid arguments. """ if not code: return if not codeOffset: codeOffset = 0 if dt not in (Decode16Bits...
Python
1
to dwell\nI walk down a lonely street to Heartbreak Hotel." | "Since my baby left me I found a new place to dwell\nDown at the end of 'Lonely Street' to 'Heartbreak Hotel.'" | EditDistance | (27, "f"), (30, "und"), (56, "Down"), (64, "t the"), (72, "en"), (75, " "), (77, "f"), (81, "...
Rust
0
from typing import Tuple import discord from rapidfuzz import process from redbot.core import commands from redbot.core.bot import Red from unidecode import unidecode async def is_allowed_by_role_hierarchy( bot: Red, bot_me: discord.Member, mod: discord.Member, role: discord.Role, ) -> Tuple[bool, st...
Python
1
Slice` type is centered // around the fact that the fields are all private, and so *safe rust* must // construct values of the type from an existing valid slice. However, because // the type is `repr(C)` it can of course be constructed with unsafe rust, or // even by foreign code. It is the responsibility of _the other...
Rust
0
b".to_string(), "aecbfdg fbg gf bafeg dbefa fcge gcbea fcaegb dgceab fcbdga | gecf egdcabf bgf bfgea".to_string(), "fgeab ca afcebg bdacfeg cfaedg gcfdb baec bfadeg bafgc acf | gebdcfa ecba ca fadegcb".to_string(), "dbcfg fgd bdegcaf fgec aegbdf ecdfab fbedc dacgb gdcebf gf | cefg dc...
Rust
0
from collections import defaultdict from django.core.management.base import BaseCommand from netbox.registry import registry from utilities.counters import update_counts class Command(BaseCommand): help = "Force a recalculation of all cached counter fields" @staticmethod def collect_models(): "...
Python
1
!("Warning: gamma1 is ignored because k1 or k2 is given.\n",); } if model.gamma2Given { println!("Warning: gamma2 is ignored because k1 or k2 is given.\n",); } } else { if !model.vbxGiven { size_params.vbx = size_params.phi - 7.7348...
Rust
0
type Components = RealtimeComponents; fn tick<R: Rng>(&mut self, rng: &mut R) -> TimeConsumingEvent<Self::Event> { let colour_hint = self.0.colour_hint.map(|r| r.choose(rng)); let light_colour = self.0.light_colour.map(|r| r.choose(rng)); let until_next_event = self.0.until_next_event.ch...
Rust
0
from opencompass.openicl.icl_prompt_template import PromptTemplate from opencompass.openicl.icl_retriever import ZeroRetriever, FixKRetriever from opencompass.openicl.icl_inferencer import GenInferencer from opencompass.datasets import TriviaQADataset, TriviaQAEvaluator triviaqa_datasets = [] for k in [0, 1, 5]: ...
Python
1
invindex().revindex(), &s.v, &s.i.invindex().revindex()) } } } /// Intersection of two RankedSets. /// Via OrderedSet for convenience, for now. /// Todo: Probably should use intersect_indexed as in `union` above. fn intersection(&self, s: &Self) -> OrderedSet<T> { let s1 = O...
Rust
0
def modify_immutable(x): x=10 print('inside function' ,x) a=5 modify_immutable(a) print('outside function ',a) def modify_mutable(lst): lst.append(5) print('inside function',lst) my_list=[1,2,3] modify_mutable(my_list) print('outside funtion',my_list)
Python
1
on tahoe-level for files) # Rate limiting might be useful to avoid excessive cpu/net usage on nodes, # and especially when uploading to rate-limited api's (like free cloud storages). # Only used when uploading objects to the grid, not when building queue file. # Format of each value is "interval[:burst]", wh...
Python
1
ound = 1814, ResourceLangNotFound = 1815, NotEnoughQuota = 1816, RpcSNoInterfaces = 1817, RpcSCallCancelled = 1818, RpcSBindingIncomplete = 1819, RpcSCommFailure = 1820, RpcSUnsupportedAuthnLevel = 1821, RpcSNoPrincipalName = 1822, RpcSNotRpcError = 1823, RpcSUuidLocalOnly = 1824...
Rust
0
from six import print_ from django.core.management.base import BaseCommand from ...base import get_registered_layout_uids, get_registered_plugin_uids from ...models import DashboardEntry __title__ = 'dash.management.commands.dash_find_broken_dashboard_entries' __author__ = 'Artur Barseghyan <artur.barseghyan@gmail.c...
Python
1
import matplotlib.pyplot as plt import numpy as np import woffl.flow.outflow as of from woffl.flow import jetflow as jf from woffl.flow import jetplot as jplt from woffl.flow import singlephase as sp from woffl.flow.inflow import InFlow from woffl.geometry.jetpump import JetPump from woffl.geometry.pipe import Annulus...
Python
1
}], output_types: vec![], }); // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2...
Rust
0
for pre-exponential factor # is too small. if -mux * np.sum((A - B) ** 2) <= cutoff: continue # Take symmetry into account, as we only loop over unique primitive # combinations. factor = 2.0 if ai == bi: factor = 1...
Python
1
<RawUri> for Uri { type Error = ErrorKind; fn try_from(raw_uri: RawUri) -> Result<Self> { let s = raw_uri.text; let s = s.trim_start_matches("mailto:"); if let Err(mail_err) = parse_email(s) { match Url::parse(s) { Ok(uri) => Ok(uri.into()), E...
Rust
0
loc, } } pub(crate) fn new_add_node( left: KTerm, right: KTerm, result: KVarTerm, cont: KNode, loc: Loc, ) -> KNode { new_basic_binary_op_node(KPrim::Add, left, right, result, cont, loc) } pub(crate) fn new_cast_node( ty: KTy2, arg: KTerm, result: KVarTerm, cont: KNode,...
Rust
0
import codecs import os from setuptools import setup, find_packages pwd = os.path.dirname(os.path.abspath(__file__)) # Get the long description with codecs.open(os.path.join(pwd, 'README.rst'), encoding='utf-8') as f: long_description = '\n{}'.format(f.read()) os.system("pwd") os.system("ls -lrt") # # Ge...
Python
1
"prowler.providers.aws.services.s3.s3_bucket_public_access.s3_bucket_public_access.s3_client", new=s3, ): with mock.patch( "prowler.providers.aws.services.s3.s3_bucket_public_access.s3_bucket_public_access.s3control_client", new=...
Python
1
=> Some(Lang::Slv), "hrv" => Some(Lang::Hrv), "srp" => Some(Lang::Srp), "mkd" => Some(Lang::Mkd), "lit" => Some(Lang::Lit), "lav" => Some(Lang::Lav), "est" => Some(Lang::Est), "tam" => Some(Lang::Tam), "vie" => Some(Lang::Vie), "urd" => Some(Lang:...
Rust
0
((A, B, C, D), (a, b, c, d)); impl_trait!((A, B, C, D, E), (a, b, c, d, e)); impl_trait!((A, B, C, D, E, F), (a, b, c, d, e, f)); impl_trait!((A, B, C, D, E, F, G), (a, b, c, d, e, f, g)); impl_trait!((A, B, C, D, E, F, G, H), (a, b, c, d, e, f, g, h)); impl_trait!((A, B, C, D, E, F, G, H, I), (a, b, c, d, e, f, g, h, ...
Rust
0
age.txt' try: content = self.load_message(filename) preview_msg = f"📄 **預覽檔案: {filename}**" if filename == self.default_message_file: preview_msg += " ⭐" preview_msg += "\n\n" preview_msg += "="...
Python
1
_SELECTED_WINDOW_FOCUSED_STATE_SET) // pub fn PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET<'env>(env: &'env __jni_bindgen::Env) -> __jni_bindgen::std::option::Option<__jni_bindgen::Local<'env, __jni_bindgen::IntArray>> { // unsafe { // let (class, field) = env.require_cl...
Rust
0
use crate::hash::hash_to_prime; use blake2::{digest::Digest, Blake2b}; use common::{ bigint::BigInteger, error::{AccumulatorError, AccumulatorErrorKind}, }; use std::convert::TryFrom; use crate::hash::hash_to_generator; /// Convenience module to include when using pub mod prelude { pub use crate::{ ...
Rust
0
""" 自然语言时间轴接口 集成自然语言处理器到现有的时间轴生成系统 """ import json import os from typing import Dict, Any, Optional from pathlib import Path from .natural_language_processor import NaturalLanguageProcessor from .timeline_generator import TimelineGenerator from .core.controller import Controller class NLTimelineInterface: """自然语...
Python
1
to_string(&deser).unwrap(); assert_eq!(ser, ser2); } <filename>src/editor.rs<gh_stars>1-10 // -------------------- // // editor use std::sync::Arc; use baseview::{Size, WindowScalePolicy, WindowOpenOptions}; use iced_baseview::{IcedWindow, Settings}; //use egui::CtxRef; //use egui_baseview::{EguiWindow, Queue, ...
Rust
0
tokens(&mut l)); } #[test] fn read_macro() { let mut l = SourceLexer::new( r#" #define ONE 1 int f(int x) { return x + ONE; }"#, ); insta::assert_debug_snapshot!(read_all_tokens_expanded(&mut l)); } #[test] fn read_macro2() { let mut l = SourceLexer::new( r#" #define F(x, y) (x) + (y) ...
Rust
0
table); // ANCHOR_END: here } #[path = "support/macros.rs"] #[macro_use] mod macros; mod support; use criterion::{criterion_group, criterion_main, Criterion}; use glam::Mat4; use std::ops::Mul; use support::*; bench_unop!( mat4_transpose, "mat4 transpose", op => transpose, from => random_srt_mat4...
Rust
0
# -*- coding: utf-8 -*- """ @summary: 股票指数 行情 @author: 1nchaos @date: 2023/06/01 16:17 """ from adata.stock.market.index_market.market_index_baidu import StockMarketIndexBaidu from adata.stock.market.index_market.market_index_east import StockMarketIndexEast from adata.stock.market.index_market.market_index_ths import ...
Python
1
, 7.0) * n2i(3.444510241015958, 11.0), n2i(7.860732745898387, 77.0) ); assert_eq2!( n2i(3.0, 3.444510241015958) * n2i(1.4901161193847656e-07, 2.2821046232627444), n2i(4.470348358154297e-07, 7.860732745898388) ); assert_eq2!( n2i(0.19162812091730785, 2.2821046232627444) * ...
Rust
0
::<f64>::from_urdf_file("../openrr-planner/sample.urdf").unwrap(); let end_link = chain.find("l_tool_fixed").unwrap(); let arm = k::SerialChain::from_end(end_link); let positions = vec![0.1, 0.2, 0.0, -0.5, 0.0, -0.3]; arm.set_joint_positions(&positions).unwrap(); let params = ik_solver_parameters(0...
Rust
0
_bpm : int, default 80 テンポ (BPM) velocity : int, default 100 ノートオン速度 """ midi = pm.PrettyMIDI(initial_tempo=tempo_bpm) inst = pm.Instrument(program=program) time = 0.0 sec_per_beat = 60.0 / tempo_bpm for pitch, dur in notes: if dur <= 0: continue ...
Python
1
ribute_request).commit().expect_success(); let post_distribute_supply = builder.total_supply(None); assert!( initial_supply < post_distribute_supply, "total supply should increase after distribute ({} >= {})", initial_supply, post_distribute_supply ); } #[ignore] #[test] fn...
Rust
0
import tempfile from django.conf import settings from django.core.management import call_command from django.test import TestCase, override_settings from parameterized import parameterized class TestCollectstatic(TestCase): """ Test manage.py collectstatic --noinput --link with different versions of STO...
Python
1
imuth_o def angel_gradient_modifier(base, grad_=None, alpha=(1.0, 1.0), center_=None): # alpha[0]: normal # alpha[1]: tangential if grad_ is None: grad_ = base.grad apply_to = True else: apply_to = False if center_ is not None: base_ = base.clone() - center_ el...
Python
1
from flask import Flask, render_template, request app = Flask(__name__) # print(__name__) @app.route('/') def home(): return render_template('home.html', name='SKY') @app.route('/your-url', methods=['GET', 'POST']) def your_url(): if request.method=='POST': return render_template('your_url.html', cod...
Python
1
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This software may be used and distributed in accordance with # the terms of the DINOv3 License Agreement. import logging from omegaconf import OmegaConf import os import sys from typing import Any from dinov3.eval.segmentation.config import SegmentationConfig f...
Python
1
eed for randomness') parser.add_argument('--port', type=int, default=8097, metavar='', help='port for visualizing training at http://localhost:port') # ======================== Hyperparameter Setings ================================== parser.add_argument('--optim-method', type=str, default='Adam', metavar='', help='th...
Python
1
es_x1 = warp_ref_patches_x1.view(N, C, H, W) warp_ref_patches_x2 = warp_ref_patches_x2.view(N, py, px, C, H//py*2, W//px*2).permute(0, 3, 1, 4, 2, 5).contiguous() # [N, C, py, H//py*2, px, W//px*2] warp_ref_patches_x2 = warp_ref_patches_x2.view(N, C, H*2, W*2) warp_ref_patches_x4 = warp_ref_pat...
Python
1
_get_qualname(func, include_module=True) obj_sigs = ["O" in sig for sig in func.types] if all(obj_sigs) or not any(obj_sigs): types = f"sampled_from({qname}.types)" else: types = f"sampled_from([sig for sig in {qname}.types if 'O' not in sig])" return _make_test_body( func, ...
Python
1
get_owner_handler, delete_owner_handler, update_owner_handler, create_owner_handler, list_owners_handler, get_shop_handler, delete_shop_handler, update_shop_handler, create_shop_handler, list_shops_ha...
Rust
0
Skip these calls to find() using parent_index. let txn = self.find(order).unwrap(); if txn.shadow_contains(target) { return true; } while let Some(&next_order) = queue.peek() { if next_order >= txn.time { // dbg!(next_order); q...
Rust
0
0, -0.0), OriginStrategy::Custom(tx, ty) => Matrix2d::translate(tx, ty), }; m *= match settings.flip { FlipStrategy::None => Matrix2d::identity(), FlipStrategy::Horizontal => Matrix2d::scale(1.0, -1.0), FlipStrategy::Vertical => Matrix2d::scale(-1.0, 1.0), FlipStrategy::H...
Rust
0
""" Utility methods for use in jupyterhub_config.py and dynamic subconfigs. Methods here can be imported by extraConfig in values.yaml """ import os from collections.abc import Mapping from functools import lru_cache import yaml # memoize so we only load config once @lru_cache def _load_config(): """Load the H...
Python
1
DreadnoughtsDrift = [ (-5119.0, -5407.0), (-4427.0, -4775.0), (-4446.0, -2638.0), (-4555.0, -5927.0), (-2949.0, -7679.0), (-2050.0, -6796.0), (-1308.0, -1897.0), (106.0, -103.0), (514.0, 176.0), (3533.0, 498.0), (4356.0, -3346.0), (4207.0, -4303.0), (3699.0, -6090.0),...
Python
1
the underlying reader. /// /// If the closure returns an error (or if the underlying reader returns an /// error), then iteration is stopped and the error is returned. If false /// is returned, then iteration is stopped and no error is returned. /// /// The closure given is called on exactly the...
Rust
0
=> { self.counter = 0; None } Err(TryRecvError::Disconnected) => { panic!("kafka input recv channel disconnected"); } } } None => None, } ...
Rust
0
#!/usr/bin/env python # -*- coding:utf-8 -*- """ @Description: 结果消息体 @Author: Kermit @Date: 2024-02-18 15:51:15 """ import numpy as np from event_bus.event_message import EventMessageBody class ResultMessageBody(EventMessageBody): """结果消息体""" def __init__( self, frame_count: int, fr...
Python
1
: "java-time-chrono-Chronology" #[cfg(any(feature = "all", all(feature = "java-time-chrono-Chronology")))] pub fn getChronology<'env>(&'env self) -> __jni_bindgen::std::result::Result<__jni_bindgen::std::option::Option<__jni_bindgen::Local<'env, crate::java::time::chrono::Chronology>>, __jni_bindgen::Lo...
Rust
0
d above. if env is not None: old_environ = os.environ.copy() _ReplaceEnvDict(os.environ, env) try: if working_dir is not None: os.chdir(working_dir) if capture_stderr: p = popen2.Popen4(command) else: p = popen2.Popen3(command) p...
Python
1
from api.schemas.base import Schema class ConfiguratorDomainSettings(Schema): domain: str | None = "" https: bool | None = True class ConfiguratorCoinDescription(Schema): enabled: bool | None = True network: str | None = "mainnet" lightning: bool | None = False class ConfiguratorAdvancedSettin...
Python
1
atic [u8; 41usize] = b"http://lv2plug.in/ns/ext/event#EventPort\0"; pub const LV2_EVENT__FrameStamp: &'static [u8; 42usize] = b"http://lv2plug.in/ns/ext/event#FrameStamp\0"; pub const LV2_EVENT__TimeStamp: &'static [u8; 41usize] = b"http://lv2plug.in/ns/ext/event#TimeStamp\0"; pub const LV2_EVENT__generates...
Rust
0
util::*; fn build_utf8_date_array(size: usize, with_nulls: bool) -> Utf8Array<i32> { use chrono::NaiveDate; // use random numbers to avoid spurious compiler optimizations wrt to branching let mut rng = seedable_rng(); let range = Uniform::new(0, 737776); (0..size) .map(|_| { i...
Rust
0
"liveliness", default_qos_profile.liveliness, ) liveliness_lease_duration: Duration = ( Duration( seconds=node_qos_config["liveliness_lease_duration"]["seconds"], nanoseconds=node_qos_config["liveliness_lease_duration"]["nanoseconds"], ) if is_valid_d...
Python
1
nsafe { (*block).count_holes_and_available_lines() }; if available_histogram.contains_key(holes) { if let Some(val) = available_histogram.get_mut(holes) { *val += free_lines; } } else { available_histogram.insert(holes, free_lin...
Rust
0
rd = ChildDropGuard { inner: &mut mock_reaped, kill_on_drop: true, }; let _ = guard.poll_unpin(&mut context); let mut guard = ChildDropGuard { inner: &mut mock_err, kill_on_drop: true, }; let _ =...
Rust
0
"kp_0" <= kname <= "kp_9": self.insertText(self.digs[int(kname[-1])]) return True elif kname in ( "period", "kp_decimal", ): self.insertText(locale_man.getNumSep()) return True else: # log.debug(kname, kval) return False def onDownButtonPress(self, button, gevent): self._arrow_press(-self...
Python
1
import pgzrun import random WIDTH = 500 HEIGHT = 700 dudu = Actor('嘟嘟') bricks = [] for i in range(5): n = random.randint(1, 4) b = Actor('踏板' + str(n)) min_x = b.width // 2 max_x = WIDTH - b.width // 2 b.x = random.randint(min_x, max_x) b.y = 140 * (i + 1) bricks.append(b) if i == 2:...
Python
1
n, }); Ok((name,Port::Out)) }, BrTrackEnd::Connection((a,b)) => { Err((a,b)) }, }; t.objs.sort_by_key(|(p,_)| OrderedFloat(*p)); let mut edge_objects = Vec::new(); for o in t.objs { match o { (_,BrObject...
Rust
0
syn!(ExprArray) => { Expr::Array } | syn!(ExprTuple) => { Expr::Tuple } | syn!(ExprIf) => { Expr::If } | syn!(ExprIfLet) => { Expr::IfLet } | syn!(ExprWhile) => { Expr::While } | syn!(ExprWhileLet) => { Expr::WhileLet } | s...
Rust
0
gher alpha value will result in more extreme holiday and outlier effects. * Holidays don't correspond to actual holidays. Instead, they are generated by randomly selecting days in the time series. * Annual seasonality is generated by Fourier series. The number of fourier terms is determined by t...
Python
1
import json import random class PathAggregator(): def __call__(self, paths): raise NotImplementedError class NonePathAggregator(PathAggregator): def __call__(self, paths): return paths class UniquePathAggregator(PathAggregator): def __call__(self, paths): # we transform the path...
Python
1
#!/usr/bin/env python ############################################################## # written by Markus Nikulski # mnikulski@extremenetworks.com # 08 Mar 2022 ############################################################## import XMC_NBI #########################################################...
Python
1
.parse() .map_err(|e: ParseIntError| AocError(e.to_string()))?, ); claims.insert(id, Patch { loc, size }); } Ok(claims) } } impl Deref for Claims { type Target = HashMap<usize, Patch>; fn deref(&self) -> &Self::Target { &self.0...
Rust
0
10 = 0b1000, Mul11 = 0b1001, Mul12 = 0b1010, Mul13 = 0b1011, Mul14 = 0b1100, Mul15 = 0b1101, Mul16 = 0b1110, } #[cfg(feature = "f3")] impl PllMul { pub fn value(&self) -> u8 { match self { Self::Mul2 => 2, Self::Mul3 => 3, Self::Mul4 => 4, ...
Rust
0
t.callRemote('UpdateExecutionStatus', cmds) dfr.addCallbacks(self.didUpdateTorrents, self._didFail) def quitTorrents(self): cmds = TorrentPinger.quitTorrents() dfr = self.torrentServerRoot.callRemote('UpdateExecutionStatus', cmds) dfr.addCallbacks(self.didQuit, self._didFail) d...
Python
1
import numpy as np import cv2 import math def setLabel(img, pts, label): (x, y, w, h) = cv2.boundingRect(pts) pt1 = (x, y) pt2 = (x + w, y + h) cv2.rectangle(img, pt1, pt2, (0, 0, 255), 1) cv2.putText(img, label, pt1, cv2.FONT_HERSHEY_PLAIN, 1, (0, 0, 255)) def main(): img = cv2.imread('poly...
Python
1
xt. It defaults to the language option # or en if the language is not set. #epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. #epub_scheme = '' # The unique identifier of the text. This can be a ISBN number # or the project homepage. #epub_identifier = '' # A unique identification f...
Python
1
#[repr(u8)] #[derive(Debug, Clone, Copy, TryFromPrimitive)] enum VarType { Short = b's', Long = b'l', Float = b'f', } impl<R: Read> Readable<R> for VarType { type Error = FieldError; fn read_val(reader: &mut R) -> Result<Self, Self::Error> { let data: u8 = reader.read_struct()?; let...
Rust
0
from typing import Any from prometheus_client import REGISTRY from litestar import get from litestar.plugins.prometheus import PrometheusMiddleware from litestar.status_codes import HTTP_200_OK from litestar.testing import TestClient def clear_collectors() -> None: collectors = list(REGISTRY._collector_to_names...
Python
1
}, inplace=True, ) temp_df = temp_df[ [ "行业编码", "证监会行业名称", "报告期", "基金覆盖家数", "行业规模", "占净资产比例", ] ] temp_df["报告期"] = pd.to_datetime(temp_df["报告期"], errors="coerce").dt.date temp_df["基金覆盖家数"] = pd.to_nume...
Python
1
_string()); } } <reponame>Emulator000/adventofcode2018 #![feature(test)] #![feature(range_contains)] extern crate test; #[macro_use] extern crate text_io; mod days; mod input; use crate::days::{day1::Day1, day2::Day2, day3::Day3, day4::Day4, day5::Day5, day6::Day6, Day}; fn main() { let day1: Box<Day>...
Rust
0
Fn(i64, u32) -> (i64, u32); } impl CargoPathExt for Path { fn rm_rf(&self) { let meta = match self.symlink_metadata() { Ok(meta) => meta, Err(e) => { if e.kind() == ErrorKind::NotFound { return; } panic!("failed to...
Rust
0
does not exist", path); return Err(Error::from_string("bad key_bindings_path")); } if display_config_path.as_path().exists() == false || display_config_path.as_path().is_file() == false { let path = display_config_path.into_os_string(); warn!("{:?} does not exist", path); return...
Rust
0
[allow(missing_docs)] pub fn new<Material>() -> T<Material> { T { components: Vec::new(), } } impl<Material> T<Material> { /// Add a component. pub fn push<Field>(&mut self, material: Material, field: Field) where Field: field::T + 'static, { self.components.push((Box::new(field), material)); }...
Rust
0
stination_type="tfrecord", ) assert "Featurestore feature values served." in caplog.text caplog.clear() def test_batch_serve_to_bq(self, shared_state, caplog): assert shared_state["featurestore"] assert shared_state["bigquery_dataset"] assert shared_state["user_age...
Python
1
#!/usr/bin/env python3 """ This script demonstrates a simple to-do list application using tkinter. It allows users to create, edit, and delete tasks. The tasks can be saved to a JSON file (``tasks.json``) upon closing the application. Modules: - tkinter: provides the Tk GUI toolkit for building the application's GUI. ...
Python
1
"""apikey-torrentitem Revision ID: df288f2cf1fa Revises: Create Date: 2024-09-20 20:37:08.652142 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = 'df288f2cf1fa' down_revision = None branch_labels = None depends_on = Non...
Python
1
m/search?q=XYZ"); Ok(()) } #[test] fn child_template_shadows_parent() -> Result<(), Error> { let config = testing::config( " templates: crates-io: https://foo.rs/{{args | join}} ", )?; let query = testing::query("crates-io", &["bar", "baz"]); let url = query.render(...
Rust
0
#Variable x = 5 y = "John" print(x) print(y) #Casting (to specify the data type of variable) x = str(3) y = int(4) z = float(7) print(x,y,z) #Get the data type x = 5 y = 'John' print(type(x)) print(type(y)) #Camel Case myVariableName = "John" #Pascal Case MyVariableName = "John" #Snake Case my_variable_name = "Joh...
Python
1
from pathlib import Path import pytest from borgboi.clients.utils import trash @pytest.fixture def tmp_trash(tmp_path: Path) -> Path: """ Fixture to create a temporary trash directory for testing. """ trash_path = tmp_path / "trash" trash_path.mkdir(parents=True, exist_ok=False) return trash...
Python
1
_pairs.iter().enumerate() { expander.sub("removable_files") .set("removable_file_idx", removable_file_idx + 1) .set("left_file_name", file_pair.left_ref().file_name(dups)) .set("right_file_name", file_pair.right_ref().file_name(dups)); } } els...
Rust
0
import torch import numpy as np from torch.utils.data import Dataset class NerDataset(Dataset): def __init__(self, data, args, tokenizer): self.data = data self.args = args self.tokenizer = tokenizer self.label2id = args.label2id self.max_seq_len = args.max_seq_len de...
Python
1