text string | label_name string | labels int64 |
|---|---|---|
# Copyright 2025 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 |
) -> dispatch_queue_attr_t;
// available(macOS 10.10, iOS 8.0)
//
// TODO: Handle availability.
fn dispatch_queue_attr_make_with_qos_class(
attr: dispatch_queue_attr_t,
qos_class: DispatchQosClass,
relative_prio... | Rust | 0 |
convert()),
202,
).await?
.into_progress(self))
}
/// Update [ranking rules](https://docs.meilisearch.com/learn/core_concepts/relevancy.html#ranking-rules) of the index.
///
/// # Example
///
/// ```
/// # use meilisearch_sdk::{client::*, indexes::*, document::*,... | Rust | 0 |
1
}
};
let area = &range[idx];
if area.end < addr {
return "<out-of-range>".to_string();
}
if let Ok(mut frames) = area.ctx.find_frames(addr - area.start) {
let mut func_name = "<empty frame>".to_string();
while let Ok(Some(f)) = frames.next() {
if let So... | Rust | 0 |
_entries!(first_index $($Struct)*);
let start_ix = start_index as usize;
let mut buffer_start_ix = 0usize;
$(
let start = $Struct::INDEX as usize - start_ix;
let end = start + $Struct::LEN_BYTES;
$binding.write_to_slice(&mut buffer[start..end]);
)*
... | Rust | 0 |
ox",
"zaniedbanie": "checkbox",
"problemy opiekuńczo-wychowawcze": "checkbox",
"uzależnienia": "checkbox",
"problemy materialno-bytowe": "checkbox",
"niepełnosprawność/choroba": "checkbox",
"sprawy okołorozwodowe": "checkbox",
"inne - j... | Python | 1 |
from django.contrib import admin
from django.urls import path
from telegram_bot.admin import my_admin_site as telegram_bot_admin
urlpatterns = [
path("admin/", admin.site.urls),
path("myadmin/", telegram_bot_admin.urls),
]
| Python | 1 |
argv: **u8) -> int
{
native::start(argc, argv, main)
}
fn lerp(a: f32, b: f32, t: f32) -> f32 { a + (b - a) * t }
fn main () -> ()
{
let width = 800;
let height = 600;
let mut cxt = context::Context
{
window: window::setup(width, height),
camera_position: Vec2::new(0.0, 0.0)
};
// Add the enti... | Rust | 0 |
#!/usr/bin/env python3
example1 = "binfilter::E3dObjList::E3dObjList(binfilter::E3dObjList const&)";
example2 = "E3dObjList::E3dObjList(E3dObjList const&)";
example3 = "E3dObjList::E3dObjList(foo const&)";
def compatrsplit(s, sep, maxsplits=0):
"""Like str.rsplit, which is Python 2.4+ only."""
L = s.split(sep... | Python | 1 |
e diesel::sql_types;
use globee::Customer;
use globee::Email;
use globee::GlobeeIpnRequest;
use globee::PaymentDetails;
use serde_json;
use uuid::Uuid;
#[cfg(test)]
mod update_box_office_pricing_tests {
use super::*;
#[actix_rt::test]
async fn update_box_office_pricing_org_member() {
base::cart::up... | Rust | 0 |
) {
for segment in segments.iter() {
let d = distance(
points[segment.source].x,
points[segment.source].y,
points[segment.target].x,
points[segment.target].y,
);
let kp = k / (num_p as usize as f32) / d;
let n = segment.point_indices.l... | Rust | 0 |
mat(args.pretrained))
model = torch.nn.DataParallel(model).cuda()
model = model.cuda()
model.load_state_dict(network_data)
else:
network_data = None
print('=> train from scratch')
model.init_weights()
print('=> model params: {:.6f}M'.format(model.num_parameter... | Python | 1 |
# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# 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://w... | Python | 1 |
self.ingest_heapam_record(&mut buf, timeline, lsn, &mut decoded)?;
}
// Handle other special record types
if decoded.xl_rmid == pg_constants::RM_SMGR_ID
&& (decoded.xl_info & pg_constants::XLR_RMGR_INFO_MASK)
== pg_constants::XLOG_SMGR_TRUNCATE
{
... | Rust | 0 |
t j = y - 1;
self.board[i][j] = point;
Ok(point)
}
#[test]
fn test() {
let mut b = Board::new();
let coord = CoordinationFlat::new(3, 3);
let p = BoardPieceType::WHITE;
b.place(coord, BoardPieceType::WHITE);
assert!(b.get(coord).unwrap() == p)
}... | Rust | 0 |
project.as_slice();
r
}
}
// Read https://graphql-rust.github.io/juniper/current/schema/schemas_and_mutations.html
// and compare to this file.
use juniper::FieldResult;
use juniper::RootNode;
use crate::type_defs::user::{User, NewUser};
pub struct QueryRoot;
graphql_object!(QueryRoot: () |&self| ... | Rust | 0 |
class Solution:
def titleToNumber(self, columnTitle: str) -> int:
letter ={
'A' : 1,
'B' : 2,
'C' : 3,
'D' : 4,
'E' : 5,
'F' : 6,
'G' : 7,
'H' : 8,
'I' : 9,
'J' : 10,
'K' : 11,... | Python | 1 |
distribution with intensity = intensity_upper_bound
# we apply fast approximation, i.e., re-use exp sample times for computation
# [batch_size, seq_len, num_exp]
exp_numbers = self.sample_exp_distribution(intensity_upper_bound)
exp_numbers = torch.cumsum(exp_numbers, dim=-1)
... | Python | 1 |
if let Some(&total) = memoizer.get(&adapters.len()) {
total
} else {
let idx = adapters.len() - 1;
let total = match (
adapters.get(idx),
idx.checked_sub(1).and_then(|idx_1| adapters.get(idx_1)),
idx.checked_sub(2).and_then(|... | Rust | 0 |
into()),
})
}
}
#[derive(Debug, PartialEq)]
pub struct Category {
pub title: String,
}
impl IterItem for Category {
fn request_next<A: http::HttpClient>(page: &Page<A>, cont: &Option<Vec<(String, String)>>)
-> Result<(Vec<Value>, Option<Vec<(String, String)>>)> {
page.reque... | Rust | 0 |
dr {
self.bind_addr
}
/// The entry nodes for bootstrapping.
pub fn entry_nodes(&self) -> &[AutopeeringMultiaddr] {
&self.entry_nodes
}
/// Whether `Ipv4` or `Ipv6` should be preferred in case a hostname supports both.
pub fn entry_nodes_prefer_ipv6(&self) -> bool {
sel... | Rust | 0 |
* and may allow some compilers to produce better code by registerizing more
* inner-loop variables.
*/
unsafe extern "C" fn find_nearby_colors(
mut cinfo: crate::jpeglib_h::j_decompress_ptr,
mut minc0: libc::c_int,
mut minc1: libc::c_int,
mut minc2: libc::c_int,
mut colorlist: *mut crate::jmore... | Rust | 0 |
) + "</pre>"
else:
agent_logs = [task_logs.format_agent_message_log(json.loads(log.obj)) for log in filtered_logs]
text = "\n\n".join(agent_logs)
return f"<pre>{text}</pre>"
@app_router.get("/api/v1/version", response_class=JSONResponse)
async def get_version() -> Dict[str, str]:
retur... | Python | 1 |
fn check_feature_support(
&self,
feature: Feature,
) -> Result<FeatureSupoortData, HResult> {
match feature {
Feature::PresentAllowTearing => {
let mut value: BOOL = FALSE;
let res = unsafe {
... | Rust | 0 |
#[derive(Debug)]
struct FrameInFlight<B>
where
B: hal::Backend,
{
/// The buffer where we store instance data.
buffer: InstanceBuffer<B>,
/// One descriptor set per draw call we do.
/// Also has the number of instances in that draw call,
/// so we can find offsets.
descriptor_sets: Vec<Escap... | Rust | 0 |
help='uses activation checkpointing from deepspeed')
group.add_argument('--partition-activations', action='store_true',
help='partition Activations across GPUs before checkpointing.')
group.add_argument('--contigious-checkpointing', action='store_true',
... | Python | 1 |
_shape = (1, 15, 3)
self.assertEqual(outputs.logits.shape, expected_shape)
expected_logits = torch.tensor(
[[-6.7329, -16.9590, 6.7447], [-8.0038, -22.3071, 6.9288], [-7.2445, -20.9855, 7.3465]],
device=torch_device,
)
self.assertTrue(torch.allclose(outputs.logit... | Python | 1 |
#! /usr/bin/env python
# lists available GPUs, up to MAX, one on each line
# available is defined as
# maxLoad=0.5
# maxMemory = 0.5
MAX=12
import GPUtil
#GPUtil.showUtilization(all=True)
deviceIDs = GPUtil.getAvailable(limit=MAX)
#print "Available GPUs:"
for ID in deviceIDs:
print ID
| Python | 1 |
tree
mineTree(newHeaderTable, minSup,
newFreqSet, freqItemList)
def powerset(s):
return chain.from_iterable(combinations(s, r) for r in range(1, len(s)))
def getSupport(testSet, itemSetList):
count = 0
for itemSet in itemSetList:
if(set(testSet).issubset(itemSet)... | Python | 1 |
[0; 8],
};
pka.ecdsa_sign(
&NIST_P256,
&INTEGER,
&PRIVATE_KEY,
&HASH,
&mut output_signature,
)
.unwrap();
assert_eq!(output_signature, SIGNATURE);
}
#[test]
fn ecdsa_verify(pka: &mut Pka) {
pka.ecds... | Rust | 0 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from markupsafe import Markup
from odoo import models, fields, _
class Users(models.Model):
_inherit = 'res.users'
odoobot_state = fields.Selection(
[
('not_initialized', 'Not initialized')... | Python | 1 |
= 34,
GlobalGet = 35,
GlobalSet = 36,
I32Load = 40,
I64Load = 41,
F32Load = 42,
F64Load = 43,
I32Load8Signed = 44,
I32Load8Unsigned = 45,
I32Load16Signed = 46,
I32Load16Unsigned = 47,
I64Load8Signed = 48,
I64Load8Unsigned = 49,
I64Load16Signed = 50,
I64Load16Unsigned = 51,
I64Load32Sign... | Rust | 0 |
) => ll_chunk,
ChunkData::Allocated(ll_chunk) => ll_chunk,
ChunkData::OwnedBuffer(ref mut chunk) => {
let ll_chunk: *mut ll::Mix_Chunk = &mut chunk.ll_chunk;
ll_chunk
}
}
}
pub fn volume(&self) -> u8 {
let ll_chunk: *const ll::... | Rust | 0 |
r ds in [ds_fa, ds_np]:
col = 2
for dtype in dtypes:
for asize in asizes:
row = 0
# can make random arrays also
array = np.arange(asize, dtype=dtype)
if dscount == 0:
# convert to FastArray for first run
... | Python | 1 |
# print(overall_df.head())
# print("pivoted_df_total_aligned_lines:")
# print(pivoted_df_total_aligned_lines.head())
# print("pivoted_df_max_cluster_length:")
# print(pivoted_df_max_cluster_length.head())
# print("top_gt_total_aligned_lines_df:")
# print(top_gt_total_alig... | Python | 1 |
TODO: flying boulders should make some damage
Throw(Throw),
Dodge(Dodge),
Bloodlust,
}
impl Effect {
pub fn to_str(&self) -> &str {
match *self {
Effect::Create(_) => "Create",
Effect::Kill(_) => "Kill",
Effect::Vanish => "Vanish",
Effect::Stun =... | Rust | 0 |
storage.
fn kill_child_storage(&mut self, storage_key: ChildStorageKey);
/// Clear storage entries which keys are start with the given prefix.
fn clear_prefix(&mut self, prefix: &[u8]);
/// Clear child storage entries which keys are start with the given prefix.
fn clear_child_prefix(&mut self, storage_key: Chil... | Rust | 0 |
Tool string Format: "tool=index", index: index of the calibrated tool coordinate system. The global tool coordinate system will be used if it is not set.
"""
string = "PositiveKin({:f},{:f},{:f},{:f},{:f},{:f}".format(
J1, J2, J3, J4, J5, J6)
params = []
if user != ... | Python | 1 |
_user_data(
shape_plan: *mut hb_shape_plan_t,
key: *mut hb_user_data_key_t,
data: *mut ::std::os::raw::c_void,
destroy: hb_destroy_func_t,
replace: hb_bool_t,
) -> hb_bool_t;
}
extern "C" {
pub fn hb_shape_plan_get_user_data(
shape_plan: *mut hb_shape_plan_t,
... | Rust | 0 |
mut ret);
ret
}
Ty::FixedVar(_) | Ty::Record(_) | Ty::Con(_, _) => {
st.err(func.unwrap_or(exp), ErrorKind::AppLhsNotFn(func_ty));
Ty::None
}
Ty::Fn(want_arg, mut want_res) => {
unify(st, *want_arg, arg_ty, arg.unwrap_or(exp));
apply(st.s... | Rust | 0 |
be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS... | Rust | 0 |
ad_test_mesh("sphere_coarse.msh");
assert!(msh_parses(&msh_bin));
let msh = mshio::parse_msh_bytes(&msh_bin).unwrap();
assert_eq!(msh.total_node_count(), 183);
assert_eq!(msh.total_element_count(), 891);
assert_eq!(msh.point_count(), 2);
assert_eq!(msh.curve_count(), 3);
assert_eq!(msh.sur... | Rust | 0 |
ize, est_queue_len: usize) -> TcpListen {
TcpListen {
syn_queue: VecDeque::with_capacity(syn_queue_len),
est_queue: VecDeque::with_capacity(est_queue_len),
context: self.context.clone(),
}
}
}
<filename>tests/analysis/mod.rs<gh_stars>10-100
mod ode;
mod newton_rap... | Rust | 0 |
rom_unix_timestamp(timestamp: i64) -> Result<Self, error::ComponentRange> {
let unix_epoch_julian_date = Date::from_ordinal_date_unchecked(1970, 1).to_julian_day();
let date = const_try!(Date::from_julian_day(
unix_epoch_julian_date + (timestamp / 86_400) as i32
));
let hou... | Rust | 0 |
= SecretScannerBuilder::new().set_json_str(regex_string).build();
//! let mut matches_map = ss.matches(b"my phone is 555-555-5555");
//! assert!(matches_map.contains_key(&String::from("Phone number")));
//!
//! let matches = matches_map.remove(&String::from("Phone number")).unwrap();
//! let match_obj = matches.into_i... | Rust | 0 |
rop_img = crop_img.squeeze(axis=0)
else:
bbox = rio.coords.BoundingBox(left=xmin, bottom=ymin, right=xmax, top=ymax)
out_rst = source_raster.reproject(bounds=bbox) # should we instead raise an issue and point to reproject?
crop_img = out_rst.data
tfm = out_rst.transform
return... | Python | 1 |
test = list()
test.append('Gustavo')
test.append(40)
dudes = list()
dudes.append(test[:])
test[0] = 'Maria'
test[1] = 22
dudes.append(test[:])
print(test)
print(dudes)
| Python | 1 |
import sys, traceback, base64, re, reprlib
from io import BytesIO
from itertools import islice
def print_html(html, out=sys.stdout):
out.write("\x1b]72;" + html + "\x07")
def display_html(html, overwrite=False, name='python_image', inline=False, out=sys.stdout):
top = 'span' if inline else 'div'
if overwr... | Python | 1 |
#!/usr/bin/python3
from scipy.integrate import ode
import numpy as np
def ode_system(x, t, i):
T = x[0]; TI = x[1]; TL = x[2]; M = x[3]; MI = x[4]; CTL = x[5]; V = x[6]
if T < .1: return np.zeros(7)
dTdt = s1[i] + p1[i]*T*V/(C1[i] + V) - d1[i]*T - (K1[i]*V + K2[i]*MI)*T
dTIdt = psy[i]*(K... | Python | 1 |
d(fish_data_copy)
df = pd.DataFrame(records)
df = df[["Group", "fish_id", "mean_vor_score", "mean_r2_score", "combined_score", "rank"]]
df.to_csv(f"{name}_{group}.csv", index=False)
# Inactivate
# ranked_fish_to_csv(r"\\172.25.250.112\arrenberg_data\shared\nkeawfanapadol\zebrafish... | Python | 1 |
_err() {
drop(ctx);
eprintln!("{:?}", err_warn);
exit(1);
}
let mut relocated = ctx.relocate().unwrap();
let addr = unsafe {
relocated
.get_symbol(CStr::from_bytes_with_nul_unchecked("greet\0".as_bytes()))
.unwrap()
};
let greet: fn() = unsafe... | Rust | 0 |
Output = Result<Vec<Repo>, Error>>,
{
if page_size == 0 {
return Err("PageSize must be greater than 0".into());
}
let page_count = user.public_repos / page_size;
let page_futures = (0..=page_count).map(|page_number| fetch_page(user.clone(), page_number));
let results = join_all_futures(page_... | Rust | 0 |
h = D.hash_geometry(precision=1e-4)
assert h == "eae9ef1c4e5a582add69fc0246218bcba4c013ec"
def test_kl_outline():
A = pg.cross(length=19, width=3.7, layer=0)
B = pg.ellipse(radii=(10, 5), angle_resolution=2.5, layer=1)
D = pg.kl_outline(
[A, B],
distance=0.1,
open_ports=Fal... | Python | 1 |
.into_repr().to_bits_le());
assert!(tmp1_int == BigInt::from(0));
assert!(tmp2_bits < 128, "tmp2 bits {}", tmp2_bits);
// equation (f): tmp1 + 2^128 tmp2 = lambda_1 * k2_sign * k2 + s - t * t_sign *
// r1 - k1
assert_eq!(
&tmp1_int + &two_to_128 * &tmp2_int,
... | Rust | 0 |
count is odd, the last elf will rob the current round's first elf,
// and reduce the count to an even number.
// if the remaining count is even, the last elf is robbed
let mut elf_count = initial_elf_count;
let mut leftmost = 1; // first using a 1-based index
... | Rust | 0 |
# -*- coding: utf-8 -*- #
# Copyright 2022 Google LLC. 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 requir... | Python | 1 |
8-12-08"
},
(...)
],
"meta": {
"success": true
}
}
```
**/
///
#[get("/times/by-stop/<stop_id>?<time_search>")]
pub fn times_stop_query(
rh: State<RoutesHandler>,
stop_id: String,
mut time_search: TimeSearch,
) -> Json<ResultArray<Time>> {
time_search.s... | Rust | 0 |
ht(&self.state_manager, height);
self.certified_height = height;
self
}
/// Convenience wrapper around
/// `self.state_manager.encode_certified_stream_slice()`.
pub fn get_slice(
&self,
subnet_id: SubnetId,
from: StreamIndex,
msg_count: usize,
) -> C... | Rust | 0 |
rwards)
def test_09_no_jump_too_far_backwards(self):
self.run_test(no_jump_too_far_backwards)
def test_10_no_jump_to_except_1(self):
self.run_test(no_jump_to_except_1)
def test_11_no_jump_to_except_2(self):
self.run_test(no_jump_to_except_2)
def test_12_no_jump_to_except_3(self):... | Python | 1 |
k!($i, $start, $fmt, $bytes, "<"),
b'>' => $callback!($i, $start, $fmt, $bytes, ">"),
b'&' => $callback!($i, $start, $fmt, $bytes, "&"),
b'"' => $callback!($i, $start, $fmt, $bytes, """),
b'\'' => $callback!($i, $start, $fmt, $bytes, "'"),
... | Rust | 0 |
, PartialEq)]
pub enum REG_GPIO_10_MASK_A {
#[doc = "0: `0`"]
UNMASKED = 0,
#[doc = "1: `1`"]
MASKED = 1,
}
impl From<REG_GPIO_10_MASK_A> for bool {
#[inline(always)]
fn from(variant: REG_GPIO_10_MASK_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `reg_gpio_10_mask` reader - Mask... | Rust | 0 |
urn full_loss, cls_loss, reg_loss, acc, f1, prec, rec, auc
def main(args):
checkpoint_dir = '/media/robert/4TB-SSD/checkpoints'
os.makedirs(checkpoint_dir, exist_ok=True)
if args.test_only:
assert args.checkpoint, "--checkpoint 必须指定一个 .pt 文件"
# 构造 test_loader (与训练时相同的数据预处理流程)
dat... | Python | 1 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-09-03 03:12
from __future__ import unicode_literals
from django.db import migrations
def update_topic_first_post_last_post(apps, schema_editor):
Topic = apps.get_model('forum_conversation', 'Topic')
for topic in Topic.objects.all():
first_p... | Python | 1 |
import requests
import json
import os
from PIL import Image
from io import BytesIO
## BIENVENIDA A LA POKEDEX
print("Bienvenido a tu POKEDEX")
## OBTENCION DE DATOS DEL POKEMON
def pokemon(nombre):
url= f"https://pokeapi.co/api/v2/pokemon/" + pokemon
respuesta = requests.get(url)
##VERIFICACION SI LA OPERACION ES... | Python | 1 |
imizer.zero_grad()
outputs = snn(inputs)
labels_ = torch.zeros(batch_size * 2, 10).scatter_(1, labels2.view(-1, 1), 1)
loss = criterion(outputs.cpu(), labels_)
_, predicted = outputs.cpu().max(1)
# ----- showing confussion matrix -----
cm += confu... | Python | 1 |
from airunner.components.nodegraph.gui.widgets.nodes.logic.base_logic_node import (
BaseLogicNode,
)
class ForLoopNode(BaseLogicNode):
"""
A node that iterates from a first index to a last index.
Similar to Unreal Engine's ForLoop node, this node has:
- An exec input to start the loop
- A loo... | Python | 1 |
, PmError, KernelError};
use sunrise_libuser::ldr::ILoaderInterfaceAsync;
use sunrise_libuser::syscalls::{self, map_process_memory};
use sunrise_libuser::types::{Pid, Process, ReadableEvent, WritableEvent, HandleRef};
use sunrise_libkern::process::*;
use sunrise_libkern::MemoryPermissions;
use sunrise_libuser::mem::{fi... | Rust | 0 |
aLight {
/// Returns a new `DiffuseAreaLight`.
///
/// * `light_to_world` - Transformation from light coordinate system to
/// world coordinate system.
/// * `medium_interface` - Participating medium.
/// * `l_emit` - Emitted radiance.
/// * `n_samples` ... | Rust | 0 |
assert_eq!(store.lookup(public_key).unwrap().unwrap().public_txt(), public_key);
}
#[cfg(feature = "draft")]
#[test]
fn test_loader_with_state_default() {
let store = ZCertStore::new(None).unwrap();
assert!(store.lookup("nonexistent_key").unwrap().is_none()); // Idiot check
... | Rust | 0 |
index = random_number_generator.gen_range(0usize..array.len());
return array[random_index].clone();
}
pub fn binary_search(array: &Vec<u32>, target: &u32) -> usize {
if array.len() == 0 {
return 0usize;
}
let mut minimum: usize = 0usize;
let mut maximum: usize = array.len() - 1;
let ... | Rust | 0 |
`if` expression",
))
}
_ => {}
}
if input.is_empty() {
return Err(syn::Error::new(
cond.span(),
"this `if` expression has a condition, but no block",
));
}
let then_branch = input.parse()?;
... | Rust | 0 |
import pickle
import numpy as np
# f = open('./node10_data/4-2023-11-20-15-42-12.pkl','rb')
# data = pickle.load(f)
# print(data)
# print(len(data))
import matplotlib.pyplot as plt
import networkx as nx
def read_pickle(pickle_path):
"""
读取pickle并转化为graph
:param pickle_path:
:return:
"""
pkl_gr... | Python | 1 |
from blendbatchnorm import fuse_bn_recursively
import onnx
from onnx2keras import onnx_to_keras
import torch
import numpy as np
from meshnet import MeshNet
import tensorflowjs as tfjs
from fixmodeljson import fixjson_file
def preprocess_image(img):
"""Unit interval preprocessing"""
img = (img - img.min()) / (i... | Python | 1 |
Clone))]
#[derive(Default, Clone, Copy)]
#[repr(C)]
pub struct DataRec {
pub packets_size: usize,
pub rx_packets: u64,
pub rx_ipv4_packets: u64,
pub rx_ipv6_packets: u64,
pub last_source_ipv4: [u8; 4],
pub last_dest_ipv4: [u8; 4],
pub last_source_mac: [u8; 6],
pub last_dest_mac: [u8; 6]... | Rust | 0 |
goals: &'a Self::InternedGoals) -> &'a [Goal<Self>];
/// Create an "interned" substitution from `data`. This is not
/// normally invoked directly; instead, you invoke
/// `SubstitutionData::intern` (which will ultimately call this
/// method).
fn intern_substitution<E>(
&self,
data... | Rust | 0 |
ate_body!($name, $operator, $return_type);
};
}
/// Alias for `infix_predicate!`
macro_rules! infix_expression {
($($args:tt)*) => { infix_predicate!($($args)*); }
}
#[macro_export]
#[doc(hidden)]
macro_rules! postfix_predicate_body {
($name:ident, $operator:expr, $return_type:ty) => {
#[derive(De... | Rust | 0 |
= env::args().collect();
if args.len() < 2 {
usage_exit!("Missing mandatory argument 'day'");
}
let day = args[1]
.parse::<u8>()
.unwrap_or_else(|e| usage_exit!("Incorrect 'day' argument. {}", e));
let input_filename = format!("input/day{}.txt", day);
let puzzle =
da... | Rust | 0 |
r_id);
Ok(())
}
}
use std::path::Path;
use std::{fmt, default};
use std::io::{BufReader,BufRead};
use std::fs::File;
use std::collections::HashMap;
use std::string;
use git2;
use regex::Regex;
macro_rules! ostring {
($e:expr) => (match $e {
Some(s) => Some(String::from(s)),
None => Non... | Rust | 0 |
dbg!(source)));
let mut iter = dbg!(literals).into_iter();
let literal = iter
.next()
.expect("Must have at least one item in laterals");
let mut cls = LiteralSet::from(literal);
for literal in iter {
assert!(cls.add_adjacent(literal).is_ok());
... | Rust | 0 |
"""Yahoo Finance Available Indices Model."""
# pylint: disable=unused-argument
from typing import Any, Dict, List, Optional
from openbb_core.provider.abstract.fetcher import Fetcher
from openbb_core.provider.standard_models.available_indices import (
AvailableIndicesData,
AvailableIndicesQueryParams,
)
from ... | Python | 1 |
mount("/api/v1/auth/", rocket::routes![
endpoints::auth::register,
endpoints::auth::login,
endpoints::auth::invalidate,
endpoints::auth::get_me,
endpoints::auth::patch_me,
endpoints::auth::delete_me
])
.mount("/api/v1/users/", rocke... | Rust | 0 |
import json
import os
from datetime import datetime
import questionary
from rich.console import Console
from rich.panel import Panel
from estilos import gamerStyle
# Consola Rich
console = Console()
# Ruta del archivo JSON
ARCHIVO = os.path.join("data", "publicaciones.json")
def cargar_contenido():
try:
... | Python | 1 |
import tkinter as tk
from tkinter import ttk
def decrypt_caesar(ciphertext, shift):
decrypted_text = ""
for char in ciphertext:
if char.isalpha():
if char.islower():
decrypted_text += chr((ord(char) - shift - ord('a')) % 26 + ord('a'))
elif char.isupper():
... | Python | 1 |
# -*- coding: utf-8 -*- #
# Copyright 2021 Google LLC. 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 requir... | Python | 1 |
{
let line = line.unwrap().to_string();
if line.trim_end().is_empty() {
// end of entry, determine whether it's valid
if validate_data(entry) {
counter += 1;
}
entry = String::new();
} else {
entry = format!("{} {}", entry, lin... | Rust | 0 |
"Starting...");
let poller = mio::Poll::new().unwrap();
let async_pin_poller_0 = self.setup_data_pin(self.data_0_gpio, 0, &poller); // Need to keep a valid reference to the async poller
let async_pin_poller_1 = self.setup_data_pin(self.data_1_gpio, 1, &poller); // Need to keep a valid reference to the async... | Rust | 0 |
,
content_length,
}
}
}
struct DurationStats {
sorted: Vec<Duration>,
}
impl DurationStats {
fn from_facts(facts: &[Fact]) -> DurationStats {
let mut sorted: Vec<Duration> = facts.iter().map(|f| f.duration).collect();
sorted.sort();
Self { sorted }
}
fn... | Rust | 0 |
mary.scalar("gen_s_loss", self.gen_s_loss)
tf.summary.scalar("gen_b_loss", self.gen_b_loss)
tf.summary.scalar("const_loss_s", self.const_loss_s)
tf.summary.scalar("const_loss_b", self.const_loss_b)
tf.summary.scalar("disc_loss", self.disc_loss)
tf.summary.scalar("disc_b_loss", se... | Python | 1 |
ilename>ag.rs
#[inline]
pub fn mrb_args_key(n1: u32, n2: u32) -> mrb_aspec {
// ```c
// #define MRB_ARGS_KEY(n1,n2) ((mrb_aspec)((((n1)&0x1f) << 2) | ((n2)?(1<<1):0)))
// ```
if n2 == 0 {
(n1 & 0x1f) << 2
} else {
(n1 & 0x1f) << 2 | 1 << 1
}
}
//! # System Integration Module (SIM... | Rust | 0 |
code(self):
deprecation_warning('HTTPError.code is deprecated, use HTTPError.status instead')
return self.status
@code.setter
def code(self, value):
return
@property
def url(self):
deprecation_warning('HTTPError.url is deprecated, use HTTPError.response.url instead')
... | Python | 1 |
# 生成实际的触发时间点(K线时间的下一分钟)
trigger_times = []
for k_h, k_m in k_line_check_times:
# 计算下一分钟作为触发时间
trigger_m = k_m + 1
trigger_h = k_h
if trigger_m >= 60:
trigger_h += 1
trigger_m = 0
# 跳过超出交易时间的触发点
... | Python | 1 |
_durability(durability));
}
pub fn calc_synthesis(&self, efficiency: f32) -> u16 {
(self.caches.base_synth * self.condition.synth_ratio() * self.buffs.synthesis(efficiency))
as u16
}
pub fn calc_touch(&self, efficiency: f32) -> u32 {
(self.caches.base_touch * self.buffs.tou... | Rust | 0 |
"^/libs/granite/security/truststore.json$",
r"^/system/console/bundles/(?P<name>[^/?#]*)$",
r"^/system/console/bundles/(?P<name>[^/?#]*).json$",
r"^/system/console/configMgr$",
r"^/system/console/configMgr/com.adobe.granite.auth.saml.SamlAuthenticationHandler$",
... | Rust | 0 |
h
Returns:
bool: True if other is same plugin instance, False otherwise
"""
if isinstance(other, Plugin):
return self is other
return False
@abstractmethod
def __call__(
self,
*args: Any,
**kwargs: Any,
) -> torch.Tensor | tup... | Python | 1 |
/// Uses the default epsilon value defined by [`NearlyEq`].
///
/// # Examples
/// ```
/// use mockiato::mockable;
///
/// # const IGNORED: &str = "
/// #[cfg_attr(test, mockable)]
/// # ";
/// # #[mockable]
/// trait FloatFormatter {
/// fn format_float(&self, value: f6... | Rust | 0 |
ye;
assert_ok!(Governance::create_vote(Origin::signed(10), 0, 5, [00].to_vec(), 0, [[00].to_vec()].to_vec()));
assert_ok!(Governance::create_vote(Origin::signed(10), 1, 5, [00].to_vec(), 0, [[00].to_vec()].to_vec()));
let vote = Governance::votes(1);
// vote should be active
ass... | Rust | 0 |
k=traceback.format_exc()
))
raise
# Replace methods with monitored versions
setattr(cls, "__init__", __monitored_init__)
if original_add_member:
setattr(cls, "add_member", __monitored_add_member__)
if original_remove_member:
setattr(cls, "remove_member", __monito... | Python | 1 |
self.n_hit_moles += 1;
let _ = self.hit_sound.play();
} else {
let _ = self.miss_sound.play();
}
}
}
}
... | Rust | 0 |
s 0 for the rest of the elements of width
for _ in statics.len()..num_statics {
let (_, var) = prover.commit(FieldElement::from(ZERO_CONST), FieldElement::zero());
statics.push(var);
}
statics
}
/// Allocate padding constant and zeroes for Verifier
pub fn allocate_statics_for_verifier(
... | Rust | 0 |
mut sess.handshake_data.server_kx_params);
if let ServerKeyExchangePayload::ECDHE(ecdhe) = decoded_kx {
info!("ECDHE curve is {:?}", ecdhe.params.curve_params);
}
Ok(&EXPECT_TLS12_SERVER_DONE_OR_CERTREQ)
}
static EXPECT_TLS12_SERVER_KX: State = State {
expect: Expectation {
content_ty... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.