text string | label_name string | labels int64 |
|---|---|---|
define_print! {
('tcx) ty::ProjectionPredicate<'tcx>, (self, f, cx) {
debug {
print!(f, cx,
write("ProjectionPredicate("),
print(self.projection_ty),
write(", "),
print(self.ty),
write(")"))
}
... | Rust | 0 |
class MonteCarloTreeSearchBasedPlayer():
def __init__(self, game, nnet, args):
"""
Args:
game: OthelloGame instance
Instance of the OthelloGame class above;
nnet: OthelloNet instance
Instance of the OthelloNNet class above;
args: dictionary
Instantiates number of ite... | Python | 1 |
rdr)
// .unwrap_or_else(|()| panic!("Can't parse tls certificate file: {}", cert_filename))
// };
// let key = {
// let mut pkcs8 = {
// let file = File::open(&key_filename)
// .unwrap_or_else(|e| panic!("Can't open tls key file: '... | Rust | 0 |
total_time = end_time - start_time
average_time = total_time / num_iterations
print(f"Average inference time for input: {average_time:.6f} seconds")
# Main function to handle different commands
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Usage:")
print("python CNNclassify... | Python | 1 |
from refo import finditer, Predicate, Star, Any, Disjunction
import re
# encoding UTF-8
"""
这是一个多行注释。
你可以在这里写很多行,
它们都不会被执行。
"""
'''
本代码设置问题模板。将自然语言问题转化为可查询的SPARQL语句
模板内容如下:
1. XX会议的参会人员有谁?
2. XX会议包括什么内容?
3. XX会议发生于什么时间?
4. XX会议举办于什么地点?
5. XX人物就职于什么组织?
6. XX决议通过的内容有几个?
7. XX决议通过XX内容吗?
8. XX会议发生于XX时间吗?
9. XX人物就职于XX组织吗?
... | Python | 1 |
import pygame, sys, random
WIDTH, HEIGHT = 800, 600
BLUE, BROWN, GREEN, WHITE, GOLD = (80, 120, 255), (139, 69, 19), (0, 150, 0), (255, 255, 255), (255, 215, 0)
player = pygame.Rect(50, HEIGHT-150, 30, 50) # HEIGHT-150 -> HEIGHT-90
velocity_y = 0
isJumping = False
gravity = 0.5
jumpStrength = 12
moveSpeed = 5
PLATFO... | Python | 1 |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the Creative Commons license found in the
# LICENSE file in the root directory of this source tree.
from habitat.config.default import get_config
def get_dataset_config(
dataset_path, data_subset, max_... | Python | 1 |
::*;
use ::*;
// TODO: redefine Debug so only initial bytes of BytesMut are printed, and printed in hex
/// Data packet for block read|write. Note that `header.data_len == data.len()`
#[derive(Debug, PartialEq, Clone)]
pub struct BlockDataPacket {
pub header: PacketHeaderProto,
pub checksum: Bytes,
pub dat... | Rust | 0 |
fied": bool(user_info.get("verified", False)),
"exp": user_info.get("exp"),
"level": user_info.get("level"),
"characters": json.loads(user_info.get("characters", '[]')) if isinstance(user_info.get("characters"), str) else user_info.get("characters", [""]),
... | Python | 1 |
se jormungandr_lib::{crypto::hash::Hash, interfaces::Block0Configuration};
use jormungandr_testing_utils::wallet::Wallet;
use rand::prelude::*;
use rand_chacha::ChaChaRng;
use std::collections::HashMap;
pub struct VoteRoundGenerator {
block0: Block0Configuration,
block0_hash: Hash,
wallets: HashMap<Address... | Rust | 0 |
() -> ::protobuf::descriptor::FileDescriptorProto {
::protobuf::Message::parse_from_bytes(file_descriptor_proto_data).unwrap()
}
pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto {
file_descriptor_proto_lazy.get(|| {
parse_descriptor_proto()
})
}
use crate::{
... | Rust | 0 |
))
}
}
pub fn find_in_slice<T: Eq>(haystack: &[T], needle: &[T]) -> Option<usize> {
// naive algorithm only meant for small needles
if needle.len() > haystack.len() {
return None;
}
for i in 0..=haystack.len() - needle.len() {
let mut matching = true;
for j in 0..nee... | Rust | 0 |
'''
Abbreviation Extension for Python-Markdown
==========================================
This extension adds abbreviation handling to Python-Markdown.
Simple Usage:
>>> import markdown
>>> text = """
... Some text with an ABBR and a REF. Ignore REFERENCE and ref.
...
... *[ABBR]: Abbreviation
... | Python | 1 |
_fields:
sample = oversized_fields[:5]
errors.append(
MetadataValueError(
f"Oversized metadata fields: {', '.join(sample)}"
f"{'...' if len(oversized_fields) > 5 else ''}",
f"Metadata field values must not exceed {MAX_JS... | Python | 1 |
# **************************************************************************** #
# #
# ::: :::::::: #
# main.py :+: :+: :+: ... | Python | 1 |
collected_attributes.update(_set_job_attributes(job_ref))
if attributes:
collected_attributes.update(attributes)
final_attributes = {k: v for k, v in collected_attributes.items() if v is not None}
return final_attributes
def _set_client_attributes(client):
return {"db.name": client.proj... | Python | 1 |
Data::Struct(ref fields, _) => {
format_struct_struct(context, struct_parts, fields, offset, one_line_width)
}
}
}
pub(crate) fn format_trait(
context: &RewriteContext<'_>,
item: &ast::Item,
offset: Indent,
) -> Option<String> {
if let ast::ItemKind::Trait(trait_kind) = &item.ki... | Rust | 0 |
# Copyright 2015 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 |
#!/usr/bin/env python3
#Ip_portatil= 192.168.68.117
#Ip_router=192.168.68.1 --> mac_router= 6c:5a:b0:c9:9e:90
#mi_mac= 50-E0-85-AA-31-D3
import scapy.all as scapy
import argparse
import signal
import sys
from termcolor import colored
def signal_handler(signal,frame):
print(colored("\nDeteniendo ARP spoofing y r... | Python | 1 |
/// (<subquery>)`.
struct Desugarer<'a> {
scx: &'a StatementContext<'a>,
status: Result<(), PlanError>,
recursion_guard: RecursionGuard,
}
impl<'a> CheckedRecursion for Desugarer<'a> {
fn recursion_guard(&self) -> &RecursionGuard {
&self.recursion_guard
}
}
impl<'ast> VisitMut<'ast, Raw> ... | Rust | 0 |
"Offset of field: ",
stringify!(st_mysql_cmd_buffer),
"::",
stringify!(length)
)
);
}
pub type MYSQL_CMD_BUFFER = st_mysql_cmd_buffer;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct st_mysql_error_info {
pub error_no: ::std::os::raw::c_uint,
pub error: [::... | Rust | 0 |
13, 0x1d, 0x47, 0x49, 0x5b, 0x55, 0x7f, 0x71, 0x63, 0x6d,
0xd7, 0xd9, 0xcb, 0xc5, 0xef, 0xe1, 0xf3, 0xfd, 0xa7, 0xa9, 0xbb, 0xb5, 0x9f, 0x91, 0x83, 0x8d,
];
#[cfg(test)]
mod tests {
use super::*;
use crate::hex;
use quickcheck_macros::quickcheck;
#[test]
fn test_encrypt_decrypt_128() {
... | Rust | 0 |
import base64
from Crypto.Cipher import AES
from django.conf import settings
def encrypt(value):
"""Return the encrypted value of the setting.
Uses the character '\0' as padding.
<target>
"""
cipher = AES.new(settings.SITE_SETTINGS_KEY, AES.MODE_ECB)
value = unicode(value).encode('utf-8')
</targe... | Python | 1 |
<<Self as frame_system::Config>::Event>;
/// A dispatchable call.
type Call: Parameter + Dispatchable<Origin=Self::Origin> + GetDispatchInfo + From<frame_system::Call<Self>>;
/// The currency trait.
type Currency: ReservableCurrency<Self::AccountId>;
/// Handler for the unbalanced decrease when fees are burne... | Rust | 0 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from pytorch3d.transforms import quaternion_multiply, quaternion_to_matrix
from scipy.stats import multivariate_normal
from scipy.linalg import sqrtm
import numpy as np
# waterstein distance of two gaussians modified by Junli
class WassersteinGaussi... | Python | 1 |
import asyncio
import json
from bot.logger import logger
async def ping_market_loop(ws):
try:
while not ws.closed:
await asyncio.sleep(30)
if ws.closed:
break
try:
ping_message = {"method": "PING"}
await ws.send_json(ping_... | Python | 1 |
,
#[doc = "0x118 - Interrupt Flag Set Register"]
pub ifs: IFS,
#[doc = "0x11c - Interrupt Flag Clear Register"]
pub ifc: IFC,
#[doc = "0x120 - I/O Routing Register"]
pub route: ROUTE,
#[doc = "0x124 - Input Sense Register"]
pub insense: INSENSE,
#[doc = "0x128 - Configuration Lock Re... | Rust | 0 |
BUCKET_CAP: i64 = 100;
const DIGITS_PER_BUCKET: usize = 2;
/// An unbounded, unsigned integer.
///
/// # Internal Representation
/// `BigUint` is represnted internally by a `Vector<i64>`.
/// Each index of the vector (referred to as a `bucket`) contains
/// up to 2 digits of a number, with the highest-order digits... | Rust | 0 |
# -*- coding: utf-8 -*-
# pylint: disable=attribute-defined-outside-init
from tcms.rpc.tests.utils import APIPermissionsTestCase
from tcms.testplans.models import PlanType
from tcms.tests.factories import PlanTypeFactory
from tcms.xmlrpc_wrapper import XmlRPCFault
class TestPlanTypeFilter(APIPermissionsTestCase):
... | Python | 1 |
{
fn can_parse(mut data: &[u8]) -> bool {
let _visibility = parse!(data, Visibility);
data.starts_with(b"enum")
}
}
impl Parse for Enum {
fn parse(mut data: &[u8]) -> (&[u8], Self) {
let visibility = parse!(data, Visibility);
assert!(data.starts_with(b"enum"));
dat... | Rust | 0 |
role = threads.THREADS[q]['role']
# Skip queues that have their data already preloaded
if threads.THREADS[q]['preload'] and data.loaded:
continue
refs = []
for idx in self.visible_rows['source_rows']:
# I... | Python | 1 |
if nbr.GetAtomicNum() == 17:
chlorine_count += 1
# Allow oxygen if it appears to be -OH (has at least one implicit H)
elif nbr.GetAtomicNum() == 8 and nbr.GetTotalNumHs() > 0:
continue
# Allow a carbon if it is part of another isol... | Python | 1 |
_FUNC121_IN_SEL`"]
pub struct GPIO_FUNC121_IN_SEL_W<'a> {
w: &'a mut W,
}
impl<'a> GPIO_FUNC121_IN_SEL_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x1f) | ((value as u32) & 0x1f);
self... | Rust | 0 |
et_token(operation_config.token_credential_resource())
.await
.map_err(list_by_subscription::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().app... | Rust | 0 |
at = slot.interned_at;
db.salsa_runtime().report_query_read(
slot.database_key_index,
INTERN_DURABILITY,
interned_at,
);
Ok(value)
}
fn durability(&self, _db: &Q::DynDb, _key: &Q::Key) -> Durability {
INTERN_DURABILITY
}
fn entries<C>... | Rust | 0 |
rue' or 'false'
else:
params['%s.%s' % (label, k)] = v
def _make_request(self, action, verb, path, params):
params['ContentType'] = 'JSON'
response = self.make_request(action=action, verb='POST',
path='/', params=params)
body ... | Python | 1 |
import os
import requests
from datetime import datetime, timedelta
import pytz
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
API_KEY = os.getenv('FOOTBALL_API_KEY')
def get_next_matchday_matches():
# Fetch all matches with relevant statuses
response = requests.get(
"https:... | Python | 1 |
)),
_,
) = response
{
if let Ok(UpdateState::Updated) = result {
trace!(
nonce,
"write_setting notify",
"setting_type"... | Rust | 0 |
import pytest
from unittest.mock import Mock, patch
from routers.costs import calculate_final_cost, find_resource_types
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
class TestCostCalculation:
"""コスト計算機能のテストクラス"""
def test_find_resource_types_simple(self):
... | Python | 1 |
def envolve(population,fitness):
#print("initial fitness = ",fitness)
selected_population, parents_fitness = select_order(population, fitness) #从上一代中挑出50个
p = parents_fitness
#kids = mutate(selected_population, N_KID)
for i in range(10):
id = random.ran... | Python | 1 |
sociated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
/... | Rust | 0 |
cadena=("hola sergio cometrabas cabron")
cadena=[x for x in cadena.title().split()]
print(cadena) | Python | 1 |
);
assert_eq!(allocator.num_allocated_chunks, 3);
}
#[test]
fn allocate_then_deallocate() {
let mem = make_memory();
let allocation_size = Bytes::from(16u64);
let allocator_addr = Address::from(0);
let mut allocator = Allocator::new(mem.clone(), allocator_a... | Rust | 0 |
in2vis=q_main2vis,
q_vis2main=q_vis2main,
config=config,
local_map_default_on=False,
mesh_default_on=mesh_on,
neural_point_map_default_on=config.neural_point_map_default_on,
)
gui_process = mp.Process(target=slam_gui.run, args=(params_gui,))
... | Python | 1 |
x=True) }}",
Extraction::populate(
Some(vec![("x".to_string(), None)]),
Some(vec![("package".to_string(), "table".to_string())]),
Some(configs),
),
);
}
// TODO wow this needs a refactor. get some helpers in here.
#[test]
fn extracts_from_deepyly_nested_config()... | Rust | 0 |
from datetime import datetime
import numpy as np
import os
import torch
import random
from models.model import CNN_cifar,LeNet_mnist,CNN_fmnist,resnet20
from sklearn.cluster import KMeans
from models.resnet50 import resnet50
def model_init(dataset,device):
if dataset=='MNIST':
model = LeNet_mnist().to(devi... | Python | 1 |
ority storage.
fn pending_priority() -> *const AtomicU8;
/// Returns a raw pointer to the thread priority storage.
fn priority(&self) -> *const AtomicU8;
/// Sets the `thr_idx` thread pending.
///
/// See [the trait level documentation](SoftThread) for details.
///
/// # Safety
///... | Rust | 0 |
Key,
iv: &[u8],
extra: &[u8],
) -> Box<dyn MessageEncrypter>;
}
/// A `MessageEncrypter` for AES-GCM AEAD ciphersuites. TLS 1.2 only.
struct GcmMessageEncrypter {
enc_key: aead::LessSafeKey,
iv: Iv,
}
/// A `MessageDecrypter` for AES-GCM AEAD ciphersuites. TLS1.2 only.
struct GcmMessageDe... | Rust | 0 |
import json
from nimbus import __version__
from nimbus.requests import NimbusCommandRequest
EXAMPLE_TAG = "??? example"
def generate_web_examples(command: str, param: dict | None = None) -> str:
return f"""
{EXAMPLE_TAG} "Example"
{generate_web_shell_example(command, param)}
{generate_web_httpx_example(... | Python | 1 |
#!/usr/bin/env python3
"""
Launcher for clang which computes the dependency for the file being compiled.
"""
import sys
import os
import subprocess
import time
import json
import tempfile
import fcntl
TOOLS_DIR = os.path.dirname(os.path.abspath(__file__))
def trim_clang_args_in_cdb(cdb):
"""Trim -Xclang options... | Python | 1 |
m affineIndex affine index to use (if < 0 or > 31 the sprite will be unrotated)"]
#[doc = " \\param sizeDouble if affineIndex >= 0 this will be used to double the sprite size for rotation"]
#[doc = " \\param hide if non zero (true) the sprite will be hidden"]
#[doc = " \\param vflip flip the spr... | Rust | 0 |
import numpy
import os
import math
import numpy as np
def parse_file(file_path):
with open(os.path.join(file_path)) as f:
lines = f.read().splitlines()
return lines
def operations(secret_number):
secret_number = (secret_number * 64) ^ secret_number
secret_number = secret_number % 16777216
... | Python | 1 |
object_mut().unwrap())
}
None => {
// Otherwise, initialize `nest_result` to result.
result
}
};
(nest_result, term_definition.container)
}
None => (result, Container::None),
};
// Initialize container to container mapping for item active property
// in active context, or to a new e... | Rust | 0 |