text
string
label_name
string
labels
int64
a> FLESA_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !(0x3fff << 2)) | (((value as u32) & 0x3fff) << 2); self.w } } #[doc = "Reader of field `LSE`"] pub type LSE_R = crate::R<u8, u8>; ...
Rust
0
function_bodies_hashes.extend(function_instruction_names_sha256); let mut reader = function_body.get_operators_reader()?; while !reader.eof() { let _op = reader.read()?; instruction_count += 1; } ...
Rust
0
RDMAWritesOrdering { #[doc = "< The device does not natively support ordering of GPUDirect RDMA writes. ::cudaFlushGPUDirectRDMAWrites() can be leveraged if supported."] cudaGPUDirectRDMAWritesOrderingNone = 0, #[doc = "< Natively, the device can consistently consume GPUDirect RDMA writes, although other CU...
Rust
0
let mut imgui_platform = imgui_winit_support::WinitPlatform::init(&mut imgui_context); imgui_platform.attach_window( imgui_context.io_mut(), window, imgui_winit_support::HiDpiMode::Locked(window.scale_factor()), ); WinitImguiManager::new(imgui_context, imgui_platform) } <repon...
Rust
0
'dano2'], i_xp= Orc_caverna['exp'] ) def combate_mf(): luta(player=player['nome'], p_dano=player['dano'][0], p_vida=player['vida'] , p_cura=player['cura'] , p_dano2=player['dano'][1], inimigo=Monstro_floresta['nome'], i_vida=Mons...
Python
1
3.2, 4.0]]; let flat: Vec<f64> = vec![0.1, 1.0, 2.0, 1.2, 1.4, 2.1, 0.5, 3.2, 4.0]; let nu_flat: &[f64] = unsafe { reinterpret_slice(vec.as_slice()) }; assert_eq!(*nu_flat, *flat.as_slice()); // Same data. assert_eq!(nu_flat, flat.as_slice()); // Same memory. let nu_slice: &[[f...
Rust
0
dth: Maximum width in pixels Returns: Wrapped text with newlines """ words = text.split() lines = [] current_line = [] for word in words: current_line.append(word) line = ' '.join(current_line) bbox = font.getbbox(line) if bbox[2] > max_width: if len(current_line) == 1: lines.append(current_...
Python
1
response) = client.get(url).send().await.and_then(|response| response.error_for_status()) { if let Ok(new_image) = response.image().await { image = Ok(new_image); break } } ...
Rust
0
"); //! //! println!( //! "iter = {}\t|| fx || = {}\tx = {:?}", //! i, //! fx.norm(), //! x.as_slice() //! ); //! //! // Check the termination criteria. //! if fx.norm() < 1e-6 { //! println!("solved"); //! break; //! } else if i == 100 { //! p...
Rust
0
emplate '{0}' (ID: {1}): {2}".format(original_name, view.Id, outer_ex)) # Escaped braces # Optional: Print summary (comment out if not desired) # print("\n# --- View Template Suffix Removal Summary ---") # print("# Total View Templates processed: {}".format(processed_templates_count)) # Escaped braces # print("# Succe...
Python
1
// # returned from call: N/A // # full stack: () // # returns: {:ok, window} // ``` process.queue_frame_with_arguments(window::window_0::frame().with_arguments(false, &[])); // ```elixir // # label 1 // # pushed to stack: () // # returned from call: {:ok, window} // # full stack...
Rust
0
= 0; let mut j = height.len()-1; let mut c = 0; let mut area = 0; let mut max_area = 0; loop { if c == height.len()-1{ break; } let left_most = height.get(i).unwrap(); let right_most = height.get(j).unwrap(); area = left_most.min(right_most) * (j...
Rust
0
rewrite user-supplied file string with a node, we need later env.Replace(YACC_GRAPH_FILE=env.File(yaccgraphfile)) return target, source def yEmitter(target, source, env) -> tuple: return _yaccEmitter(target, source, env, ['.y', '.yacc'], '$YACCHFILESUFFIX') def ymEmitter(target, source, env) -> tu...
Python
1
reated keyboard"] pub fn lv_kb_create(par: *mut lv_obj_t, copy: *const lv_obj_t) -> *mut lv_obj_t; } extern "C" { #[doc = " Assign a Text Area to the Keyboard. The pressed characters will be put there."] #[doc = " @param kb pointer to a Keyboard object"] #[doc = " @param ta pointer to a Text Area object...
Rust
0
with open(out_filename_gpt, "w") as file: pass # 创建空文件 else: out_filename_gpt = None # 统一为三目标权重向量 ref_dirs = get_reference_directions("uniform", 3, n_partitions=n_partition) # 替换为自定义问题模型 from MODTSRA.fitness i...
Python
1
}, }, ], ): channel.execute_command_help() def test_channel_command_help_in_group(self): """Ensures the command '/help' works in a group""" test_user = self.env['res.users'].create({ "login": "mario", "name": "...
Python
1
_SPEC>; #[doc = "Interrupt endpoint 8. Only valid for HOST mode."] pub mod addr_endp8; #[doc = "ADDR_ENDP9 register accessor: an alias for `Reg<ADDR_ENDP9_SPEC>`"] pub type ADDR_ENDP9 = crate::Reg<addr_endp9::ADDR_ENDP9_SPEC>; #[doc = "Interrupt endpoint 9. Only valid for HOST mode."] pub mod addr_endp9; #[doc = "ADDR_...
Rust
0
import numpy as np def hilbert_curve(n, p): """Principal Hilbert Curve. \n Vectorized implementation of the principal Hilbert curve by J. Skilling. Reference: J. Skilling, "Programming the Hilbert curve". AIP Conf. Proc., 2004, 707, 381-387. Algorithm: A single global Gray code is being...
Python
1
config['mapper']['decoder']['geo_feat_dim'], hidden_dim=config['mapper']['decoder']['hidden_dim'], num_layers=config['mapper']['decoder']['num_layers']) def forward(self, embed, embed_pos, embed_color): if embed_pos is not None: h = self.sdf_net(tor...
Python
1
/// /// (note that this mapping is the same as that of [`Func::wrap`]). /// /// Note that once the [`TypedFunc`] return value is acquired you'll use either /// [`TypedFunc::call`] or [`TypedFunc::call_async`] as necessary to actually invoke /// the function. This method does not invoke any WebAssemb...
Rust
0
let builder = WalkerTableBuilder::new(&index_weights); let wa_table = builder.build(); for i in (0..10).map(|_| wa_table.next()) { println!("{}", fruit[i]); } } <gh_stars>1-10 #[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pu...
Rust
0
u64) << 16); let x31: u64 = (((arg1[1]) as u64) << 8); let x32: u8 = (arg1[0]); let x33: u64 = (x31 + (x32 as u64)); let x34: u64 = (x30 + x33); let x35: u64 = (x29 + x34); let x36: u64 = (x28 + x35); let x37: u64 = (x27 + x36); let x38: u64 = (x26 + x37); let x39: u64 = (x25 + x38)...
Rust
0
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies building a target from a .gyp file a few subdirectories deep when the --generator-output= option is used to put the build confi...
Python
1
ld_wide_thread", "Counts things").unwrap()); let mut threads = Vec::with_capacity(5); for _ in 0..5 { threads.push(thread::spawn(|| { INT.inc(); })); } for thread in threads { thread.join().unwrap(); } assert_eq!(INT....
Rust
0
-> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_225) = &input.input_key { object.key("InputKey").string(var_225.as_str()); } if let Some(var_226) = &input.max_width { object.key("MaxWidth").string(var_226.as_str()); } if let Some(var_227) = &input.max_...
Rust
0
import warnings from dataclasses import dataclass from enum import Enum from pathlib import Path from typing import Union # According to https://learn.microsoft.com/windows/apps/design/shell/tiles-and-notifications/custom-audio-on-toasts SUPPORTED_FILE_TYPES = [".aac", ".flac", ".m4a", ".mp3", ".wav", ".wma"] class ...
Python
1
from einops import rearrange from torch import nn class CNN(nn.Module): def __init__(self): super(CNN, self).__init__() self.conv1 = nn.Sequential( nn.Conv3d(in_channels=1, out_channels=32, kernel_size=(3, 3, 3), stride=(1, 1, 1), padding='same'), nn.ReLU(), nn....
Python
1
ng_http_request_t, index: size_t, sa_family: *mut u16, ip_addr: *mut c_void, port: *mut u16, ) -> bool { let request: &Request = request.into(); return match request.resolved_socket_addrs().as_ref().get(index) { Some(SocketAddr::V4(socket_addr)) => set_resolved_socket_addr_as_ipv4(socket...
Rust
0
from fastapi import APIRouter, HTTPException, Depends, BackgroundTasks, Query from fastapi.responses import FileResponse import os from typing import Dict, Any, List, Optional import os import logging from app.core.config import settings from app.core.deps import get_api_key, get_project_id from app.schemas.dataset im...
Python
1
t_name = "_fltused"] static _FLTUSED: i32 = 0; #[panic_handler] fn panic(_info: &PanicInfo) -> ! { unsafe { DbgBreakPoint(); } loop {} } // NT related definitions. #[allow(overflowing_literals)] const STATUS_CANCELLED: NTSTATUS = 0xC0000120; const PAGE_SIZE: u32 = 0x1000; extern "system" { pu...
Rust
0
`type`s that pass /// pointers to the kernel as `u64`, you need to ensure that things like /// lifetimes are correct. pub const unsafe fn classic(request: c_ulong) -> Self { Self(request, PhantomData) } /// Lie about the ioctl direction or type /// /// This function should be avoid...
Rust
0
sentiment: Sentiment, pub symbol: String, } #[derive(Serialize, Deserialize, Debug)] pub struct Buzz { pub articlesInLastWeek: usize, pub buzz: f64, pub weeklyAverage: f64, } #[derive(Serialize, Deserialize, Debug)] pub struct Sentiment { pub bearishPercent: f64, pub bullishPercent: f64, } #...
Rust
0
), end=datetime.fromtimestamp(i["end"]).isoformat() if i["end"] else None, ) for i in res ] return api_response( result=res, command="get_map_history", arguments={}, failed=False ) @csrf_exempt @stats_login_required @require_http_methods(["...
Python
1
G STRATEGIES: def filter_identical_rings( result, strategy=2 ): """ Filtering strategy to exclude molecules with three identical rings. Returns True if the molecule should be kept, False if it should be discarded. """ smiles_list = result[1] ring1, ring2, ring3 = smiles_list #return ...
Python
1
""" Constants specific to the SQL storage portion of the ORM. """ # Size of each "chunk" for get_iterator calls. # Larger values are slightly faster at the expense of more storage space. GET_ITERATOR_CHUNK_SIZE = 100 # Namedtuples for sql.* internal use. # How many results to expect from a cursor.execute call MULTI ...
Python
1
args.to_vec(), body: substitute( &proc.body.to_vec(), vars.iter() .map(|s| s.to_owned().clone()) .collect::<Vec<_>>() .as_slice(), exps.iter() .map(...
Rust
0
field::HIP_DH_GROUP_LIST_OFFSET.start ..field::HIP_DH_GROUP_LIST_OFFSET.start + groups_len] .copy_from_slice(groups); } let pad_len: usize = (8 - (4 + groups_len) % 8) % 8; // pad_len is computed at runtime - i.e. a non-constant let padding = [0; 8]; // max paddin...
Rust
0
MmrTree::Utxo, sync_horizon_height) .unwrap(); let bob_num_utxos = bob_store .fetch_mmr_node_count(MmrTree::Utxo, sync_horizon_height) .unwrap(); let alice_num_rps = alice_store .fetch_mmr_node_count(MmrTree::RangeProof, sync_horizon_height) .unwrap(); let bob_num_rps...
Rust
0
"""Gecko APING handlers.""" from __future__ import annotations import logging import struct from typing import Any from geckolib.config import GeckoConfig from .packet import GeckoPacketProtocolHandler PING_VERB = b"APING" _LOGGER = logging.getLogger(__name__) class GeckoPingProtocolHandler(GeckoPacketProtocolH...
Python
1
ues.try_into().unwrap(); F::Extension::from_basefield_array(arr) }; // Compute the interpolant. let points = self.gate.coset(get_local_wire(self.gate.wire_shift())); let points = points .into_iter() .enumerate() .map(|(i, point)| (point.in...
Rust
0
from __future__ import annotations import polars as pl from polars.testing import assert_frame_equal, assert_series_equal def test_arr_to_list() -> None: s = pl.Series("a", [[1, 2], [4, 3]], dtype=pl.Array(pl.Int8, 2)) result = s.arr.to_list() expected = pl.Series("a", [[1, 2], [4, 3]], dtype=pl.List(p...
Python
1
} ListCasts(c) => { commands::list_casts(cli, &options, &c.pattern, c.case_sensitive).await?; } ListIndexes(c) => { commands::list_indexes(cli, &options, &c.pattern, c.system, c.case_sensitive, c.verbose).await?; } L...
Rust
0
Mock() mock_openai_response.choices[0].message.content = '{"test": "result"}' with ( patch("llm_ci_runner.llm_execution.AsyncAzureOpenAI") as mock_azure_client, patch("llm_ci_runner.llm_execution.AsyncOpenAI") as mock_openai_client, patch("llm_ci_runner.llm_execution._create_azure_clie...
Python
1
#!/usr/bin/python # -*- coding: utf-8 -*- # # Licensed under the GNU General Public License, version 3. # See the file http://www.gnu.org/licenses/gpl.txt from pisi.actionsapi import get from pisi.actionsapi import kde6 from pisi.actionsapi import pisitools from pisi.actionsapi import shelltools from pisi.actionsapi i...
Python
1
8dacf25412e2a23e6a175291453a"] .unchecked_into(), ), ], // Initial nominators vec![], // Pre-funded accounts Some(vec![ // <KEY> hex!["f03941f93b990c271015d3b485f137e117aab80af0a03b557966927caaa7d44f"].into(), ]), // Appchain config appchain_config( // Appchain...
Rust
0
Rock => (128, 128, 128), Element::Wood => (119, 64, 27), Element::Iron => (151, 152, 157), Element::Rust => (184, 83, 46), Element::Sand => (219, 176, 125), Element::Water => (16, 16, 128), Element::Drain => (0, 0, 0), Element::Acid => ...
Rust
0
33 30 24.505149051733333 39 fn main() { println!("Hello, world!"); for_each_planet(|planet| println!("{}", planet)); // borrow rule also apply let greeting = String::from("Good to see you"); for_each_planet(|planet| println!("{}, {}", greeting, planet)); for_each_planet_static(move |planet| p...
Rust
0
id; let ability = player_card.base_card.ability(); let mut events = vec![ CombatEvents::ApplyAbility { card_index, player_id, ability, card_id: player_card.id } ]; match ability { Abilities::ToxicSpores => { opponent_hb.board[opponent_card_index as usize].hp = 0; } ...
Rust
0
children .entry(parent_color.to_string()) .or_insert_with(HashSet::new) .insert((child_color.to_string(), n)); parents .entry(child_color.to_string()) .or_insert_with(HashSet::new) .insert((parent_color....
Rust
0
core.\n\tExpected: {}\n\tActual: {}" } #[derive(Clone)] pub struct CommandProxy { pub command: Box<dyn Command>, _lib: Arc<Library>, _lib_name: String, pub aliases: Vec<String>, pub is_alias: bool, } #[async_trait] impl Command for CommandProxy { async fn execute( &self, me...
Rust
0
dollars' [102] StaticText '$460' [103] button 'Monday, February 3, 2025 , 460 US dollars' [104] StaticText '$460' [105] button 'Tuesday, February 4, 2025 , 460 US dollars' [106] StaticText '$460' [107] button 'Wednesday, February 5, 2025 , 460 US dollars' [108] StaticText '$460' [109] button 'Previ...
Python
1
.") def delete_message(self): """Delete a saved message""" print("\n--- 시스템 메시지 삭제 ---") name = self.get_user_input("삭제할 메시지 이름: ") if self.system_message_manager.delete_system_message(name): print("메시지가 성공적으로 삭제되었습니다.") else: print(f"메시지 ...
Python
1
_events: Vec::new(), }; vd.append_external_event(ExternalEvent::Duplicate{from: None, to: Some(x.clone())}, &(2 as usize)); vd.append_external_event(ExternalEvent::Duplicate{from: Some(x.clone()), to: Some(y.clone())}, &(3 as usize)); vd.append_external_event(ExternalEvent::PassByStaticReference{from: ...
Rust
0
20., -10.), (50., 0.), (80., -10.)], ); } pub fn get_world() -> World { let mut world = World::new(); world.insert(Time::default()); world.insert(PlayerPosition::default()); register!(Transform, Circle, Color, Moving, BallEnemy, EnemySpawner, Triangle -> world); ...
Rust
0
date(&mut self) -> Result<()> { Ok(()) } fn draw(&mut self) -> Result<()> { let Self { space, text } = self; let graphics = space.fetch_one::<Graphics>()?; let gfx = &mut *graphics.borrow_mut(); gfx.set_projection(Orthographic3::new(0., 1280., 960., 0., -1., 1.)); ...
Rust
0
= x; // `x` is now immutable and is bound to `7`. let y = 4; let y = "I can also be bound to text!"; // `y` is now of a different type. } #[doc = "Reader of register DTTIME"] pub type R = crate::R<u32, super::DTTIME>; #[doc = "Writer for register DTTIME"] pub type W = crate::W<u32, super::DTTIME>; #[doc = "Re...
Rust
0
#! /usr/bin/python import os, re, sys # Split pg_dump files to schema/type file hierarchy # Use with files produced by pg_dump -s #TODO: Identify dropped objects and delete from tree # Detect object header lines re_obj = re.compile(r'-- Name: ([-\w\s\.]+)(?:\([-\w\s\[\],]*\))?; Type: ([-\w\s]+); Schema: ([-\w]+); Ow...
Python
1
id, buf.len() as u32, buf.as_mut_ptr_range().end, (buf.capacity() - buf.len()) as u32, )?; assert!(remaining <= 0, "should have read whole block"); } let size = (buf.capacity() as i64) + (remaining as i64); assert!...
Rust
0
let tmp_r2 = r2.0 as i32; r3 = U16!(((tmp_r3 - tmp_r2) >> 1) as u16); r4 -= r0; r4 -= r6 << 6; r4 = (r4 << 1) + r5; r2 += r3; r1 -= (r2 << 6) + r2; r2 -= r6; r2 -= r0; r1 += U16!(45) * r2; let tmp_r4: i32 = r4.0 as i32; let t...
Rust
0
where T: Serialize + Sync, { pub ts: String, pub service: String, pub collector: &'static str, pub labels: Vec<String>, #[serde(flatten)] pub data: &'a T, } /// Stub collectors are used to substitute collectors disabled in compile time. pub struct StubCollector<TCfg> { pub id: String, ...
Rust
0
tdict['user_install2_' + ctn] = 1 featdict['ctn_1rec_type_1'] = 0 featdict['ctn_1rec_type_2'] = 0 featdict['ctn_1rec_type_3'] = 0 featdict['user_install_NUNIQUE'] = df['user_install'].nunique() # user_install 用户安装渠道 留存率分级 if df['user_install'].iloc[0] in in...
Python
1
# (nkpoints,nbands, nspin, natom, norbital) temp_spd = np.swapaxes(temp_spd, 2, 4) # (nkpoints,nbands, norbital , natom , nspin) temp_spd = np.swapaxes(temp_spd, 2, 3) # (nkpoints,nbands, natom, norbital, nspin) # projected[ikpoint][iband][iatom][iprincipal][iorbital][ispin] ...
Python
1
import sqlite3 from datetime import datetime, timedelta # Connect to the database db_file = "vehicle.db" conn = sqlite3.connect(db_file) cursor = conn.cursor() # Function to optimize and maintain the database def optimize_database(): cursor.execute("CREATE INDEX IF NOT EXISTS idx_license_plate_auth ON authorized_...
Python
1
def __getNextPrimeNumber(self, num: int)->int: if num in self.primes: i = self.primes.index(num) else: i = len(self.primes) - 1 if i + 1 < len(self.primes): return self.primes[i+1] self.primeRange = self.primeRange * ...
Python
1
e defined"); interval.tick().await; // 0 second tick loop { let config = match get_realtime_feed_config(&realtime_config_filepath).await { Ok(c) => c, Err(e) => { error!("Error fetching gtfs realtime configs: {}", e); tokio::time::delay_for(std::...
Rust
0
item<K: Eq + Hash, V: PartialEq>( map: &Mutex<HashMap<K, Arc<V>>>, k: K, v: V, ) -> Arc<V> { match map.lock().await.entry(k) { Entry::Occupied(e) if **e.get() == v => Arc::clone(e.get()), Entry::Occupied(mut e) => { let v = Arc::new(v); e.insert(Arc::clone(&v)); ...
Rust
0
"custom_operation_exec_time": 11400, "custom_json_operation_exec_time": 11400, "custom_binary_operation_exec_time": 11400, "decline_voting_rights_operation_exec_time": 5300, "delegate_ve...
Python
1
: data_x,\ self.y: data_y,\ self.m: data_m,\ self.delta: data_delta,\ self.mean: data_mean,\ self.x_lengths: data_x_lengths,\ self.lastvalues: data_lastvalues,\ self.keep_prob: 0.5...
Python
1
tImplementedError(f"Task '{task}' is not yet implemented.") # Automatically determine update time interval based on the Row Count if row_count <= 1000: interval = 10 * 60 elif row_count <= 3000: interval = 30 * 60 elif row_count <= 6000: interval = 60...
Python
1
5, 0xF0), _mm_blend_epi16(m3, m1, 0xF0), _mm_alignr_epi8(m6, m0, 8), _mm_blend_epi16(m4, m6, 0xF0), ) }; } macro_rules! load5 { () => { ( _mm_unpacklo_epi64(m1, m3), _mm_unpacklo_epi64(m0, m4...
Rust
0
"HashmapEntry<User>"); }/* * Copyright 2017 <NAME> * * 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 applicable...
Rust
0
from django.template.defaultfilters import linebreaksbr from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import setup class LinebreaksbrTests(SimpleTestCase): """ The contents in "linebreaksbr" are escaped according to the current autoescape setting. "...
Python
1
IRI::from_str("url(#id)").unwrap(), FuncIRI("id")); } #[test] fn parse_func_iri_2() { assert_eq!(FuncIRI::from_str("url(#1)").unwrap(), FuncIRI("1")); } #[test] fn parse_func_iri_3() { assert_eq!(FuncIRI::from_str(" url( #id ) ").unwrap(), FuncIRI("id")); } ...
Rust
0
_at_text(-1223.129) -> Text, *"-1223.129"); assert_call_eq!(Number::qs_at_text(Number::INF) -> Text, *"inf"); assert_call_eq!(Number::qs_at_text(-Number::INF) -> Text, *"-inf"); for _ in 0..1000 { let n = random::<IntegerType>(); let f = random::<FloatType>(); assert_call_eq!(Number::qs_at_text(n)...
Rust
0
if path_s.ends_with("_compare.html") || !path_s.ends_with(".html") { continue } if !run_test(path_s) { failures += 1; } } } failures } #[test] fn test_files() { assert_eq!(visit_test_dir(&"test_files"), 0); } use crate::{confi...
Rust
0
))) # Delete old checkpoints if checkpoint_save_total_limit is not None and checkpoint_save_total_limit > 0: old_checkpoints = [] for subdir in os.listdir(checkpoint_path): if subdir.isdigit(): old_checkpoints.append({"step": int(subdir), "pat...
Python
1
def multiply(p1, p2): return p1 * p2 print(multiply(10,20)) print(multiply('a',20)) print(multiply(5,'d'))
Python
1
Disable internal ram mapping completely RAM_DIS OFFSET(4) NUMBITS(1) [], /// On-die ram is enabled for generic mailbox mode. Note when this field /// is 1, internal ram mapping is automatically disabled MAILBOX_EN OFFSET(5) NUMBITS(1) [], /// Prefetch limit for internal flash re...
Rust
0
""" website URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-b...
Python
1
_add.unwrap() as u16; retval = retval | add<<8; Ok(retval as u64) } pub fn read_32(&self, addr: usize) -> Result<u64, ()> { let _retval = self.read_16(addr); if _retval.is_err() { return Err(()); } let mut retval = _retval.unwrap() as u32; let...
Rust
0
_SystemServices'*"] pub const IMAGE_REL_BASED_MACHINE_SPECIFIC_9: u32 = 9u32; #[doc = "*Required features: 'Win32_System_SystemServices'*"] pub const IMAGE_REL_BASED_MIPS_JMPADDR: u32 = 5u32; #[doc = "*Required features: 'Win32_System_SystemServices'*"] pub const IMAGE_REL_BASED_MIPS_JMPADDR16: u32 = 9u32; #[doc = "*Re...
Rust
0
.inner().space; let upper = space.persistent_context(); let x = value.val.read().take(); upper.inner().roots.push_back(x); Local { val: upper.inner().roots.back_mut().unwrap(), _marker: Default::default(), } } } } ...
Rust
0
test] fn test_data (){ let bytes = [0xefu8, 0xbe, 0xad, 0xde, 0, 0, 0, 0, 0, 0, 224, 63]; let data: Data = bytes.pread_with(0, LE).unwrap(); println!("data: {:?}", &data); assert_eq!(data.id, 0xdeadbeefu32); assert_eq!(data.timestamp, 0.5f64); let mut bytes2 = vec![0; ::std::mem::size_of::<Data>...
Rust
0
rsing requirements files with -r includes.""" content = """-r base.txt # Comments requests>=2.25.0 click>=8.0.0""" with tempfile.NamedTemporaryFile(mode="w", suffix=".in", delete=False) as f: f.write(content) f.flush() temp_path = Path(f.name) try: ...
Python
1
: ", stringify!(JoinExpr), "::", stringify!(alias) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<JoinExpr>())).rtindex as *const _ as usize }, 56usize, concat!( "Offset of field: ", stringify!(JoinExpr), "...
Rust
0
) + x.powi(2) + 1.0 } // The derivative of f fn fd(x: f64) -> f64 { (3.0 * x.powi(2)) + (2.0 * x) } #[test] pub fn test_find_root_fails_with_precision() { find_root(&f, &fd, 100.0, 0.001, 10).unwrap_err(); } #[test] pub fn test_find_root_finds_result_to_precision() { let precision = 0.1; let result =...
Rust
0
+ ('-' + rest if rest else '')) def to_ordinal(self, value): if value < 0: return self.negword + self.to_ordinal(-value) if value == 1: return 'első' elif value == 2: return 'második' else: out = self.to_cardinal(value) fo...
Python
1
elf, pos): """Accurately seek to frame position, this is slower than `seek` but guarantees accurate position. Parameters ---------- pos : integer Non negative seeking position. """ assert self._handle is not None assert pos >= 0 and pos < sel...
Python
1
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2024/8/13 21:57 @Author : thezehui@gmail.com @File : logging_extension.py """ import logging import os.path from flask import Flask from concurrent_log_handler import ConcurrentTimedRotatingFileHandler def init_app(app: Flask): """日志记录器初始化""" #1...
Python
1
""" 2) Faça um programa que grave uma lista com dez números reais, calcule e mostre a quantidade de números negativos e a soma dos números positivos dessa lista. """ from random import * while True: try: lista = [] positivos = 0 negativos = 0 for _ in range(0, 10): ...
Python
1
import json import os import warnings warnings.warn("Built-in hermes is deprecated. " "Up to date version can be downloaded with 'pip3 install armada' " "and imported with 'from armada import hermes' line.") def get_config_file_path(key): for env in os.environ.get('CONFIG_PATH', '')....
Python
1
de::*; pub use crate::settings::prelude::*; pub use crate::solid_tag::SolidTag; pub use crate::states::helpers::*; } mod helpers; pub use prelude::*; use std::hash::{Hash, Hasher}; use std::fmt; use std::fmt::Debug; use traits::Fact; use ordered_float::NotNaN; use runtime::memory::SymbolId; use num::Float...
Rust
0
doc.set_image(out, step_name="WaveScale HDR") elif hasattr(self._doc, "apply_numpy"): self._doc.apply_numpy(out, step_name="WaveScale HDR") else: self._doc.image = out except Exception as e: QMessageBox.critical(self, "WaveScale HDR", f"Failed ...
Python
1
") st.write(f"• Similarity: {similarity:.4f}") if item_type == 'tool': st.write(f"• Tool: {item.get('name', 'Unknown')}") st.write(f"• Description: {item.get('description', 'No description')}") st.write(f"• C...
Python
1
clone(), &self.lve_renderer.get_swapchain_render_pass()); self.rebuild = false; } match self.lve_renderer.begin_frame(&self.window) { Some(command_buffer) => { let frame_index = self.lve_renderer.get_frame_index(); let frame_info = FrameInfo { ...
Rust
0
read_pos); if write_slot == read_slot && write_pos != read_pos { // writer is one cycle ahead of reader Err(value) } else { // this bucket belongs to the writer now, so we are allowed to create a &mut let bucket = unsafe { &mut *self.buckets[write_slot].ge...
Rust
0
_DS_MODULE_HIERARCHICAL_OPERATIONAL_BINDINGS => 2, 5, 1, 20, 8; JOINT_ISO_ITU_T_DS_MODULE_DSA_OPERATIONAL_ATTRIBUTE_TYPES => 2, 5, 1, 22, 8; JOINT_ISO_ITU_T_DS_MODULE_SCHEMA_ADMINISTRATION => 2, 5, 1, 23, 8; JOINT_ISO_ITU_T_DS_MODULE_BASIC_ACCESS_CONTROL => 2, 5, 1, 24, 8; JOINT_ISO_ITU_T_DS_MODULE_DIRE...
Rust
0
from fatcat_openapi_client import * from fixtures import * def test_creators(api): eg = quick_eg(api) # all the fields! c1 = CreatorEntity( display_name="Emma Smith", given_name="emma", surname="smith", orcid="0000-0002-1825-0097", wikidata_qid="Q9542248", ...
Python
1
Mut for W { #[inline(always)] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<crate::W<GPDAC_CONFIG_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<GPDAC_CONFIG_SPEC>) -> Self { W(writer) } } #[doc = "Field `rsvd_31_24` reader - "] pub struct RS...
Rust
0
: bool) { TEST.push(repeat2_node(cnt, compressable)) } pub fn repeat2_node(cnt: u32, compressable: bool) -> Node { node!(Cycle, cnt, compressable) } <filename>src/sql-parser/src/ast/defs/expr.rs // Copyright 2018 sqlparser-rs contributors. All rights reserved. // Copyright Materialize, Inc. All rights reserved...
Rust
0