text
string
label_name
string
labels
int64
: check the reachability of a host or IP address. http: do a GET request to an URL and print the response header. dns: perform a DNS lookup of a domain name. proxy: resolve the current proxy configuration for a given URL. list networks: show properties of all networks connected ...
Rust
0
# Copyright (c) 2019-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # def f_gold ( a , n , k ) : if k >= n - 1 : return n best = 0 times = 0 for i in range ( n ) : if...
Python
1
} #[doc = "Mapping `.10` for Tuple12"] pub trait Tuple12Map10<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> { #[doc = "Mapping `.10` for Tuple12"] fn map10<U>(self, f: impl FnOnce(T10) -> U) -> (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, U, T11); } impl<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Tuple1...
Rust
0
LIBRARY_COLLECTION_CREATED, "library_collection": LibraryCollectionData(collection_key), }) # Update the collection: self._update_collection(collection_key, description="Updated description") self.expect_new_events({ "signal": LIBRARY_COLLECTION_UPDATED, ...
Python
1
update_to_latest_ledger( &self, _request: tonic::Request<UpdateToLatestLedgerRequest>, ) -> Result<tonic::Response<UpdateToLatestLedgerResponse>, tonic::Status> { unimplemented!("This method is not needed for this test"); } } #[test] fn test_submit_txn_inner_vm() { let ac_service =...
Rust
0
# Copyright 1999-2021 Alibaba Group Holding Ltd. # # 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 law or a...
Python
1
y.grid(row=2,column=1,columnspan=1) email_entry.insert(0,"Adams_email.email") # Pre-fill with a default email password_entry = Entry(width=35) password_entry.grid(row=3,column=1,columnspan=1) # ---------------------------- Buttons------------------------------- # generate_button = Button(text="Generate Password",co...
Python
1
'): browser.open(page_url) links = self.get_all_links_with_selene() return await self.check_all_links(links, page_url) async def check_links_on_page_with_bs4(self, page_url): """ Проверяет все ссылки на указанной странице с использованием BeautifulSoup и логирует битые с...
Python
1
or i in aa.len() + bb.len() - 1..c.len() { debug_assert!(c[i] == ModInt::new(0)); } c.resize(aa.len() + bb.len() - 1, ModInt::new(0)); return c; } } #[allow(unused)] mod dynamic_modint { use crate::gcd; pub use crate::modint::*; // For a = aa mod m, // it compute...
Rust
0
# Problem: Find Minimum in Rotated Sorted Array - https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/ class Solution: def findMin(self, nums: List[int]) -> int: # return min(nums) l=0 r=len(nums)-1 while r>l: mid=(l+r)//2 print(mid...
Python
1
{ Ok(Self( std::num::NonZeroU64::new(value.as_i64()? as u64) .expect("SQLite autoincrement indices start at 1"), )) } } pub(crate) mod convert { use super::*; #[allow(unused)] pub fn mode_to_i64(mode: Option<Mode>) -> Option<i64> { mode.map(|mode| m...
Rust
0
# Copyright 2021 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
Python
1
name.into(), vertex_id, update, force_wait_for_sync: None, if_match: None, keep_none: None, } } pub fn with_force_wait_for_sync(mut self, force_wait_for_sync: bool) -> Self { self.force_wait_for_sync = Some(force_wait_for_sync); ...
Rust
0
(dff["Glucose"] >= 100 ) & (dff["Glucose"] <125)) & ((dff["Age"] >= 50)), "New_Age_Glucose_Nom"] = "hiddensenior" dff.loc[((dff["Glucose"] >= 125 )) & ((dff["Age"] >=21) & (dff["Age"] < 50)), "New_Age_Glucose_Nom"] = "highmature" dff.loc[((dff["Glucose"] >= 125 )) & ((dff["Age"] >=50)), "New_Age_Glucose_Nom"] = "highma...
Python
1
grouped_data = active_companies_df.groupby('Date').agg({ 'Active Branches': 'max', 'Active Companies': 'max', 'Branches Change': 'sum', 'Companies Change': 'sum' }).reset_index() # Линейные графики line_chart = al...
Python
1
#[test] fn bytes_loader_ok() { let raw = raw("Hello World!"); let loaded: Vec<u8> = BytesLoader::load(raw.clone(), "").unwrap(); assert_eq!(loaded, b"Hello World!"); let loaded: Box<[u8]> = BytesLoader::load(raw, "").unwrap(); assert_eq!(&*loaded, b"Hello World!"); } #[test] fn parse_loader_ok()...
Rust
0
S::ND_INS_VMINSD => Ok(Mnemonic::Vminsd), ffi::_ND_INS_CLASS::ND_INS_VMINSH => Ok(Mnemonic::Vminsh), ffi::_ND_INS_CLASS::ND_INS_VMINSS => Ok(Mnemonic::Vminss), ffi::_ND_INS_CLASS::ND_INS_VMLAUNCH => Ok(Mnemonic::Vmlaunch), ffi::_ND_INS_CLASS::ND_INS_VMLOAD => Ok(Mnemonic:...
Rust
0
#!/usr/bin/env python """Read from the EEPROM chip on A20-OLinuXino-MICRO On the board there is small chip U3. This is 16kb eeprom memory AT24C16BN. The i2c address can be different, but on this specific board is 0x50. The text will be big mess if python3 is used. """ from pyA20 import i2c __author__ = "Stefan Mavr...
Python
1
pected_action_meanings = ["FIRE", "LEFT", "RIGHT"] class mock_input: def __init__(self): self.index = 0 def __call__(self, _): key = provided_keys[self.index] self.index += 1 return key with mock.patch("builtins.input", mock_input()): fo...
Python
1
import time import joblib from scipy.io import loadmat from sklearn.preprocessing import StandardScaler from sklearn.neural_network import MLPClassifier def CreateBPNN(train_X, train_Y, test_X, layersize, t, saveflag=False): # 数据标准化:神经网络对数据尺度敏感,所以最好在训练前标准化,或者归一化,或者缩放到[-1,1] scaler = StandardScaler() # 标准化转换 ...
Python
1
aspect: f64, ) -> i32; pub fn dx_CreateScalingMatrix(Out: *mut Matrix, sx: f32, sy: f32, sz: f32) -> i32; pub fn dx_CreateScalingMatrixD(Out: *mut DMatrix, sx: f64, sy: f64, sz: f64) -> i32; pub fn dx_CreateRotationXMatrix(Out: *mut Matrix, Angle: f32) -> i32; pub fn dx_CreateRotationXMatrix...
Rust
0
psc::channel; use std::thread::{spawn, JoinHandle}; pub struct MPSCQConsumerWorker<T: Sized> { thread_handle: JoinHandle<()>, phantom: PhantomData<T>, } impl<T> MPSCQConsumerWorker<T> where T: Send + Sized, { pub fn start(new_queue_handler: Arc<&'static (dyn Fn(T) + Send + Sync)>) -> (Sender<T>, Self)...
Rust
0
X-License-Identifier: Apache-2.0 // 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 law or agreed to in wr...
Rust
0
file=f) def main(): if 'OPENAI_API_KEY' in os.environ: openai.api_key = os.environ['OPENAI_API_KEY'] else: raise Exception("Missing openai key!") if 'OPENAI_ORGANIZATION' in os.environ: openai.organization = os.environ['OPENAI_ORGANIZATION'] res, answer = [], [] match args....
Python
1
# -*- coding: utf-8 -*- ''' 【简介】 PyQt5中 处理database 例子 ''' import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5.QtSql import QSqlDatabase , QSqlQuery def createDB(): db = QSqlDatabase.addDatabase('QSQLITE') db.setDatabaseName('./db/database.db') ...
Python
1
(1, epochs + 1): train_loss = train(model, train_dataloader, criterion, optimizer, device) val_loss, val_ndcg = evaluate(model, val_dataloader, criterion, device, top_k=top_k) print(f'Epoch {epoch}/{epochs}, Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val NDCG@{top_k}: {val_ndcg:.4f}...
Python
1
# Python Markdown # A Python implementation of John Gruber's Markdown. # Documentation: https://python-markdown.github.io/ # GitHub: https://github.com/Python-Markdown/markdown/ # PyPI: https://pypi.org/project/Markdown/ # Started by Manfred Stienstra (http://www.dwerg.net/). # Maintained for a few years by Yuri Tak...
Python
1
).grid(row=1, column=0, sticky="w") # Actions on the right - always visible actions_frame = ttk.Frame(footer_frame) actions_frame.grid(row=1, column=2, sticky="e") ttk.Button(actions_frame, text="📁 Ordner öffnen", command=lambda: os.startfile(results_dir)).pack(side=tk.LEFT, ...
Python
1
for i in range(1): for j in range(2): h = np.array(state_embeddings[i, j, :, :].array.sum()) h = F.sigmoid(F.sigmoid(F.sigmoid(h))) self.assertEqual(h.array, layer_encodings.array[i, j]) def test_Decoder(self): initialW = np.ones((1, 2)) ...
Python
1
for done in done_list.list.iter() { writeln!(file, "DONE: {}", done).unwrap(); } } // TODO: Save system // TODO: ADD notification system // TODO: Rename items fn main() -> crossterm::Result<()> { sleep_ms(0); // TODO: remove this when the func that this points to is used in this li...
Rust
0
_pos = scene.get_pos(creature_id)?; let pts = self.tile_system.open_points_in_range(creature_pos, &scene.terrain, range); Ok(PotentialTargets::Points(pts)) } fn creatures_in_range( &self, scene: SceneID, creature_id: CreatureID, distance: u32units::Length, ) -> Result<PotentialTargets, GameError> { ...
Rust
0
"""Pydantic-specific warnings.""" from __future__ import annotations as _annotations from .version import version_short __all__ = 'PydanticDeprecatedSince20', 'PydanticDeprecationWarning' class PydanticDeprecationWarning(DeprecationWarning): """A Pydantic specific deprecation warning. This warning is raise...
Python
1
#################################################################################################### # Copyright (c) 2020 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
Python
1
.to_str()?; let chrom = chroms.iter().find(|x| x.name == chr); if chrom.is_none() { let msg = format!("Chrom {} doesn't exists", chr); return Err(std::io::Error::new(std::io::ErrorKind::Other, msg).into()); } let (begin, end) = match (begin...
Rust
0
alue *= character_data.mana_point / 100 # 监狱长的对抗值 warden_data = cache.character_data[warden_id] warden_value = warden_data.ability[42] warden_value *= warden_data.hit_point / 100 warden_value *= warden_data.mana_point / 100 # 对比 if escape_value > warden_value: return True, escape_v...
Python
1
Expr.Nop, Expr.Return, ), ) Battle(0x00002712, 0x00300011, 0x00, 0x0000, 0xFF) ExecExpressionWithVar( 0x30, ( (Expr.PushLong, 0x10), Expr.Nop, Expr.Return, ), ) Jump('loc_3BAD') def _loc_3B7A(): pass label...
Python
1
#%% import numpy as np import os import pickle import argparse import dash from lpu3dnet.post_process.util import generate_compare_img from lpu3dnet.post_process.util import generate_compare_img_morecond from dash import html, dcc, Input, Output import plotly.graph_objects as go # %% def create_dash_app(data): ap...
Python
1
e_details, product, state, district): district for district in districts} for future in as_completed(futures): district = futures[future] try: price_details = future.result() if price_details: all_pr...
Python
1
Deserialize; use super::{food::Food, inverse_map_range, Entity}; /// The indicies of each animation frame for the fish. /// /// The order of the animation frames will be from the beginning of the array to the end. Ultimately specifying which /// animation frame to switch to next and looping back to the beginning of t...
Rust
0
-ast<filename>src/types/parsers.rs // Copyright (c) 2021 FZI Forschungszentrum Informatik // SPDX-License-Identifier: Apache-2.0 //! Parsers for types use std::sync::Arc; use nom::branch::alt; use nom::bytes::complete::take_while; use nom::combinator::{map, opt, value}; use nom::error::context; use nom::multi::{fold_...
Rust
0
ndImageInfoEntry, "rndStackUnitNumber": rndStackUnitNumber, "rndImage1Name": rndImage1Name, "rndImage2Name": rndImage2Name, "rndImage1Version": rndImage1Version, "rndImage2Version": rndImage2Version, "rndImage1Date": rndImage1Date, "rndImage2Date": rndImage2Date, ...
Python
1
ortMode, /// File format version #[serde(rename = "jsonVersion")] pub json_version: String, /// The default naming convention for level identifiers. #[serde(rename = "levelNamePattern")] pub level_name_pattern: String, /// All levels. The order of this array is only relevant in `LinearHor...
Rust
0
eprecated and will be removed in Flask" " 2.3. Use 'jinja2.utils.htmlsafe_json_dumps' instead.", DeprecationWarning, stacklevel=2, ) return _jinja_htmlsafe_dumps(obj, dumps=dumps, **kwargs) def htmlsafe_dump(obj: t.Any, fp: t.IO[str], **kwargs: t.Any) -> None: """Serialize an objec...
Python
1
// Identifies which column this item should be placed in. fn db_column() -> DBColumn; /// Serialize `self` as bytes. fn as_store_bytes(&self) -> Vec<u8>; /// De-serialize `self` from bytes. fn from_store_bytes(bytes: &mut [u8]) -> Result<Self, Error>; /// Store `self`. fn db_put(&self, st...
Rust
0
i_info)], CHOOSE_ROUTE: [MessageHandler(Filters.text & ~Filters.command, choose_route)], CHOOSE_ROUTE_BACK: [MessageHandler(Filters.text & ~Filters.command, back_to_choose_route)], END_CONVERSATION: [MessageHandler(Filters.text('Начать путешествие'), end_conversation)] }, ...
Python
1
) -> Mem { Mem(mem_str.trim().split(",") .map(|chunk| chunk.parse().unwrap()) .enumerate() .collect()) } enum ParamMode { Position, Immediate, Relative } fn param_mode(mem: &Mem, pc: usize, param_num: usize) -> ParamMode { match mem[pc] / i64::pow(10, param_num as u32 + 1) ...
Rust
0
ew.dart", get_new_file_name( /*filename*/ "hello.copy.new.c", /*file extension*/ "dart" ), "It changes only the last extension for the file" ); } } <reponame>ever0de/prisma-engines use crate::{ ast, types::IdAttribute, walkers::...
Rust
0
), ha='center', va='bottom', color='b') for i, value in enumerate(edges): ax2.text(i, value, str(value), ha='center', va='top', color='r') # Настраиваем цвета делений на осях ax1.tick_params(axis='y', labelcolor='b') ax2.tick_params(axis='y', labelcolor='r') # Добавляем легенду ...
Python
1
false); assert!(spotify.alarm_time(alarm).is_err()); assert!(spotify.alarm_reschedule(alarm).is_ok()); assert_eq!(spotify.alarm_time(alarm).unwrap().format("%Y-%m-%d %H:%M:%S").to_string(), "2017-06-22 08:00:00"); } } <filename>src/sample1/variable.rs pub fn test(){ println!("## Variabl...
Rust
0
mport time crypto = PaillierCrypto() # より少ない数でテスト(現実的な負荷) values = list(range(10)) start_time = time.time() encrypted_values = [crypto.encrypt(v) for v in values] encryption_time = time.time() - start_time # 復号化時間を測定 start_time = time.time() de...
Python
1
# Copyright 2018 The TensorFlow 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 applica...
Python
1
fn into_child<'a>(self: Box<Self>, i: usize) -> Result<Resolvable<'w,E>,()> where Self: 'a { if i != 0 {return Err(());} Ok(self.inner.into_ref()) } impl_traitcast!( dyn AtomState<E,(u32,u32)> => |s| &s.scroll; ); } impl<'w,E,W,Scroll> WidgetMut<E> for Area<'w,E,W,Scroll> where ...
Rust
0
#!/usr/bin/env python3 import os import sys # Argument enhancement: to only run `astyle` on a specified directory, to # only include changed source code, these arguments have been added. If # run with no arguments, all the normal directories are examined as before: # - /demos/ # - /examples/ # - /src/ # - /tests/ #...
Python
1
# -*- coding:utf-8 -*- from win32api import GetSystemMetrics import win32gui, win32con, win32api, os, re, subprocess import win32clipboard as w from pyefun import * # 字母键 按键_A, 按键_B, 按键_C, 按键_D, 按键_E, 按键_F, 按键_G, 按键_H, 按键_I, 按键_J, 按键_K, 按键_L, 按键_M, 按键_N, 按键_O, 按键_P, 按键_Q, 按键_R, 按键_S, 按键_T, 按键_U, 按键_V, 按键_W, 按键_X, 按键_Y...
Python
1
7:]: v for k, v in state_dict.items()} # load state_dict meg = self.load_state_dict(state_dict, False) logger.info(meg) def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=.02) if isinstance(m, nn.Linear) and m.bi...
Python
1
; } } answer } } #[derive(Clone, Debug, PartialEq)] pub enum Query { Read(Key), Write(Key, Value), } impl Proto<queries::Commands> for Query { fn from_proto(msg: &queries::Commands) -> Self { match msg.get_field_type() { Commands_CommandType::Read => Que...
Rust
0
<< 5 | rt } pub(super) fn simd_across_lanes( q: u32, u: u32, size: u32, opcode: u32, rn: NeonRegister, rd: NeonRegister, ) -> u32 { assert!(fits_bit(q)); assert!(fits_bit(u)); assert!(fits_u2(size)); assert!(fits_u5(opcode)); ...
Rust
0
r. shs = None colors_precomp = torch.ones_like(pc.get_xyz) # Ashawkey version rendered_image, radii, rendered_depth, rendered_alpha = rasterizer( means3D=means3D, means2D=means2D, shs=shs, colors_precomp=colors_precomp, opacities=opacity, scales=s...
Python
1
"""Celery worker configuration""" import os from celery import Celery # Create Celery app app = Celery("worker") # Configuration app.conf.update( broker_url=os.getenv("REDIS_URL", "redis://redis:6379/0"), result_backend=os.getenv("REDIS_URL", "redis://redis:6379/0"), task_serializer="json", accept_c...
Python
1
from transformers import pipeline, BlipProcessor, BlipForConditionalGeneration from PIL import Image import torch import streamlit as st st.title("Image Caption Generator") @st.cache_resource def load_model(): processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base") model = BlipForCo...
Python
1
import torch import torch.nn as nn from pcdet.utils import loss_utils class Balancer(nn.Module): def __init__(self, fg_weight, bg_weight, downsample_factor=1): """ Initialize fixed foreground/background loss balancer Args: fg_weight: float, Foreground loss weight b...
Python
1
let beta_m_theta = beta_m * henyey_greenstein_phase(cos_theta, MIE_DIRECTIONAL_G); let sun_e = sun_intensity(sun_direction.dot(up)); let mut lin = (sun_e * ((beta_r_theta + beta_m_theta) / (beta_r + beta_m)) * (Vec3::splat(1.0) - fex)) .pow(1.5); lin *= Vec3::splat(1.0).lerp( ...
Rust
0
(format!( "'{}' cannot be parsed into a number", raw_number )) )?; } let sign = if raw_sign == '-' { -1 } else { 1 }; charge[atom_i] = number as i64 * sign; } } Py...
Rust
0
, S::Error> where S: Serializer, { serializer.serialize_i32(pid.as_raw()) } pub fn deserialize<'de, D>(deserializer: D) -> Result<Pid, D::Error> where D: Deserializer<'de>, { Ok(Pid::from_raw(i32::deserialize(deserializer)?)) } } use miro_image::{GrayImage, G...
Rust
0
# 1. ls = [3, 1, 2, 3, -4, 2] min = ls[0] min_index = 0 max = ls[0] for i in range(1, len(ls)): if min > ls[i] and min > 0: #print("hello") min = ls[i] max = ls[i] #print(f"minimum is: {min}") #print(f"maximum is: {max}") # 4. sum = 0 mul = 1 for i in ls: sum = sum + i mul = mul * i #print(sum) #pr...
Python
1
persist, keys, persist=True) assert result2 == [] # First call with persist=False should return the item result3 = await deduplicate(items_no_persist, keys, persist=False) assert result3 == items_no_persist # Second call with persist=False should also return the item (no persis...
Python
1
# -*- mode: python -*- # ============================================================================= # @@-COPYRIGHT-START-@@ # # Copyright (c) 2024, Qualcomm Innovation Center, Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided t...
Python
1
# Copyright HeteroCL authors. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import heterocl as hcl import os def top_floyd_warshall(N=60, dtype=hcl.Int(), target=None): hcl.init(dtype) path = hcl.placeholder((N, N), "path") def kernel_floyd_warshall(path): def loop_1(): ...
Python
1
import pygame import time from config.settings import BUILDING, TXT # crear_ascensor(posicion_columna, piso_inicial, total_pisos) # Crea un diccionario que representa un elevator. # # Parámetros: # - column (int): posición horizontal del elevator (respecto a las coordenadas de l edificio). # - currentFloor (int): p...
Python
1
import nibabel as nib import os from torch.utils.data import Dataset import numpy as np import torch import random class AD_Standard_CNN_Dataset(Dataset): """labeled Faces in the Wild dataset.""" def __init__(self, root_dir, data_file, transform=None, noise=True): """ Args: roo...
Python
1
lass Chrome17CookiePlugin(BaseChromeCookiePlugin): """SQLite parser plugin for Google Chrome 17 - 65 cookies database files.""" NAME = 'chrome_17_cookies' DATA_FORMAT = 'Google Chrome 17 - 65 cookies SQLite database file' REQUIRED_STRUCTURE = { 'cookies': frozenset([ 'creation_utc', 'host_key'...
Python
1
#!/usr/bin/env python3 """ サンドボックスサービスの完全なテストスクリプト """ import sys import os import asyncio # パスを追加 sys.path.append(os.path.dirname(os.path.abspath(__file__))) from services.sandbox_service import ( execute_python_code_sync, execute_python_code_in_docker, ) def test_sync_functionality(): """同期版のテスト""" ...
Python
1
asmInstr, opcodes}; use crate::wasm::wasm_serialize::{serialize_i32, serialize_i64, serialize_f32, serialize_f64}; use crate::compile_int::compile_int_member_func; use crate::compile_ptr::compile_unsafeptr_member_func; #[derive(PartialEq, Copy, Clone)] pub enum TranslationUnitType{ Simple, LinkedSourceFile, ...
Rust
0
BLACK: i8 = 0b10; pub const RED: i8 = BLACK ^ 1; // 0b11 const EMPTY: i8 = 0b00; #[derive(Debug)] pub enum BipartiteCheckError { NotTwoColorable, UnreachableNodes, } impl WeightedAdjacencyList { // If the input graph is bipartite it has a two coloring which can be obtained // through this method. Eac...
Rust
0
ram idx # \return # def __getitem__(idx: int) -> AtomBondMapping: pass ## # \brief # \return # def __len__() -> int: pass ## # \brief # \param arg1 # \return # def __nonzero__(self: MolecularGraph) -> bool: pass ## # \brief # \param arg1 ...
Python
1
class Solution: def maxScore(self, cardPoints: List[int], k: int) -> int: temp = sum(cardPoints[:k]) ans = temp j = len(cardPoints)-1 for i in range(k-1, -1, -1): temp = (temp - cardPoints[i]) + cardPoints[j] ans = max(temp, ans) j -= 1 ...
Python
1
der::default(); if experimental_api() { build = build.clang_arg(format!("-D{}", EXPERIMENTAL_API).as_str()); } let bindings = build .header("src/include/redismodule.h") .whitelist_var("(REDIS|Redis).*") .blacklist_type("__darwin_.*") .size_t_is_usize(true) ....
Rust
0
gs.rs"); include!("types/ibv_port_state.rs"); include!("types/ibv_qp_attr_mask.rs"); include!("types/ibv_qp_init_attr_mask.rs"); include!("types/ibv_qp_open_attr_mask.rs"); include!("types/ibv_qp_state.rs"); include!("types/ibv_qp_type.rs"); include!("types/ibv_rate.rs"); include!("types/ibv_rereg_mr_err_code.rs"); inc...
Rust
0
).m_current_tile_number as isize); while (*p_j2k).m_current_tile_number < l_nb_tiles && (*l_tcp).m_data.is_null() { (*p_j2k).m_current_tile_number = (*p_j2k).m_current_tile_number.wrapping_add(1); l_tcp = l_tcp.offset(1) } if (*p_j2k).m_current_tile_number == l_nb_tiles { *p_go_on = 0 as l...
Rust
0
import streamlit as st import mysql.connector from openai import OpenAI from typing import List, Dict import json import pandas as pd import plotly.express as px import sqlite3 import hashlib import requests from datetime import datetime, timedelta from pygments.lexers import go class SemanticQueryCache: def __i...
Python
1
&m.query_id }, |m: &mut Query| { &mut m.query_id }, )); ::protobuf::reflect::MessageDescriptor::new::<Query>( "Query", fields, file_descriptor_proto() ) }) } } fn...
Rust
0
0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, ], }; use ristretto::RistrettoBasepointTable; pub const RISTRETTO_BASEPOINT_TABLE: RistrettoBasepointTable = RistrettoBasepointTable(ED25519_BASEPOINT_TABLE); #[cfg(test)] mod test { use consta...
Rust
0
es preset_engines_to_remove = [name for name in cls._available_engines.keys() if name.startswith("OpenAI Api ")] for engine_name in preset_engines_to_remove: del cls._available_engines[engine_name] if engine_name in cls._engine_presets: del cls._engine_presets[eng...
Python
1
(Debug)] enum IpVersion { V4, V6, } #[derive(Debug)] enum IpAddr { V4(u8, u8, u8, u8), V6(String), } #[derive(Debug)] enum Message { Write(String), Read(), } #[derive(Debug)] struct IpData { version: IpVersion, address: String, } impl Message { fn send(&self) { println!("...
Rust
0
df_dict['replay_delay_mean']) prod_count = int(df_dict['request_count_production']) # 仅当两个均值都有效且生产环境计数>0时纳入加权计算 if not pd.isna(prod_mean) and not pd.isna(replay_mean) and prod_count > 0: weight = prod_count # 以生产环境请求数为权重 total_wei...
Python
1
start_register + destructure.start.len(); if let Some(middle) = &destructure.middle { if let Some(lvalue) = middle.extra.to_lvalue() { self.assign(executable, &lvalue, start_register)?; } } let start_register = start_register + 1; for (i, lvalue)...
Rust
0
buffer as write-only (otherwise read-only). */ pub const VIRTQ_DESC_F_WRITE: u16 = 2; /* This means the buffer contains a list of buffer descriptors. */ pub const VIRTQ_DESC_F_INDIRECT: u16 = 4; /* The feature bitmap for virtio net */ pub const VIRTIO_NET_F_CSUM: usize = 0; /* Host ...
Rust
0
stringify!(m_unNumResultsReturned) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<SteamUGCQueryCompleted_t>())).m_unTotalMatchingResults as *const _ as usize }, 16usize, concat!( "Offset of field: ", stringify!(SteamUGCQueryCompleted_t), "::", stringify!(m_unTotalMatchingResults) ) ...
Rust
0
from rest_framework import generics from api.models.takeaway_type import TakeawayType from api.serializers.takeaway_type import TakeawayTypeSerializer class TakeawayTypeRetrieveUpdateDestroyView(generics.RetrieveUpdateDestroyAPIView): queryset = TakeawayType.objects.all() serializer_class = TakeawayTypeSeria...
Python
1
_shot_prompt(self, history, dev_df): prompt = history k = self.k if self.k == -1: k = dev_df.shape[0] for i in range(k): prompt += self.format_example(dev_df.iloc[i, :], few_shot=True) return prompt def generate_alpaca3_few_shot_prompt(self, history, ...
Python
1
String>>, }, RegisterDistribution { start_height: u64, end_height: u64, recipient: String, amount: Uint128, message: Option<Binary>, }, UpdateDistribution { id: u64, start_height: Option<u64>, end_height: Option<u64>, amount: Option...
Rust
0
(Clone, Debug)] pub struct Sprite { dir: PathBuf, palettes: Vec<String>, animations: Vec<String>, assembled_index: u8, // Zero => unassembled. } impl Sprite { pub fn load(_: &str, dir: &Path) -> Result<Sprite, SpriteLoadError> { let spritesheet = fs::read_to_string(dir.join("SpriteSheet.x...
Rust
0
import codecs import csv import os import ssl import zipfile from datetime import date from tempfile import TemporaryDirectory from urllib.request import urlretrieve header = { "Evidenční číslo dotace": "evidencni_cislo_dotace", "Identifikator dotace": "identifikator_dotace", "Název dotace": "nazev_dotace"...
Python
1
from Vintageous.ex.ex_error import VimError from Vintageous.ex.ex_error import ERR_INVALID_ARGUMENT from .state import EOF from .tokens import TokenEof from .tokens_base import TOKEN_COMMAND_READ_SHELL_OUT from .tokens_base import TokenOfCommand from Vintageous import ex plus_plus_translations = { 'ff': 'filefor...
Python
1
{cos, fabs, get_high_word, get_low_word, log, sin, sqrt}; const INVSQRTPI: f64 = 5.64189583547756279280e-01; /* 0x3FE20DD7, 0x50429B6D */ const TPI: f64 = 6.36619772367581382433e-01; /* 0x3FE45F30, 0x6DC9C883 */ fn common(ix: u32, x: f64, y1: bool, sign: bool) -> f64 { let z: f64; let mut s: f64; let c: f...
Rust
0
fication, CertificationMessage, CertificationShare}, dkg::Dealings, BlockProposal, CatchUpPackage, CatchUpPackageShare, ConsensusMessage, ConsensusMessageHash, Finalization, FinalizationShare, HasHeight, Notarization, NotarizationShare, Payload, RandomBeacon, RandomBeaconShare, RandomTap...
Rust
0
import sys import copy import math import numpy as np # input: # output: # parameters minSeparation=1e4 interSeparation=1e9 minCount=3 resolution=1e6 numOfQuantiles=20 percentileValues=[] for i in range(numOfQuantiles): percentileValues.append(float(i)/(numOfQuantiles-1)*100) # read IO locations from arguments i...
Python
1
import os import discord from discord.ext import commands from dotenv import load_dotenv from keep_alive import keep_alive import asyncio # Charger les variables d'environnement load_dotenv() BOT_TOKEN = os.getenv("BOT_TOKEN") # Intents nécessaires intents = discord.Intents.default() intents.messages = True intents.g...
Python
1
c_mem_size_helper(mp, obj_num, pg_shift,"] #[doc = " 0, min_chunk_size, align)."] pub fn rte_mempool_op_calc_mem_size_default( mp: *const rte_mempool, obj_num: u32, pg_shift: u32, min_chunk_size: *mut size_t, align: *mut size_t, ) -> ssize_t; } #[doc = " Function to b...
Rust
0
let mut p = Lexer::<Context<TestIncludeLocator>>::new( concat!( "#define PATH <path1>\n", "#include PATH\n", "#define test1 foo\n", ) .as_bytes(), ); p.consume_all(); assert_eq!(eval!("test1", p), "123 "); } ...
Rust
0