text
string
label_name
string
labels
int64
from todo.main import TodoTest def test_todo(tmp): with TodoTest() as app: res = app.run() print(res) raise Exception def test_command1(tmp): argv = ['command1'] with TodoTest(argv=argv) as app: app.run()
Python
1
e_query = "vk"; assert_eq!( utils::vkontakte::construct_vkontakte_url(fake_query), "https://vk.com" ); } #[test] fn test_construct_vkontakte_profile_url_with_id() { let fake_query = "vk id60890979"; assert_eq!( utils::vkontakte::construct_vkontakte_url(fake_query), "http...
Rust
0
4; let bottom: f32 = -3.4; let near: f32 = -1.0; let far: f32 = -6.2; let m_persp_proj = super::perspective_projection_matrix(left, right, top, bottom, near, far); let m_persp = super::perspective_matrix(near, far); let m_orth = super::orthographic_matrix(left, ri...
Rust
0
Obstacle distance membership functions self.obs_dist.close = np.vectorize(gauss(0, 17)) self.obs_dist.medium = np.vectorize(gauss(0.5, 100)) self.obs_dist.far = np.vectorize(gauss(1, 17)) # Manipulability membership functions self.manipulability.low = np.vectorize(gauss(0, 17))...
Python
1
integration is disabled.""" return self.manifest.get("disabled") @property def name(self) -> str: """Return name of the integration.""" name: str = self.manifest["name"] return name @property def quality_scale(self) -> str | None: """Return quality scale of the ...
Python
1
VariantSerializer<'a, 'j, C> where C: Context<'j>, { type Ok = Handle<'j, JsValue>; type Error = Error; #[inline] fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> where T: Serialize, { use serde::ser::SerializeSeq; self.i...
Rust
0
maxval=max_prob, dtype=tf.float32) func, _, args = _parse_policy_info(op_name, prob, self.magnitude, replace_value, ...
Python
1
pub enum RPCResponse { /// An RPC message. Message(Vec<u8>), } #[derive(Debug)] pub enum RPCErrorResponse { Success(RPCResponse), InvalidRequest(ErrorMessage), ServerError(ErrorMessage), Unknown(ErrorMessage), } impl RPCErrorResponse { /// Used to encode the response. pub fn as_u8(&sel...
Rust
0
"\nError! Undefined."); } else if dividend % divisor > 0 { println!("\n{} % {} has remainder of {}", dividend, divisor, (dividend % divisor)); } else { println!("\n{} % {} has no remainder", dividend, divisor); } } // Function return values fn is_divisible_by(dividend:u32, divisor:u32) -> b...
Rust
0
; } // Get the operations count for this account and check if it's beyond the limit. let account_ops_count = self .account_ops .entry(tx.account_id) .and_modify(|e| *e += 1) .or_insert(1); if *account_ops_count > MAX_OPS_PER_DAY { ...
Rust
0
STATISTIC_TESSELLATION_EVALUATION_SHADER_INVOCATIONS_BIT = 0x00000200, VK_QUERY_PIPELINE_STATISTIC_COMPUTE_SHADER_INVOCATIONS_BIT = 0x00000400, VK_QUERY_PIPELINE_STATISTIC_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF, } // @see https://www.khronos.org/registry/vulkan/specs/1.1-extensions/man/html/VkCommandBufferBeginInfo.h...
Rust
0
other: &Self) -> bool { self.id == other.id } } impl Eq for TourPrefix {} impl PartialOrd for TourPrefix { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl Ord for TourPrefix { fn cmp(&self, other: &Self) -> Ordering { self.to_cmp_eleme...
Rust
0
t__(cfg, norm_func=group_norm) _TRANSFORMATION_MODULES = Registry({ "BottleneckWithFixedBatchNorm": BottleneckWithFixedBatchNorm, "BottleneckWithGN": BottleneckWithGN, }) _STEM_MODULES = Registry({ "StemWithFixedBatchNorm": StemWithFixedBatchNorm, "StemWithGN": StemWithGN, }) _STAGE_SPECS = Registry...
Python
1
import os import json from datetime import datetime from time import sleep import random def generate_record(): return { "datetime": datetime.now().isoformat(), "sales": { "quantity": random.randint(1, 10), "total_price": abs(round(random.random(), 2) * 10) }, ...
Python
1
emy in &world.enemies { draw_enemy(enemy.x(), enemy.y()); } draw_player(world.player.x(), world.player.y(), world.player.direction()); draw_score(data.state.score as f64); } #[no_mangle] pub extern "C" fn update(time: c_double) { let data: &mut GameData = &mut DATA.lock().unwrap(); data.ti...
Rust
0
let connection_end_a = query_connection_end(handle_a, connection_id_a)?; if !connection_end_a .value() .state_matches(&ConnectionState::Open) { return Err(Error::generic(eyre!( "expected connection end A to be in open state" ...
Rust
0
bols.pop().unwrap() { (__l, __Symbol::Nt_28_22_2b_22_20_3cType1_3e_29_2b(__v), __r) => (__l, __v, __r), _ => panic!("symbol type mismatch") } } fn __pop_Nt_28_22_2d_3e_22_20_3cType_3e_29< 'input, >( __symbols: &mut ::std::vec::Vec<(usize,__Symbol<'input>,usize)>...
Rust
0
.startswith("mender-client"): clients.append(service) return clients def setup(self): compose_args = "up -d " + " ".join( ["--scale %s=0" % service for service in self.client_services()] ) self._docker_compose_cmd(compose_args) self._wait_for_cont...
Python
1
ss("✓ PDF loaded successfully") else: st.success("✓ Image loaded successfully") except Exception as e: st.error(f"Error: {str(e)}") # Always show preview display_file_preview(uploaded_file) # OCR button if st.button("🔍 Ext...
Python
1
import asyncio from typing import Optional from api.endpoints.room.utils import get_users_from_db from api.endpoints.users.controller import get_current_user from core.errors.game import AlreadyInGameError from core.errors.room import * from db.models.user import User from db.session import get_db from fastapi import ...
Python
1
else: filename_txt=open('GoodFiles'+'/'+dir_name+'/'+value+'.TXT','w') #files are trimmed using strip() filename_txt.write(self.file_content[value].strip('\x00')) filename_txt.close() counter+=1 print("\n") ...
Python
1
from indicators.base.core import CoreIndicators import numpy as np class Dimensions(CoreIndicators): """ Dimensions indicator. The Dimensions indicator calculates the fractal dimensions of a time series based on different modes of analysis (flat, expanding, or rolling). Fractal dimensions can p...
Python
1
import docker import os import pytest import sys import os.path from siliconcompiler import Project, Flowgraph, Design from siliconcompiler.tools.builtin.nop import NOPTask from siliconcompiler.scheduler import DockerSchedulerNode from siliconcompiler import __version__, NodeStatus from siliconcompiler.utils.paths i...
Python
1
Some(ret_place) => Some(ret_place.to_addr(fx)), None => Some(fx.bcx.ins().iconst(fx.pointer_type, 43)), }, PassMode::ByVal(_) | PassMode::ByValPair(_, _) => None, }; let (call_inst, meta) = f(fx, return_ptr); match output_pass_mode { PassMode::NoPass => {} Pass...
Rust
0
8 { match *self { ConsistencyLevel::One => 1, ConsistencyLevel::Quorum => replicas / 2 + 1, ConsistencyLevel::All => replicas, } } } // Copyright 2020-2021 The Datafuse Authors. // // SPDX-License-Identifier: Apache-2.0. use datafuse_cli::cmds::Config; use datafu...
Rust
0
ange(SOURCE, "random_macro", 4, false)?; k9_stable::assert_equal!(&range.start, &range.end); k9_stable::assert_matches_inline_snapshot!( format!("{:?}", range), r##"Range { start: LineColumn { line: 4, column: 24 }, end: LineColumn { line: 4, column: 24 } }"## ); ...
Rust
0
d>; /// Type alias of ShardByShard over GF(2^8). pub type ShardByShard<'a> = crate::ShardByShard<'a, Field>; /// Add two elements. pub const fn add(a: u8, b: u8) -> u8 { a ^ b } /// Subtract `b` from `a`. #[cfg(test)] pub const fn sub(a: u8, b: u8) -> u8 { a ^ b } /// Multiply two elements. pub fn mul(a: u8...
Rust
0
""" Brain Module - responsible for switching and configuring LLMs - handles the clipboard """ from lingu import log, Populatable from pydantic import Field import pyperclip # # This is out data module whose fields will be populated by AI # class SwitchLanguageModel(Populatable): # "Select between GPT 4, GPT 3....
Python
1
automatically. First argument is the top-level node for the code in question. Optional second argument is why it can't be converted. """ lineno = node.get_lineno() for_output = node.clone() for_output.prefix = "" msg = "Line %d: could not convert: %s" se...
Python
1
# -*- coding: utf-8 -*- """ Задание 23.1 В этом задании необходимо создать класс IPAddress. При создании экземпляра класса, как аргумент передается IP-адрес и маска, а также должна выполняться проверка корректности адреса и маски: * Адрес считается корректно заданным, если он: - состоит из 4 чисел разделенных точ...
Python
1
uppression to emphasize the peaks #val, result = cv2.threshold(result, 0.01, 0, cv2.THRESH_TOZERO) # And normalize #result_normed = cv2.normalize(result, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8U) # Find the maximum value on the result map ...
Python
1
# ruff: noqa: E501 # fmt: off from evidently.core.metric_types import MetricTest from evidently.pydantic_utils import register_type_alias register_type_alias(MetricTest, "evidently.metrics.column_statistics.ValueDriftTest", "evidently:test_v2:ValueDriftTest") register_type_alias(MetricTest, "evidently.tests.categorica...
Python
1
idx += 1; } target.push(digits[18]); } //------------ Class --------------------------------------------------------- /// The class portion of a DER tag. #[derive(Clone, Copy, Debug)] enum Class { Universal, Application, Context, Private, } //------------ StringValue -----------------...
Rust
0
#!/usr/bin/python3 def magic_string(i=[0]): i[0] += 1 return "BestSchool" + (", " + "BestSchool") * (i[0] - 1)
Python
1
env.ar_context['bquat'][ind - 1].flatten() # prev_bquat = env.prev_bquat # pose_gt_diff = multi_quat_norm_v2(multi_quat_diff(gt_bquat, cur_bquat)).mean() # cur_bangvel = get_angvel_fd(prev_bquat, cur_bquat, env.dt) # tgt_bangvel = get_angvel_fd(gt_prev_bquat, gt_bquat, env.dt) # vel_dist = np...
Python
1
from tkinter import * from tkinter import messagebox import pymysql from PIL import Image, ImageTk from bookings import * #connecting data base conn = pymysql.connect(host="localhost",user="root",password="Admin@123",database="hotel_management") con= conn.cursor() def cancel_fun(): user =e1.get() deletesql = ...
Python
1
import tkinter as tk import time def update_time(): curr_time = time.strftime('%H:%M:%S') label.configure(text=curr_time) label.after(1000, update_time) root = tk.Tk() root.title('Digital Clock') label = tk.Label(root, font=('calibri', 40, 'bold'), background='black', foreground='white') label.pack(ancho...
Python
1
type == 'cg': solve_potential_cg(u,rho) else: raise ValueError(f"Invalid solver_type: {solver_type}. Choose 'iterative' or 'tridiagonal' or 'cg'.") computeEF(u, efx) if boundary_condition == 'pbc': push_species(electrons, efx) push_species(ions, efx) push_species(negi...
Python
1
pub group: bool, pub resp: bool, pub file_id: u8, pub offset: u32, pub data: Box<[u8]>, } impl WriteFileData { pub fn build(self) -> Result<super::WriteFileData, Error> { super::WriteFileData::new(self) } } pub struct ReturnFileData { ...
Rust
0
"""Functions to visualize human poses""" import matplotlib.pyplot as plt import data_utils import numpy as np import h5py import os from mpl_toolkits.mplot3d import Axes3D def show3Dpose(channels, ax, lcolor="#3498db", rcolor="#e74c3c", add_labels=False): # blue, orange """ Visualize a 3d skeleton Args ch...
Python
1
ength). /// /// This module corresponds to the [`crypto_stream_xsalsa20` /// API](https://doc.libsodium.org/advanced/stream_ciphers/xsalsa20) from Sodium. /// /// # Security Considerations /// For this algorithm, nonces must *never* be used more than once with the same key. For XSalsa20, /// the nonce size is sufficien...
Rust
0
_DRIVER | SERVICE_FILE_SYSTEM_DRIVER | SERVICE_RECOGNIZER_DRIVER; pub const SERVICE_WIN32_OWN_PROCESS: DWORD = 0x00000010; pub const SERVICE_WIN32_SHARE_PROCESS: DWORD = 0x00000020; pub const SERVICE_WIN32: DWORD = SERVICE_WIN32_OWN_PROCESS | SERVICE_WIN32_SHARE_PROCESS; pub const SERVICE_INTERACTIVE_PROCESS: DWORD...
Rust
0
new() }; for i in iter { match i { "id" => ret.gens.push(Box::new(IdGenerator::new())), "date" => ret.gens.push(Box::new(DateGenerator::new())), f if f.contains('-') => ret.gens.push(Box::new(RangeGenerator::new_from_format(f))), f => r...
Rust
0
hor=(1.02, 0.65)) plt.xticks(rotation=90) plt.show() ## Surprisingly, rentals are quite invariant across regions. Not sure why #%% ''' Plotting price/sqm vs storey range ''' sns.scatterplot(data=new_resales, x='storey_range', y='price/sqm', hue='flat_type_group').set( title=f'Resales after {year_cutoff}') plt....
Python
1
from source.py.feature import ast def ss06_subst(): # Only handle glyphs that contains: # - default letter & default `l` # - default `ll` # - `ff` # - `tt` return ast.subst_map( [ ast.gly("Cl"), ast.gly("al"), ast.gly("cl"), ast.gly("el")...
Python
1
ST100 processor ST100, // Advanced Logic Corp. TinyJ embedded processor TinyJ, // Advanced Micro Devices X86-64 processor X8664, // Sony DSP Processor PSDP, // Digital Equipment Corp. PDP-10 PDP10, // Digital Equipment Corp. PDP-11 PDP11, // Siemens FX66 microcontroller ...
Rust
0
(nn.Module): """ DropBlock. See https://arxiv.org/pdf/1810.12890.pdf """ def __init__(self, drop_prob=0.1, block_size=7, gamma_scale=1.0, with_noise=False, inplace=False, batchwise=False, f...
Python
1
responsive-court'> <div class='half-court'></div> <div class='top-hoop'></div> <div class='bottom-hoop'></div> <div class='top-ft-arc'></div> ...
Python
1
ty and state, e.g. San Francisco, CA" }, "unit": { "type": "string", "enum": [ "celsius", "fahrenheit" ] ...
Python
1
t least one file entry. Check those file entries // to make sure they're formatted correctly and point to a valid music file. lazy_static! { static ref RE: Regex = Regex::new(r#"\s*(("file")|(file))\s+(("[^"\{\}]*")|([\S&&[^"\{\}]]+))\s*"#).unwrap(); } for cap in RE.captures_iter(&content...
Rust
0
import os from extract_jira_adf import extract_json # ADF 필드를 받아서 텍스트를 문자열로 반환하는 함수 def extract_text_from_adf_field(adf_field): """ Atlassian Document Format(ADF)에서 모든 텍스트를 재귀적으로 추출 - paragraph, orderedList, listItem 등 다양한 구조 지원 """ result = [] # 내부 함수(클로저) 구조 # 계층구조 문서 포맷에서 엑스트 추출 de...
Python
1
verbosity", short = "v")] verbose: u8, #[options(help = "output various timings / perf stats")] timings: bool, #[options(help = "suppress output of evaluated data")] quiet: bool, #[cfg(feature = "compile")] #[options( help = "each given element has the format '$1=$2' -> map '$1=$...
Rust
0
import re import discord from grief.core.commands import Context USER_MENTIONS = discord.AllowedMentions.none() USER_MENTIONS.users = True WEBHOOK_RE = re.compile( r"discord(?:app)?.com/api/webhooks/(?P<id>[0-9]{17,21})/(?P<token>[A-Za-z0-9\.\-\_]{60,68})" ) async def _monkeypatch_send( ctx: Context, cont...
Python
1
from django.urls import include, path from . import views general_urlpatterns = [ path('tool_settings_save_ajax/', views.annotation_tool_settings_save, name="annotation_tool_settings_save"), ] image_urlpatterns = [ path('tool/', views.annotation_tool, name="annotation_tool"), pa...
Python
1
CE_AUTH_METHOD_25519.id.as_str()); let did_resolver = ExampleDIDResolver::new(vec![ALICE_DID_DOC.clone(), BOB_DID_DOC.clone()]); let secrets_resolver = ExampleSecretsResolver::new(ALICE_SECRETS.clone()); let opts = PackEncryptedOptions { forward: false, pro...
Rust
0
, &[&elems[0], &elems[1], &elems[2], &elems[3]], ); } } } fn init_database(conn: &Connection) { conn.execute(CREATE_TABLE, NO_PARAMS).unwrap(); } fn query(conn: &Connection) { let mut stmt = conn .prepare("SELECT id, title, author, year FROM books WHERE year >= ...
Rust
0
", answer, pa ) .unwrap(); } } } else { writeln!(&mut to_print, "INCORRECT.\n").unwrap(); writeln!( &mut to_print, "your ans...
Rust
0
conform to `ForceOrigin`. /// /// Unlike `create`, no funds are reserved. /// /// - `class`: The identifier of the new asset. This must not be currently in use. /// - `owner`: The owner of this class of assets. The owner has full superuser permissions /// over this asset, but may later change and configure...
Rust
0
Token::new(SyntaxKind::Sym_Eq, "=", 8..9), Token::new(SyntaxKind::Whitespace, " ", 9..10), Token::new(SyntaxKind::Lit_Integer, "1", 10..11), Token::new(SyntaxKind::Newline, "\n ", 11..14), Token::new(SyntaxKind::Identifier, "y", 14..15), ...
Rust
0
- "] pub struct DM_PULLUP_HISEL_OVERRIDE_EN_W<'a> { w: &'a mut W, } impl<'a> DM_PULLUP_HISEL_OVERRIDE_EN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_b...
Rust
0
.ctx)); } } if !self.ctx.is_null() { unsafe { gvr::gvr_destroy(mem::transmute(&self.ctx)); } } } } #[cfg(target_os="android")] #[no_mangle] #[allow(non_snake_case)] #[allow(dead_code)] pub extern fn Java_com_rust_webvr_GVRService_nativeO...
Rust
0
định.""" bins = [0] * 10 for score in scores: if score >= 10: bins[9] += 1 elif score >= 0: bin_index = int(score) bins[bin_index] += 1 series = QBarSeries() bar_set = QBarSet("Số lượng sinh viên") bar_set....
Python
1
d::Mutex(mutex_cb)) = payload { Some(mutex_cb) } else { None } }); if let Some(waited_mutex) = waited_mutex { if !mutex::does_held_mutex_allow_new_task_base_priority( lock.borrow_mut(), waited_mutex, ...
Rust
0
format Author: <NAME> */ /* * Copyright (c) 2021 Arm Limited. * * SPDX-License-Identifier: MIT * * 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 wit...
Rust
0
} else { dict = A; key = "D"; D = pdf_deref_obj((*A).as_dict_mut().get_mut(key)); current_block = 9828876828309294594; } } } else { ...
Rust
0
.print_stats()?; } Ok(()) } } #[cfg(feature = "telemetry")] struct RecvTransferFecTelemetry { flags: AtomicU32, len: AtomicU32, tag: AtomicU32 } #[cfg(feature = "telemetry")] impl RecvTransferFecTelemetry { const FLAG_RECEIVE_STARTED: u32 = 0x01; const FLAG_RECEIVED: u32 ...
Rust
0
root // of the tree) are incremented by one. let mut heap = BinaryHeap::with_capacity(frequency_count); for index in frequency_heap.drain(..frequency_count) { heap.push(HeapFrequency { position: index, frequency: frequencies[index] }); } let mut s_code = vec![0_u64; ENCODING_TABLE_SIZE]; ...
Rust
0
GPU"] #[doc = ""] #[doc = " In GPU-accelerated mode, an <em>additional</em> state-vector is created in GPU memory."] #[doc = " Therefore both RAM and VRAM must be of sufficient memory to store the state-vector,"] #[doc = " each of the size indicated in the Serial table above."] #[doc = ""] #[doc...
Rust
0
import mlflow import pytest from mlflow.tracking import MlflowClient from kedro_mlflow.io.metrics import MlflowMetricHistoryDataset @pytest.fixture def mlflow_tracking_uri(tmp_path): tracking_uri = (tmp_path / "mlruns").as_uri() mlflow.set_tracking_uri(tracking_uri) return tracking_uri @pytest.fixture ...
Python
1
ttp://192.168.250.64/v1") # client = WorkflowClient(api_key="app-xxx", base_url="http://192.168.250.64/v1") # client = CompletionClient(api_key="app-xxx", base_url="http://192.168.250.64/v1") # 测试 streaming 模式 query = "每月几号发工资?" user = "user" response_mode = "streaming" conversation_id = Non...
Python
1
> bool { unsafe { ndless_sys::hwtype() < 1 } } /// since Ndless v3.1 r863. TRUE on TI-Nspire CM/CM-C. pub fn is_cm() -> bool { hw_subtype() == 1 } /// since Ndless v3.1. TRUE if the device has a screen in color. pub fn has_colors() -> bool { !is_classic() } /// TRUE on a TI-Nspire Touchpad or on a TI-Nspire CX. p...
Rust
0
# _*_ coding: utf-8 _*_ """ Usually used for match the sta_ID to all the Sta_ID which is used to verificate the forecast """ from datetime import datetime import itertools import string from datetime import datetime, timedelta import pkg_resources import numpy as np import pandas as pd import cartopy.crs as ccrs fr...
Python
1
_life_stage_id, "current_plot_segment_id": role.current_plot_segment_id, "current_materials_id": role.current_materials_id, "created_at": role.created_at, "updated_at": role.updated_at } } except HTTPException: raise exc...
Python
1
"""Client adapters for different AI applications.""" from mcp_manager.core.adapters.base import BaseAdapter from mcp_manager.core.adapters.claude_code import ClaudeCodeAdapter from mcp_manager.core.adapters.claude_desktop import ClaudeDesktopAdapter from mcp_manager.core.adapters.vscode import VSCodeAdapter __all__ =...
Python
1
import json from utils import GoEmotionConfig from gpt2 import EmotionDetector import math class EmotionScoreCalculator: def __init__(self): # Initialize model and config self.config = GoEmotionConfig() self.detector = EmotionDetector(self.config) # Load sentiment mapping f...
Python
1
.expected_element_spec) values = {c: 0 for c in range(12)} for x, y in out_ds.take(3): for x_ in x: values[x_.numpy()[0]] += 1 self.assertEqual(values[1], 1) self.assertEqual(values[2], 1) self.assertEqual(values[3], 1) self.assertEqual(values[...
Python
1
write!(f, "{:?}", self) } } impl ResponseError for ApiErrors { fn error_response(&self) -> HttpResponse { let message = self.message(); match self { ApiErrors::MutexGuard(_e) => { log::error!(r"[ErrorResponse] [MutexGuardError]: {:?}", message,); ...
Rust
0
from arm.logicnode.arm_nodes import * class ValueChangedNode(ArmLogicTreeNode): """Upon activation through the `In` input, this node checks whether the given value is different than the value from the last execution of this node. @output Changed: Activates if the value has changed compared to the ...
Python
1
25, 25, proj_life1, proj_speed1, [0,0], spread1, effect_ID) particle_emitter.piercing = att1_pierce ...
Python
1
from ElectronRedoFromRaw_driver_cfg import * import os, sys import DQMOffline.EGamma.electronDataDiscovery as dd process.source.fileNames = cms.untracked.vstring() process.source.fileNames.extend(dd.search()) process.source.secondaryFileNames = cms.untracked.vstring() process.maxEvents = cms.untracked.PSet(input = c...
Python
1
# server.py from mcp.server.fastmcp import FastMCP import psutil import requests import socket import ipaddress from typing import Literal # Create an MCP server mcp = FastMCP("Demo") def get_ip_type(ip: str) -> Literal["loopback", "link-local", "private", "public"]: """ 判断IP地址类型 Args: ip: I...
Python
1
a copy of the GNU General Public License // along with substrate-subxt. If not, see <http://www.gnu.org/licenses/>. //! Implements support for the pallet_balances module. use crate::frame::system::{ System, SystemEventsDecoder, }; use codec::{ Decode, Encode, }; use core::marker::PhantomData; use fr...
Rust
0
::transmute(raw.offset(0)) } pub unsafe fn _timer(&mut self) -> *mut Struct_Unnamed17 { let raw: *mut u8 = ::std::mem::transmute(&self._bindgen_data_); ::std::mem::transmute(raw.offset(0)) } pub unsafe fn _rt(&mut self) -> *mut Struct_Unnamed18 { let raw: *mut u8 = ::std::mem::tr...
Rust
0
ame": "custom_tool", "parameters": {{"data": "analyze this data"}}}}` ### Usage Examples - **Example 1**: Retrieving Weather Information ```json {tool_usage_browser} ``` - **Example 2**: System Check via Terminal ```json {tool_usage_terminal} ``` - **E...
Python
1
_ => panic!("No TRUE for type {}", t), } } fn min_val(t: &str) -> &'static str { match &t[..3] { "u8x" => "0", "u16" => "0", "u32" => "0", "u64" => "0", "i8x" => "-128", "i16" => "-32768", "i32" => "-2147483648", "i64" => "-92233720368547...
Rust
0
cx, ButtonLogicEvent::Default); return ButtonEvent::Up; } } _ => (), }; ButtonEvent::None } <gh_stars>1-10 // This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files // DO NOT EDIT #[cfg(any(feature = "v1_18", feature = "dox"))] #[cfg_attr(fe...
Rust
0
[u8; 64]) -> [u8; 256] { let mut table = [0xff; 256]; let mut i = 0; while i < charset.len() { table[charset[i] as usize] = i as u8; i += 1; } table } pub(crate) const STANDARD_DECODE_TABLE: &[u8; 256] = &decode_table(STANDARD_CHARSET); pub(crate) const URL_SAFE_DECODE_TABLE: &[u8; ...
Rust
0
let random_data = random_bytes(0, 100 * 1024); let (public_key, secret_key) = gen_keypair(); let mut encrypter = SaltlickEncrypter::new(public_key.clone(), Vec::new()); encrypter.write_all(&random_data[..]).unwrap(); let mut ciphertext = encrypter.finalize().unwrap(); // Inject ...
Rust
0
Grey); skin.paragraph.align = Alignment::Center; skin.table.align = Alignment::Left; skin.term_text(&full).to_string() } pub fn markdown_table(matches: Vec<&Match>, allowlist: Vec<String>) -> String { let mut txt: Vec<String> = vec![]; txt.push(HEADER.to_string()); let empty = String::new(); ...
Rust
0
/// result and handle operations that were not canceled or that have already /// completed. /// /// # Examples /// /// Cancel an outstanding aio operation. Note that we must still call /// `aio_return` to free resources, even though we don't care about the /// result. /// /// `...
Rust
0
import c3py # import the python interface to the c3 library import numpy as np import matplotlib.pyplot as plt np.random.seed(10) def func(x): return x[:, 0]**2 + x[:, 1]**2 + x[:, 0] * x[:, 1] + np.sin(np.sum(x, axis=1)) \ + x[:,0] * x[:,-1] + x[:, -1]**2.0 * np.cos(x[:, 0]) LB = -1.0 ...
Python
1
#Password Generator Project import random letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] numbers...
Python
1
spatialDateTime(dt_str,julian.as_mut_slice().as_mut_ptr(),sec.as_mut_slice().as_mut_ptr()) }; match status { 0 => Some(HecTime{value:sec[0],granularity:HecTimeGranularity::second,basedate:julian[0]}), _ => { println!("HecTime from datatime string retur...
Rust
0
= id, 11 => (*(arg as *mut sctp_assocparams)).sasoc_assoc_id = id, 7 => (*(arg as *mut sctp_setprim)).ssp_assoc_id = id, 10 => (*(arg as *mut sctp_paddrparams)).spp_assoc_id = id, 14 => (*(arg as *mut sctp_assoc_value)).assoc_id = id, 19 => (*(arg as *mut sctp_authkey)).sca_asso...
Rust
0
} }) } fn code_label_decl_and_impls<Pat>( rules: &RuleMap<'_, Pat>, code_labels: &OrderMap<Rc<CodeLabel>, usize>, ) -> Src { let all_labels = rules .named .keys() .map(|r| CodeLabel::NamedRule(r.clone())) .chain(code_labels.iter().flat_map(|(fn_label, &counter)| ...
Rust
0
> = Result<U, ErrorOf<'s, T>>; type SpanFn<'s, T> = fn(ResultOf<'s, T, T>, &Lexer<'s, T>) -> ResultOf<'s, T, (T, Span)>; /// A `Lexer` allows you to read through a source (a type implementing the [Source] trait, like a string /// slice) and produce tokens using the [Logos] trait. It's important to note that you should...
Rust
0
d have received a copy of the MIT License // along with this software. // If not, see <https://opensource.org/licenses/MIT>. use std::io::{Read, Write}; use bitcoin::consensus::deserialize; use bitcoin::{hashes, secp256k1, Script}; use bitcoin_scripts::{hlc, PubkeyScript}; use super::{strategies, Strategy}; use crat...
Rust
0
# # Open Loop Brushless Motor Test # # Seeed Xiao RP2040 # # Based off the Arduino code from this video: # https://www.youtube.com/watch?v=zSdetJsSeNw # import machine from machine import Pin, ADC, PWM import time import math pot = ADC(Pin(26)) # A0 enable_pin = Pin(1, Pin.OUT) # D7 phase_a_pin = Pin(2, ...
Python
1
tml_string, clean_html=True, output_format=OutputFormat.JSON_STRING): if clean_html: html_string = clean_article_html(html_string) body = preprocess_fragments( _fragments_from_string(html_string) ) if body is not None: desc = [x for x in body.iterdescendants(...
Python
1
from sqlalchemy import create_engine, MetaData, Table, select from supabase import create_client, Client import json import os # --- CONFIG --- WP_DB_URL = "mysql+pymysql://wp_user:wp_pass@localhost:3306/wordpress" SUPABASE_URL = os.getenv("SUPABASE_URL") SUPABASE_KEY = os.getenv("SUPABASE_SERVICE_ROLE") # --- Init -...
Python
1