text
string
label_name
string
labels
int64
dbg!(hull); // let p2 = p.cast(|v| BigRational::from_i32(v).unwrap()); // dbg!(p2.centroid()); // let a: Array2<BigRational> = unimplemented!(); // let b = array![7, 8, 9]; // // let c: Array2<i32> = arr1(&b); // dbg!(a.dot(&b)); // let m = vec![vec![1, 2, 3], vec![4, 5, 6]]; // let v = vec![7, 8, 9]; ...
Rust
0
possible security implications associated with the " "subprocess module.", "LOW", ) ) # Most of this is based off of Christian Heimes' work on defusedxml: # https://pypi.org/project/defusedxml/#defusedxml-sax xml_msg = ( "Using {name} to parse untrusted XML da...
Python
1
().join(".git")) .unwrap_or_else(|e| panic!("Error renaming .git dir {entry:?}: {e:?}")); renamed_git_dirs += 1; // Stop iterating, we don't want to look inside .git dirs for .git dirs. it.skip_current_dir(); } } assert_eq!(expected_git_dirs_count, re...
Rust
0
ace.co/uploads'; const response = await fetch(UPLOAD_URL, { method: 'POST', headers: { 'Content-Type': file.type, 'X-Requested-With': 'XMLHttpRequest', }, body: file, /// <- File inherits from Blob }); const url = aw...
Python
1
_base` global doesn't have the type `i32`"); } if global.mutable { bail!("the `__heap_base` global is unexpectedly mutable"); } let offset = match &mut global.kind { GlobalKind::Local(InitExpr::Value(Value::I32(n))) => n, _ => bail!("`__heap_base` not ...
Rust
0
fn mobileactivation_activate_with_session( client: mobileactivation_client_t, activation_record: plist_t, headers: plist_t, ) -> mobileactivation_error_t; } extern "C" { #[doc = " Deactivates the device."] #[doc = ""] #[doc = " @param client The mobileactivation client"] pub...
Rust
0
from collections import defaultdict class Solution: def maxOperations(self, nums, k: int) -> int: ans = 0 dic = defaultdict(int) for num in nums: if k - num in dic and dic[k-num] > 0: dic[k-num]-=1 ans+=1 else: dic[num]+...
Python
1
a model from the bytes pointed to by `model_data` with length `model_data_len`. On success, a pointer to the loaded model will be written to `model_ptr`. You must call `tangram_model_delete` when you are done with it. #[no_mangle] pub unsafe extern "C" fn tangram_model_from_bytes( model_bytes: *const c_void, model_b...
Rust
0
"Alignment of field: ", stringify!(elf64_rela), "::", stringify!(r_addend) ) ); } impl Clone for elf64_rela { fn clone(&self) -> Self { *self } } pub type Elf64_Rela = elf64_rela; #[repr(C)] #[derive(Debug, Default, Copy)] pub struct elf32_sym ...
Rust
0
al in tokens { let git_token: GitToken = serde_json::from_value(val.clone()).unwrap(); let token_type = if git_token.symbol.to_uppercase() == "PAY" { TokenType::WrappedPay } else { get_token_type_from_tags(&git_token.tags) }; let name = if is_saber && toke...
Rust
0
' typed as "{}"'.format(gamma[instr["dest"]], instr["type"]) ) elif instr["op"] == "jmp": typecheck_label(instr["labels"][0], gamma) elif instr["op"] == "br": typecheck_label(instr["labels"][0], gamma) typecheck_label(in...
Python
1
file: File) { let cancellable = Cancellable::new(); let filepath_raw = &file .path() .expect("Could not get the file path of the file."); let filepath = Path::new(&filepath_raw); let info = file .query_info("*", gio::FileQueryInfoFlags::NONE, Some(&ca...
Rust
0
t = t.clone(); } { let _u = || s.len(); let _v = [&t; 32]; let _s = s.clone(); // ok let _t = t.clone(); // ok } { let _u = { let u = Some(&s); let _ = s.clone(); // ok u }; let _s = s.clone(); // ok } ...
Rust
0
g` pub fn get_num_bits(&self) -> usize { self.num_bits } /// Set the length of a `BitString` and initialize any new values to 0 pub fn set_num_bits(&mut self, n: usize) { self.num_bits = n; self.data.resize(n, 0); } /// Check if bit `i` is set. pub fn is_set(&self, ...
Rust
0
return "\n".join( [ f"*** {tool.name} ***:\n {tool.description}" for tool in self.tool_agents ] ) else: return "" def get_tool_agent_names(self) -> List[str]: r"""Returns the names of tool agents. ...
Python
1
#!/usr/bin/env python3 """Compila y ejecuta los ejemplos LLVM comparando resultados.""" from __future__ import annotations import subprocess from pathlib import Path from cobra.core import Lexer, Parser, TipoToken from core.ast_nodes import NodoFuncion, NodoValor, NodoOperacionBinaria from core.interpreter import In...
Python
1
first_row = input().split() second_row = input().split() third_row = input().split() # Three down - left, middle, right # Left if first_row[0] == second_row[0] == third_row[0] != '0': if first_row[0] == "1": print("First player won") elif first_row[0] == "2": print("Second player won") # Mid1d...
Python
1
wrap_by_(w, "return", ";\\n", |w| { option(w, &**expr, |w, e| { w.write_all(b" ")?; print_expr(ctx, w, env, e) }) }), S_::Expr(expr) => { print_expr(ctx, w, env, &**expr)?; w.write_all(b";\\n") } S_::Throw(e...
Rust
0
/ // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language govern...
Rust
0
hs.data[lcix][lrix], &rhs.data[rcix][rrix]) { (Value::Number(x), Value::Number(y)) => { match x.$op(*y) { Ok(op_result) => out.data[i][j] = Value::from_quantity(op_result), Err(error) => errors.push(error), // Throw an error here } ...
Rust
0
ag_occurrence) tag_occurrence_dependency_source = str(text_id) + "_" + str(sentence_id) + "_" + str(token.head.idx) dependency = {"source": tag_occurrence_dependency_source, "destination": tag_occurrence_id, "type": token.dep_} tag_occurrence_dependencies.append(dependenc...
Python
1
.writeTitle() print() csv_data = [] for instance in ins_list: list1 = [] ins = instCol.write(instance) list1.append(ins) filename = OUTPUT_DIR + '/' + instance + ".out" try: fil = open(filename, 'r') outfile = fil.read().split('\n') fil.close() except IOError: ...
Python
1
Info('FPGA RMIO Test Module: started.') #SelfTest_CF.My_Modules_Results.append(FPGA_RMIO_Operations(gRPC_channel, RMIO_FPGA_ResourceName, RMIO_Bitfile_Path, RMIO_Bitfile_Signature)) #SelfTest_CF.Display_Debug_Info('FPGA RMIO Module: completed.') # #**************************************************** FPGA ...
Python
1
, mul: &(u64, u64), j: u32, vp: *mut u64, vm: *mut u64, mm_shift: u32, ) -> u64 { m <<= 1; // m is maximum 55 bits let (lo, tmp) = umul128(m, mul.0); let (mut mid, mut hi) = umul128(m, mul.1); mid = mid.wrapping_add(tmp); hi = hi.wrapping_add((mid < tmp) as u64); // overflow ...
Rust
0
teral::hex!("2af92814c67489757805f93158045703708339848e2a8ff60ba056ef1453797e")), // AccountId::from(hex_literal::hex!("7a1261d55c86a66f999eb4e4ecab326f88a4afdbf68e020e46e461fffe32d848")), // AccountId::from(hex_literal::hex!("227d4b2c2a60014d71099e06e22647f217bc26284e8933b7e7411c1a0c02d127")), // AccountId::f...
Rust
0
term, index_record_option, similarity_weight, } } } #![feature(proc_macro_hygiene, decl_macro)] #[macro_use] extern crate rocket; #[macro_use] extern crate rocket_contrib; extern crate serde_derive; mod llvm_wasmer; mod types; mod wasmer; use base64::encode; use rocket_contrib::j...
Rust
0
event_receiver.try_recv(); assert_debug_snapshot!(click_event); }); } // FIXME - Test equivalent of Either } //! Simple helpers for building and parsing k8s paths. //! //! Loosely based on https://github.com/kubernetes/kubernetes/blob/31305966789525fca49ec26c289e565467d1f1c4/pkg/kubelet/ku...
Rust
0
import pandas as pd def get_result(results, input_file='input.xlsx', output_file='output_data.xlsx'): df = pd.read_excel(input_file) rows = [] for key, value in results.items(): row = { 'SrNO': key, 'status': value.get('status', None), 'uid': value.get('data...
Python
1
= 1.0 - v - w return np.array([u, v, w]).squeeze() def get_offsets_from_ma(ma_fpath, parents2d, parents2d_to_kps, names, dim=2): all_offsets = None with ( open(ma_fpath) as fin, ): for line in fin: if "animCurveTL" not in line: continue *_, jo...
Python
1
import unittest from unittest import mock from unittest.mock import Mock from my_package import FhirTerminologyValidation, TerminologyParam from com.nedap.archie.rm.datavalues import DvCodedText import com.nedap.archie.rm.datavalues.*; // Example usage class ExternalTerminologyValidationServerTest(unittest.TestCa...
Python
1
# Generated by Django 5.0.1 on 2024-01-11 11:35 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ('app', '0004_delete_song'), ] operations = [ migrations.CreateModel( name='Prod...
Python
1
import urllib.parse from fastapi import APIRouter, UploadFile, Form, File, HTTPException from fastapi.params import Query, Body from starlette.responses import JSONResponse, Response from common_lib.file_storage.file_manager import file_manager from schemas import methodical_book as mb_schemes from database import ...
Python
1
# create nodes by instantiation ksampler_3 = KSampler(seed=1103641334004632, control_after_generate="""randomize""", steps=20, cfg=2.5, sampler_name="""euler""", scheduler="""karras""", denoise=1) svd_img2vid_conditioning_12 = SVD_img2vid_Conditioning(width=1024, height=576, video_frames=24, motion_bucket_id=127, fps=8...
Python
1
/*/lib/linux/", ]; /// Obtains the expected name part of the compiler-rt profiler library for the specific target. /// /// The compiler-rt profiler library is always named as `libclang_rt.profile*.a`, but the `*` part is target-specific. /// For instance, on Linux and Windows x86-64 it is `"-x86_64"`, but for macOS i...
Rust
0
}\n}"})) // .json(&serde_json::json!({ // "operationName":"IcapPrice", // "variables":{"id":"0xd83c569268930fadad4cde6d0cb64450fef32b65", "block": block_num }, // "query":"query IcapPrice($id: String!, $block: Int!) ...
Rust
0
mut list_4201 = scope_4198.start_list(true, Some("item")); for item_4200 in var_4199 { #[allow(unused_mut)] let mut entry_4202 = list_4201.entry(); entry_4202.string(item_4200.as_str()); } list_4201.finish(); } #[allow(unused_mut)] let mut scope_4...
Rust
0
| { let pool = rayon::ThreadPoolBuilder::new() .num_threads(threads) .build() .unwrap(); pool.install(|| b.iter(|| task_get_rwlock_std_u64_u64(&map))); }, ); } group.finish(); } criterion_group!(ben...
Rust
0
#!/usr/bin/python3 """ defines Class Square""" from models.rectangle import Rectangle class Square(Rectangle): """class Square, a sub class of Rectangle Args: Rectangle (class): Parent class size (int): length of Square x(int): x coordinate y (int): y coordinate """ ...
Python
1
from sklearn.utils import shuffle import datetime import time from cryptography.fernet import Fernet from dateutil.parser import parse import base64 from scipy.stats import ttest_ind from http.client import HTTPConnection def my_decorator(func): parse('2024-10-19 22:16:19') def dec_result(*args, **kwargs): ...
Python
1
font: Option<Font>, text_font: Option<Font>, ) -> Self::Output; } #[cfg(debug_assertions)] impl Renderer for iced_native::renderer::Null { type Style = (); const DEFAULT_ICON_SIZE: u16 = 0; const DEFAULT_TEXT_SIZE: u16 = 0; const DEFAULT_CLOSE_SIZE: u16 = 0; const DEFAULT_PADDING: u...
Rust
0
hart.blank` will supply the template objects. Not all SSC properties are valid for SM simfiles, including some gameplay events and timing data. If one of those types of properties are found and contain a non-default value, :class:`InvalidPropertyException` will be raised. The behavior describe...
Python
1
return func return _message def callbackquery(self, pattern: str = None, run_async: bool = True): def _callbackquery(func): self._dispatcher.add_handler( CallbackQueryHandler( pattern=pattern, callback=func, run_async=run_async ...
Python
1
child, boxed, action) } TypeAscription(child, ty) => { visitor.visit_type_ascription(this, child, ty) } SpannedExpr(child) => { visitor.visit_spanned_expr(this, child) } RangeExpr(child) => { visitor.visit_range_expr(this, child) } } } pub fn walk_exprs<R: Default, V: ?...
Rust
0
g. //! //! All geometry types implementing [GeozeroGeometry](crate::GeozeroGeometry) can be encoded as PostGIS EWKB geometry using [wkb::Encode](crate::wkb::Encode). //! //! Geometry types implementing [FromWkb](crate::wkb::FromWkb) can be decoded from PostGIS geometries using [wkb::Decode](crate::wkb::Decode). #[cfg(f...
Rust
0
# pip install gtts => Convert text to speech # pip install playsound==1.2.2 => Play an mp3 file with Python # pip install -U PyObjC => If the following error occurs, ModuleNotFoundError: No module named 'AppKit' # Import the gTTS module for text-to-speech conversion from gtts import gTTS # Im...
Python
1
import re from node import Node import math import individuo import random def caminho_aleatorio(inicio, lista_arestas): caminho = [inicio] copia_arestas = lista_arestas.copy() copia_arestas.remove(inicio) tamanho_grafo = len(copia_arestas) - 1 while (tamanho_grafo >= 0): prox_no = copia_arestas[random.rand...
Python
1
l_size) { return; } const int bs = batch_size; const int vs = voxel_size; int z = i % vs; int x = (i / vs) % vs; int y = (i / (vs * vs)) % vs; int bn = i / (vs * vs * vs); int pn = i; if ((y == 0) || (y == vs - 1) || (x == 0) || (x == vs - 1) || (z == 0) || (z == vs - 1)) re...
Python
1
prepend); // Add required arguments args_builder = Self::add_required_arguments(args_builder, runtime_config, internal_config); // Add optional arguments args_builder = Self::add_optional_arguments(args_builder, jvm_config); // Append extra user arguments args_builder ...
Rust
0
_column(Column { width: 60.0 }); wb.write_sheet(&mut ws, |sw| { sw.append_row(row!["Name", "Title", "Success", "Remark"]) .unwrap(); sw.append_row(row![ "Mary", "Acountant", false, r#"<xml><tag>"" & 'World'</tag></xml>"# ]) ...
Rust
0
mut self) -> usize { // What I really wanted to do was: (this saves one instruction) // const N: isize = 4; // let data_ptr = self.data_ptr.offset(N); // if data_ptr <= self.max_data_ptr { // + update the code below // but the compiler generates worse code when '<=' is used instead of '<'. // Instead ...
Rust
0
root) => { for node in root { let prefix = format!("{}/{}", prefix, node.label); let child_path_vec = compute_path_from_tree(&tree, node.id, prefix.clone()); if child_path_vec.is_empty() { // no children == leaf path.pu...
Rust
0
specCtrl.onSpectatorViewModeChanged += self.__onSpectatorModeChanged return def _stopBattleSession(self): ctrl = self.sessionProvider.dynamic.respawn if ctrl is not None: ctrl.onRespawnVisibilityChanged -= self.__onRespawnVisibility self.removeListener(events.GameEv...
Python
1
shaper_freq_x = self.shaper_freq_x self.saved_shaper_freq_y = self.shaper_freq_y self._set_input_shaper(self.shaper_type_x, self.shaper_type_y, 0., 0., self.damping_ratio_x, self.damping_ratio_y) def enable_shaping(self): saved = self.saved_shaper_freq_x or sel...
Python
1
te(model, verbose=False) assert pbar.calls["validate"] == [] trainer.test(model, verbose=False) assert pbar.calls["test"] == [] @mock.patch("lightning.pytorch.trainer.trainer.Trainer.is_global_zero", new_callable=PropertyMock, return_value=False) def test_tqdm_progress_bar_disabled_when_not_rank_zero(is_...
Python
1
"mokdpstk"); pub const MinimumRemainingAmount: Balance = MINIMUM_REMAINING_AMOUNT; pub const MaxUnlockingChunks: u32 = MAX_UNLOCKING_CHUNKS; pub const UnbondingPeriod: EraIndex = UNBONDING_PERIOD; pub const MaxEraStakeValues: u32 = MAX_ERA_STAKE_VALUES; } impl pallet_dapi_staking::Config for TestRuntime { type Ev...
Rust
0
(Point::new(1, y), ColorPair::new(cyan, black), to_cp437('»')); draw_batch.set( Point::new(1, y + 2), ColorPair::new(med_red, black), to_cp437('Ω'), ); draw_batch.bar_horizontal( Point::new(3, y + 2), bar_end, player_stats.health.hp, player_stats.healt...
Rust
0
imple_error::{SimpleResult, SimpleError, bail}; use crate::project::H2Project; #[derive(Serialize, Deserialize, Debug)] pub struct ActionBufferEditForward { pub name: String, pub new_data: Vec<u8>, pub offset: usize, } #[derive(Serialize, Deserialize, Debug)] struct ActionBufferEditBackward { name: S...
Rust
0
from pathlib import Path from typing import List, Optional import manticore.utils.log from sqlalchemy.orm import Session from dwarfcore.dwarfcore import DwarfCore from dwarfcore.helper import setup_generic_manticore from dwarfcore.plugins.dwarf_trace import DwarfTrace from mate_query.db import Graph as CPG def setu...
Python
1
gs.debug: import logging logging.basicConfig(level=logging.DEBUG) try: # Create and run OAuth server print("🚀 Starting MCP-OAuth 2.0 Server") print("=" * 50) oauth_server = OAuthServer( host=args.host, port=args.port, ...
Python
1
import pandas as pd # Load the existing dataset file_path = 'C:/Users/zakar/anaconda3/Untitled Folder 7/commentaires_normalises_final.csv' # Update with your file path df = pd.read_csv(file_path) # Prepare new comments new_comments = [ { "user_name": "Fatima Zahra", "user_link": "https://www.face...
Python
1
), PhantomData) } } impl<T: ?Sized, R: PartialEq + Clone + fmt::Display + fmt::Debug + Hash + PartialOrd + Ord> PartialOrd for Id<T, R> { fn partial_cmp(&self, other: &Self) -> std::option::Option<std::cmp::Ordering> { self.raw_id().partial_cmp(other.raw_id()) } ...
Rust
0
#fout = 'Pk_trans_z=%.3f.txt'%z # notice that transfer functions have an inverted order:i=0 ==>z_max #np.savetxt(fout,np.transpose([Tk[0,:,i],Tk[1,:,i],Tk[2,:,i],Tk[3,:,i], # Tk[4,:,i],Tk[5,:,i],Tk[6,:,i]])) # compute growth rates for z in z_list: dz_abs = (1.0+...
Python
1
"""Реализуйте класс FieldTracker, наследники которого получают возможность отслеживать состояние определенных атрибутов своих экземпляров класса. Дочерние классы должны наследовать четыре метода экземпляра: base() — метод, принимающий в качестве аргумента имя атрибута и возвращающий либо текущее значение этого атрибут...
Python
1
HP_USDHC1_R = crate::R<bool, HP_USDHC1_A>; impl HP_USDHC1_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> HP_USDHC1_A { match self.bits { false => HP_USDHC1_A::HP_USDHC1_0, true => HP_USDHC1_A::HP_USDHC1_1, } } #[doc =...
Rust
0
segment header lsn ({}) != expected lsn ({})", segment_header.lsn, lsn ); return Err(io::Error::new( io::ErrorKind::Other, "encountered torn segment", ) .into()); } trace!("read segment header {:?}", segment...
Rust
0
# outliers = (stand_v > 3) # outlier_indices = df.index[outliers].tolist() # st.dataframe(outliers) # st.write('###### ***Outlier Indices***') # st.dataframe(outlier_indices) "_________" if len(numeric_columns) >= 1: st.write("### Histogram") colhist,...
Python
1
me(Box::new(parameter)), ) } /// 更新文档 /// /// **PUT:** `/repos/:namespace/docs/:id` `/repos/:repo_id/docs/:id` pub fn update( &self, repo: &str, id: &str, parameter: UpdateDocParameter, ) -> Result<DocListEntity, ClientError> { Request::new(&self....
Rust
0
om.random((2, 4, 50)).astype(self.dtype) self.x2 = np.random.random((3, 4, 50)).astype(self.dtype) self.axis = 0 def test_check_output(self): x0_fp8 = paddle.to_tensor(self.x0, dtype="float16").to(dtype="float8_e4m3fn") x1_fp8 = paddle.to_tensor(self.x1, dtype="float16").to(dtype="f...
Python
1
import numpy as np from metaworld.policies.action import Action from metaworld.policies.policy import Policy, assert_fully_parsed, move class SawyerDoorCloseV2Policy(Policy): @staticmethod @assert_fully_parsed def _parse_obs(obs): return { 'hand_pos': obs[:3], 'unused_1':...
Python
1
cope_4880 = writer.prefix("NotBefore"); if let Some(var_4881) = &input.not_before { scope_4880.date_time(var_4881, aws_smithy_types::date_time::Format::DateTime)?; } writer.finish(); Ok(aws_smithy_http::body::SdkBody::from(out)) } pub fn serialize_operation_crate_operation_modify_instance_event...
Rust
0
#!/usr/bin/env python3 import string import codecs import enchant # to encrypt we add <key>, to decrypt we sub <key> OR to encrypt we sub (26 - <key>), to decrypt we add (<26 - <key>) # since the key of 13 is equal to 26//2, to encrypt or decrypt we use the same method. def ROT13A(s): new = "" for char in s: if(...
Python
1
t::Ok(()) } } } macro_rules! vecdeque { ($( $v: expr ),*) => {{ let mut vec = ::std::collections::VecDeque::new(); $( vec.push_back($v); )* vec }} } pub type BinomialHeap<T> = VecDeque<Rc<BinomialTree<T>>>; #[derive(Clone, Debug, Eq, PartialEq)] pub struct BinomialTree<...
Rust
0
op @ 0x8000 ... 0x8FFF if (op & 0x000F) == 0xE => { $this.shl(((op & 0x0F00) >> 8) as u8) }, op @ 0x9000 ... 0x9FFF if (op & 0x000F) == 0x0 => { $this.sne_reg(((op & 0x0F00) >> 8) as u8, ((op & 0x00F0) >> 4) as u8) }, op @ 0xA000 ... 0xAFFF => { $this.ldi(op & 0x0FFF)}, op @ 0xB000 ... 0xBFFF => { $this.jp...
Rust
0
ict=False, latents=latents, num_inference_steps=self.num_steps, num_inversion_steps=inversion_steps) inv_img = TF.resize(inv_img, original_size, interpolation=TF.InterpolationMode.NEAREST) if inv_img.shape[0] == 1 and not is_batched: inv_img = inv_img[0] r...
Python
1
# api/tasks.py from celery import shared_task from django.core.mail import send_mail from django.conf import settings from core.models import ContactSubmission from .zoho_integration import ZohoIntegration @shared_task def send_notification_email(contact_id): """Enviar email a secretaria cuando hay nuevo contacto"...
Python
1
::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [perbuf_dith5](perbuf_dith5) module"] pub type PERBUF_DITH5 = c...
Rust
0
} impl Field for Fr { fn random<R: RngCore + ?std::marker::Sized>(rng: &mut R) -> Self { Fr(Wrapping(rng.next_u32()) % MODULUS_R) } fn zero() -> Self { Fr(Wrapping(0)) } fn one() -> Self { Fr(Wrapping(1)) } fn is_zero(&self) -> bool { (self.0).0 == 0 }...
Rust
0
ways ) ] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 1; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } # [ doc = "Values that can be w...
Rust
0
pub struct BizUuid { pub id: Option<Uuid>, pub name: Option<String>, } /// you may should use pg database! this is docker command for example: /// docker run -d --name postgres -e POSTGRES_PASSWORD=<PASSWORD> -p 5432:5432 -d postgres /// #[tokio::test] pub async fn test_pos...
Rust
0
need_update { return prev_time; } let now_best_nonce_at_source = strategy.best_at_source(); let now_best_nonce_at_target = strategy.best_at_target(); log::info!( target: "bridge", "Synced {:?} of {:?} nonces in {} -> {} race", now_best_nonce_at_target, now_best_nonce_at_source, P::source_name(), P::t...
Rust
0
count = 0; let mut o_post_sal: Option<(usize, usize)> = None; let mut post_start_index = index; while ante_count < ante_sal.1 { post_start_index = index; o_post_sal = self.get_post_sal_at(lines, index)?; if o_post_sal.is_some() { break; ...
Rust
0
# Pedia overhaul by Toffer for Caveman2Cosmos. from CvPythonExtensions import * class Page: def __init__(self, parent, H_BOT_ROW): self.main = parent self.H_PEDIA_PAGE = H_PEDIA_PAGE = parent.H_PEDIA_PAGE self.W_PEDIA_PAGE = parent.W_PEDIA_PAGE self.Y_TOP_ROW = Y_TOP_ROW = parent.Y_PEDIA_PAGE self.Y_BOT...
Python
1
#!/usr/bin/env python # -*- coding: utf-8 -*- from vtkmodules.vtkCommonTransforms import vtkTransform class SliceOrder(object): ''' These transformations permute medical image data to maintain proper orientation regardless of the acquisition order. After applying these transforms with vt...
Python
1
"Offset of field: ", stringify!(sctp_common_header), "::", stringify!(verification_tag) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<sctp_common_header>())).crc32c as *const _ as usize }, 8usize, concat!( "Offset of field: ...
Rust
0
, then it's simply /// parsed and returned. If source is a filesystem path, then it is canonicalized and returned as a /// `file:///` URL. Will return an error if the filesystem path does not exist. pub fn source_to_url(source: &str) -> Result<Url, anyhow::Error> { match Url::parse(source) { Ok(url) => Ok(u...
Rust
0
p::new(); /* this is a big comment */ map.insert("one\n", r"two\n"); } <filename>src/entities/guilds.rs<gh_stars>1-10 use crate::schema::guilds; use diesel::*; #[derive(Queryable, Insertable)] #[table_name = "guilds"] pub struct Guild { pub id: i64, pub channel_id: i64, } pub fn create_guild(c...
Rust
0
mode. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum HSEClockMode { /// Enable HSE oscillator to use external crystal or ceramic resonator. Oscillator, /// Bypass HSE oscillator to use external clock source. Bypass, } /// HSE Clock. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct HSEClo...
Rust
0
#################################### IMPORTS ################################### if __name__ == '__main__': import sys import os pkg_dir = os.path.split(os.path.abspath(__file__))[0] parent_dir, pkg_name = os.path.split(pkg_dir) is_pygame_pkg = (pkg_name == 'tests' and os.path....
Python
1
put_dir, 'GMX_PROLIG_MD')}") return self.output_dir except Exception as e: print(f"Error during GAFFMaker workflow: {e}") import traceback traceback.print_exc() raise def main(): """Main function to parse arguments and r...
Python
1
npacklogicaldescriptor(self, desc): operator = self.kTypeLogicalDescriptorOperators[desc.getparam(kae.keyAELogicalOperator, kae.typeEnumeration).data] operands = self.unpack(desc.getparam(kae.keyAELogicalTerms, kae.typeAEList)) return operator == 'NOT' and operands[0].NOT or getattr(operands[0], operator)(*operan...
Python
1
eprintln!("error running rustfmt: {:?}", e); // exit(1) } Ok(output) => { if !output.status.success() { io::stdout().write_all(&output.stdout).unwrap(); io::stderr().write_all(&output.stderr).unwrap(); ...
Rust
0
from functools import partial from itertools import repeat from autograd.tracer import Node, trace from autograd.util import subvals, toposort from autograd.wrap_util import wraps class ConstGraphNode(Node): __slots__ = ["parents", "partial_fun"] def __init__(self, value, fun, args, kwargs, parent_argnums, ...
Python
1
{178F}\u{17CA}\u{17C0}", "", ), "uni17C1=0+288|\ uni17D2179A=0+287|\ uni179F=0+928|\ uni17D2178F=0@14,-26+0|\ uni17CA=0@-32,-29+0|\ uni17C0.right1.high=0+288" ); } #[test] fn khmer_misc_081() { assert_eq!( shape( "test...
Rust
0
= package( vec![ ( "templates/main.jsonnet", "local valid = import 'ksonnet/ksonnet.beta.4/k8s.libjsonnet'; valid", ), ( "vendor/ksonnet/ksonnet.beta.4/k8s.libjsonnet", "(import 'kct.io').input", ), ], vec![], ); let package = package.unwrap(); let inpu...
Rust
0
# Configuration file for the Sphinx documentation builder. # # For the full list of built-in configuration values, see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Project information ----------------------------------------------------- # https://www.sphinx-doc.org/en/master...
Python
1
ctl, #[doc = "0x14 - OTG_HS core interrupt register"] pub otg_hs_gintsts: OtgHsGintsts, #[doc = "0x18 - OTG_HS interrupt mask register"] pub otg_hs_gintmsk: OtgHsGintmsk, #[doc = "0x1c - OTG_HS Receive status debug read register (host mode)"] pub otg_hs_grxstsr_host: OtgHsGrxstsrHost, #[doc = "0x20 ...
Rust
0
""" Classifies: CHEBI:51129 nitrohydrocarbon """ """ Classifies: CHEBI:51753 nitrohydrocarbon """ from rdkit import Chem from rdkit.Chem import AllChem def is_nitrohydrocarbon(smiles: str): """ Determines if a molecule is a nitrohydrocarbon based on its SMILES string. A nitrohydrocarbon is a hydrocarbon wh...
Python
1
return cutmix_augmentation(imgs, cls_labels, sbsparams, self.cutmix, self, rot=self.cutmix_rot) else: # expand cls_labels and sbsparams to be spatial tensor: cls_labels = torch.nn.functional.one_hot(cls_labels.long(), num_classes=len(self.noise_types)).float() # (num_classes,...
Python
1
dio(content, project_path) def safe_videotalk_with_fallback(self, video_url: str, audio_url: str, project_path: str) -> Optional[str]: """安全的数字人视频生成,支持人脸检测失败的降级处理""" try: print("🤖 正在生成数字人视频...") digital_human_url = get_videotalk(video_url, audio_url) ...
Python
1
def area(l, c): a = l * c print(f'A area de um terreno com extensao de {l}x{c} é {a}m') #principal print('Controle de Terrenos') print('-' * 20) l = float(input('LARGURA (m): ')) c = float(input('COMPRIMENTO (c): ')) area (l,c)
Python
1