text
string
label_name
string
labels
int64
import os import unittest from pyats.topology import loader from genie.libs.sdk.apis.iosxe.dhcp.configure import configure_ip_dhcp_snooping_verify_mac_address class TestConfigureIpDhcpSnoopingVerifyMacAddress(unittest.TestCase): @classmethod def setUpClass(self): testbed = f""" devices: ...
Python
1
e\x03\x80\xc4\xf0\xab9\xa6\xc4W&`\xb4\x18N\ \x1c\x1caXJ-\x1d\x05\x1c\x85\xe7\x7f-}\xd5@\ ^\xec\xc7\xd9\xccYz\xd0^\xbc\xa7\x17\xf7\xab\x12v\ WB\xec\xfb\xbb;t6\x9f\xb1\x00\x01\xc7\x01\xef\xab\ C\xf4_\xe8\x1b\x1b\xf5\x0f\x09\xcf>\xa01\xf9}<\ t\xf2\xae\x169c\x0b\xa8\x81g\xcc\xd8\xbb\x93e\x98\ \xd1\xcc\xca\x94\x94\xdf\xbc\x...
Python
1
ize, opt.image_size], device=opt.device) mask[:, ...] = mask_b def inpaint_center(img): # img[mask==0] = img[mask==0], img[mask==1] = 1 (white) if opt.add_noise: img = img + torch.randn_like(img) * 0.04 return img * (1. - mask) + mask, mask return inpaint_center def bu...
Python
1
rkspace_team_filters)["data"] if target_workspace_teams: for target_workspace_team in target_workspace_teams: target_workspace_team_data = self._api_target.teams.show( \ target_workspace_team["relationships"]["team"]["data"]["id"])...
Python
1
import json f = open("outputs/enemyindividualcommondata.user.3.json") data = json.load(f)["app.user_data.EnemyIndividualCommonData"]["_Data"]["_ParamList"] for e in data: if e["_InstantiatePriority"] == 3: print(e["EnumValue"])
Python
1
u8), Out(u8, Gpr), /// Set bit in IO register. Sbi(u8, u8), /// Clear bit in IO register. Cbi(u8, u8), Jmp(u32), Call(u32), Rjmp(i16), Rcall(i16), Brbs(u8, RelativeAddress7), Brbc(u8, RelativeAddress7), Breq(RelativeAddress7), Brne(RelativeAddress7), Brcs(Relat...
Rust
0
.map(|key| { let chunk_extent = self.indexer.extent_for_chunk_at_key(key); let intersection = extent.intersection(&chunk_extent); ( intersection, self.get_chunk(key) .map(|chunk| Either::Left(ArrayCopySrc(ch...
Rust
0
from dl_formula.definitions.base import TranslationVariant import dl_formula.definitions.operators_unary as base from dl_connector_trino.formula.constants import TrinoDialect as D V = TranslationVariant.make DEFINITIONS_UNARY = [ # isfalse base.UnaryIsFalseStringGeo.for_dialect(D.TRINO), base.UnaryIsFal...
Python
1
class Solution: def asteroidCollision(self, asteroids: List[int]) -> List[int]: ## int -> size, sign -> direction ## smaller will be explode. same size? both explode ## same direction will never mmet stack = [] for asteroid in asteroids: # print(f'aster: {astero...
Python
1
rive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug)] pub enum OrderType { Buy = 0, Sell, } impl Not for OrderType { type Output = OrderType; fn not(self) -> Self::Output { match self { OrderType::Sell => OrderType::Buy, OrderType::Buy => OrderType::Sell, ...
Rust
0
contrar el indice dentro del arreglo que requiere ID. # my_posts.pop(index) # conn = get_database_connection() # if conn: # with conn.cursor() as cur: # cur.execute("""DELETE FROM posts WHERE ID = %s RETURNING*""", (str(id),)) # deleted_post = cur.fetchone() # con...
Python
1
0x01; const MODE_HI = 0x02; const LYC_EQ_LC = 0x04; const HBANLK_INTERUPT_SOURCE = 0x08; const VBANLK_INTERUPT_SOURCE = 0x10; const OAM_INTERUPT_SOURCE = 0x20; const LYC_EQ_LC_INTERUPT_SOURCE = 0x40; const UNUSED = 0x80; } } impl LcdStatus { pub fn set_m...
Rust
0
# -*- coding: UTF-8 -*- """ __Author__ = "WECENG" __Version__ = "1.0.0" __Description__ = "" __Created__ = 2023/10/10 17:00 """ import os.path import pickle import time from time import sleep from selenium import webdriver from selenium.webdriver.common.by import By class Concert: def __init__(self, config): ...
Python
1
rsing along class III grids. * * Current digit -> direction -> new ap7 move (at coarser level). */ const NEW_ADJUSTMENT_III: [[Direction; 7]; 7] = [ [ CENTER_DIGIT, CENTER_DIGIT, CENTER_DIGIT, CENTER_DIGIT, CENTER_DIGIT, CENTER_DIGIT, CENTER_DIGIT, ], ...
Rust
0
repeat=True, config=config, ) in_nchannel = len(dataloader.dataset) net = GenerativeNet(config.resolution, in_nchannel=in_nchannel) net.to(device) logging.info(net) if not config.eval: train(net, dataloader, device, config) else: if not os.path.exists(config.w...
Python
1
def get_default_data(entry_data): data = entry_data.get() if not data: data = "www.myskillhub.pt" return data
Python
1
0][1],color=(255,255,255),size=5,thickness=2) img565.draw_cross(corners[1][0],corners[1][1],color=(255,255,255),size=5,thickness=2) img565.draw_cross(corners[2][0],corners[2][1],color=(255,255,255),size=5,thickness=2) img565.draw_cross(corners[3][0],corners[3][1],color=(255,255,255),size=5,thick...
Python
1
ext, dasm::TokenAttributes, }; fn test_context() -> Context { let ctx = Context::new(0x600, 0x700); ctx } fn test_arch() -> Arch { make_arch(&make_instructions65c816(IMMEDIATE_SIZE16), None) } #[test] fn it_should_use_insert_token_plugin() { let mu...
Rust
0
2) merged_df['electric_diff'] = merged_df['Electric_22'] - merged_df['Electric_21'] merged_df['Electric_pct_diff'] = round(merged_df['electric_diff'] / merged_df['Electric_21']*100,2) filtered_df = merged_df[['district',selected_col]] if selected_col == 'Petrol_pct_diff': styles = data_bar...
Python
1
fusion with Rust types. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[repr(i32)] pub enum CheckTxKind { /// A full check is required (the default). New = 0, /// Indicates that the mempool is initiating a recheck of the transaction. Recheck = 1, } impl Default for CheckTxKind { fn default() -...
Rust
0
seq = range(10) for i in seq: print(i)
Python
1
arent: if tok.parent.type == "class": colour = options.singleton().colours[ "member" ] # assing properties ctr.set_property("text", name) ctr.set_property("style", style) ctr.set_property("foreground-gdk", colour) def pixbufrenderer(self, column, crp, m...
Python
1
""" Classifies: CHEBI:15341 beta-D-glucosiduronic acid """ from rdkit import Chem from rdkit.Chem import rdMolDescriptors def is_beta_D_glucosiduronic_acid(smiles: str): """ Determines if a molecule is a beta-D-glucosiduronic acid based on its SMILES string. A beta-D-glucosiduronic acid involves a beta-D-g...
Python
1
# -*- coding: utf-8 -*- import numpy as np from scipy.optimize import leastsq import pylab as pl def func(x, p): """ 数据拟合所用的函数: A*sin(2*pi*k*x + theta) """ A, k, theta = p return A*np.sin(2*np.pi*k*x+theta) def residuals(p, y, x): """ 实验数据x, y和拟合函数之间的差,p为拟合需要找到的系数 """ return y -...
Python
1
gle.com" } </tool><|im_end|> """, ) ##################################################################### # Step 4: Performing the Search # ----------------------------- # # With the browser open, we can now type our query and execute the search. # First, we'll type the search query into Google's search bo...
Python
1
::Cycle, }; use super::{Delegates, DelegatesError}; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "fuzzing", derive(fuzzcheck::DefaultMutator))] pub struct RightsCycleDelegatesGetAction { pub cycle: Cycle, pub block_header: BlockHeader, } impl EnablingCondition<State> for...
Rust
0
rate::DisplayableClosure::new(move |fm| { if let Some(step) = step { let k = (-step.log10()).ceil(); let k = k.max(0.0); write!(fm, "{0:.1$}", a, k as usize) } else { write!(fm, "{0:e}", a) } }) } fn make_science(a: f64, step: Option<f64>) -> ...
Rust
0
OwnerChange { NewOwner, Destroy, Close, #[doc(hidden)] __Unknown(i32), } impl fmt::Display for OwnerChange { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "OwnerChange::{}", match *self { OwnerChange::NewOwner => "N...
Rust
0
le(tes_spat, args.rsz) tes_XX_spat = torch.from_numpy(tes_spat.transpose(0, 3, 1, 2)) del tes_spat print('Experiment {},Testing spatial dataset preparation Finished!'.format(count)) ################### testing ################ tes_dataset=TensorDataset(tes_XX_spec,tes_XX_spat,tes_YY) tes_loa...
Python
1
model(**inputs) iou_scores = outputs.iou_scores.cpu() self.assertTrue(iou_scores.shape == (1, 2, 3)) torch.testing.assert_allclose( iou_scores, torch.tensor([[[0.9105, 0.9825, 0.9675], [0.7646, 0.7943, 0.7774]]]), atol=1e-4, rtol=1e-4 ) def test_inference_mask_generatio...
Python
1
GlConfig]>, fbconfigs: Arc<[GlConfig]>, ) -> breadx::Result<Self> { // first, figure out which file descriptor corresponds to our screen let root = dpy.screens()[scr].root; let fd = dpy.open_dri3_immediate(root, 0)?; // TODO: figure out if we need to use a different file des...
Rust
0
ate::CheckerBabel; let lab_babel : CieLab<D50, CieObs1931> = CheckerBabel.into(); println!("{:.3}", lab_babel.data.transpose()); } #[test] fn test_babel2(){ use scot::{illuminants::D65, models::{CieCamUcs, VcAvg}, observers::CieObs1964}; use crate::CheckerBabel; let jab_babel : CieCamUcs<VcAvg, ...
Rust
0
_children and class_name in model._children: # type: ignore return parse_obj( model=model._children[class_name], # type: ignore data=data, lazy_parse=lazy_parse, ) # type: ignore if ( lazy_parse and hasattr(model, "get_model...
Python
1
"ASCII85Decode" => StreamFilter::ASCII85Decode, "LZWDecode" => StreamFilter::LZWDecode (LZWFlateParams::from_primitive(params, r)?), "FlateDecode" => StreamFilter::FlateDecode (LZWFlateParams::from_primitive(params, r)?), "JPXDecode" => StreamFilter::JPXDecode, "D...
Rust
0
, data4: [135, 224, 150, 25, 69, 248, 247, 206] }; pub const MF_CAPTURE_ENGINE_EVENT_STREAM_INDEX: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2187951940, data2: 45519, data3: 17131, data4: [151, 83, 248, 109, 100, 156, 136, 101] }; pub const MF_CAPTURE_ENGINE_INITIALIZED: ::windows_sys::core::GUID =...
Rust
0
trol(Some(new_non_zero_u8(protocol_code)))), (0x10, 0x02, 0x00) => AudioVideo(DataVideoStreamingInterface(None)), (0x10, 0x02, _) => AudioVideo(DataVideoStreamingInterface(Some(new_non_zero_u8(protocol_code)))), (0x10, 0x03, 0x00) => AudioVideo(DataAudioStreamingInterface(None)), (0x10, 0x04, _) => AudioVid...
Rust
0
n, m = map(int, input().split()) army = list(map(int, input().split())) prefix_sum = [0] sum = 0 for i in range(n): sum += army[i] prefix_sum.append(sum) ans = [] for _ in range(1, m + 1): num_teams, num_ork = map(int, input().split()) l = 0 r = n - num_teams mid = (l + r) // 2 while l <= r:...
Python
1
print('Informe dois números e veja se o primeiro é um \ multiplo do segundo.') print('\n') numero_A = input("Informe um número: ") numero_A = int(numero_A) numero_B = input("Informe outro número: ") numero_B = int(numero_B) if (numero_A % numero_B) == 0: print(f"\nO número {numero_A} é multiplo de {numero_B}\n\n")...
Python
1
from flask import Flask, request import socket import subprocess app = Flask(__name__) @app.route('/', methods=['POST']) def stress_cpu(): subprocess.Popen(['python3', 'stress_cpu.py']) return "CPU stress initiated", 202 @app.route('/', methods=['GET']) def get_private_ip(): hostname = socket.gethostname...
Python
1
from django.contrib import admin from employee.models.config import Config @admin.register(Config) class ConfigAdmin(admin.ModelAdmin): def has_module_permission(self, request): return False
Python
1
from ultralytics import YOLO import cv2 from PIL import Image import os import scipy import tqdm import numpy as np import matplotlib.pyplot as plt def margen(masks): # reuslts[0] conf = masks.boxes.conf # mask的置信度 mask = masks.masks[0] # 用来获得原始图片的shape masks = masks.masks # 所有mask ...
Python
1
STOM, [ "Allowed characters: a-z, 0-9 and '-'", "The name must not contain the following:", "\n\n", "● Any special characters", "● No leading or trailing '-'", ], ) ...
Python
1
y = "unix"))] pub type Args = *mut sys::__va_list_tag; /// Type of a log callback pub type Callback = unsafe extern "C" fn(context: Context, level: c_int, fmt: *const c_char, args: Args); /// Sets a log callback pub fn set_raw_callback(callback: Callback) { unsafe { sys::av_log_set_callback(Some(callback)...
Rust
0
__sym0 = __sym0.take().unwrap(); let __start = __sym0.0.clone(); let __end = __sym0.2.clone(); let __nt = super::__action69(input, __sym0); let __nt = __Nonterminal::TYPE(( __start, __nt, __end, ...
Rust
0
1072512> test"; let mention = parse_direct_mention(message); assert_eq!(mention, Some(UserId(766407857851072512))); } } <gh_stars>1-10 mod error; mod instruction; mod program; mod vm; pub use error::*; pub use instruction::*; pub use program::*; pub use vm::*; pub type ParseResult<T> = std::result...
Rust
0
pub use project_dirs::ProjectDirs; pub use user_dirs::UserDirs; #[cfg(not(windows))] pub(crate) fn not_found() -> io::Error { rsix::io::Error::NOENT.into() } #[cfg(windows)] pub(crate) fn not_found() -> io::Error { io::Error::from_raw_os_error(winapi::shared::winerror::ERROR_PATH_NOT_FOUND as i32) } <gh_star...
Rust
0
ener.accept().await { let clone_identity_db = Arc::clone(&identity_db); let clone_message_db = Arc::clone(&message_db); tokio::spawn(handle_connection( clone_identity_db, clone_message_db, stream, )); } } #[doc = r"Register block"] #[repr(C)] pub s...
Rust
0
merate(option): for idx_n, m in enumerate(data[:min(len(option), len(data))]): if k == m: if idx_d == idx_n: score += loc_equl_ else: score += equl_ break ...
Python
1
_variable_token() { let token = Token::Variable("some_variable_name",0); assert_shape(&token,Shape::variable("some_variable_name")); assert_length(&token,18); } #[test] fn construct_external_name_token() { let token = Token::External("camelCase",0); assert_shape(&tok...
Rust
0
def space_game(text): if text.count(' ') % 2 == 0: print('Вы выиграли') else: print('Вы проиграли') space_game('я иду с мечем судия')
Python
1
c.update(dict(six.iteritems(flask.request.args))) log.debug("Combined arguments: %s", c) if not {'girder_token', 'girder_origin', 'girder_apiRoot'} \ .difference(c.keys()): g_token = c['girder_token'] log.debug("G-token: %s", g_token) ...
Python
1
# get the stars and pixels stars, _, star_pixels = get_stars_directions_and_pixels(cat, image, model, 7) half_dsize = 20 delta_pix = np.arange(-half_dsize, half_dsize+1) motion_blur = get_motion_blur_kernel(int(np.floor(half_dsize/np.sqrt(2))), int(np.floor(half_dsize/np.sqrt(2))), ksize=...
Python
1
Local Iceberg SQL Examples") # Create Iceberg manager iceberg_manager = LocalIcebergManager() # Run SQL examples iceberg_manager.run_sql_examples() # Create SQL script file sql_script = create_iceberg_sql_script() script_path = Path("iceberg_setup.sql") with open(scri...
Python
1
) with gr.Tab("批量处理"): gr.Markdown("### 批量处理图像目录") with gr.Row(): input_dir = gr.Textbox( label="输入目录", placeholder="包含图像的目录路径" ) output_dir = gr.Textbox( label="输出目录", ...
Python
1
import google.generativeai as genai from llm_wrapper import LLMWrapper class Gemini(LLMWrapper): def __init__(self, apikey): super().__init__() # Pass in Google API key genai.configure(api_key=apikey) def generate(self, prompt): # Prompts Gemini and returns the result model = genai.Generat...
Python
1
, type=str, default='text', choices=OUTPUT_TYPES, help="Output type") parser.add_argument("--max_length", type=int, default=None, help="Max number of tokens (input and output)") parser.add_argument("--max_new_tokens", type=int, default=2048, help="Max number of tokens to generate") parser.add_argument("--sa...
Python
1
evt).unwrap()) }); assert_eq!( state.completed.unwrap(), EndCause::MechVictory("al".to_string()) ); } #[test] fn death_by_splash() { let path_to_death = INITIAL_HEALTH / SECONDARY_SPLASH_DAMAGE; let state = gen_root_state( vec![(...
Rust
0
", TThostFtdcErrorIDType), ("ErrorMsg", TThostFtdcErrorMsgType), ("LongCustomerName", TThostFtdcLongIndividualNameType), ] def getTradeCode(self): '''业务功能码''' return str(self.TradeCode, 'GBK') def getBankID(self): '''银行代码''' return str(self.BankID, '...
Python
1
from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.vectorstores import Bagel # Create a way to dynamically look up deprecated imports. # Used to consolidate logic for raising deprecation warnings and # handling optional imports. DEPRECATED_...
Python
1
scene = ( scene .add(outside_wall.translate((0,y_translate,0))) .add(outside_wall.rotate((0,0,1),(0,0,0),180).translate((0,-y_translate,0))) ) if self.render_magnets and self.magnet: length = self.length - self.overhang[0]*2 ...
Python
1
7 = crate::Reg<mjpeg_start_addr7::MJPEG_START_ADDR7_SPEC>; #[doc = "mjpeg_start_addr7."] pub mod mjpeg_start_addr7; #[doc = "mjpeg_bit_cnt7 register accessor: an alias for `Reg<MJPEG_BIT_CNT7_SPEC>`"] pub type MJPEG_BIT_CNT7 = crate::Reg<mjpeg_bit_cnt7::MJPEG_BIT_CNT7_SPEC>; #[doc = "mjpeg_bit_cnt7."] pub mod mjpeg_bit...
Rust
0
#set -> collection of items #no duplicate items #unordered collection #mutable -> After creation you can add delete and perform other operations s = {10, 20, 30} # print(s) # print(type(s)) #typecasting # lst = ['a', 'b', 'c'] # print(lst) # print(type(lst)) # s = set(lst) # print(s) # print(type(s)) s = {'hey', 'th...
Python
1
(3+3)", split(==): (1 + 1 == 2 + 2 == 3 + 3)} assert_tm!{"(1+1) (2+2) (3+3)", split(foo): (1 + 1 foo 2 + 2 foo 3 + 3)} assert_tm!{"(1+1) (2+2) (3+3)", split(foo bar): (1 + 1 foo bar 2 + 2 foo bar 3 + 3)} assert_tm!{"(1+1) (2+2) (3+3)", split((foo)): (1 + 1 (foo) 2 + 2 (foo) 3 + 3)} assert_tm!{"(1+1) (2+...
Rust
0
gui, settings: Settings { min_radius: 10.0, max_radius: 100.0, circle_count: 10, }, } } fn update(_app: &App, model: &mut Model, update: Update) { let Model { ref mut egui, ref mut settings, ref mut circles, .. } = *model; ...
Rust
0
p_create_infos.first().map_or(ptr::null(), |s| s as *const _), p_allocator.map_or(ptr::null(), |r| r), p_pipelines, ); match v_err { vk::Result::SUCCESS => Ok(()), _ => Err(v_err), } } pub unsafe fn create_ray_tracing_pipelines_nv_to_vec( ...
Rust
0
reply_id = None if message.message_reference: reply_id = message.message_reference.message_id if message.content.strip().startswith("/"): prefixes = ["/"] require_enable_modules = False msg_chain = MessageChain.assign(message.content) session = a...
Python
1
.into_iter() .filter(|x| x.state == "Open") .collect(); instruments } #[test] fn verify_normalize_pair() { let instruments = fetch_instruments(); for instrument in instruments.iter() { let symbol = instrument.symbol.as_str(); let pair = normalize_pair(symbol, EXCHANGE_NAM...
Rust
0
documents=documents, storage_manager=self.storage_manager ) chatbot = ChatBot( title=desc["title"], description=desc["description"], icon=desc["icon"], access=desc["access"], suggested_prompts=suggested_prompts, se...
Python
1
<Store> where Store: ?Sized + DataStore, {} impl<Store> PartialEq for StoreId<Store> where Store: ?Sized + DataStore, { fn eq(&self, other: &Self) -> bool { self.value.eq(&other.value) } } impl<Store> Identity<Store, <Store::Allocator as TemporaryIdAllocator>::Type> for StoreId<Store> where...
Rust
0
_t = 32; pub const KERN_INVALID_LEDGER: kern_return_t = 33; pub const KERN_INVALID_MEMORY_CONTROL: kern_return_t = 34; pub const KERN_INVALID_SECURITY: kern_return_t = 35; pub const KERN_NOT_DEPRESSED: kern_return_t = 36; pub const KERN_TERMINATED: kern_return_t = 37; pub const KERN_LOCK_SET_DESTROYED: kern_return_t = ...
Rust
0
"""Init file for utils."""
Python
1
odel_kwargs = super()._update_model_kwargs_for_generation( outputs, model_kwargs, is_encoder_decoder, standardize_cache_format, ) if "image_attention_mask" in model_kwargs: image_attention_mask = model_kwargs["image_attention_mask"] ...
Python
1
#!/usr/bin/env python """ Copyright (c) 2006-2024 sqlmap developers (https://sqlmap.org/) See the file 'LICENSE' for copying permission """ from lib.core.common import Backend from lib.core.common import Format from lib.core.data import conf from lib.core.data import kb from lib.core.data import logger from lib.core....
Python
1
(exception)) return len(matches) - len(matches_exception) elif prop == "num_disulfide": smarts = '[#16X2H0][#16X2H0]' matches = mol.GetSubstructMatches(Chem.MolFromSmarts(smarts)) return len(matches) elif prop == "num_sulfoxide": smarts = '[$([#16X3]=[OX1]),$([#16X3+]...
Python
1
= models.DateTimeField(default=timezone.now) commenter = models.ForeignKey('profiles.Profile', on_delete=models.CASCADE, default=1) post = models.ForeignKey('Video', on_delete=models.CASCADE) likes = models.ManyToManyField(User, blank=True, related_name='comment_likes') dislikes = models.ManyToManyField...
Python
1
import torch from lada.deepmosaics.models import model_util from lada.deepmosaics.models.BVDNet import define_G as video_G def video(gpu_id, model_path): netG = video_G(N=2,n_blocks=4,gpu_id=gpu_id) netG.load_state_dict(torch.load(model_path)) netG = model_util.todevice(netG,gpu_id) netG.eval() ret...
Python
1
#!/usr/bin/env python # mapper.py # Maps values that are used in a stripes-based statistical aggregation. # # Author: Benjamin Bengfort <benjamin@bengfort.com> # Created: Tue Dec 01 13:40:05 2015 -0500 """ Maps values that are used in a stripes-based statistical aggregation. To execute this mapper and associated r...
Python
1
_w = tf.constant(0.001,name='lambda_w') lambda_v = tf.constant(0.001,name='lambda_v') l2_norm = tf.reduce_sum( tf.add( tf.multiply(lambda_w,tf.pow(w,2)), tf.multiply(lambda_v,tf.pow(v,2)) ) ) error = tf.reduce_mean(tf.square(y-y_hat)) loss = tf.add(error,l2_norm) train_op = tf.train.Gradient...
Python
1
import os from setuptools import setup with open(os.path.join(os.path.dirname(__file__), 'README.rst'), encoding='utf-8') as f: README = f.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name="simpleidml", version="1.3....
Python
1
*; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct BundleResponse { #[serde(flatten)] pub doc: DocInfo, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SearchResponse { pub count: u64, pub docs: Vec<DocInfo>, } }use crate::*; use async_t...
Rust
0
import collections class TrieNode: def __init__(self, letter): self.letter = letter self.children = {} self.terminal = False class Trie: dict = {} for i in range(1, 27): dict[i] = chr(ord('a') + i - 1) def __init__(self): self.root = TrieNode([]) def add_wo...
Python
1
new_queries.into_iter().for_each(|new_query| { let NewQuery { name, query } = new_query; plan.queries.insert(name, query); }); Ok(warp::reply::json(&ApiMsg { code: 201, msg: "all queries added.".to_string(), })) } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pu...
Rust
0
if matches.is_present("debug") { env::set_var("RUST_LOG", "lulzvm::vm=debug,error,info,warn,trace"); let _ = env_logger::init().unwrap(); } let termination_scheduled = Arc::new(AtomicBool::new(false)); let r = termination_scheduled.clone(); ctrlc::set_handler(move || { info!...
Rust
0
path): """Helper method to validate Vagrantfile syntax.""" # In actual implementation, would run vagrant validate content = vagrantfile_path.read_text() # Basic syntax checks if "Vagrant.configure" not in content: return False # Check for balanced do/end blo...
Python
1
cfg.optional_package), ).replace( "java/util/Optional", &format!("{}/Optional", java_cfg.optional_package.replace('.', "/")), ), }); } LanguageConfig::CppConfig(..) => { ...
Rust
0
import time #Жадібні алгоритми def find_coins_greedy(amount): coins = [50, 25, 10, 5, 2, 1] result = {} for coin in coins: if amount >= coin: num_coins = amount // coin result[coin] = num_coins amount -= coin * num_coins return result # Приклад вико...
Python
1
from fluiddyn.clusters.legi import Calcul8 as Cluster max_elapsed = "07:40:00" walltime = "08:00:00" cluster = Cluster() cluster.commands_setting_env = [ "source /etc/profile", 'export PATH="$HOME/miniconda3/bin:$PATH"' "export FLUIDSIM_PATH=/fsnet/project/meige/2020/20PHASESHIFT", ] def submit_simul( ...
Python
1
from collections import defaultdict import json import os.path import pickle import re import subprocess import urllib2 def get_existing(project='canvas'): args = ["python", "manage.py", "test", "--collect-only", "--with-id", "--exclude=compressor", "--noinput"] if project == 'drawquest': args = ['DJAN...
Python
1
#!/usr/bin/env python3 """ measure_runtime coroutine """ import time import asyncio async_comprehension = __import__('1-async_comprehension').async_comprehension async def measure_runtime() -> float: """ Run time for four parallel comprehensions """ start = time.perf_counter() coroutines = [] for i...
Python
1
create_dir_all(mount_dir.join("sys"))).and_then(|_| fs::create_dir_all(mount_dir.join("dev"))).expect("failed to create mount dir"); for mount in &binds { fs::create_dir_all(mount_dir.join(rootless(mount.last_mount()))).expect("failed to create mount dir") ...
Rust
0
= ( [LitellmConverter.convert_tool_call_to_openai(tool) for tool in message.tool_calls] if message.tool_calls else None ) provider_specific_fields = message.get("provider_specific_fields", None) refusal = ( provider_specific_fields.get("refusal", ...
Python
1
def format_places_result(self, places): if not places: return "К сожалению, места поблизости не найдены 😔" formatted_result = "места поблизости:\n\n" for place in places: formatted_result += f"🏠 {place['name']}\n" formatted_result += f"📍 Адрес: {plac...
Python
1
import pygame from Characters.action import Action class SoundObject: def __init__(self, target_object): """ :param target_object: Объект, к которому привязаны звуки (персонаж, платформа и т.д.) """ self.target = target_object self.sounds = {} # Словарь для хранения звуков {SoundAct...
Python
1
import numpy as np import tensorcircuit as tc from typing import List import math tc.set_backend("tensorflow") def get_qubit_count(p: int) -> int: """根据模数p计算所需的量子比特数量:n = ceil(log2(p))""" return math.ceil(math.log2(p)) def int_to_qubits(c: tc.Circuit, value: int, qubits: List[int]): """将整数编码到量子比特寄存器中(小端序...
Python
1
0] = m[r * 0 + 0] * n[r * 1 + 0] + m[r * 1 + 0] * n[r * 1 + 1] + m[r * 2 + 0] * n[r * 1 + 2]; result[r * 1 + 1] = m[r * 0 + 1] * n[r * 1 + 0] + m[r * 1 + 1] * n[r * 1 + 1] + m[r * 2 + 1] * n[r * 1 + 2]; result[r * 1 + 2] = m[r * 0 + 2] * n[r * 1 + 0] + m[r * 1 + 2] * n[r * 1 + 1] + m[r * 2 + ...
Rust
0
'ᵤ', 'v': 'ᵥ', 'w': 'w', 'x': 'ₓ', 'y': 'ყ', 'z': '𝆎', 'A': 'ₐ', 'B': 'ᵦ', 'C': '꒝', 'D': 'd', 'E': 'ₑ', 'F': 'Բ', 'G': 'g', 'H': 'ₕ', 'I': 'ᵢ', 'J': 'ⱼ', 'K': 'ₖ', 'L': 'ₗ', 'M': 'ᙢ', 'N': 'ₙ', 'O': 'ₒ', 'P': 'ₚ', 'Q': 'q', 'R...
Python
1
use crate::packets::icmp::v6::{Icmpv6, Icmpv6Packet, Icmpv6Payload, Icmpv6Type, Icmpv6Types}; use crate::packets::ip::v6::Ipv6Packet; use crate::packets::{buffer, EthernetHeader, Fixed, Packet}; use std::fmt; /* From https://tools.ietf.org/html/rfc4443#section-3.2 Packet Too Big Message 0 ...
Rust
0
s[0], parsed_mac_address[1], parsed_mac_address[2], parsed_mac_address[3], parsed_mac_address[4], parsed_mac_address[5]); }; if matches.is_present("dashed") { ...
Rust
0
(n - 1) for n in nobs_list) - 1 / (nobs - m) c1 *= (2 * k*k + 3 * k - 1) / (6 * (k + 1) * (m - 1)) df_chi2 = (m - 1) * k * (k + 1) / 2 statistic_chi2 = (1 - c1) * stat0 pvalue_chi2 = stats.chi2.sf(statistic_chi2, df_chi2) c2 = sum(1 / (n - 1)**2 for n in nobs_list) - 1 / (nobs - m)**2 c2 *= (k...
Python
1
# Copyright (c) 2025 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